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
25,479,984
Get the name (string) of a generic type in Swift
<p>I have a generic class of type T and I would like to get the name of the type that passed into the class when instantiated. Here is an example.</p> <pre><code>class MyClass&lt;T&gt; { func genericName() -&gt; String { // Return the name of T. } } </code></pre> <p>I have been looking around for hours and I can't seem to find any way to do this. Has anyone tried this yet?</p> <p>Any help is greatly appreciated.</p> <p>Thanks</p>
25,480,722
6
1
null
2014-08-25 06:16:37.287 UTC
2
2020-09-29 21:10:53.413 UTC
null
null
null
null
177,962
null
1
32
generics|types|swift|introspection
18,874
<p>A pure swift way to achieve that is not possible.</p> <p>A possible workaround is:</p> <pre><code>class MyClass&lt;T: AnyObject&gt; { func genericName() -&gt; String { let fullName: String = NSStringFromClass(T.self) let range = fullName.rangeOfString(".", options: .BackwardsSearch) if let range = range { return fullName.substringFromIndex(range.endIndex) } else { return fullName } } } </code></pre> <p>The limitations relies on the fact that it works with classes only.</p> <p>If this is the generic type:</p> <pre><code>class TestClass {} </code></pre> <p><code>NSStringFromClass()</code> returns the full name (including namespace):</p> <pre><code>// Prints something like "__lldb_expr_186.TestClass" in playground NSStringFromClass(TestClass.self) </code></pre> <p>That's why the func searches for the last occurrence of the <code>.</code> character.</p> <p>Tested as follows:</p> <pre><code>var x = MyClass&lt;TestClass&gt;() x.genericName() // Prints "TestClass" </code></pre> <p><strong>UPDATE Swift 3.0</strong></p> <pre><code>func genericName() -&gt; String { let fullName: String = NSStringFromClass(T.self) let range = fullName.range(of: ".") if let range = range { return fullName.substring(from: range.upperBound) } return fullName } </code></pre>
20,834,002
Building dynamic URL using 'a href'
<p>I am using spring-3.2 version.</p> <pre><code>@RequestMapping("/company={companyId}/branch={branchId}/employee={employeeId}/info") </code></pre> <p>The requestmapping is used to map a URL, so in this case when ever a URL is called using</p> <pre><code>&lt;a href="company=1/branch=1/employee=1/info" &gt; employee info &lt;/a&gt; </code></pre> <p>the method is called in the controller with the exact @RequestMapping annotation, now I want to create the "a href" tag dynamically and want to create companyId,branchId,or employeeId dynamically.</p>
20,834,652
3
2
null
2013-12-30 05:43:56.617 UTC
2
2022-01-13 01:19:35.253 UTC
2013-12-30 05:47:50.897 UTC
null
438,154
null
1,147,361
null
1
3
jquery|html|spring|dynamic-url
52,486
<p>You could of course build the string pointing to the respective URL dynamically. </p> <p>A first option would be using a javascript function. However, even this function has to take the IDs from somewhere. In my example, I suppose that there are javascript variables which already contain the right IDs.</p> <pre><code>function createDynamicURL() { //The variable to be returned var URL; //The variables containing the respective IDs var companyID=... var branchID=... var employeeID=... //Forming the variable to return URL+="company="; URL+=companyID; URL+="/branch="; URL+=branchID; URL+="/employee="; URL+=employeeID; URL+="/info"; return URL; } </code></pre> <p>Then your html would be like:</p> <pre><code>&lt;a href="javascript:window.location=createDynamicURL();" &gt; employee info &lt;/a&gt; </code></pre> <p>Another, more elegant solution would be to use the onClick event:</p> <pre><code>&lt;a href="#" onclick="RedirectURL();return false;" &gt; employee info &lt;/a&gt; </code></pre> <p>with the function</p> <pre><code>function RedirectURL() { window.location= createDynamicURL(); } </code></pre> <p>Hope I helped!</p>
4,533,816
Gap above NSMenuItem custom view
<p>I am using the <code>setView:</code> method on an <code>NSMenuItem</code> to set a custom view. In this custom view there is an image which takes the whole of the view. The <code>NSMenuItem</code> with this custom view is the first in the menu but the problem is it doesn't sit flush with the top of the menu, there is a big gap as you can see here:</p> <p><img src="https://i.stack.imgur.com/jIWQD.png" alt="alt text"></p> <p>Why is this happening and how can I stop it?</p> <hr> <p><strong>EDIT</strong></p> <p>I am using this code now but I am getting <code>EXC_BAD_ACCESS</code> on the line <code>InstallControlEventHandler</code>. </p> <pre><code>-(void)applicationDidFinishLaunching:(NSNotification *)aNotification { HIViewRef contentView; MenuRef menuRef = [statusMenu carbonMenuRef]; HIMenuGetContentView(menuRef, kThemeMenuTypePullDown, &amp;contentView); EventTypeSpec hsEventSpec[1] = { { kEventClassMenu, kEventMenuCreateFrameView } }; InstallControlEventHandler(contentView, NewEventHandlerUPP((EventHandlerProcPtr)hsMenuCreationEventHandler), GetEventTypeCount(hsEventSpec), hsEventSpec, NULL, NULL); // Get EXC_BAD_ACCESS here. } static OSStatus hsMenuContentEventHandler( EventHandlerCallRef caller, EventRef event, void* refcon ) { OSStatus err; check( GetEventClass( event ) == kEventClassControl ); check( GetEventKind( event ) == kEventControlGetFrameMetrics ); err = CallNextEventHandler( caller, event ); if ( err == noErr ) { HIViewFrameMetrics metrics; verify_noerr( GetEventParameter( event, kEventParamControlFrameMetrics, typeControlFrameMetrics, NULL, sizeof( metrics ), NULL, &amp;metrics ) ); metrics.top = 0; verify_noerr( SetEventParameter( event, kEventParamControlFrameMetrics, typeControlFrameMetrics, sizeof( metrics ), &amp;metrics ) ); } return err; } static OSStatus hsMenuCreationEventHandler( EventHandlerCallRef caller, EventRef event, void* refcon ) { OSStatus err = eventNotHandledErr; if ( GetEventKind( event ) == kEventMenuCreateFrameView) { err = CallNextEventHandler( caller, event ); if ( err == noErr ) { static const EventTypeSpec kContentEvents[] = { { kEventClassControl, kEventControlGetFrameMetrics } }; HIViewRef frame; HIViewRef content; verify_noerr( GetEventParameter( event, kEventParamMenuFrameView, typeControlRef, NULL, sizeof( frame ), NULL, &amp;frame ) ); verify_noerr( HIViewFindByID( frame, kHIViewWindowContentID, &amp;content ) ); InstallControlEventHandler( content, hsMenuContentEventHandler, GetEventTypeCount( kContentEvents ), kContentEvents, 0, NULL ); } } return err; } </code></pre> <p>Also note the line <code>metrics.top = 0</code> this is the line which should remove the gap at the top. However I cannot get it work that far. Does anyone know why I would be recieving an <code>EXC_BAD_ACCESS</code> there. I have already created and allocated <code>statusMenu</code> so surely it should work?</p>
5,214,165
1
10
null
2010-12-26 12:34:25.147 UTC
13
2011-03-07 22:25:12.213 UTC
2010-12-27 08:23:55.883 UTC
null
92,714
null
92,714
null
1
19
objective-c|cocoa|macos|nsmenu|nsmenuitem
4,260
<p>Your post is tagged "Objective-C" and "Cocoa", although your sample code is C and Carbon. I assume you'd prefer a Cocoa solution?</p> <p>It's actually pretty simple in Cocoa. The only trick is learning how to draw outside the lines. :-)</p> <pre><code>@interface FullMenuItemView : NSView @end @implementation FullMenuItemView - (void) drawRect:(NSRect)dirtyRect { NSRect fullBounds = [self bounds]; fullBounds.size.height += 4; [[NSBezierPath bezierPathWithRect:fullBounds] setClip]; // Then do your drawing, for example... [[NSColor blueColor] set]; NSRectFill( fullBounds ); } @end </code></pre> <p>Use it like this:</p> <pre><code>CGFloat menuItemHeight = 32; NSRect viewRect = NSMakeRect(0, 0, /* width autoresizes */ 1, menuItemHeight); NSView *menuItemView = [[[FullMenuItemView alloc] initWithFrame:viewRect] autorelease]; menuItemView.autoresizingMask = NSViewWidthSizable; yourMenuItem.view = menuItemView; </code></pre>
20,000,560
Android Layout: width half of parent
<p>I have a very simple layout that I can't make it looks like I want. It's a LinearLayout with a button and a Switch. I want them to show one above the other, but I want their width to be the half of the parent layout.</p> <pre><code>|--LinearLayout---------| | | | ----------- | || Switch | | | ----------- | | ----------- | || button | | | ----------- | ------------------------ </code></pre> <p>I've been looking at other similar answer in SO but I couldn't find a solution that works for me. This is what I've tried so far:</p> <pre><code> &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:weightSum="2" &gt; &lt;Switch android:id="@+id/remember_me_switch" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:hint="@string/remember" /&gt; &lt;Button android:id="@+id/share_button" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:onClick="loginOnclick" android:text="@string/login_button_text" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>With this, the button and the switch take all the space of the parent instead of take only the half. I've tried with <code>android:layout_width = 0dp</code> in the children but it makes they disappear.</p> <p>Any help, please?</p>
20,000,701
6
1
null
2013-11-15 11:56:39.973 UTC
11
2021-06-03 11:53:36.623 UTC
null
null
null
null
1,909,783
null
1
47
android|android-layout
91,053
<p>One possible way is to have a master horizontal LinearLayout that splits the width to 2, and inside it have the vertical layout</p> <pre><code> &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" &gt; &lt;LinearLayout android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight="1" android:orientation="vertical" &gt; &lt;Switch android:id="@+id/remember_me_switch" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/remember" /&gt; &lt;Button android:id="@+id/share_button" android:layout_width="match_parent" android:layout_height="match_parent" android:onClick="loginOnclick" android:text="@string/login_button_text" /&gt; &lt;/LinearLayout&gt; &lt;!-- Right side spacer --&gt; &lt;View android:layout_width="0dp" android:layout_height="1dp" android:layout_weight="1" /&gt; &lt;/LinearLayout&gt; </code></pre>
7,280,716
PHP - Break after return?
<p>do I need to use break here or will it stop looping and just return once?</p> <pre><code>for($i = 0; $i &lt; 5; $i ++) { if($var[$i] === '') return false; // break; } </code></pre> <p>Thank you!</p>
7,280,731
3
0
null
2011-09-02 08:05:25.553 UTC
1
2021-10-21 11:44:56.073 UTC
null
null
null
null
890,144
null
1
29
php|for-loop|return|break
33,404
<p>It will run just once, stop looping, and exit from the function/method.</p> <p>It could be argued though that this is bad style. It is very easy to overlook that <code>return</code> later, which is bad for debugging and maintenance.</p> <p>Using <code>break</code> might be cleaner:</p> <pre><code>for($i = 0; $i &lt; 5; $i ++) { if($var[$i] === '') { set_some_condition; break; } } if (some_condition) return; </code></pre>
7,239,192
How to automatically close NERDTree after a file has been opened?
<p>The file is opened with the 'return' key on the current tab or with the 't' key to open it on a new VIM tab.</p>
7,239,411
4
0
null
2011-08-30 05:53:04.797 UTC
4
2021-02-18 00:34:44.427 UTC
null
null
null
null
418,831
null
1
37
vim|nerdtree
11,208
<p>Try <code>:help nerdtreequitonopen</code>.</p>
7,259,065
In Javascript, is it OK to put the ternary operator's `?` on then next line?
<p>I really like aligning the ? and the : of my ternary operator when they don't fit on a line, like this:</p> <pre><code>var myVar = (condition ? ifTrue : ifFalse ); </code></pre> <p>However, <a href="http://jshint.com/">JSHint</a> complains with:</p> <blockquote> <p>Bad line breaking before '?'</p> </blockquote> <p>Why would JSHint have this warning? Is there any nastyness (like semicolon insertion, etc) it is protecting me against or can I safely change my JSHINT configuration to ignore it?</p>
7,259,126
4
0
null
2011-08-31 15:05:24.903 UTC
8
2020-02-12 17:30:03.297 UTC
null
null
null
null
90,511
null
1
39
javascript|jshint
23,727
<p>This works and is certainly valid. It's especially useful in more complicated use cases, like nested ones.</p> <pre><code>var a = test1 ? b : test2 ? c : d; </code></pre>
7,417,426
Why are annotations under Android such a performance issue (slow)?
<p>I'm the lead author of <a href="http://ormlite.com/" rel="nofollow noreferrer">ORMLite</a> which uses Java annotations on classes to build database schemas. A big startup performance problem for our package turns out to be the calling of annotation methods under Android 1.6. I see the same behavior up through 3.0.</p> <p>We are seeing that the following simple annotation code is <em>incredibly</em> GC intensive and a real performance problem. 1000 calls to an annotation method takes almost a second on a fast Android device. The same code running on my Macbook Pro can do 28 million (sic) calls in the same time. We have an annotation that has 25 methods in it and we'd like to do more than 50 of these a second.</p> <p>Does anyone know why this is happening and if there is any work around? There are certainly things that ORMLite can do in terms of caching this information but is there anything that we can do to "fix" annotations under Android? Thanks.</p> <pre><code>public void testAndroidAnnotations() throws Exception { Field field = Foo.class.getDeclaredField("field"); MyAnnotation myAnnotation = field.getAnnotation(MyAnnotation.class); long before = System.currentTimeMillis(); for (int i = 0; i &lt; 1000; i++) myAnnotation.foo(); Log.i("test", "in " + (System.currentTimeMillis() - before) + "ms"); } @Target(FIELD) @Retention(RUNTIME) private static @interface MyAnnotation { String foo(); } private static class Foo { @MyAnnotation(foo = "bar") String field; } </code></pre> <p>This results in the following log output:</p> <pre><code>I/TestRunner( 895): started: testAndroidAnnotations D/dalvikvm( 895): GC freed 6567 objects / 476320 bytes in 85ms D/dalvikvm( 895): GC freed 8951 objects / 599944 bytes in 71ms D/dalvikvm( 895): GC freed 7721 objects / 524576 bytes in 68ms D/dalvikvm( 895): GC freed 7709 objects / 523448 bytes in 73ms I/test ( 895): in 854ms </code></pre> <p><strong>EDIT:</strong></p> <p>After @candrews pointed me in the right direction, I did some poking around the code. The performance problem looks to be caused by some terrible, gross code in <code>Method.equals()</code>. It is calling the <code>toString()</code> of both methods and then comparing them. Each <code>toString()</code> use <code>StringBuilder</code> with a bunch of append methods without a good initializing size. Doing the <code>.equals</code> by comparing fields would be significantly faster.</p> <p><strong>EDIT:</strong></p> <p>An interesting reflection performance improvement was given to me. We are now using reflection to peek inside the <code>AnnotationFactory</code> class to read the list of fields directly. This makes the reflection class 20 <em>times</em> faster for us since it bypasses the invoke which is using the <code>method.equals()</code> call. It is not a generic solution but here's the Java code from <a href="http://ormlite.svn.sourceforge.net/viewvc/ormlite/ormlite-android/trunk/src/main/java/com/j256/ormlite/android/DatabaseTableConfigUtil.java?view=markup" rel="nofollow noreferrer">ORMLite SVN repository</a>. For a generic solution, see <a href="https://stackoverflow.com/a/18066332/179850">yanchenko's answer below</a>.</p>
7,418,025
4
3
null
2011-09-14 13:49:50.987 UTC
33
2016-08-31 15:47:28.95 UTC
2017-05-23 12:09:20.68 UTC
null
-1
null
179,850
null
1
50
java|android|performance|garbage-collection|annotations
12,449
<p>Google has acknowledged the issue and fixed it "post-Honeycomb" </p> <blockquote> <p><a href="https://code.google.com/p/android/issues/detail?id=7811" rel="noreferrer">https://code.google.com/p/android/issues/detail?id=7811</a></p> </blockquote> <p>So at least they know about it and have supposedly fixed it for some future version.</p>
24,065,801
Exponentiation operator in Swift
<p>I don't see an exponentiation operator defined in the base arithmetic operators in the Swift language reference. </p> <p>Is there really no predefined integer or float exponentiation operator in the language?</p>
24,065,980
10
1
null
2014-06-05 16:46:44.857 UTC
9
2022-05-25 02:48:56.673 UTC
2017-01-13 10:43:59.53 UTC
null
2,227,743
null
2,708,519
null
1
95
swift|exponentiation
74,641
<p>There isn't an operator but you can use the pow function like this:</p> <pre><code>return pow(num, power) </code></pre> <p>If you want to, you could also make an operator call the pow function like this:</p> <pre><code>infix operator ** { associativity left precedence 170 } func ** (num: Double, power: Double) -&gt; Double{ return pow(num, power) } 2.0**2.0 //4.0 </code></pre>
66,996,319
The "correct" way to create a .NET Core console app without background services
<p>I'm building a simple .NET Core console application that will read in basic options from the command line, then execute and terminate without user interaction. I'd like to take advantage of DI, so that lead me to using the .NET Core generic host.</p> <p>All of the examples I've found that build a console app create a class that either implements IHostedService or extends BackgroundService. That class then gets added to the service container via AddHostedService and starts the application's work via StartAsync or ExecuteAsync. However, it seems that in all of these examples, they are implemementing a background service or some other application that runs in a loop or waits for requests until it gets shut down by the OS or receives some request to terminate. What if I just want an app that starts, does its thing, then exits? For example:</p> <p>Program.cs:</p> <pre><code>namespace MyApp { using System; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; public static class Program { public static async Task Main(string[] args) { await CreateHostBuilder(args).RunConsoleAsync(); } private static IHostBuilder CreateHostBuilder(string[] args) =&gt; Host.CreateDefaultBuilder(args) .UseConsoleLifetime() .ConfigureLogging(builder =&gt; builder.SetMinimumLevel(LogLevel.Warning)) .ConfigureServices((hostContext, services) =&gt; { services.Configure&lt;MyServiceOptions&gt;(hostContext.Configuration); services.AddHostedService&lt;MyService&gt;(); services.AddSingleton(Console.Out); }); } } </code></pre> <p>MyServiceOptions.cs:</p> <pre><code>namespace MyApp { public class MyServiceOptions { public int OpCode { get; set; } public int Operand { get; set; } } } </code></pre> <p>MyService.cs:</p> <pre><code>namespace MyApp { using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; public class MyService : IHostedService { private readonly MyServiceOptions _options; private readonly TextWriter _outputWriter; public MyService(TextWriter outputWriter, IOptions&lt;MyServiceOptions&gt; options) { _options = options.Value; _outputWriter = outputWriter; } public async Task StartAsync(CancellationToken cancellationToken) { _outputWriter.WriteLine(&quot;Starting work&quot;); DoOperation(_options.OpCode, _options.Operand); _outputWriter.WriteLine(&quot;Work complete&quot;); } public async Task StopAsync(CancellationToken cancellationToken) { _outputWriter.WriteLine(&quot;StopAsync&quot;); } protected void DoOperation(int opCode, int operand) { _outputWriter.WriteLine(&quot;Doing {0} to {1}...&quot;, opCode, operand); // Do work that might take awhile } } } </code></pre> <p>This code compiles and runs just fine, producing the following output:</p> <pre><code>Starting work Doing 1 to 2... Work complete </code></pre> <p>However, after that, the application will just sit there waiting until I press Ctrl+C. I know I could force the application to shutdown after the work is complete, but at this point, I feel like I'm not using IHostedService correctly. It seems as though it's designed for recurring background processes, and not simple console applications like this. However, in an actual application where DoOperation might take 20-30 minutes, I would like to take advantage of the StopAsync method to do cleanup before terminating. I also know I could create the service container myself and all that, but the .NET Core generic host already does a lot of stuff I would want to do anyway. It <em>seems</em> to be the right way to write console applications, but without adding a hosted service that kicks off the actual work, how do I get the app to actually <em>do</em> anything?</p>
66,996,436
2
2
null
2021-04-08 01:53:08.41 UTC
12
2021-04-08 13:10:44.73 UTC
null
null
null
null
2,820,102
null
1
22
c#|.net-core|console-application
6,166
<p>Instead of a hosted service, I would recommend the following;</p> <pre class="lang-cs prettyprint-override"><code>using (var host = CreateHostBuilder(args).Build()) { await host.StartAsync(); var lifetime = host.Services.GetRequiredService&lt;IHostApplicationLifetime&gt;(); // do work here / get your work service ... lifetime.StopApplication(); await host.WaitForShutdownAsync(); } </code></pre>
21,537,469
How to make LEFT JOIN in Lambda LINQ expressions
<p>How to make this expression as LEFT JOIN</p> <pre><code>var query = order.Items.Join(productNonCriticalityList, i =&gt; i.ProductID, p =&gt; p.ProductID, (i, p) =&gt; i); </code></pre>
21,537,737
2
2
null
2014-02-03 20:50:15.883 UTC
4
2017-05-30 12:50:28.903 UTC
null
null
null
null
656,606
null
1
17
c#|linq|entity-framework
45,731
<p>And this is the more complicated way using lambda expressions to write it:</p> <pre><code>order.Items .GroupJoin ( productNonCriticalityList, i =&gt; i.ProductID, p =&gt; p.ProductID, (i, g) =&gt; new { i = i, g = g } ) .SelectMany ( temp =&gt; temp.g.DefaultIfEmpty(), (temp, p) =&gt; new { i = temp.i, p = p } ) </code></pre>
2,034,059
How to read lines from stdin (*in*) in clojure
<p>I am writing my first clojure program, and want to read lines from stdin.</p> <p>When I try this:</p> <pre><code>(doall (map #(println %) (line-seq *in*))) </code></pre> <p>I get this exception:</p> <pre><code>Exception in thread "main" java.lang.ClassCastException: clojure.lang.LineNumberingPushbackReader cannot be cast to java.io.BufferedReader (test.clj:0) </code></pre> <p>I get the same results in version 1.0 and 1.1</p> <p>So how do I convert <code>*in*</code> into a seq I can iterate over? I would have thought that this is common enough that <code>*in*</code> itself would be iterable, but that does not work either - if I try to use it directly I get:</p> <pre><code>java.lang.IllegalArgumentException: Don't know how to create ISeq from: clojure.lang.LineNumberingPushbackReader (NO_SOURCE_FILE:0) </code></pre> <p>Also, are there any examples of doing general file handling in clojure? </p>
2,034,175
4
1
null
2010-01-09 16:47:03.71 UTC
12
2018-03-05 14:53:40.52 UTC
null
null
null
null
206,417
null
1
42
clojure|stdin
18,220
<p>Try wrapping <a href="https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/*in*" rel="noreferrer"><code>*in*</code></a> in a <code>java.io.BufferedReader</code>. And also use <code>doseq</code> instead of <code>doall</code>, as devstopfix pointed out:</p> <pre><code>(doseq [ln (line-seq (java.io.BufferedReader. *in*))] (println ln)) </code></pre> <p>Note that <a href="https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/line-seq" rel="noreferrer"><code>line-seq</code></a> is documented to require a <a href="http://java.sun.com/javase/7/docs/api/java/io/BufferedReader.html" rel="noreferrer"><code>BufferedReader</code></a> as its source.</p>
2,042,470
Can I copy a Git working copy onto another machine?
<p>I am in the process of creating a Git working copy from our SVN server with 'git svn clone'. But this takes quite some time (we have > 20.000 revs and almost 10.000 files). I have some other machines (for other developers) that I would like to setup the same way. Will it be possible to copy the resulting files from the first machine onto others, so as to spend less time?</p> <p>In other words, is there anything in a Git working copy that ties it to the machine it was created on?</p> <p>Thanks.</p>
2,042,483
4
1
null
2010-01-11 14:43:36.103 UTC
9
2021-06-06 07:13:16.36 UTC
null
null
null
null
4,177
null
1
42
git|git-svn
27,108
<p>You can copy it, everything is inside the .git folder and is not dependant on anything else.</p>
26,112,233
How Can I Hide Kendo UI Grid Columns using JavaScript, React, Angular, Vue or ASP.NET MVC
<p>I'm working on a HTML5 and JavaScript website.</p> <p>Is it possible to have a hidden column in Kendo UI Grid and access the value using JQuery?</p>
26,112,267
2
1
null
2014-09-30 03:18:51.503 UTC
9
2018-06-01 03:45:14.627 UTC
2018-06-01 03:45:14.627 UTC
null
2,450,507
null
1,076,698
null
1
42
javascript|c#|.net|kendo-ui|kendo-grid
85,627
<h1>Using JavaScript</h1> <p>See the <a href="https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/hidecolumn" rel="noreferrer">Kendo UI API reference</a>.</p> <p><strong>Hide a column during grid definition</strong></p> <p>You can add <code>hidden: true</code>:</p> <pre><code>$("#gridName").kendoGrid({ columns: [ { hidden: true, field: "id" }, { field: "name" } ], dataSource: [ { id: 1, name: "Jane Doe" }, { id: 2, name: "John Doe" } ] }); </code></pre> <p><strong>Hide a column by css selector</strong></p> <pre><code>$("#gridName").find("table th").eq(1).hide(); </code></pre> <p><strong>Hide a column by column index</strong></p> <pre><code>var grid = $("#gridName").data("kendoGrid"); grid.hideColumn(1); </code></pre> <p><strong>Hide a column by column name</strong></p> <pre><code>var grid = $("#gridName").data("kendoGrid"); grid.hideColumn("Name"); </code></pre> <p><strong>Hide a column by column object reference</strong></p> <pre><code>var grid = $("#gridName").data("kendoGrid"); grid.hideColumn(grid.columns[0].columns[1]); </code></pre> <h1>Using React</h1> <p>See the <a href="https://www.telerik.com/kendo-react-ui/components/grid/" rel="noreferrer">Kendo UI for React API reference</a></p> <p><strong>Hide a column during grid definition</strong></p> <p>You can set <code>show: false</code>:</p> <pre><code>class App extends React.Component { columns = [ { title: 'Product Id', field: 'ProductID', show: false }, { title: 'Product Name', field: 'ProductName', show: true }, { title: 'Unit Price', field: 'UnitPrice', show: true } ] constructor() { super(); this.state = { columns: this.columns, show:false }; } render() { return ( &lt;div&gt; &lt;Grid data={products} &gt; {this.state.columns.map((column, idx) =&gt; column.show &amp;&amp; (&lt;Column key={idx} field={column.field} title={column.title} /&gt;) )} &lt;/Grid&gt; &lt;/div&gt; ); } } </code></pre> <h1>Using Angular</h1> <p>See the <a href="https://www.telerik.com/kendo-angular-ui/components/grid/api/ColumnComponent/#toc-hidden" rel="noreferrer">Kendo UI for Angular API reference</a></p> <p><strong>Hide a column during grid definition</strong></p> <p>You can add <code>[hidden]="true"</code></p> <pre><code>@Component({ selector: 'my-app', template: ` &lt;kendo-grid [data]="gridData" [scrollable]="scrollable" style="height: 200px"&gt; &lt;kendo-grid-column [hidden]="true" field="ID" width="120"&gt; &lt;/kendo-grid-column&gt; &lt;kendo-grid-column field="ProductName" title="Product Name" width="200"&gt; &lt;/kendo-grid-column&gt; &lt;kendo-grid-column field="UnitPrice" title="Unit Price" width="230"&gt; &lt;/kendo-grid-column&gt; &lt;/kendo-grid&gt; ` }) </code></pre> <p><strong>Programmatically hide a column</strong></p> <pre><code>@Component({ selector: 'my-app', template: ` &lt;div class="example-config"&gt; &lt;button (click)="restoreColumns()" class="k-button"&gt;Restore hidden columns&lt;/button&gt; &lt;/div&gt; &lt;kendo-grid [data]="gridData" style="height:400px"&gt; &lt;ng-template ngFor [ngForOf]="columns" let-column&gt; &lt;kendo-grid-column field="{{column}}" [hidden]="hiddenColumns.indexOf(column) &gt; -1" &gt; &lt;ng-template kendoGridHeaderTemplate let-dataItem&gt; {{dataItem.field}} &lt;button (click)="hideColumn(dataItem.field)" class="k-button k-primary" style="float: right;"&gt; Hide &lt;/button&gt; &lt;/ng-template&gt; &lt;/kendo-grid-column&gt; &lt;/ng-template&gt; &lt;/kendo-grid&gt; ` }) export class AppComponent { public gridData: any[] = sampleCustomers; public columns: string[] = [ 'CompanyName', 'ContactName', 'ContactTitle' ]; public hiddenColumns: string[] = []; public restoreColumns(): void { this.hiddenColumns = []; } public hideColumn(field: string): void { this.hiddenColumns.push(field); } } </code></pre> <h1>Using Vue</h1> <p>See the <a href="https://www.telerik.com/kendo-vue-ui/components/grid/" rel="noreferrer">Kendo UI for Vue API reference</a></p> <p><strong>Hide a column during grid definition</strong></p> <p>You can add <code>:hidden="true"</code></p> <pre><code>&lt;kendo-grid :height="600" :data-source-ref="'datasource1'" :pageable='true'&gt; &lt;kendo-grid-column field="ProductID" :hidden="true"&gt;&lt;/kendo-grid-column&gt; &lt;kendo-grid-column field="ProductName"&gt;&lt;/kendo-grid-column&gt; &lt;kendo-grid-column field="UnitPrice" title="Unit Price" :width="120" :format="'{0:c}'"&gt;&lt;/kendo-grid-column&gt; &lt;kendo-grid-column field="UnitsInStock" title="Units In Stock" :width="120"&gt;&lt;/kendo-grid-column&gt; &lt;/kendo-grid&gt; </code></pre> <h1>Using ASP.NET MVC</h1> <p>See the <a href="http://docs.telerik.com/aspnet-mvc/api/Kendo.Mvc.UI.Fluent/GridColumnBuilderBase#methods-Hidden" rel="noreferrer">Kendo MVC API reference</a></p> <p><strong>Hide a column during grid definition</strong></p> <pre><code>@(Html.Kendo().Grid&lt;Something&gt;() .Name("GridName") .Columns(columns =&gt; { columns.Bound(m =&gt; m.Id).Hidden() columns.Bound(m =&gt; m.Name) }) ) </code></pre> <h1>Using PHP</h1> <p>See the <a href="http://docs.telerik.com/kendo-ui/api/php/Kendo/UI/GridColumn#hidden" rel="noreferrer">Kendo UI for PHP API reference</a></p> <p><strong>Hide a column during grid definition</strong></p> <pre><code>&lt;?php $column = new \Kendo\UI\GridColumn(); $column-&gt;hidden(true); ?&gt; </code></pre>
7,266,298
Android: sound API (deterministic, low latency)
<p>I'm reviewing all kinds of Android sound API and I'd like to know which one I should use. My goal is to get low latency audio or, at least, deterministic behavior regarding delay of playback.</p> <p>We've had a lot of problems and it seems that Android sound API is crap, so I'm exploring possibilities.</p> <p>The problem we have is that there is significant delay between <code>sound_out.write(sound_samples);</code> and actual sound played from the speakers. Usually it is around 300 ms. The problem is that on all devices it's different; some don't have that problem, but most are crippled (however, CS call has zero latency). The biggest issue with this ridiculous delay is that on some devices this delay appears to be some random value (i.e. it's not always 300ms).</p> <p>I'm reading about OpenSL ES and I'd like to know if anybody had experience with it, or it's the same shit but wrapped in different package?</p> <p>I prefer to have native access, but I don't mind Java layer indirection as long as I can get deterministic behavior: either the delay has to be constant (for a given device), or I'd like to get access to current playback position instead of guessing it with a error range of ±300 ms...</p> <p><b>EDIT:</b><br/>1.5 years later I tried multiple android phones to see how I can get best possible latency for a real time voice communication. Using specialized tools I measured the delay of waveout path. Best results were over 100 ms, most phones were in 180ms range. Anybody have ideas?</p>
12,309,643
5
6
null
2011-09-01 05:03:31.393 UTC
18
2022-04-15 06:10:38.873 UTC
2013-02-28 21:23:30.08 UTC
null
468,725
null
468,725
null
1
35
android|android-ndk
18,749
<p>SoundPool is the lowest-latency interface on most devices, because the pool is stored in the audio process. All of the other audio paths require inter-process communication. OpenSL is the best choice if SoundPool doesn't meet your needs.</p> <p>Why OpenSL? AudioTrack and OpenSL have similar latencies, with one important difference: AudioTrack buffer callbacks are serviced in Dalvik, while OpenSL callbacks are serviced in native threads. The current implementation of Dalvik isn't capable of servicing callbacks at extremely low latencies, because there is no way to suspend garbage collection during audio callbacks. This means that the minimum size for AudioTrack buffers has to be larger than the minimum size for OpenSL buffers to sustain glitch-free playback.</p> <p>On most Android releases this difference between AudioTrack and OpenSL made no difference at all. But with Jellybean, Android now has a low-latency audio path. The actual latency is still device dependent, but it can be considerably lower than previously. For instance, <a href="http://code.google.com/p/music-synthesizer-for-android/" rel="noreferrer">http://code.google.com/p/music-synthesizer-for-android/</a> uses 384-frame buffers on the Galaxy Nexus for a total output latency of under 30ms. This requires the audio thread to service buffers approximately once every 8ms, which was not feasible on previous Android releases. It is still not feasible in a Dalvik thread.</p> <p>This explanation assumes two things: first, that you are requesting the smallest possible buffers from OpenSL and doing your processing in the buffer callback rather than with a buffer queue. Second, that your device supports the low-latency path. On most current devices you will not see much difference between AudioTrack and OpenSL ES. But on devices that support Jellybean+ and low-latency audio, OpenSL ES will give you the lowest-latency path.</p>
7,291,120
Get unicode code point of a character using Python
<p>In Python API, is there a way to extract the unicode code point of a single character?</p> <p><strong>Edit:</strong> In case it matters, I'm using Python 2.7.</p>
7,291,170
5
7
null
2011-09-03 04:12:47.93 UTC
21
2020-08-11 21:06:03.77 UTC
2020-08-11 21:06:03.77 UTC
null
4,197,269
null
283,311
null
1
86
python|python-2.7|unicode|codepoint
78,390
<pre><code>&gt;&gt;&gt; ord(u"ć") 263 &gt;&gt;&gt; u"café"[2] u'f' &gt;&gt;&gt; u"café"[3] u'\xe9' &gt;&gt;&gt; for c in u"café": ... print repr(c), ord(c) ... u'c' 99 u'a' 97 u'f' 102 u'\xe9' 233 </code></pre>
7,182,485
CursorLoader usage without ContentProvider
<p>Android SDK documentation says that <code>startManagingCursor()</code> method is depracated:</p> <blockquote> <p>This method is deprecated. Use the new CursorLoader class with LoaderManager instead; this is also available on older platforms through the Android compatibility package. This method allows the activity to take care of managing the given Cursor's lifecycle for you based on the activity's lifecycle. That is, when the activity is stopped it will automatically call deactivate() on the given Cursor, and when it is later restarted it will call requery() for you. When the activity is destroyed, all managed Cursors will be closed automatically. If you are targeting HONEYCOMB or later, consider instead using LoaderManager instead, available via getLoaderManager()</p> </blockquote> <p>So I would like to use <code>CursorLoader</code>. But how can I use it with custom <code>CursorAdapter</code> and without <code>ContentProvider</code>, when I needs URI in constructor of <code>CursorLoader</code>?</p>
7,422,343
5
0
null
2011-08-24 21:26:27.793 UTC
101
2021-12-22 19:28:10.123 UTC
2021-12-22 19:28:10.123 UTC
null
4,294,399
null
539,284
null
1
107
android|android-contentprovider|android-cursorloader|android-loadermanager
47,115
<p>I wrote a <a href="https://gist.github.com/1217628" rel="noreferrer">simple CursorLoader</a> that does not need a content provider:</p> <pre><code>import android.content.Context; import android.database.Cursor; import android.support.v4.content.AsyncTaskLoader; /** * Used to write apps that run on platforms prior to Android 3.0. When running * on Android 3.0 or above, this implementation is still used; it does not try * to switch to the framework's implementation. See the framework SDK * documentation for a class overview. * * This was based on the CursorLoader class */ public abstract class SimpleCursorLoader extends AsyncTaskLoader&lt;Cursor&gt; { private Cursor mCursor; public SimpleCursorLoader(Context context) { super(context); } /* Runs on a worker thread */ @Override public abstract Cursor loadInBackground(); /* Runs on the UI thread */ @Override public void deliverResult(Cursor cursor) { if (isReset()) { // An async query came in while the loader is stopped if (cursor != null) { cursor.close(); } return; } Cursor oldCursor = mCursor; mCursor = cursor; if (isStarted()) { super.deliverResult(cursor); } if (oldCursor != null &amp;&amp; oldCursor != cursor &amp;&amp; !oldCursor.isClosed()) { oldCursor.close(); } } /** * Starts an asynchronous load of the contacts list data. When the result is ready the callbacks * will be called on the UI thread. If a previous load has been completed and is still valid * the result may be passed to the callbacks immediately. * &lt;p/&gt; * Must be called from the UI thread */ @Override protected void onStartLoading() { if (mCursor != null) { deliverResult(mCursor); } if (takeContentChanged() || mCursor == null) { forceLoad(); } } /** * Must be called from the UI thread */ @Override protected void onStopLoading() { // Attempt to cancel the current load task if possible. cancelLoad(); } @Override public void onCanceled(Cursor cursor) { if (cursor != null &amp;&amp; !cursor.isClosed()) { cursor.close(); } } @Override protected void onReset() { super.onReset(); // Ensure the loader is stopped onStopLoading(); if (mCursor != null &amp;&amp; !mCursor.isClosed()) { mCursor.close(); } mCursor = null; } } </code></pre> <p>It only needs the <code>AsyncTaskLoader</code> class. Either the one in Android 3.0 or higher, or the one that comes with the compatibility package.</p> <p>I also <a href="https://github.com/casidiablo/groundy/blob/d60a51760582b8a03ea9a06ea7ca938d3785ea15/library/src/main/java/com/telly/groundy/loader/ListLoader.java" rel="noreferrer">wrote a <code>ListLoader</code></a> which is compatible with the <code>LoadManager</code> and is used to retrieve a generic <code>java.util.List</code> collection.</p>
7,694,989
How to use a private method in Java
<p>I am given a class that has a private method say setCoors(int x, int y). The constructor of that class has the setCoors in it too. In a different class, I want to have a method setLocation which calls setCoors. Is this possible? </p> <p>New Question:</p> <p>If I am not allowed to set the method to public, is this possible?</p> <pre><code>public class Coordinate{ public Coordinate(int a, int b){ setCoors(a,b) } private void setCoords(int x, int y) } public class Location{ private Coordinate loc; public void setLocation(int a, int b) loc = new Coordinate(a,b) } </code></pre>
7,694,994
6
2
null
2011-10-08 05:25:21.437 UTC
null
2013-02-04 18:53:20.833 UTC
2013-02-04 18:53:20.833 UTC
null
1,288
null
253,425
null
1
5
java|methods|private-methods
39,802
<p>No, <code>private</code> means the method can only be called inside of the Class in which it is defined. You will probably want to have <code>setLocation</code> create a new instance of the class <code>setCoords</code> resides in, or change the visibility on <code>setCoords</code>.</p> <p><strong>EDIT:</strong> The code you have posted will work. Just be aware that any instance of the <code>Location</code> class will be bound to its own <code>Coordinate</code> object. If you create a new <code>Coordinate</code> object somewhere else in your code, you will be unable to modify its internal state. In other words, the line</p> <pre><code>Coordinate myCoord = new Coordinate(4, 5); </code></pre> <p>will create the object <code>myCoord</code> which will forever have the coordinates <code>4</code> and <code>5</code>.</p>
7,314,942
python imaplib to get gmail inbox subjects titles and sender name
<p>I'm using pythons imaplib to connect to my gmail account. I want to retrieve the top 15 messages (unread or read, it doesn't matter) and display just the subjects and sender name (or address) but don't know how to display the contents of the inbox.</p> <p>Here is my code so far (successful connection)</p> <pre><code>import imaplib mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login('[email protected]', 'somecrazypassword') mail.list() mail.select('inbox') #need to add some stuff in here mail.logout() </code></pre> <p>I believe this should be simple enough, I'm just not familiar enough with the commands for the imaplib library. Any help would be must appreciated...</p> <p><strong>UPDATE</strong> thanks to Julian I can iterate through each message and retrieve the entire contents with: </p> <pre><code>typ, data = mail.search(None, 'ALL') for num in data[0].split(): typ, data = mail.fetch(num, '(RFC822)') print 'Message %s\n%s\n' % (num, data[0][1]) mail.close() </code></pre> <p>but I'm wanting just the subject and the sender. Is there a imaplib command for these items or will I have to parse the entire contents of data[0][1] for the text: Subject, and Sender?</p> <p><strong>UPDATE</strong> OK, got the subject and sender part working but the iteration (1, 15) is done by desc order apparently showing me the oldest messages first. How can I change this? I tried doing this:</p> <pre><code>for i in range( len(data[0])-15, len(data[0]) ): print data </code></pre> <p>but that just gives me <code>None</code> for all 15 iterations... any ideas? I've also tried <code>mail.sort('REVERSE DATE', 'UTF-8', 'ALL')</code> but gmail doesnt support the .sort() function</p> <p><strong>UPDATE</strong> Figured out a way to do it: </p> <pre><code>#....^other code is the same as above except need to import email module mail.select('inbox') typ, data = mail.search(None, 'ALL') ids = data[0] id_list = ids.split() #get the most recent email id latest_email_id = int( id_list[-1] ) #iterate through 15 messages in decending order starting with latest_email_id #the '-1' dictates reverse looping order for i in range( latest_email_id, latest_email_id-15, -1 ): typ, data = mail.fetch( i, '(RFC822)' ) for response_part in data: if isinstance(response_part, tuple): msg = email.message_from_string(response_part[1]) varSubject = msg['subject'] varFrom = msg['from'] #remove the brackets around the sender email address varFrom = varFrom.replace('&lt;', '') varFrom = varFrom.replace('&gt;', '') #add ellipsis (...) if subject length is greater than 35 characters if len( varSubject ) &gt; 35: varSubject = varSubject[0:32] + '...' print '[' + varFrom.split()[-1] + '] ' + varSubject </code></pre> <p>this gives me the most recent 15 message subject and sender address in decending order as requested! Thanks to all who helped!</p>
7,316,295
6
3
null
2011-09-06 04:29:13.473 UTC
20
2021-04-22 12:26:56 UTC
2012-05-05 18:04:35.387 UTC
null
387,076
null
281,488
null
1
30
python|gmail|imaplib|email-headers
62,910
<pre><code> c.select('INBOX', readonly=True) for i in range(1, 30): typ, msg_data = c.fetch(str(i), '(RFC822)') for response_part in msg_data: if isinstance(response_part, tuple): msg = email.message_from_string(response_part[1]) for header in [ 'subject', 'to', 'from' ]: print '%-8s: %s' % (header.upper(), msg[header]) </code></pre> <p>This should give you an idea on how to retrieve the subject and from?</p>
7,682,277
Xcode 4.2 jumps to main.m every time after stopping simulator
<p>This is more of a general annoyance. Every time after stopping the simulator, Xcode jumps to main.m for some reason. On the left nav, it jumps to the Debug Navigator.</p> <p>Is there a way to fix this?</p> <p>It's annoying because I might be testing a certain line of code, and now each time, I need to make a couple of clicks just to go back to that code.</p> <p>This problem is not new, seems to get worse though. At the time of writing this, I was on the GM seed, but this problem persists in XCode 4.2 final. This was not a problem in previous versions of XCode.</p>
7,993,410
11
11
null
2011-10-07 01:40:19.74 UTC
23
2013-03-15 20:26:42.347 UTC
2011-11-02 21:42:59.827 UTC
null
241,232
null
58,505
null
1
66
ios|xcode
5,544
<p>When we start debug from xcode, the debugger sets itself up to monitor signals from OS. When we press stop button in XCode (or hit cmd + R - which first stops existing instance running and then try to start new one, somewhat equalant to we press manually stop first and then run) <strong>SIGKILL is sent to the debugger</strong>. </p> <p>Whenever the cause of interruption is from outside the app (in other words all cases where SIGKILL is sent, like stop button press) , debugger jumps to <code>main</code>, since <strong>main is the root of the app and the place where your app meets the OS</strong>. Debugger has no way to identify why this SIGKILL is issued (pressing stop button in xcode/ press cmd + R/ delete app from multitasking bar etc), but <strong>it treats SIGKILL as outside interrupt, and nothing related with your code</strong>. So it jumps to main. </p> <p>If the cause of interruption is from inside the app (like app crash/SIGABRT) debugger handles it and jumps to the place of crash, which we normally see.</p> <p>I do not consider this as an xcode bug, rather a normal way of handling SIGKILL. But if you want to stay at your code and do not want to jump to main you can do two things</p> <ol> <li><p>You can do as Gabe suggested. As BBonified said, it is like a band-aide, but I think it should work (personally I never tried that)</p></li> <li><p>Report a bug/request for a feature <a href="http://developer.apple.com/bugreporter/" rel="nofollow">here</a>. Let me tell you you are not the first one to do so. Already a bug has been reported. See <a href="https://devforums.apple.com/message/555098#555098" rel="nofollow">this</a> and <a href="https://devforums.apple.com/message/492920#492920" rel="nofollow">this</a>. But I don't have much hope of a positive action from Apple</p></li> </ol> <p>And I agree with you, it is sometimes annoying. Especially if you have experienced differently in previous XCode versions. But we can only take what they give here.</p>
7,377,876
CodeIgniter 500 Internal Server Error
<p>I downloaded a PHP script written using CodeIgniter. when I run it from the localhost, on going to the admin folder, it shows localhost again. Also when running from my web host, it shows a 500 Internal Server Error.</p> <p>I run the site from <a href="http://localhost/myproj">http://localhost/myproj</a> It works. Then when I try to go to the admin page which is at <a href="http://localhost/myproj/administrator">http://localhost/myproj/administrator</a>, it gives a 500 Internal Server Error.</p> <p>I read here that this might be due to a wrong code in the .htaccess file. This is my present .htaccess file</p> <p></p> <pre><code>RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)/$ $1 [L,R=301] RewriteCond %{REQUEST_URI} ^system.* RewriteRule ^(.*)$ /index.php/$1 [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php/$1 [L] </code></pre> <p></p> <p></p> <pre><code># Without mod_rewrite, route 404's to the front controller ErrorDocument 404 /index.php </code></pre> <p></p> <p>Please help me. I know it might be a very small problem, but I'm unable to find the error.</p>
7,395,299
12
0
null
2011-09-11 11:22:15.58 UTC
1
2021-08-23 15:12:46.22 UTC
null
null
null
null
939,100
null
1
13
php|.htaccess|codeigniter|internal-server-error
130,393
<p>The problem with 500 errors (with CodeIgniter), with different apache settings, it displays 500 error when there's an error with PHP configuration.</p> <p>Here's how it can trigger 500 error with CodeIgniter:</p> <ol> <li>Error in script (PHP misconfigurations, missing packages, etc...)</li> <li>PHP "Fatal Errors"</li> </ol> <p>Please check your apache error logs, there should be some interesting information in there.</p>
13,940,404
What's the simplest way to get a dump of all memcached keys into a file?
<p>This is from just a single memcached server with around 20M keys (no expiry) and around 2G of data.</p> <p>What's the easiest way to get a dump of all the key/value pairs into a flat file? I first looked at the java net.spy.memcached.MemcachedClient, but this client does not support getting all keys (I think). If I had a list of all keys (which I don't), I could easily use this client to get all of the values.</p> <p>I know I can get all keys using some telnet commands (e.g., telnet localhost 11211; stats items; stats cachedump ), but it's not clear to me how to automate this robustly.</p> <p>EDIT: Here's what I did to get this working on a toy memcached server on my machine. It seems to work but I only put two keys in memcached, so hopefully this method will scale ok:</p> <p>shell commands:</p> <pre><code>sudo yum install memcached sudo /etc/init.d/memcached restart # maybe unnecessary sudo yum install php sudo yum install php-pecl-memcache sudo service httpd reload </code></pre> <p>php script, based on <a href="http://100days.de/serendipity/archives/55-Dumping-MemcacheD-Content-Keys-with-PHP.html">this</a>:</p> <pre><code>&lt;?php $memcache = new Memcache(); $memcache-&gt;connect('127.0.0.1', 11211) or die ("Could not connect"); $list = array(); $allSlabs = $memcache-&gt;getExtendedStats('slabs'); $items = $memcache-&gt;getExtendedStats('items'); foreach($allSlabs as $server =&gt; $slabs) { foreach($slabs AS $slabId =&gt; $slabMeta) { if (!is_int($slabId)) { continue; } $cdump = $memcache-&gt;getExtendedStats('cachedump', (int) $slabId, 100000000); foreach($cdump AS $server =&gt; $entries) { if ($entries) { foreach($entries AS $eName =&gt; $eData) { print_r($eName); print_r(":"); $val = $memcache-&gt;get($eName); print_r($val); print_r("\n"); } } } } } ?&gt; </code></pre> <p>EDIT2: The above script does not seem to return all of the mappings. If I insert the line <code>count($entries)</code>, it only returns a little over 50k, even with the limit parameter set to 100M, but executing <code>stats items</code> from telnet shows over 5M entries. Does anyone know why this might be the case?</p> <p>EDIT3: This <a href="http://code.google.com/p/memcached/wiki/NewProgrammingFAQ">link</a> suggests that cachedump doesn't get all keys from memcached. I've hit a limit of around 50k keys that are returned either by cachedump, this PHP script, or a perl script similar to one in the link provided by Zach Bonham. Is there any way around this?</p>
13,941,700
5
2
null
2012-12-18 19:49:21.917 UTC
5
2019-03-13 14:37:40.253 UTC
2012-12-19 00:51:29.33 UTC
null
329,781
null
329,781
null
1
16
memcached
52,722
<p><em>disclaimer: I don't know what I"m doing, just sounded like an interesting problem.</em></p> <p>Did you see this article? <a href="https://lzone.de/blog/How-to%20Dump%20Keys%20from%20Memcache" rel="nofollow noreferrer">"How to Dump Keys from Memcache"</a> by Lars Windolf. </p> <p>From the article:</p> <blockquote> <p>Memcache itself provide the means to peak into the data. The protocol provides commands to peak into the data that is organized by slabs (categories of data of a given size range. There are some significant limitations though:</p> <ul> <li>You can only dump keys per slab class (keys with roughly the same content size)</li> <li>You can only dump one page per slab class (1MB of data)</li> <li>This is an unofficial feature that might be removed anytime.</li> </ul> </blockquote> <p>Effectively, it requires some knowledge of how memcache stores data in memory (which I don't). You need to find each 'slab', then you can dump the keys for that slab, and then ultimately, the values for those keys.</p> <p>There is a tools section in the article which uses various languages to dump at least the keys, but only the perl script dumps both keys and values. </p>
13,966,467
How to Avoid Lock wait timeout exceeded exception.?
<pre><code> java.sql.SQLException: Lock wait timeout exceeded; try restarting tra nsaction at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3558) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3490) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2648) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.ja va:2077) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java: 2228) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java: 208) at org.hibernate.loader.Loader.getResultSet(Loader.java:1812) at org.hibernate.loader.Loader.doQuery(Loader.java:697) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Lo ader.java:259) at org.hibernate.loader.Loader.loadEntity(Loader.java:1885) ... 131 more </code></pre> <p>I am getting repeated lock timeout exceeded exception while I update the records.</p> <p>I am using Java Struts 2.1 Hibernate configuration. DB Used is MYSQL.</p> <p>Anyone know how to solve it..??</p>
13,967,358
7
3
null
2012-12-20 06:25:15.483 UTC
7
2020-11-24 18:52:33.703 UTC
2012-12-20 06:31:19.73 UTC
null
1,065,180
null
1,844,148
null
1
26
java|mysql|hibernate
90,459
<p>Here are some suggestions:</p> <ol> <li>‘<strong>Lock wait timeout</strong>’ occurs typically when a transaction is waiting on row(s) of data to update which is already been locked by some other transaction. </li> <li>Most of the times, the problem lies on the database side. The possible causes may be a inappropriate table design, large amount of data, constraints etc. </li> <li>Please check out this <a href="https://stackoverflow.com/a/6005564/750040">elaborate answer</a> .</li> </ol>
13,959,218
Latitude/Longitude dataset for country borders
<p>I'm writing a program to display the expected lifetime of our product as it relates to average weather conditions in various locations across the globe and I'd like my map to reflect the latest country borders.</p> <p>Can anyone recommend somewhere to get a dataset of latitude/longitude points for the world's latest country borders?</p>
13,959,546
4
3
null
2012-12-19 18:58:05.613 UTC
10
2019-07-16 00:06:04.31 UTC
null
null
null
null
333,486
null
1
27
latitude-longitude
36,279
<p>You can get the world country borders for free from Natural Earth:</p> <p><a href="http://www.naturalearthdata.com/downloads/10m-cultural-vectors/" rel="noreferrer">Natural Earth</a></p> <p>Layer Admin 0 contains the country borders</p>
13,844,678
"Order By" using a parameter for the column name
<p>We would like to use a parameter in the "Order By" clause of a query or stored procedure created with the Visual Studio DataSet Designer.</p> <p>Example:</p> <pre><code> FROM TableName WHERE (Forename LIKE '%' + @SearchValue + '%') OR (Surname LIKE '%' + @SearchValue + '%') OR (@SearchValue = 'ALL') ORDER BY @OrderByColumn </code></pre> <p>This error is displayed:</p> <pre><code>Variables are only allowed when ordering by an expression referencing a column name. </code></pre>
13,846,257
1
8
null
2012-12-12 16:53:40.927 UTC
7
2021-01-15 21:22:00.45 UTC
2012-12-12 18:15:06.923 UTC
null
908,123
null
908,123
null
1
32
sql|sql-server|visual-studio|parameters|sql-order-by
62,559
<p>You should be able to do something like this:</p> <pre><code>SELECT * FROM TableName WHERE (Forename LIKE '%' + @SearchValue + '%') OR (Surname LIKE '%' + @SearchValue + '%') OR (@SearchValue = 'ALL') ORDER BY CASE @OrderByColumn WHEN 1 THEN Forename WHEN 2 THEN Surname END; </code></pre> <ul> <li>Assign 1 to <code>@OrderByColumn</code> to sort on <code>Forename</code>.</li> <li>Assign 2 to sort on <code>Surname</code>.</li> <li>Etc... you can expand this scheme to arbitrary number of columns.</li> </ul> <hr> <p>Be careful about performance though. These kinds of constructs may interfere with query optimizer's ability to find an optimal execution plan. For example, even if <code>Forename</code> is covered by index, query may still require the full sort instead of just traversing the index in order.</p> <p>If that is the case, and you can't live with the performance implications, it may be necessary to have a separate version of the query for each possible sort order, complicating things considerably client-side.</p>
14,177,225
Why does field declaration with duplicated nested type in generic class results in huge source code increase?
<p>Scenario is very rare, but quite simple: you define a generic class, then create a nested class which inherits from outer class and define a associative field (of self type) within nested. Code snippet is simpler, than description:</p> <pre><code>class Outer&lt;T&gt; { class Inner : Outer&lt;Inner&gt; { Inner field; } } </code></pre> <p>after decompilation of IL, C# code look like this:</p> <pre><code>internal class Outer&lt;T&gt; { private class Inner : Outer&lt;Outer&lt;T&gt;.Inner&gt; { private Outer&lt;Outer&lt;T&gt;.Inner&gt;.Inner field; } } </code></pre> <p>This seems to be fair enough, but when you change the type declaration of the field, things become trickier. So when I change the field declaration to</p> <pre><code>Inner.Inner field; </code></pre> <p>After decompilation this field will looks like this:</p> <pre><code>private Outer&lt;Outer&lt;Outer&lt;T&gt;.Inner&gt;.Inner&gt;.Inner field; </code></pre> <p>I understand, that class 'nestedness' and inheritance don't quite get along with each other, but <em>why do we observe such behavior? Is the</em> <code>Inner.Inner</code> <em>type declaration has changed the type at all? Are</em> <code>Inner.Inner</code> <em>and</em> <code>Inner</code> <em>types differ in some way in this context?</em></p> <h2>When things become very tricky</h2> <p>You can see the <a href="http://codepaste.net/6f63no" rel="noreferrer">decompiled source code</a> for the class below. It's really huge and has total length of 12159 symbols.</p> <pre><code>class X&lt;A, B, C&gt; { class Y : X&lt;Y, Y, Y&gt; { Y.Y.Y.Y.Y.Y y; } } </code></pre> <p>Finally, this class:</p> <pre><code>class X&lt;A, B, C, D, E&gt; { class Y : X&lt;Y, Y, Y, Y, Y&gt; { Y.Y.Y.Y.Y.Y.Y.Y.Y y; } } </code></pre> <p>results in <code>27.9 MB (29,302,272 bytes)</code> assembly and <code>Total build time: 00:43.619</code></p> <h2>Tools used</h2> <p>Compilation is done under C# 5 and C# 4 compilers. Decompilation is done by dotPeek. Build configurations: <code>Release</code> and <code>Debug</code></p>
14,178,014
3
5
null
2013-01-05 22:45:08.98 UTC
14
2013-01-06 05:29:29.583 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,283,124
null
1
41
c#|.net|c#-4.0|generics|nested
1,588
<p>The core of your question is why <code>Inner.Inner</code> is a different type than <code>Inner</code>. Once you understand that, your observations about compile time and generated IL code size follow easily.</p> <p>The first thing to note is that when you have this declaration</p> <pre><code>public class X&lt;T&gt; { public class Y { } } </code></pre> <p>There are infinitely many types associated with the name <code>Y</code>. There is one for each generic type argument <code>T</code>, so <code>X&lt;int&gt;.Y</code> is different than <code>X&lt;object&gt;.Y</code>, and, important for later, <code>X&lt;X&lt;T&gt;&gt;.Y</code> is a different type than <code>X&lt;T&gt;.Y</code> for all <code>T</code>'s. You can test this for various types <code>T</code>.</p> <p>The next thing to note is that in</p> <pre><code>public class A { public class B : A { } } </code></pre> <p>There are infinitely many ways to refer to nested type <code>B</code>. One is <code>A.B</code>, another is <code>A.B.B</code>, and so on. The statement <code>typeof(A.B) == typeof(A.B.B)</code> returns <code>true</code>.</p> <p>When you combine these two, the way you have done, something interesting happens. The type <code>Outer&lt;T&gt;.Inner</code> is not the same type as <code>Outer&lt;T&gt;.Inner.Inner</code>. <code>Outer&lt;T&gt;.Inner</code> is a subclass of <code>Outer&lt;Outer&lt;T&gt;.Inner&gt;</code> while <code>Outer&lt;T&gt;.Inner.Inner</code> is a subclass of <code>Outer&lt;Outer&lt;Outer&lt;T&gt;.Inner&gt;.Inner&gt;</code>, which we established before as being different from <code>Outer&lt;T&gt;.Inner</code>. So <code>Outer&lt;T&gt;.Inner.Inner</code> and <code>Outer&lt;T&gt;.Inner</code> are referring to different types.</p> <p>When generating IL, the compiler always uses fully qualified names for types. You have cleverly found a way to refer to types with names whose lengths that grow at exponential rates. That is why as you increase the generic arity of <code>Outer</code> or add additional levels <code>.Y</code> to the field <code>field</code> in <code>Inner</code> the output IL size and compile time grow so quickly.</p>
14,218,307
Select arrow style change
<p>I'm trying to replace the arrow of a select with a picture of my own. I'm including the select in a div with the same size, I set the background of the select as transparent and I'm including a picture(with the same size as the arrow) in the right top corner of the div as background. </p> <p>It only works in Chrome. </p> <p><img src="https://i.stack.imgur.com/o2JSU.png" alt="enter image description here"> </p> <p>How can I make it work in Firefox and IE9 where I'm getting this: </p> <p><img src="https://i.stack.imgur.com/EpxWl.png" alt="enter image description here"></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.styled-select { width: 100px; height: 17px; overflow: hidden; overflow: -moz-hidden-unscrollable; background: url(images/downarrow_blue.png) no-repeat right white; border: 2px double red; display: inline-block; position: relative; } .styled-select select { background: transparent; -webkit-appearance: none; width: 100px; font-size: 11px; border: 0; height: 17px; position: absolute; left: 0; top: 0; } body { background-color: #333333; color: #FFFFFF; } .block label { color: white; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;p/&gt; &lt;form action="/prepareUpdateCategoryList.do?forwardto=search"&gt; &lt;fieldset class="block" id="searchBlock"&gt; &lt;p&gt; &lt;label style="width:80px"&gt;Class&lt;/label&gt; &lt;div class="styled-select"&gt; &lt;select property="voucherCategoryClass"&gt; &lt;option value="0"&gt;Select &lt;/option&gt; &lt;option value="7382"&gt;steam &lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/p&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;/BODY&gt; &lt;/HTML&gt;</code></pre> </div> </div> </p>
14,218,448
19
0
null
2013-01-08 15:25:46.507 UTC
38
2022-04-20 19:55:00.747 UTC
2017-06-19 14:44:31.427 UTC
null
1,685,157
null
1,802,439
null
1
210
css|select
841,625
<p>Have you tried something like this:</p> <pre><code>.styled-select select { -moz-appearance:none; /* Firefox */ -webkit-appearance:none; /* Safari and Chrome */ appearance:none; } </code></pre> <p>Haven't tested, but should work.</p> <p><strong>EDIT</strong>: It looks like Firefox doesn't support this feature up until version 35 (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=649849" rel="noreferrer">read more here</a>)</p> <p>There is a workaround <a href="https://stackoverflow.com/questions/4142619/how-to-make-select-element-be-transparent-in-chrome/">here</a>, take a look at <code>jsfiddle</code> on that post.</p>
29,188,612
Arrows in matplotlib using mplot3d
<p>I am trying to use matplotlib to recreate the diagram on this page: <a href="http://books.google.co.uk/books?id=sf9Qn9MS0ykC&amp;pg=PA18" rel="noreferrer">http://books.google.co.uk/books?id=sf9Qn9MS0ykC&amp;pg=PA18</a></p> <p>Here is what I have so far:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.patches import FancyArrowPatch from mpl_toolkits.mplot3d import proj3d class Arrow3D(FancyArrowPatch): def __init__(self, xs, ys, zs, *args, **kwargs): FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs) self._verts3d = xs, ys, zs def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0],ys[0]),(xs[1],ys[1])) FancyArrowPatch.draw(self, renderer) def Rx(phi): return np.array([[1, 0, 0], [0, np.cos(phi), -np.sin(phi)], [0, np.sin(phi), np.cos(phi)]]) def Ry(theta): return np.array([[np.cos(theta), 0, np.sin(theta)], [0, 1, 0], [-np.sin(theta), 0, np.cos(theta)]]) def Rz(psi): return np.array([[np.cos(psi), -np.sin(psi), 0], [np.sin(psi), np.cos(psi), 0], [0, 0, 1]]) # define origin o = np.array([0,0,0]) # define ox0y0z0 axes x0 = np.array([1,0,0]) y0 = np.array([0,1,0]) z0 = np.array([0,0,1]) # define ox1y1z1 axes psi = 20 * np.pi / 180 x1 = Rz(psi).dot(x0) y1 = Rz(psi).dot(y0) z1 = Rz(psi).dot(z0) # define ox2y2z2 axes theta = 10 * np.pi / 180 x2 = Rz(psi).dot(Ry(theta)).dot(x0) y2 = Rz(psi).dot(Ry(theta)).dot(y0) z2 = Rz(psi).dot(Ry(theta)).dot(z0) # define ox3y3z3 axes phi = 30 * np.pi / 180 x3 = Rz(psi).dot(Ry(theta)).dot(Rx(phi)).dot(x0) y3 = Rz(psi).dot(Ry(theta)).dot(Rx(phi)).dot(y0) z3 = Rz(psi).dot(Ry(theta)).dot(Rx(phi)).dot(z0) # produce figure fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # plot ox0y0z0 axes a = Arrow3D([o[0], x0[0]], [o[1], x0[1]], [o[2], x0[2]], mutation_scale=20, arrowstyle='-|&gt;', color='k') ax.add_artist(a) a = Arrow3D([o[0], y0[0]], [o[1], y0[1]], [o[2], y0[2]], mutation_scale=20, arrowstyle='-|&gt;', color='k') ax.add_artist(a) a = Arrow3D([o[0], z0[0]], [o[1], z0[1]], [o[2], z0[2]], mutation_scale=20, arrowstyle='-|&gt;', color='k') ax.add_artist(a) # plot ox1y1z1 axes a = Arrow3D([o[0], x1[0]], [o[1], x1[1]], [o[2], x1[2]], mutation_scale=20, arrowstyle='-|&gt;', color='k') ax.add_artist(a) a = Arrow3D([o[0], y1[0]], [o[1], y1[1]], [o[2], y1[2]], mutation_scale=20, arrowstyle='-|&gt;', color='k') ax.add_artist(a) a = Arrow3D([o[0], z1[0]], [o[1], z1[1]], [o[2], z1[2]], mutation_scale=20, arrowstyle='-|&gt;', color='k') ax.add_artist(a) # draw dotted arc in x0y0 plane arc = np.arange(-5,116) * np.pi / 180 p = np.array([np.cos(arc),np.sin(arc),arc * 0]) ax.plot(p[0,:],p[1,:],p[2,:],'k--') # mark z0 rotation angles (psi) arc = np.linspace(0,psi) p = np.array([np.cos(arc),np.sin(arc),arc * 0]) * 0.6 ax.plot(p[0,:],p[1,:],p[2,:],'k') p = np.array([-np.sin(arc),np.cos(arc),arc * 0]) * 0.6 ax.plot(p[0,:],p[1,:],p[2,:],'k') # plot ox2y2z2 axes a = Arrow3D([o[0], x2[0]], [o[1], x2[1]], [o[2], x2[2]], mutation_scale=20, arrowstyle='-|&gt;', color='k') ax.add_artist(a) a = Arrow3D([o[0], y2[0]], [o[1], y2[1]], [o[2], y2[2]], mutation_scale=20, arrowstyle='-|&gt;', color='k') ax.add_artist(a) a = Arrow3D([o[0], z2[0]], [o[1], z2[1]], [o[2], z2[2]], mutation_scale=20, arrowstyle='-|&gt;', color='k') ax.add_artist(a) # draw dotted arc in x1z1 plane arc = np.arange(-5,105) * np.pi / 180 p = np.array([np.sin(arc),arc * 0,np.cos(arc)]) p = Rz(psi).dot(p) ax.plot(p[0,:],p[1,:],p[2,:],'k--') # mark y1 rotation angles (theta) arc = np.linspace(0,theta) p = np.array([np.cos(arc),arc * 0,-np.sin(arc)]) * 0.6 p = Rz(psi).dot(p) ax.plot(p[0,:],p[1,:],p[2,:],'k') p = np.array([np.sin(arc),arc * 0,np.cos(arc)]) * 0.6 p = Rz(psi).dot(p) ax.plot(p[0,:],p[1,:],p[2,:],'k') # plot ox3y3z3 axes a = Arrow3D([o[0], x3[0]], [o[1], x3[1]], [o[2], x3[2]], mutation_scale=20, arrowstyle='-|&gt;', color='k') ax.add_artist(a) a = Arrow3D([o[0], y3[0]], [o[1], y3[1]], [o[2], y3[2]], mutation_scale=20, arrowstyle='-|&gt;', color='k') ax.add_artist(a) a = Arrow3D([o[0], z3[0]], [o[1], z3[1]], [o[2], z3[2]], mutation_scale=20, arrowstyle='-|&gt;', color='k') ax.add_artist(a) # draw dotted arc in y2z2 plane arc = np.arange(-5,125) * np.pi / 180 p = np.array([arc * 0,np.cos(arc),np.sin(arc)]) p = Rz(psi).dot(Ry(theta)).dot(p) ax.plot(p[0,:],p[1,:],p[2,:],'k--') # mark x2 rotation angles (phi) arc = np.linspace(0,phi) p = np.array([arc * 0,np.cos(arc),np.sin(arc)]) * 0.6 p = Rz(psi).dot(Ry(theta)).dot(p) ax.plot(p[0,:],p[1,:],p[2,:],'k') p = np.array([arc * 0,-np.sin(arc),np.cos(arc)]) * 0.6 p = Rz(psi).dot(Ry(theta)).dot(p) ax.plot(p[0,:],p[1,:],p[2,:],'k') text_options = {'horizontalalignment': 'center', 'verticalalignment': 'center', 'fontsize': 14} # add label for origin ax.text(0.0,0.0,-0.05,r'$o$', **text_options) # add labels for x axes ax.text(1.1*x0[0],1.1*x0[1],1.1*x0[2],r'$x_0$', **text_options) ax.text(1.1*x1[0],1.1*x1[1],1.1*x1[2],r'$x_1$', **text_options) ax.text(1.1*x2[0],1.1*x2[1],1.1*x2[2],r'$x_2, x_3$', **text_options) # add lables for y axes ax.text(1.1*y0[0],1.1*y0[1],1.1*y0[2],r'$y_0$', **text_options) ax.text(1.1*y1[0],1.1*y1[1],1.1*y1[2],r'$y_1, y_2$', **text_options) ax.text(1.1*y3[0],1.1*y3[1],1.1*y3[2],r'$y_3$', **text_options) # add lables for z axes ax.text(1.1*z0[0],1.1*z0[1],1.1*z0[2],r'$z_0, z_1$', **text_options) ax.text(1.1*z2[0],1.1*z2[1],1.1*z2[2],r'$z_2$', **text_options) ax.text(1.1*z3[0],1.1*z3[1],1.1*z3[2],r'$z_3$', **text_options) # add psi angle labels m = 0.55 * ((x0 + x1) / 2.0) ax.text(m[0], m[1], m[2], r'$\psi$', **text_options) m = 0.55 * ((y0 + y1) / 2.0) ax.text(m[0], m[1], m[2], r'$\psi$', **text_options) # add theta angle lables m = 0.55 * ((x1 + x2) / 2.0) ax.text(m[0], m[1], m[2], r'$\theta$', **text_options) m = 0.55 * ((z1 + z2) / 2.0) ax.text(m[0], m[1], m[2], r'$\theta$', **text_options) # add phi angle lables m = 0.55 * ((y2 + y3) / 2.0) ax.text(m[0], m[1], m[2], r'$\phi$', **text_options) m = 0.55 * ((z2 + z3) / 2.0) ax.text(m[0], m[1], m[2], r'$\phi$', **text_options) # show figure ax.view_init(elev=-150, azim=60) ax.set_axis_off() plt.show() </code></pre> <p>Which produces the following image:</p> <p><img src="https://i.stack.imgur.com/Kgahz.png" alt="enter image description here"></p> <p>The arrows appear to be slightly too short; they do not meet in the middle and they do not quite touch the dotted lines either. Is there a way to fix this?</p>
29,188,796
1
3
null
2015-03-21 22:04:42.093 UTC
8
2015-07-16 08:36:15.8 UTC
2015-07-16 08:36:15.8 UTC
null
1,792,328
null
1,792,328
null
1
12
python|matplotlib|mplot3d
4,473
<p>This code could be well served by some for-loops, but I leave that as as exercise for the reader ;)</p> <p>The key change is the <code>shirnkA</code> and <code>shrinkB</code> paramaters in</p> <pre><code>arrow_prop_dict = dict(mutation_scale=20, arrowstyle='-|&gt;', color='k', shrinkA=0, shrinkB=0) </code></pre> <p><img src="https://i.stack.imgur.com/kWZj9.png" alt="enter image description here"></p> <p>The full code is below:</p> <pre><code>import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.patches import FancyArrowPatch from mpl_toolkits.mplot3d import proj3d class Arrow3D(FancyArrowPatch): def __init__(self, xs, ys, zs, *args, **kwargs): FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs) self._verts3d = xs, ys, zs def draw(self, renderer): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M) self.set_positions((xs[0],ys[0]),(xs[1],ys[1])) FancyArrowPatch.draw(self, renderer) def Rx(phi): return np.array([[1, 0, 0], [0, np.cos(phi), -np.sin(phi)], [0, np.sin(phi), np.cos(phi)]]) def Ry(theta): return np.array([[np.cos(theta), 0, np.sin(theta)], [0, 1, 0], [-np.sin(theta), 0, np.cos(theta)]]) def Rz(psi): return np.array([[np.cos(psi), -np.sin(psi), 0], [np.sin(psi), np.cos(psi), 0], [0, 0, 1]]) # define origin o = np.array([0,0,0]) # define ox0y0z0 axes x0 = np.array([1,0,0]) y0 = np.array([0,1,0]) z0 = np.array([0,0,1]) # define ox1y1z1 axes psi = 20 * np.pi / 180 x1 = Rz(psi).dot(x0) y1 = Rz(psi).dot(y0) z1 = Rz(psi).dot(z0) # define ox2y2z2 axes theta = 10 * np.pi / 180 x2 = Rz(psi).dot(Ry(theta)).dot(x0) y2 = Rz(psi).dot(Ry(theta)).dot(y0) z2 = Rz(psi).dot(Ry(theta)).dot(z0) # define ox3y3z3 axes phi = 30 * np.pi / 180 x3 = Rz(psi).dot(Ry(theta)).dot(Rx(phi)).dot(x0) y3 = Rz(psi).dot(Ry(theta)).dot(Rx(phi)).dot(y0) z3 = Rz(psi).dot(Ry(theta)).dot(Rx(phi)).dot(z0) # produce figure fig = plt.figure() ax = fig.add_subplot(111, projection='3d') arrow_prop_dict = dict(mutation_scale=20, arrowstyle='-|&gt;', color='k', shrinkA=0, shrinkB=0) # plot ox0y0z0 axes a = Arrow3D([o[0], x0[0]], [o[1], x0[1]], [o[2], x0[2]], **arrow_prop_dict) ax.add_artist(a) a = Arrow3D([o[0], y0[0]], [o[1], y0[1]], [o[2], y0[2]], **arrow_prop_dict) ax.add_artist(a) a = Arrow3D([o[0], z0[0]], [o[1], z0[1]], [o[2], z0[2]], **arrow_prop_dict) ax.add_artist(a) # plot ox1y1z1 axes a = Arrow3D([o[0], x1[0]], [o[1], x1[1]], [o[2], x1[2]], **arrow_prop_dict) ax.add_artist(a) a = Arrow3D([o[0], y1[0]], [o[1], y1[1]], [o[2], y1[2]], **arrow_prop_dict) ax.add_artist(a) a = Arrow3D([o[0], z1[0]], [o[1], z1[1]], [o[2], z1[2]], **arrow_prop_dict) ax.add_artist(a) # draw dotted arc in x0y0 plane arc = np.arange(-5,116) * np.pi / 180 p = np.array([np.cos(arc),np.sin(arc),arc * 0]) ax.plot(p[0,:],p[1,:],p[2,:],'k--') # mark z0 rotation angles (psi) arc = np.linspace(0,psi) p = np.array([np.cos(arc),np.sin(arc),arc * 0]) * 0.6 ax.plot(p[0,:],p[1,:],p[2,:],'k') p = np.array([-np.sin(arc),np.cos(arc),arc * 0]) * 0.6 ax.plot(p[0,:],p[1,:],p[2,:],'k') # plot ox2y2z2 axes a = Arrow3D([o[0], x2[0]], [o[1], x2[1]], [o[2], x2[2]], **arrow_prop_dict) ax.add_artist(a) a = Arrow3D([o[0], y2[0]], [o[1], y2[1]], [o[2], y2[2]], **arrow_prop_dict) ax.add_artist(a) a = Arrow3D([o[0], z2[0]], [o[1], z2[1]], [o[2], z2[2]], **arrow_prop_dict) ax.add_artist(a) # draw dotted arc in x1z1 plane arc = np.arange(-5,105) * np.pi / 180 p = np.array([np.sin(arc),arc * 0,np.cos(arc)]) p = Rz(psi).dot(p) ax.plot(p[0,:],p[1,:],p[2,:],'k--') # mark y1 rotation angles (theta) arc = np.linspace(0,theta) p = np.array([np.cos(arc),arc * 0,-np.sin(arc)]) * 0.6 p = Rz(psi).dot(p) ax.plot(p[0,:],p[1,:],p[2,:],'k') p = np.array([np.sin(arc),arc * 0,np.cos(arc)]) * 0.6 p = Rz(psi).dot(p) ax.plot(p[0,:],p[1,:],p[2,:],'k') # plot ox3y3z3 axes a = Arrow3D([o[0], x3[0]], [o[1], x3[1]], [o[2], x3[2]], **arrow_prop_dict) ax.add_artist(a) a = Arrow3D([o[0], y3[0]], [o[1], y3[1]], [o[2], y3[2]], **arrow_prop_dict) ax.add_artist(a) a = Arrow3D([o[0], z3[0]], [o[1], z3[1]], [o[2], z3[2]], **arrow_prop_dict) ax.add_artist(a) # draw dotted arc in y2z2 plane arc = np.arange(-5,125) * np.pi / 180 p = np.array([arc * 0,np.cos(arc),np.sin(arc)]) p = Rz(psi).dot(Ry(theta)).dot(p) ax.plot(p[0,:],p[1,:],p[2,:],'k--') # mark x2 rotation angles (phi) arc = np.linspace(0,phi) p = np.array([arc * 0,np.cos(arc),np.sin(arc)]) * 0.6 p = Rz(psi).dot(Ry(theta)).dot(p) ax.plot(p[0,:],p[1,:],p[2,:],'k') p = np.array([arc * 0,-np.sin(arc),np.cos(arc)]) * 0.6 p = Rz(psi).dot(Ry(theta)).dot(p) ax.plot(p[0,:],p[1,:],p[2,:],'k') text_options = {'horizontalalignment': 'center', 'verticalalignment': 'center', 'fontsize': 14} # add label for origin ax.text(0.0,0.0,-0.05,r'$o$', **text_options) # add labels for x axes ax.text(1.1*x0[0],1.1*x0[1],1.1*x0[2],r'$x_0$', **text_options) ax.text(1.1*x1[0],1.1*x1[1],1.1*x1[2],r'$x_1$', **text_options) ax.text(1.1*x2[0],1.1*x2[1],1.1*x2[2],r'$x_2, x_3$', **text_options) # add lables for y axes ax.text(1.1*y0[0],1.1*y0[1],1.1*y0[2],r'$y_0$', **text_options) ax.text(1.1*y1[0],1.1*y1[1],1.1*y1[2],r'$y_1, y_2$', **text_options) ax.text(1.1*y3[0],1.1*y3[1],1.1*y3[2],r'$y_3$', **text_options) # add lables for z axes ax.text(1.1*z0[0],1.1*z0[1],1.1*z0[2],r'$z_0, z_1$', **text_options) ax.text(1.1*z2[0],1.1*z2[1],1.1*z2[2],r'$z_2$', **text_options) ax.text(1.1*z3[0],1.1*z3[1],1.1*z3[2],r'$z_3$', **text_options) # add psi angle labels m = 0.55 * ((x0 + x1) / 2.0) ax.text(m[0], m[1], m[2], r'$\psi$', **text_options) m = 0.55 * ((y0 + y1) / 2.0) ax.text(m[0], m[1], m[2], r'$\psi$', **text_options) # add theta angle lables m = 0.55 * ((x1 + x2) / 2.0) ax.text(m[0], m[1], m[2], r'$\theta$', **text_options) m = 0.55 * ((z1 + z2) / 2.0) ax.text(m[0], m[1], m[2], r'$\theta$', **text_options) # add phi angle lables m = 0.55 * ((y2 + y3) / 2.0) ax.text(m[0], m[1], m[2], r'$\phi$', **text_options) m = 0.55 * ((z2 + z3) / 2.0) ax.text(m[0], m[1], m[2], r'$\phi$', **text_options) # show figure ax.view_init(elev=-150, azim=60) ax.set_axis_off() plt.show() </code></pre>
47,196,800
ReactJS and images in public folder
<p>Im new in ReactJS and I want to import images in a component. These images are inside of the public folder and I do not know how to access the folder from the react component. </p> <p>Any ideas ?</p> <p><strong>EDIT</strong></p> <p>I want to import an image inside Bottom.js or Header.js</p> <p>The structure folder is:</p> <p><a href="https://i.stack.imgur.com/nQvPK.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nQvPK.png" alt="enter image description here"></a></p> <p>I do not use webpack. Should I ?</p> <p><strong>Edit 2</strong></p> <p>I want to use webpack for loading the images and the rest of assets. So in my config folder I have the next files:</p> <p><a href="https://i.stack.imgur.com/mZbHB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mZbHB.png" alt="enter image description here"></a></p> <p>Where I need to add the paths of the images and how?</p> <p>Thanks</p>
54,844,591
13
6
null
2017-11-09 08:06:29.61 UTC
39
2022-08-17 13:34:53.32 UTC
2017-11-09 08:35:31.123 UTC
null
6,752,591
null
6,752,591
null
1
190
javascript|reactjs
363,269
<p>To reference images in public there are two ways I know how to do it straight forward. One is like above from Homam Bahrani.</p> <p>using </p> <pre><code> &lt;img src={process.env.PUBLIC_URL + '/yourPathHere.jpg'} /&gt; </code></pre> <p>And since this works you really don't need anything else but, this also works...</p> <pre><code> &lt;img src={window.location.origin + '/yourPathHere.jpg'} /&gt; </code></pre>
62,477,034
Is it possible that TreeSet equals HashSet but not HashSet equals TreeSet
<p>I had a interview today and the person taking my interview puzzled me with his statement asking if it possible that <code>TreeSet</code> equals <code>HashSet</code> but not <code>HashSet</code> equals <code>TreeSet</code>. I said &quot;no&quot; but according to him the answer is &quot;yes&quot;.</p> <p>How is it even possible?</p>
62,477,121
5
0
null
2020-06-19 19:08:48.78 UTC
10
2020-08-23 07:06:17.88 UTC
2020-07-31 11:12:07.94 UTC
user11141611
null
user13777664
null
null
1
65
java|collections|hashset|treeset
2,236
<p>Your interviewer is right, they do not hold equivalence relation for some specific cases. It is possible that <code>TreeSet</code> can be equal to <code>HashSet</code> and not vice-versa. Here is an example:</p> <pre><code>TreeSet&lt;String&gt; treeSet = new TreeSet&lt;&gt;(String.CASE_INSENSITIVE_ORDER); HashSet&lt;String&gt; hashSet = new HashSet&lt;&gt;(); treeSet.addAll(List.of("A", "b")); hashSet.addAll(List.of("A", "B")); System.out.println(hashSet.equals(treeSet)); // false System.out.println(treeSet.equals(hashSet)); // true </code></pre> <p>The reason for this is that a <code>TreeSet</code> uses comparator to determine if an element is duplicate while <code>HashSet</code> uses <code>equals</code>.</p> <p>Quoting <code>TreeSet</code>:</p> <blockquote> <p>Note that the ordering maintained by a set (whether or not an explicit comparator is provided) <strong><em>must be consistent with equals</em></strong> if it is to correctly implement the Set interface.</p> </blockquote>
49,637,589
Android Studio 3.1 not showing build error details
<p>I have updated to Android Studio 3.1 and it doesn't show the details of error during compile time. Suppose if I miss a semicolon somewhere or I haven't implemented a method of an interface, then it gives me this error all the time, but doesn't tell me what or where the error occurred! <strong>All error details were perfectly shown in Studio 3.0. How do I see them in 3.1?</strong></p> <p>This is the message that I get every time an error occurs.</p> <pre><code>Compilation error. See log for more details </code></pre>
49,745,282
3
12
null
2018-04-03 19:15:30.537 UTC
8
2018-09-02 21:37:42.877 UTC
2018-04-04 06:06:32.693 UTC
null
7,171,824
null
6,878,730
null
1
32
android|error-log|android-studio-3.1
20,828
<p>There is a toggle button just below the build button that will show the verbose build logs. Tap that and you should be able to see errors like before AS 3.1.</p> <p><a href="https://i.stack.imgur.com/MfoCp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MfoCp.png" alt="toggle button"></a></p>
46,020,237
Install app via usb: The device is temporarily restricted
<p>When I toggle on the <em>install via USB</em> in developer mode:</p> <ul> <li>it will pop the toast message said that <em>the device is temporarily restricted</em></li> <li>then toggle off the settings. </li> </ul> <p>Is there any solution for this?<br> I searched through all the way like turning off MIUI optimization but still does not work. I cannot debug my application by Android Studio in this way...... </p>
47,546,215
34
5
null
2017-09-03 04:21:07.33 UTC
14
2022-08-10 08:56:56.273 UTC
2017-12-04 15:42:35.953 UTC
null
1,778,421
null
6,303,082
null
1
76
android|adb|development-environment|miui
136,389
<p>For me on a rooted <strong>MIUI v.8.5.1</strong> I just need to: </p> <ul> <li>turn off wifi </li> <li>turn on mobile connection In development options </li> </ul> <p>after doing that both <em>Install via USB</em> and <em>USB debugging</em> started to work.</p>
19,537,480
JSHint: Overwrite single .jshintrc option for whole folder
<p>I have a <code>.jshintrc</code> at the root of my project with the following configuration:</p> <pre><code>{ "node": true, "smarttabs": true, "undef": true, "unused": true } </code></pre> <p>This is fine for all the node related stuff I have in the project, but not for the browser related scripts. Which are sitting in a subfolder.<br> Is it possible overwrite just the <code>node</code> option while preserving the other options for a whole folder? </p> <p>If I create another <code>.jshintrc</code> file for the browser side folder I have to tell JSHint again about all my configurations, although I actually just want to unset the <code>node</code> option.</p> <p>I know that I can set this option in every file but I actually would like to avoid that.</p> <p>Many thanks in advance!</p>
25,213,836
1
2
null
2013-10-23 09:07:53.11 UTC
5
2014-11-28 13:28:34.417 UTC
2014-11-28 13:28:34.417 UTC
null
2,274,224
null
2,274,224
null
1
28
javascript|node.js|browser|jshint
2,787
<p>Yes, there's a feature in <strong>jshint v2.5.1</strong> that is "extends", for your example this could be like this:</p> <p>/.jshintrc</p> <pre><code>{ "smarttabs": true, "undef": true, "unused": true } </code></pre> <p>/server/.jshintrc</p> <pre><code>{ "extends": "../.jshintrc", "node": true } </code></pre> <p>/client/.jshintrc</p> <pre><code>{ "extends": "../.jshintrc", "browser": true } </code></pre> <p>You can read more about this feature here: <a href="https://github.com/jshint/jshint/releases/tag/2.5.1">https://github.com/jshint/jshint/releases/tag/2.5.1</a></p>
34,055,713
How to add a char/int to an char array in C?
<p>How can I add '.' to the char Array := "Hello World" in C, so I get a char Array: "Hello World." The Question seems simple but I'm struggling.</p> <p>Tried the following:</p> <pre><code>char str[1024]; char tmp = '.'; strcat(str, tmp); </code></pre> <p>But it does not work. It shows me the error: "passing argument 2 of ‘strcat’ makes pointer from integer without a cast" I know that in C a char can be cast as int aswell. Do I have to convert the tmp to an char array aswell or is there a better solution?</p>
34,055,805
5
4
null
2015-12-03 00:27:41.903 UTC
8
2015-12-03 09:02:26.307 UTC
null
null
null
null
5,020,085
null
1
21
c
157,881
<p><code>strcat</code> has the declaration:</p> <pre><code>char *strcat(char *dest, const char *src) </code></pre> <p>It expects 2 strings. <a href="http://ideone.com/F2WTgp" rel="noreferrer">While this compiles:</a></p> <pre><code>char str[1024] = "Hello World"; char tmp = '.'; strcat(str, tmp); </code></pre> <p>It will cause bad memory issues because <code>strcat</code> is looking for a null terminated cstring. You can do this:</p> <pre><code>char str[1024] = "Hello World"; char tmp[2] = "."; strcat(str, tmp); </code></pre> <p><a href="http://ideone.com/VNtvIM" rel="noreferrer">Live example.</a></p> <p>If you really want to append a char you will need to make your own function. Something like this:</p> <pre><code>void append(char* s, char c) { int len = strlen(s); s[len] = c; s[len+1] = '\0'; } append(str, tmp) </code></pre> <p>Of course you may also want to check your string size etc to make it memory safe. </p>
305,880
Hibernate Annotation Placement Question
<p>I've got what I think is a simple question. I've seen examples both ways. The question is - "why can't I place my annotations on the field?". Let me give you an example....</p> <pre><code>@Entity @Table(name="widget") public class Widget { private Integer id; @Id @GeneratedValue(strategy=GenerationType.AUTO) public Integer getId() { return this.id; } public Integer setId(Integer Id) { this.id = id;} } </code></pre> <p>The above code works fine (assuming there's not a typo in there). When the annotation is placed on the getter of the property everything is perfect.</p> <p>However, that seems awkward to me. In my mind it's cleaner to place the annotation on the field, like so --</p> <pre><code>@Entity @Table(name="widget") public class Widget { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; public Integer getId() { return this.id; } public Integer setId(Integer Id) { this.id = id;} } </code></pre> <p>I've seen examples of both ways. However, when I run this second example I get the following...</p> <pre> java.lang.NullPointerException at com.widget.util.hibernate.HibernateSessionFactory$ThreadLocalSession.initialValue(HibernateSessionFactory.java:25) at com.widget.util.hibernate.HibernateSessionFactory$ThreadLocalSession.initialValue(HibernateSessionFactory.java:1) at java.lang.ThreadLocal$ThreadLocalMap.getAfterMiss(Unknown Source) at java.lang.ThreadLocal$ThreadLocalMap.get(Unknown Source) at java.lang.ThreadLocal$ThreadLocalMap.access$000(Unknown Source) at java.lang.ThreadLocal.get(Unknown Source) at com.widget.util.hibernate.HibernateSessionFactory.get(HibernateSessionFactory.java:33) at com.widget.db.dao.AbstractDao.(AbstractDao.java:12) at com.widget.db.dao.WidgetDao.(WidgetDao.java:9) at com.widget.db.dao.test.WidgetDaoTest.findById(WidgetDaoTest.java:17) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) ... </pre> <p>Here's the skeleton of <code>HibernateSessionFactory</code> (line 25 is marked) ....</p> <pre><code>protected Session initialValue() { SessionFactory sessionFactory = null; try { Configuration cfg = new AnnotationConfiguration().configure(); String url = System.getProperty("jdbc.url"); if (url != null) { cfg.setProperty("hibernate.connection.url", url); } sessionFactory = cfg.buildSessionFactory(); } catch (Exception e) { } Session session = sessionFactory.openSession(); // LINE 25 return session; } </code></pre> <p>Anyone have an idea what's going on here?</p>
307,238
5
1
null
2008-11-20 16:20:45.473 UTC
20
2011-06-10 18:19:27.117 UTC
2008-11-20 16:35:36.627 UTC
sblundy
4,893
K-Boo
39,374
null
1
24
java|hibernate|annotations
20,850
<p>From a performance and design perspective, using annotations on getters is a better idea than member variables, because the getter setters are called using reflection if placed on the field, than a method. Also if you plan to use validation and other features of hibernate, you'll have all the annotations at one place, rather than scattering them all over the place.</p> <p>My recommendation go with methods not member variables.</p> <p>From the documentation</p> <blockquote> <p>Depending on whether you annotate fields or methods, the access type used by Hibernate will be field or property. The EJB3 spec requires that you declare annotations on the element type that will be accessed, i.e. the getter method if you use property access, the field if you use field access. Mixing EJB3 annotations in both fields and methods should be avoided. Hibernate will guess the access type from the position of @Id or @EmbeddedId.</p> </blockquote>
246,275
Modified files in a git branch are spilling over into another branch
<p>I am working on a git repository with a master branch and another the topic branch. I have switched to topic branch and modified a file. Now, if I switched to the master branch, that same file is shown as modified.</p> <p>For example:</p> <p>git status in git-build branch:</p> <pre><code># On branch git-build # Changes to be committed: # (use &quot;git reset HEAD &lt;file&gt;...&quot; to unstage) # # modified: cvsup_current # </code></pre> <p>Switch to master branch</p> <pre><code>[root@redbull builder_scripts (git-build)]# git co master M builder_scripts/cvsup_current Switched to branch &quot;master&quot; </code></pre> <p>git status in master branch</p> <pre><code>[root@redbull builder_scripts (master)]# git status # On branch master # Changes to be committed: # (use &quot;git reset HEAD &lt;file&gt;...&quot; to unstage) # # modified: cvsup_current # </code></pre> <p>Why is that the file is shown as modified in the master branch even though it was modified in git-build branch?</p> <p>My understanding was that the branches are independent of each other and when I change from one branch to another the changes do not &quot;spill over&quot; from one branch to another. So I am obviously missing something here.</p> <p>Has anyone got a clue stick?</p>
246,286
5
0
null
2008-10-29 09:58:30.833 UTC
14
2021-08-23 11:37:18.14 UTC
2021-08-23 11:37:18.14 UTC
null
6,530,134
Rajkumar S
25,453
null
1
58
git|git-branch
18,576
<p>This is the default behaviour of git.</p> <p>You can use <strong>-f</strong> flag to checkout to do "clean checkout" if you like.</p>
1,255,635
How do I add to a specific column in Listview item?
<p>I create a listview and the number of columns are determined at runtime. I have been reading texts on the web all over about listview( and I still am) but I wish to know how to add items to a specific column in listview I thought something like:</p> <pre><code>m_listview.Items.Add("1850").SubItems.Add("yes"); </code></pre> <p>would work assuming the <strong>"1850"</strong> which is the text of the column would be the target column.</p>
1,255,788
6
0
null
2009-08-10 15:41:23.33 UTC
2
2020-10-23 23:37:10.777 UTC
2012-08-07 19:35:34.893 UTC
null
1,539,296
null
107,301
null
1
5
c#|.net|winforms|listview|user-interface
50,527
<p>ListViewItems aren't aware of your ListView columns.</p> <p>In order to directly reference the column, you first need to add all the columns to the ListViewItem.</p> <p>So... lets say your ListView has three columns A, B and C; This next bit of code will only add data to column A:</p> <pre><code>ListViewItem item = new ListViewItem(); item.Text = &quot;Column A&quot;; m_listView.Items.Add(item); </code></pre> <p>To get it to add text to column C as well, we first need to tell it it has a column B...</p> <pre><code>ListViewItem item = new ListViewItem(); item.Text = &quot;Column A&quot;; item.SubItems.Add(&quot;&quot;); item.SubItems.Add(&quot;Column C&quot;); m_listView.Items.Add(item); </code></pre> <p>So now we'll have columns A, B and C in the ListViewItem, and text appearing in the A and C columns, but not the B.</p> <p>Finally... now that we HAVE told it it has three columns, we can do whatever we like to those specific columns...</p> <pre><code>ListViewItem item = new ListViewItem(); item.Text = &quot;Column A&quot;; item.SubItems.Add(&quot;&quot;); item.SubItems.Add(&quot;Column C&quot;); m_listView.Items.Add(item); m_listView.Items[0].SubItems[2].Text = &quot;change text of column C&quot;; m_listView.Items[0].SubItems[1].Text = &quot;change text of column B&quot;; m_listView.Items[0].SubItems[0].Text = &quot;change text of column A&quot;; </code></pre> <p>hope that helps!</p>
984,484
jQuery onchange/onfocus select box to display an image?
<p>I need some help finding a jQuery plugin which will allow me to display an image preview from a select list of images - onfocus/onchange..</p> <p>Example:</p> <pre><code>&lt;select name="image" id="image" class="inputbox" size="1"&gt; &lt;option value=""&gt; - Select Image - &lt;/option&gt; &lt;option value="image1.jpg"&gt;image1.jpg&lt;/option&gt; &lt;option value="image2.jpg"&gt;image2.jpg&lt;/option&gt; &lt;option value="image3.jpg"&gt;image3.jpg&lt;/option&gt; &lt;/select&gt; &lt;div id="imagePreview"&gt; displays image here &lt;/div&gt; </code></pre> <p>Has anyone come across something like this? I've tried searching for it to no avail..</p> <p>Thank you!</p>
984,505
6
0
null
2009-06-12 00:26:03.027 UTC
11
2021-04-26 18:30:47.09 UTC
null
null
null
null
92,129
null
1
9
jquery|select|jquery-plugins|onchange|onfocus
90,954
<p>I'm not sure you need a plugin to deal with this:</p> <pre><code>$(document).ready(function() { $("#image").change(function() { var src = $(this).val(); $("#imagePreview").html(src ? "&lt;img src='" + src + "'&gt;" : ""); }); }); </code></pre>
37,982,842
How do I wrap a React component that returns multiple table rows and avoid the "<tr> cannot appear as a child of <div>" error?
<p>I have a component called OrderItem that takes an object with multiple objects (at least two) inside it, and renders them as multiple rows inside a table. There will be multiple OrderItem components inside the table. The problem is that in the component's render function, I can't return multiple lines. I can only return a single component, and if I wrap them in a div, it says " <code>&lt;tr&gt;</code> cannot appear as a child of <code>&lt;div&gt;</code>"</p> <p>The code looks something like this (I left some stuff out for easier readability)</p> <pre class="lang-js prettyprint-override"><code>Parent() { render() { return ( &lt;table&gt; &lt;tbody&gt; { _.map(this.state.orderItems, (value, key) =&gt; { return &lt;OrderItem value={value} myKey={key}/&gt; }) } &lt;/tbody&gt; &lt;/table&gt; ) } } class OrderItem extends React.Component { render() { return ( &lt;div&gt; // &lt;-- problematic div &lt;tr key={this.props.myKey}&gt; &lt;td&gt; Table {this.props.value[0].table}&lt;/td&gt; &lt;td&gt; Item &lt;/td&gt; &lt;td&gt; Option &lt;/td&gt; &lt;/tr&gt; {this.props.value.map((item, index) =&gt; { if (index &gt; 0) { // skip the first element since it's already used above return ( &lt;tr key={this.props.myKey + index.toString()}&gt; &lt;td&gt;&lt;img src={item.image} alt={item.name} width="50"/&gt; {item.name}&lt;/td&gt; &lt;td&gt;{item.selectedOption}&lt;/td&gt; &lt;/tr&gt; ) } })} &lt;/div&gt; ) } } </code></pre> <p>Is there a way I can return those multiple rows and have them be in the same table without wrapping them in a div and getting an error? I realize I can make a separate table for each component, but that throws my formatting off a bit.</p>
38,021,769
6
3
null
2016-06-23 05:14:16.557 UTC
8
2020-01-31 22:48:13.623 UTC
2019-03-06 22:29:14.347 UTC
null
1,120,027
null
680,550
null
1
59
javascript|reactjs
51,667
<p>It seems there is no way to wrap them cleanly, so the easier solution is to just put the whole table in the component and just have multiple tables and figure out the formatting.</p> <pre class="lang-js prettyprint-override"><code>Parent() { render() { return ( {_.map(this.state.orderItems, (value, key) =&gt; { return &lt;OrderItem value={value} myKey={key} key={key}/&gt; })} ) } } class OrderItem extends React.Component { render() { return ( &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; Table {this.props.value[0].table}&lt;/td&gt; &lt;td&gt; Item &lt;/td&gt; &lt;td&gt; Option &lt;/td&gt; &lt;/tr&gt; {this.props.value.map((item, index) =&gt; { if (index &gt; 0) { // skip the first element since it's already used above return ( &lt;tr key={this.props.myKey + index.toString()}&gt; &lt;td&gt; &lt;img src={item.image} alt={item.name} width="50"/&gt; {item.name}&lt;/td&gt; &lt;td&gt;{item.selectedOption}&lt;/td&gt; &lt;/tr&gt; ) } })} &lt;/tbody&gt; &lt;/table&gt; ) } } </code></pre>
18,078,153
error: ‘unique_ptr’ is not a member of ‘std’
<p>I guess it's pretty self explanatory - I can't seem to use C++11 features, even though I think I have everything set up properly - which likely means that I don't.</p> <p>Here's my code:</p> <pre><code>#include &lt;cstdlib&gt; #include &lt;iostream&gt; class Object { private: int value; public: Object(int val) { value = val; } int get_val() { return value; } void set_val(int val) { value = val; } }; int main() { Object *obj = new Object(3); std::unique_ptr&lt;Object&gt; smart_obj(new Object(5)); std::cout &lt;&lt; obj-&gt;get_val() &lt;&lt; std::endl; return 0; } </code></pre> <p>Here's my version of g++:</p> <pre class="lang-none prettyprint-override"><code>ubuntu@ubuntu:~/Desktop$ g++ --version g++ (Ubuntu/Linaro 4.7.3-2ubuntu1~12.04) 4.7.3 Copyright (C) 2012 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. </code></pre> <p>Here's how I'm compiling the code:</p> <pre class="lang-none prettyprint-override"><code>ubuntu@ubuntu:~/Desktop$ g++ main.cpp -o run --std=c++11 main.cpp: In function ‘int main()’: main.cpp:25:2: error: ‘unique_ptr’ is not a member of ‘std’ main.cpp:25:24: error: expected primary-expression before ‘&gt;’ token main.cpp:25:49: error: ‘smart_obj’ was not declared in this scope </code></pre> <p>Note that I've tried both <code>-std=c++11</code> and <code>-std=c++0x</code> to no avail.</p> <p>I'm running Ubuntu 12.04 LTS from a flash drive on an Intel x64 machine.</p>
18,078,167
3
1
null
2013-08-06 10:52:24.957 UTC
6
2021-03-31 18:57:30.123 UTC
2016-06-14 21:54:51.037 UTC
null
1,281,433
null
1,974,937
null
1
64
c++|c++11|g++|unique-ptr
69,402
<p>You need to include header where <a href="http://en.cppreference.com/w/cpp/memory/unique_ptr" rel="noreferrer"><code>unique_ptr</code></a> and <a href="http://en.cppreference.com/w/cpp/memory/shared_ptr" rel="noreferrer"><code>shared_ptr</code></a> are defined</p> <pre><code>#include &lt;memory&gt; </code></pre> <p>As you already knew that you need to compile with <code>c++11</code> flag</p> <pre><code>g++ main.cpp -o run -std=c++11 // ^ </code></pre>
33,305,574
Why does const int main = 195 result in a working program but without the const it ends in a segmentation fault?
<p>Consider following C program (see live demo <a href="http://melpon.org/wandbox/permlink/556rmrO8S41o2Ul0" rel="noreferrer">here</a>).</p> <pre><code>const int main = 195; </code></pre> <p>I know that in the real world no programmer writes code like this, because it serves no useful purpose and doesn't make any sense. But when I remove the <code>const</code> keyword from above the program it immediately results in a <a href="http://en.wikipedia.org/wiki/Segmentation_fault" rel="noreferrer">segmentation fault</a>. Why? I am eager to know the reason behind this.</p> <p>GCC 4.8.2 gives following warning when compiling it.</p> <blockquote> <p>warning: 'main' is usually a function [-Wmain]</p> <pre><code>const int main = 195; ^ </code></pre> </blockquote> <p>Why does the presence and absence of <code>const</code> keyword make a difference here in the behavior of the program?</p>
33,305,685
2
5
null
2015-10-23 15:02:24.54 UTC
5
2015-10-24 15:41:30.83 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
3,777,958
null
1
33
c|segmentation-fault|constants|program-entry-point
4,234
<p>Observe how the value 195 corresponds to the <code>ret</code> (return from function) instruction on 8086 compatibles. This definition of <code>main</code> thus behaves as if you defined it as <code>int main() {}</code> when executed.</p> <p>On some platforms, <code>const</code> data is loaded into an executable but not writeable memory region whereas mutable data (i.e. data not qualified <code>const</code>) is loaded into a writeable but not executable memory region. For this reason, the program “works” when you declare <code>main</code> as <code>const</code> but not when you leave off the <code>const</code> qualifier.</p> <p>Traditionally, binaries contained three <em>segments:</em></p> <ul> <li>The <code>text</code> segment is (if supported by the architecture) write-protected and executable, and contains executable code, variables of <em>static</em> storage duration qualified <code>const</code>, and string literals</li> <li>The <code>data</code> segment is writeable and cannot be executed. It contains variables not qualified <code>const</code> with <em>static</em> storage duration and (at runtime) objects with <em>allocated</em> storage duration</li> <li>The <code>bss</code> segment is similar to the <code>data</code> segment but is initialized to all zeroes. It contains variables of <em>static</em> storage duration not qualified <code>const</code> that have been declared without an initializer</li> <li>The <code>stack</code> segment is not present in the binary and contains variables with <em>automatic</em> storage duration</li> </ul> <p>Removing the <code>const</code> qualifier from the variable <code>main</code> causes it to be moved from the <code>text</code> to the <code>data</code> segment, which isn't executable, causing the segmentation violation you observe.</p> <p>Modern platforms often have further segments (e.g. a <code>rodata</code> segment for data that is neither writeable nor executable) so please don't take this as an accurate description of your platform without consulting platform-specific documentation.</p> <p>Please understand that not making <code>main</code> a function is usually incorrect, although technically a platform could allow <code>main</code> to be declared as a variable, cf. ISO 9899:2011 §5.1.2.2.1 ¶1, emphasis mine:</p> <blockquote> <p>1 The function called at program startup is named <code>main</code>. The implementation declares no prototype for this function. It shall be defined with a return type of <code>int</code> and with no parameters (...) or with two parameters (...) or equivalent; or <em>in some other implementation-defined manner.</em></p> </blockquote>
69,424,363
Is it allowed to name a global variable `read` or `malloc` in C++?
<p>Consider the following C++17 code:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; int read; int main(){ std::ios_base::sync_with_stdio(false); std::cin &gt;&gt; read; } </code></pre> <p>It compiles and runs fine on <a href="https://godbolt.org/z/asKsv95G5" rel="noreferrer">Godbolt</a> with GCC 11.2 and Clang 12.0.1, but results in runtime error if compiled with a <code>-static</code> key.</p> <p>As far as I understand, there is a POSIX(?) function called <code>read</code> (see <a href="https://man7.org/linux/man-pages/man2/read.2.html" rel="noreferrer"><code>man read(2)</code></a>), so the example above actually invokes ODR violation and the program is essentially ill-formed even when compiled without <code>-static</code>. GCC even emits warning if I try to name a variable <code>malloc</code>: <code>built-in function 'malloc' declared as non-function</code></p> <p>Is the program above valid C++17? If no, why? If yes, is it a compiler bug which prevents it from running?</p>
69,424,708
2
20
null
2021-10-03 11:20:17.89 UTC
3
2021-10-04 09:43:30.543 UTC
2021-10-03 11:36:30.553 UTC
null
767,632
null
767,632
null
1
38
c++|gcc|language-lawyer|posix|clang++
2,919
<p>The code shown is valid (all C++ Standard versions, I believe). The similar restrictions are all listed in <a href="https://timsong-cpp.github.io/cppwp/n4659/reserved.names" rel="noreferrer">[reserved.names]</a>. Since <code>read</code> is not declared in the C++ standard library, nor in the C standard library, nor in older versions of the standard libraries, and is not otherwise listed there, it's fair game as a name in the global namespace.</p> <p>So is it an implementation defect that it won't link with <code>-static</code>? (Not a &quot;compiler bug&quot; - the compiler piece of the toolchain is fine, and there's nothing forbidding a warning on valid code.) It does at least work with default settings (though because of how the GNU linker doesn't mind duplicated symbols in an unused object of a dynamic library), and one could argue that's all that's needed for Standard compliance.</p> <p>We also have at <a href="https://timsong-cpp.github.io/cppwp/n4659/intro.compliance#8" rel="noreferrer">[intro.compliance]/8</a></p> <blockquote> <p>A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any well-formed program. Implementations are required to diagnose programs that use such extensions that are ill-formed according to this International Standard. Having done so, however, they can compile and execute such programs.</p> </blockquote> <p>We can consider POSIX functions such an extension. This is intentionally vague on when or how such extensions are enabled. The g++ driver of the GCC toolset links a number of libraries by default, and we can consider that as adding not only the availability of non-standard <code>#include</code> headers but also adding additional translation units to the program. In theory, different arguments to the g++ driver might make it work without the underlying link step using <code>libc.so</code>. But good luck - one could argue it's a problem that there's no simple way to link only names from the C++ and C standard libraries without including other unreserved names.</p> <p>(Does not altering a well-formed program even mean that an implementation extension can't use non-reserved names for the additional libraries? I hope not, but I could see a strict reading implying that.)</p> <p>So I haven't claimed a definitive answer to the question, but the practical situation is unlikely to change, and a Standard Defect Report would in my opinion be more nit-picking than a useful clarification.</p>
23,157,613
How to iterate through string one word at a time in zsh
<p>How do I modify the following code so that when run in zsh it expands <code>$things</code> and iterates through them one at a time?</p> <pre><code>things="one two" for one_thing in $things; do echo $one_thing done </code></pre> <p>I want the output to be:</p> <pre><code>one two </code></pre> <p>But as written above, it outputs:</p> <pre><code>one two </code></pre> <p>(I'm looking for the behavior that you get when running the above code in bash)</p>
23,157,823
4
2
null
2014-04-18 15:52:51.79 UTC
2
2022-06-16 20:15:06.273 UTC
2020-12-25 07:39:17.097 UTC
null
10,248,678
null
875,915
null
1
34
while-loop|zsh|expansion
54,183
<p>In order to see the behavior compatible with Bourne shell, you'd need to set the option <code>SH_WORD_SPLIT</code>:</p> <pre><code>setopt shwordsplit # this can be unset by saying: unsetopt shwordsplit things="one two" for one_thing in $things; do echo $one_thing done </code></pre> <p>would produce:</p> <pre><code>one two </code></pre> <p>However, it's recommended to use an array for producing word splitting, e.g., </p> <pre><code>things=(one two) for one_thing in $things; do echo $one_thing done </code></pre> <hr> <p>You may also want to refer to:</p> <p><a href="http://zsh.sourceforge.net/FAQ/zshfaq03.html" rel="noreferrer">3.1: Why does $var where var="foo bar" not do what I expect?</a></p>
2,173,797
How to sort 2d array by row in python?
<p>I have 2d array, dimension 3x10, and I want to sort by values in 2nd row, from lowest to highest value.</p>
2,173,843
5
0
null
2010-01-31 23:11:51.85 UTC
7
2018-11-16 03:58:33.09 UTC
2018-11-16 03:58:33.09 UTC
null
1,033,581
null
257,522
null
1
19
python|sorting
113,441
<p>Python, per se, has no "2d array" -- it has (1d) lists as built-ins, and (1d) arrays in standard library module <a href="http://docs.python.org/library/array.html?highlight=array#module-array" rel="noreferrer">array</a>. There are third-party libraries such as <code>numpy</code> which do provide Python-usable multi-dimensional arrays, but of course you'd be mentioning such third party libraries if you were using some of them, rather than just saying "in Python", <em>right</em>?-)</p> <p>So I'll assume that by "2d array" you mean a list of lists, such as:</p> <pre><code>lol = [ range(10), range(2, 12), range(5, 15) ] </code></pre> <p>or the like -- i.e. a list with 3 items, each item being a list with 10 items, and the "second row" would be the sublist item <code>lol[1]</code>. Yeah, lots of assumptions, but your question is so maddeningly vague that there's no way to avoid making assumptions - edit your Q to clarify with more precision, and an example!, if you dislike people trying to read your mind (and probably failing) as you currently make it impossible to avoid.</p> <p>So under these assumptions you can sort each of the 3 sublists in the order required to sort the second one, for example:</p> <pre><code>indices = range(10) indices.sort(key = lol[1].__getitem__) for i, sublist in enumerate(lol): lol[i] = [sublist[j] for j in indices] </code></pre> <p>The general approach here is to sort the range of indices, then just use that appropriately sorted range to reorder all the sublists in play.</p> <p>If you actually have a different problem, there will of course be different solutions;-).</p>
2,194,998
BoxLayout stretches component to fit parent panel
<p>Hi I am using a <code>BoxLayout</code> to stack <code>JPanel</code>s on top of each other (<code>BoxLayout.Y_AXIS</code>), for example if my parent <code>JPanel</code> is of height 500 pixels and I add two child panels to it both of height 100 pixels. The <code>BoxLayout</code> stretches them so that together they occupy the the 500px space. Does anyone know how to disable this feature?</p>
2,195,049
5
2
null
2010-02-03 19:58:55.763 UTC
4
2018-05-02 11:23:30.96 UTC
2015-12-14 15:37:57.343 UTC
null
4,857,909
null
225,814
null
1
22
java|user-interface|swing
40,038
<p>Use <a href="http://java.sun.com/docs/books/tutorial/uiswing/layout/gridbag.html" rel="noreferrer">GridBagLayout</a> instead. You have much more control over your UI.</p> <p>But if you want to use BoxLayout still, and don't want them to stretch, you can check out using <a href="http://java.sun.com/docs/books/tutorial/uiswing/layout/box.html#filler" rel="noreferrer">invisible component fillers</a> like rigid areas, glue and fillers.</p>
2,035,567
NSString: newline escape in plist
<p>I'm writing a property list to be in the resources bundle of my application. An <code>NSString</code> object in the plist needs to have line-breaks in it. I tried <code>\n</code>, but that doesn't work. What do I do to have newlines in my string in the plist?</p> <p>Thanks.</p>
2,327,317
5
0
null
2010-01-10 00:34:55.99 UTC
12
2017-07-07 07:44:15.58 UTC
null
null
null
null
125,361
null
1
51
iphone|nsstring|plist
18,416
<p>If you're editing the plist in Xcode's inbuild plist editor, you can press option-return to enter a line break within a string value.</p>
2,311,205
The best way to parse a FIX message?
<p>How do you parse a FIX message using python ? (FIX message as in the 'financial' FIX Protocol)</p>
2,311,241
6
4
null
2010-02-22 13:46:15.783 UTC
8
2016-01-06 19:26:51.093 UTC
2016-01-06 19:26:51.093 UTC
null
5,753,864
null
278,720
null
1
31
finance|quickfix
27,447
<p>do you mean by using QuickFIX ? (I can see QuickFIX in your tags)</p> <p>if that is the case, I don't know. Generally it's not difficult to write a simple parser for a FIX message. I found that the web tools on <a href="http://www.validfix.com/" rel="noreferrer">valid fix</a> do the job.</p>
1,811,782
When should I use ConcurrentSkipListMap?
<p>In Java, <code>ConcurrentHashMap</code> is there for better <code>multithreading</code> solution. Then when should I use <code>ConcurrentSkipListMap</code>? Is it a redundancy?</p> <p>Does multithreading aspects between these two are common?</p>
1,811,810
6
0
null
2009-11-28 06:33:25.68 UTC
30
2020-07-06 00:01:53.013 UTC
2009-11-29 06:59:20.203 UTC
null
194,764
null
194,764
null
1
93
java|performance|multithreading|map|concurrenthashmap
41,972
<p>These two classes vary in a few ways.</p> <p><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="noreferrer">ConcurrentHashMap</a> does not guarantee* the runtime of its operations as part of its contract. It also allows tuning for certain load factors (roughly, the number of threads concurrently modifying it).</p> <p><a href="http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ConcurrentSkipListMap.html" rel="noreferrer">ConcurrentSkipListMap</a>, on the other hand, guarantees average O(log(n)) performance on a wide variety of operations. It also does not support tuning for concurrency's sake. <code>ConcurrentSkipListMap</code> also has a number of operations that <code>ConcurrentHashMap</code> doesn't: ceilingEntry/Key, floorEntry/Key, etc. It also maintains a sort order, which would otherwise have to be calculated (at notable expense) if you were using a <code>ConcurrentHashMap</code>.</p> <p>Basically, different implementations are provided for different use cases. If you need quick single key/value pair addition and quick single key lookup, use the <code>HashMap</code>. If you need faster in-order traversal, and can afford the extra cost for insertion, use the <code>SkipListMap</code>.</p> <p><sub>*Though I expect the implementation is roughly in line with the general hash-map guarantees of O(1) insertion/lookup; ignoring re-hashing</sub></p>
1,626,023
C# Normal Random Number
<p>I would like to create a function that accepts <code>Double mean</code>, <code>Double deviation</code> and returns a random number with a normal distribution. </p> <p>Example: if I pass in 5.00 as the mean and 2.00 as the deviation, 68% of the time I will get a number between 3.00 and 7.00</p> <p>My statistics is a little weak…. Anyone have an idea how I should approach this? My implementation will be C# 2.0 but feel free to answer in your language of choice as long as the math functions are standard.</p> <p>I think <a href="https://stackoverflow.com/questions/1197321/need-help-generating-discrete-random-numbers-from-distribution/1197393#1197393">this</a> might actually be what I am looking for. Any help converting this to code?</p> <p>Thanks in advance for your help.</p>
1,626,561
9
3
null
2009-10-26 17:12:10.907 UTC
14
2017-09-16 12:42:13.917 UTC
2017-05-23 11:46:31.853 UTC
null
-1
null
180,385
null
1
24
c#|algorithm|math|statistics|random
29,332
<p>See this CodeProject article: <a href="http://www.codeproject.com/KB/recipes/SimpleRNG.aspx" rel="noreferrer">Simple Random Number Generation</a>. The code is very short, and it generates samples from uniform, normal, and exponential distributions.</p>
1,795,109
What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS
<p>I am currently wondering what is the difference between the two. When I used both they seem to break the word if it is not fitting the container. But why did W3C made two ways to do it?</p>
1,795,878
13
0
null
2009-11-25 06:56:24.187 UTC
97
2021-11-03 12:31:45.667 UTC
2012-05-17 14:44:26.03 UTC
null
106,224
null
121,859
null
1
423
css|word-wrap
238,065
<p><a href="http://www.w3.org/TR/css3-text/" rel="noreferrer">The W3 specification that talks about these</a> seem to suggest that <code>word-break: break-all</code> is for requiring a particular behaviour with CJK (Chinese, Japanese, and Korean) text, whereas <code>word-wrap: break-word</code> is the more general, non-CJK-aware, behaviour.</p>
1,762,088
Common reasons for bugs in release version not present in debug mode
<p>What are the typical reasons for bugs and abnormal program behavior that manifest themselves only in release compilation mode but which do not occur when in debug mode?</p>
1,762,110
18
2
2010-05-11 15:17:25.11 UTC
2009-11-19 09:46:42.537 UTC
26
2020-01-16 10:40:51.36 UTC
2009-11-19 12:17:29.703 UTC
null
124,061
null
124,061
null
1
73
c++|release-mode|debug-mode
32,101
<p>Many times, in debug mode in C++ all variables are null initialized, whereas the same does not happen in release mode unless explicitly stated.</p> <p>Check for any debug macros and uninitialized variables</p> <p>Does your program uses threading, then optimization can also cause some issues in release mode.</p> <p>Also check for all exceptions, for example not directly related to release mode but sometime we just ignore some critical exceptions, like mem access violation in VC++, but the same can be a issue at least in other OS like Linux, Solaris. Ideally your program should not catch such critical exceptions like accessing a NULL pointer. </p>
1,653,308
Access-Control-Allow-Origin Multiple Origin Domains?
<p>Is there a way to allow multiple cross-domains using the <code>Access-Control-Allow-Origin</code> header?</p> <p>I'm aware of the <code>*</code>, but it is too open. I really want to allow just a couple domains.</p> <p>As an example, something like this:</p> <pre><code>Access-Control-Allow-Origin: http://domain1.example, http://domain2.example </code></pre> <p>I have tried the above code but it does not seem to work in Firefox.</p> <p>Is it possible to specify multiple domains or am I stuck with just one?</p>
1,850,482
32
6
null
2009-10-31 03:27:44.493 UTC
358
2022-07-20 19:25:31.49 UTC
2019-02-02 04:22:44.863 UTC
null
441,757
null
133,776
null
1
1,286
.htaccess|http|cors|xmlhttprequest|cross-domain
1,031,871
<p>Sounds like the recommended way to do it is to have your server read the Origin header from the client, compare that to the list of domains you would like to allow, and if it matches, echo the value of the <code>Origin</code> header back to the client as the <code>Access-Control-Allow-Origin</code> header in the response.</p> <p>With <code>.htaccess</code> you can do it like this:</p> <pre><code># ---------------------------------------------------------------------- # Allow loading of external fonts # ---------------------------------------------------------------------- &lt;FilesMatch "\.(ttf|otf|eot|woff|woff2)$"&gt; &lt;IfModule mod_headers.c&gt; SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com|otherdomain.example|dev02.otherdomain.example)$" AccessControlAllowOrigin=$0 Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin Header merge Vary Origin &lt;/IfModule&gt; &lt;/FilesMatch&gt; </code></pre>
8,412,882
c# - Show a decimal to 6 decimal places
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/3059759/double-tostring-with-n-number-of-decimal-places">Double.ToString with N Number of Decimal Places</a> </p> </blockquote> <p>I want to show a decimal to 6 decimal places, even if it contains 6 x 0's For example:</p> <pre><code>3.000000 5.100000 3.456789 </code></pre> <p>and so forth, is this possible?</p>
8,412,895
2
2
null
2011-12-07 09:18:55.343 UTC
5
2011-12-07 09:23:24.427 UTC
2017-05-23 12:25:22.817 UTC
null
-1
null
1,005,030
null
1
15
c#
54,186
<p>Use <code>N6</code> as the <a href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx" rel="noreferrer">numeric format string</a>.</p> <pre><code>myDecimal.ToString("N6"); </code></pre> <p>or</p> <pre><code>string.Format("{0:N6}", myDecimal); </code></pre>
46,195,553
Component (unscoped) may not reference scoped bindings
<p>I've recently started using dagger-2 with kotlin. Unfortunately I have ecnountered a problem with sumbcomponants and I have trouble understanding why I get this gradle error:</p> <pre><code>...NetComponent (unscoped) may not reference scoped bindings: @dagger.Subcomponent(modules = {com.example.kremik.cryptodroid.di.module.NetModule.class}) @Singleton @Provides com.example.kremik.cryptodroid.data.remote.CMCService com.example.kremik.cryptodroid.di.module.NetModule.providesCMCService(retrofit2.Retrofit) @Singleton @Provides retrofit2.Retrofit com.example.kremik.cryptodroid.di.module.NetModule.providesRetrofit() @org.jetbrains.annotations.NotNull @Singleton @Provides com.example.kremik.cryptodroid.data.service.CurrencyDataPresenter com.example.kremik.cryptodroid.di.module.NetModule.providesCurrencyDataPresenter(com.example.kremik.cryptodroid.data.local.CurrenciesProvider, com.example.kremik.cryptodroid.ui.LivePrices.LivePricesPresenter) </code></pre> <p>Module:app</p> <pre><code>apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' android { compileSdkVersion 26 buildToolsVersion "26.0.1" defaultConfig { applicationId "com.example.kremik.cryptodroid" minSdkVersion 19 targetSdkVersion 26 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } configurations.all { resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9' } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } // dataBinding { // enabled = true // } kapt { generateStubs = true } } dependencies { (...) //Dagger2 implementation 'com.google.dagger:dagger:2.11' implementation 'com.google.dagger:dagger-android-support:2.11' implementation 'com.google.dagger:dagger-android-processor:2.11' kapt 'com.google.dagger:dagger-compiler:2.11' (...) } </code></pre> <p>NetModule: @Module class NetModule(private val BASE_URL: String) {</p> <pre><code>@Provides @Singleton fun providesCurrencyDataPresenter(provider: CurrenciesProvider, pricesPresenter: LivePricesPresenter) = CurrencyDataPresenter(provider, pricesPresenter) @Provides @Singleton fun providesRetrofit() = Retrofit.Builder() .baseUrl(BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() @Provides @Singleton fun providesCMCService(retrofit: Retrofit) = retrofit.create(CMCService::class.java) } </code></pre> <p>NetComponent:</p> <pre><code>@Subcomponent(modules = arrayOf(NetModule::class)) interface NetComponent { fun inject(service: CurrencyDownloaderService) } </code></pre> <p>Does anyone know what could be the issue ?</p>
47,120,351
1
6
null
2017-09-13 10:49:37.267 UTC
3
2017-11-05 10:10:14.593 UTC
null
null
null
null
8,352,819
null
1
39
android|kotlin|dagger-2
17,270
<p>Put @Singleton with your Component</p> <pre><code>@Singleton @Subcomponent(modules = arrayOf(NetModule::class)) interface NetComponent { fun inject(service: CurrencyDownloaderService) } </code></pre>
17,921,886
Update-Database fails due to Pending Changes, but Add-Migration Creates a Duplicate Migration
<p>I'm working with Entity Framework 5.0 Code First Migrations, and am having a problem with running Update-Database. It says there are pending model changes; but it should be up-to-date, so I run</p> <pre><code>Add-Migration SomeMigrationName </code></pre> <p>and it creates a file... however, it creates a file which is essentially the same a duplicate of a prior Migration (if I try to Update-Database again on that file, it fails with issues related to trying to drop a non-existent constraint). Furthermore, I have been able to confirm that the 'original' migration has been run based on both the data model in the DB, and from the presence of a record in the __MigrationHistory table!</p> <p>If I delete the whole database, and run all the migrations again, automatically or by hand, I have the same problem.</p> <p>The 'original' migration file I had is as follows:</p> <pre><code>public partial class RenameLinkColumns : DbMigration { public override void Up() { DropForeignKey("dbo.Listing", "OfferedByUserId", "dbo.User"); DropIndex("dbo.Listing", new[] { "OfferedByUserId" }); AddColumn("dbo.Listing", "ListedByUserId", c =&gt; c.Int(nullable: false)); AddForeignKey("dbo.Listing", "ListedByUserId", "dbo.User", "UserId", cascadeDelete: true); CreateIndex("dbo.Listing", "ListedByUserId"); DropColumn("dbo.Listing", "OfferedByUserId"); } public override void Down() { AddColumn("dbo.Listing", "OfferedByUserId", c =&gt; c.Int(nullable: false)); DropIndex("dbo.Listing", new[] { "ListedByUserId" }); DropForeignKey("dbo.Listing", "ListedByUserId", "dbo.User"); DropColumn("dbo.Listing", "ListedByUserId"); CreateIndex("dbo.Listing", "OfferedByUserId"); AddForeignKey("dbo.Listing", "OfferedByUserId", "dbo.User", "UserId", cascadeDelete: true); } } </code></pre> <p>When I ran that Add-Migration again, the Up/Down methods in that file are exactly the same as these.</p> <p>I'm quite impressed that migrations were correctly able to detect that I had renamed a ForeignKey column; but is that what is causing this to choke?</p> <p>It seems there is a work-around: I have deleted the database, and all migration files, and created a new 'Initial' Migration, but I would prefer not to do this if possible.</p> <p><strong>Update:</strong> This was <em>not</em> the latest migration that caused this issue, but the problem started after a merge (I am working alone, but am simulating team work on branches to learn more about git too), and trying to get the database in step with the merge. Might this have come about from placing migrations in some particular order after a merge - though a noted, the migrations <em>did</em> work as expected in the order they ran when I gave them an empty DB.</p> <p>Additionally, this original migration needed manually tweaking when the tables had data in, because data needed to be copied from the old to the new column. However, I tested that file with and without my manual edits in that file, and still encountered the behaviour noted.</p>
27,962,520
5
0
null
2013-07-29 10:38:47.857 UTC
5
2019-09-12 10:23:48.853 UTC
2013-07-29 14:52:23.797 UTC
null
6,004
null
6,004
null
1
32
c#|entity-framework|entity-framework-migrations
12,027
<p><a href="https://stackoverflow.com/questions/19136066/why-does-add-migration-sometimes-create-duplicate-migrations">This answer explains why it happens</a>. To resolve it I call <code>add-migration</code> and name it <code>MERGE</code> and then remove any duplicate migration code that has already happened. This is just to update the model snapshot to reflect the merged model.</p> <p>Example:</p> <pre><code>public partial class MERGE : DbMigration { public override void Up() { // Intentionally left blank. // This may seem like a hack, but it is necessary when using source control. // When a migration is created via add-migration, EF creates // an .edmx file from the current code first classes. It compares this .edmx to the .edmx stored in the last migration before this, // which I'll call it's parent migration. The edmx snapshots are gzipped and stored in base64 in the resource files (.resx) if you // want to see them. EF uses the difference between these two snapshots to determine what needs to be migrated. // When using source control it will happen that two users add entities to the model independently. The generated edmx snapshots will // only have the changes that they have made. When they merge in source control, they will end up with this: // Migration | Snapshot Contents // -------------------------------- | ---------------- // 20150101_Parent Migration | A // 20150102_Developer 1's Migration | A + Change 1 // 20150103_Developer 2's Migration | A + Change 2 // So calling add-migration will create the current snapshot edmx from the Code First model and compare it to the // the latest migration's snapshot, which is A + Change 2, and see that Change 1 is missing. That is why it // creates a duplicate migration. We know that the migrations have already been applied, so the only thing that this // migration will do is update the current snapshot .edmx so that later migrations work fine. } public override void Down() { } } </code></pre>
17,996,957
fe_sendauth: no password supplied
<p>database.yml:</p> <pre><code># SQLite version 3.x # gem install sqlite3 # # Ensure the SQLite 3 gem is defined in your Gemfile # gem 'sqlite3' development: adapter: postgresql encoding: utf8 database: sampleapp_dev #can be anything unique #host: localhost #username: 7stud #password: #adapter: sqlite3 #database: db/development.sqlite3 pool: 5 timeout: 5000 # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: adapter: postgresql encoding: utf8 database: sampleapp_test #can be anything unique #host: localhost #username: 7stud #password: #adapter: sqlite3 #database: db/test.sqlite3 pool: 5 timeout: 5000 production: adapter: postgresql database: sampleapp_prod #can be anything unique #host: localhost #username: 7stud #password: #adapter: sqlite3 #database: db/production.sqlite3 pool: 5 timeout: 5000 </code></pre> <p>pg_hba.conf:</p> <pre><code># TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all trust # IPv4 local connections: host all all 127.0.0.1/32 trust # IPv6 local connections: host all all ::1/128 trust # Allow replication connections from localhost, by a user with the # replication privilege. #local replication postgres md5 #host replication postgres 127.0.0.1/32 md5 #host replication postgres ::1/128 md5 </code></pre> <p>I changed the METHOD in the first three lines from md5 to trust, but I still get the error.</p> <p>And no matter what combinations of things I try in database.yml, when I do:</p> <pre><code>~/rails_projects/sample_app4_0$ bundle exec rake db:create:all </code></pre> <p>I always get the error:</p> <blockquote> <p>fe_sendauth: no password supplied</p> </blockquote> <p>I followed this tutorial to get things setup:</p> <p><a href="https://pragtob.wordpress.com/2012/09/12/setting-up-postgresql-for-ruby-on-rails-on-linux">https://pragtob.wordpress.com/2012/09/12/setting-up-postgresql-for-ruby-on-rails-on-linux</a></p> <pre><code>Mac OSX 10.6.8 PostgreSQL 9.2.4 installed via enterpriseDB installer Install dir: /Library/PostgreSQL/9.2 </code></pre>
17,997,528
6
5
null
2013-08-01 14:31:44.087 UTC
20
2022-06-26 15:41:40.743 UTC
2013-08-01 14:37:37.017 UTC
null
926,143
null
926,143
null
1
103
postgresql|ruby-on-rails-4
331,305
<p>After making changes to the <code>pg_hba.conf</code> or <code>postgresql.conf</code> files, the cluster needs to be reloaded to pick up the changes.</p> <p>From the command line: <code>pg_ctl reload</code></p> <p>From within a db (as superuser): <code>select pg_reload_conf();</code></p> <p>From PGAdmin: right-click db name, select "Reload Configuration"</p> <p>Note: the reload is not sufficient for changes like enabling archiving, changing <code>shared_buffers</code>, etc -- those require a cluster restart.</p>
41,743,253
What's the point of input type in GraphQL?
<p>Could you please explain why if input argument of mutation is object it should be <strong>input type</strong>? I think much simpler just reuse <strong>type</strong> without providing id.</p> <p>For example:</p> <pre><code>type Sample { id: String name: String } input SampleInput { name: String } type RootMutation { addSample(sample: Sample): Sample # &lt;-- instead of it should be addSample(sample: SampleInput): Sample } </code></pre> <p>It's okay for small object, but when you have plenty of objects with 10+ properties in schema that'll become a burden.</p>
55,881,719
3
3
null
2017-01-19 13:42:50.167 UTC
29
2022-04-11 02:35:42.657 UTC
2018-12-24 07:05:44.667 UTC
null
297,939
null
297,939
null
1
154
graphql
52,580
<p>From the spec:</p> <blockquote> <p>The GraphQL Object type (ObjectTypeDefinition)... is inappropriate for re‐use [as an input], because Object types can contain fields that define arguments or contain references to interfaces and unions, neither of which is appropriate for use as an input argument. For this reason, input objects have a separate type in the system.</p> </blockquote> <p>That's the "official reason", but there's several practical reasons why you can't use an object type as an input object type or use an object type as an input object type:</p> <h3>Functionality</h3> <p>Object types and input object types both have fields, however those fields have different properties that reflect how these types are used by the schema. Your schema will potentially define arguments and some kind of resolver function for an object type's fields, but these properties don't make sense in an input context (i.e. you can't <em>resolve</em> an input object's field -- it already has an explicit value). Similarly, default values can only be provided for input object type fields, and not object type fields.</p> <p>In other words, this may seem like duplication:</p> <pre><code>type Student { name: String grade: Grade } input StudentInput { name: String grade: Grade } </code></pre> <p>But adding features specific to either object types or input object types makes it clear that they behave differently:</p> <pre><code>type Student { name(preferred: Boolean): String grade: Grade } input StudentInput { name: String grade: Grade = F } </code></pre> <h3>Type system limitations</h3> <p>Types in GraphQL are grouped into <em>output types</em> and <em>input types</em>.</p> <p>Output types are types that may be returned as part of a response produced by a GraphQL service. Input types are types that are valid inputs for field or directive arguments.</p> <p>There's overlap between these two groups (i.e. scalars, enums, lists and non-nulls). However, <em>abstract types</em> like unions and interfaces don't make sense in an input context and cannot be used as inputs. Separating object types and input object types allows you to ensure that an abstract type is never used where an input type is expected.</p> <h3>Schema design</h3> <p>When representing an entity in your schema, it's likely that some entities will indeed "share fields" between their respective input and output types:</p> <pre><code>type Student { firstName: String lastName: String grade: Grade } input StudentInput { firstName: String lastName: String grade: Grade } </code></pre> <p>However, object types can (and in reality frequently do) model very complex data structures:</p> <pre><code>type Student { fullName: String! classes: [Class!]! address: Address! emergencyContact: Contact # etc } </code></pre> <p>While these structures <em>may</em> translate into appropriate inputs (we create a Student, so we also pass in an object representing their address), often they do not -- i.e. maybe we need to specify the student's classes by class ID and section ID, not an object. Similarly, we may have fields that we want to return, but don't want to mutate, or vice versa (like a <code>password</code> field).</p> <p>Moreover, even for relatively simple entities, we often have different requirements around nullability between object types and their "counterpart" input objects. Often we want to guarantee that a field will also be returned in a response, but we don't want to make the same fields required in our input. For example,</p> <pre><code>type Student { firstName: String! lastName: String! } input StudentInput { firstName: String lastName: String } </code></pre> <p>Lastly, in many schemas, there's often not a one-to-one mapping between object type and input object type for a given entity. A common pattern is to utilize separate input object types for different operations to further fine-tune the schema-level input validation:</p> <pre><code>input CreateUserInput { firstName: String! lastName: String! email: String! password: String! } input UpdateUserInput { email: String password: String } </code></pre> <p>All of these examples illustrate an important point -- while an input object type may mirror an object type some of the time, you're much less likely to see that in production schemas due to business requirements.</p>
7,001,320
mysql_fetch_array return only one row
<p>Ok, I have the following code:</p> <pre><code>$array = mysql_query("SELECT artist FROM directory WHERE artist LIKE 'a%' OR artist LIKE 'b%' OR artist LIKE 'c%'"); $array_result= mysql_fetch_array($array); </code></pre> <p>Then, when I try to echo the contents, I can only echo <code>$array_result[0];</code>, which outputs the first item, but if I try to echo <code>$array_result[1];</code> I get an undefined offset.</p> <p>Yet if I run the above query through PHPMyAdmin it returns a list of 10 items. Why is this not recognized as an array of 10 items, allowing me to echo 0-9?</p> <p>Thanks for the help.</p>
7,001,347
3
1
null
2011-08-09 18:49:19.9 UTC
0
2014-04-01 05:14:36.97 UTC
2011-08-09 18:54:01.873 UTC
null
768,110
null
868,437
null
1
2
php|mysql|fetch
43,446
<p>That's because the array represents a single row in the returned result set. You need to execute the <a href="http://php.net/manual/en/function.mysql-fetch-array.php" rel="noreferrer"><code>mysql_fetch_array()</code> function</a> again to get the next record. Example:</p> <pre><code>while($data = mysql_fetch_array($array)) { //will output all data on each loop. var_dump($data); } </code></pre>
6,680,430
Get unique results from JSON array using jQuery
<p>I have this block of code that displays the "categories" from my array into a JQuery simple list.</p> <p>It works fine, but if there are 3 items from the category "basketball", the category will appear 3 times.</p> <p>How could I make it so they only appear once ? Thank you.</p> <p>Here's the code :</p> <pre><code>function loadCategories() { console.debug('About to refresh with sort type : ' + sortType); var items = []; $.each(catalog.products, function(index, value) { items.push('&lt;li id="' + index + '"&gt;' + '&lt;a data-identity="productId" href="./productList.page?category=' + value.category + '" &gt;' + '&lt;p style="margin-bottom:0px;margin-top:0px;"&gt;' + value.category + '&lt;/p&gt;&lt;/a&gt; &lt;/li&gt;'); } ); categoryView.html(items.join('')); categoryView.listview('refresh'); } </code></pre> <p>Here's the code for my array :</p> <pre><code>var catalog = {"products": [ {"id": "10001", "name": "Mountain bike", "color": "Grey/Black", "long-desc": "12-speed, carbon mountain bike.", "description": "", "size": "20 inches", "category": "Outdoors/ Equipment rental", "sport": "Cycling", "brand": "DaVinci", "top-seller": ""}, {"id": "10002", "name": "Pro Multi Basketball", "color": "Rainbow", "long-desc": "On sale this week only! This limited edition basketball is multi-coloured, and offers pro performance. Fun and games on the court!", "description": "Limited edition basketball.", "size": "N/A", "category": "Team gear", "sport": "Basketball", "brand": "Nike", "top-seller": "x"}, </code></pre>
6,680,842
3
0
null
2011-07-13 14:21:57.613 UTC
7
2018-04-19 06:21:03.953 UTC
2011-07-13 15:02:50.307 UTC
null
821,641
null
821,641
null
1
12
javascript|jquery|arrays|json
49,716
<p>I don't know how your <code>products</code> array is built up (so my example might need some modification according to your needs), but you could write a little piece of code that will first collect your unique categories into a new array:</p> <pre><code>var categories = []; $.each(catalog.products, function(index, value) { if ($.inArray(value.category, categories) === -1) { categories.push(value.category); } }); </code></pre> <p><a href="http://jsfiddle.net/3wHfB/" rel="noreferrer">jsFiddle Demo</a></p> <p><code>categories</code> will hold the unique categories you need, you can use it to build your HTML from that (be careful with the IDs of those <code>li</code> elements though, remember that IDs cannot be duplicate, you might give them a little prefix).</p>
6,952,173
Get image src with jQuery
<pre><code>&lt;img src="../img/arnold.png" alt="Arnold"&gt; </code></pre> <p>How do I get with jQuery absolute path of this image? </p> <p><code>img.attr("src")</code> gives me just "<strong>../img/arnold.png</strong>", should give something like "<strong>http://site.com/data/2011/img/arnold.png</strong>" (full url).</p>
6,952,240
3
1
null
2011-08-05 06:14:08.58 UTC
8
2016-07-05 10:08:19.51 UTC
null
null
null
null
723,627
null
1
27
javascript|jquery|html|css|image
92,894
<pre><code>alert( $('img')[0].src ); </code></pre> <p>this might do the trick... but not sure about cross browser....</p> <p><a href="http://jsfiddle.net/reigel/H6vBx/" rel="noreferrer">demo in here</a></p> <p>also try <a href="http://api.jquery.com/prop" rel="noreferrer">prop</a> of jQuery 1.6..</p> <pre><code>alert( $('img').prop('src') ); </code></pre> <p><a href="http://jsfiddle.net/reigel/caVYd/" rel="noreferrer">demo here</a></p>
6,935,828
Viewbag check to see if item exists and write out html and value error
<p>I'm using razor syntax and I want to check to see if certain ViewBag values are set before I spit out the html. If a value is set then I want to write it out. If not I want it to do nothing.</p> <pre><code>@if (ViewBag.UserExists != null) { Response.Write(String.Format("&lt;h3&gt;{0}&lt;/h3&gt;", ViewBag.UserExists)); } </code></pre> <p>This doesn't appear to be working correctly. The code shows up on top of another h2 I have above the code above. I have two register controller methods. One is the get and the other accepts the post. If the user exists I am setting a ViewBag item that needs to be displayed to the user.</p> <p>Thanks</p>
6,935,907
3
0
null
2011-08-04 03:20:08.16 UTC
2
2018-10-05 16:15:00.737 UTC
2013-10-08 12:52:34.25 UTC
null
27,756
null
734,587
null
1
36
c#|asp.net-mvc|viewbag
78,194
<p>Don't use Response.Write. Instead do this:</p> <pre><code>@if (ViewBag.UserExists != null) { &lt;h3&gt;@ViewBag.UserExists&lt;/h3&gt; } </code></pre>
23,824,397
Get list of users with assigned roles in asp.net identity 2.0
<p>I have a drop down list box which lists roles. I want to get the list of users having that role. I mean list of users that are in "Administrator" role or "CanEdit" role. Here is my code:</p> <pre><code>public IQueryable&lt;Microsoft.AspNet.Identity.EntityFramework.IdentityUser&gt; GetRolesToUsers([Control] string ddlRole) { //ddlRole returns role Id, based on this Id I want to list users var _db = new ApplicationDbContext(); IQueryable&lt;Microsoft.AspNet.Identity.EntityFramework.IdentityUser&gt; query = _db.Users; if (ddlRole != null) { //query = query.Where(e =&gt; e.Claims == ddlRole.Value); ??????? } return query; } </code></pre> <p>Please help.</p> <p><strong>Updated Code (still error)</strong></p> <pre><code>public List&lt;IdentityUserRole&gt; GetRolesToUsers([Control]string ddlRole) { var roleManager = new RoleManager&lt;IdentityRole&gt;(new RoleStore&lt;IdentityRole&gt;(new ApplicationDbContext())); var users = roleManager.FindByName("Administrator").Users.ToList(); return users; } </code></pre> <p>Error: The Select Method must return one of "IQueryable" or "IEnumerable" or "Microsoft.AspNet.Identity.EntityFramework.IdentityUser" when ItemType is set to "Microsoft.AspNet.Identity.EntityFramework.IdentityUser".</p> <p>I tried various castings but none of them helped.</p> <p><strong>UPDATE (working solution)</strong></p> <p>Thanks to chris544, his idea helped me to fix this. Here is working method:-</p> <pre><code>public List&lt;ApplicationUser&gt; GetRolesToUsers([Control]string ddlRole) { var context = new ApplicationDbContext(); var users = context.Users.Where(x =&gt; x.Roles.Select(y =&gt; y.RoleId).Contains(ddlRole)).ToList(); return users; } </code></pre>
23,854,281
8
4
null
2014-05-23 08:27:23.647 UTC
12
2018-07-02 19:43:51.867 UTC
2017-12-02 18:44:58.827 UTC
null
75,500
null
1,386,991
null
1
33
asp.net|asp.net-mvc|asp.net-mvc-4|asp.net-identity|asp.net-identity-2
55,074
<p>Not an expert, but ...</p> <p>There seemed to be no built in funcionality for this in Identity and I could not get it work from built in Roles also (it seems to not work with claims based Identity).</p> <p>So I ended up doing something like this:</p> <pre><code>var users = context.Users .Where(x =&gt; x.Roles.Select(y =&gt; y.Id).Contains(roleId)) .ToList(); </code></pre> <ul> <li><code>x.Roles.Select(y =&gt; y.Id)</code> gets a list of all role ids for <code>user x</code></li> <li><code>.Contains(roleId)</code> checks if this list of ids contains necessary <code>roleId</code></li> </ul>
4,998,757
moving elements with jquery
<p>How can I use jQuery to move an element from:</p> <pre><code>position: absolute; left: 169px; top: 182px; </code></pre> <p>to:</p> <pre><code>position: absolute; left: 169px; top: 230px; </code></pre> <p>with clear moving so not just css, it has to be moving.</p> <p>Thanks.</p>
4,998,786
2
0
null
2011-02-15 00:06:10.92 UTC
2
2011-02-15 00:16:02.907 UTC
2011-02-15 00:12:21.137 UTC
null
405,143
null
603,951
null
1
7
jquery
41,589
<p><a href="http://api.jquery.com/animate/" rel="noreferrer">http://api.jquery.com/animate/</a></p> <p>Demo: <a href="http://jsfiddle.net/pHwMK/" rel="noreferrer">http://jsfiddle.net/pHwMK/</a></p> <p>JS:</p> <pre><code>$(function() { $("div.ele").animate({ top: '230px' }); });</code></pre>
5,270,917
Why doesn't my global .gitignore file ignore?
<pre><code>$ cat ~/.gitconfig [core] editor = vim excludefiles = /home/augustin/.gitignore $ cat ~/.gitignore toto $ mkdir git_test $ cd git_test/ $ git init $ touch toto $ git status # On branch master # # Initial commit # # Untracked files: # (use "git add &lt;file&gt;..." to include in what will be committed) # # toto nothing added to commit but untracked files present (use "git add" to track) $ git --version git version 1.6.3.3 </code></pre> <p>Why isn't toto being ignored?</p> <p>Other settings in ~/.gitconfig are taken into account (colors, editor). </p>
5,271,411
2
3
null
2011-03-11 09:05:23.897 UTC
17
2018-09-10 19:53:21.7 UTC
2011-03-11 09:13:51.137 UTC
null
401,523
null
401,523
null
1
49
gitignore
22,444
<p><code>git config --global core.excludesfile ~/.gitignore</code></p>
16,182,915
Open link in Popup Window with Javascript
<p>I'm trying to load a href into a popup window of specific dimensions which also centers in the screen. </p> <p>Here is my source:</p> <pre><code>&lt;li&gt; &lt;a class="sprite_stumbleupon" href="http://www.stumbleupon.com/submit?url=http://www.your_web_page_url" target="_blank" onclick="return windowpop(545, 433)"&gt;&lt;/a&gt; &lt;/li&gt; </code></pre> <p>And here is my javascript:</p> <pre><code>function windowpop(url, width, height) { var leftPosition, topPosition; //Allow for borders. leftPosition = (window.screen.width / 2) - ((width / 2) + 10); //Allow for title and status bars. topPosition = (window.screen.height / 2) - ((height / 2) + 50); //Open the window. window.open(url, "Window2", "status=no,height=" + height + ",width=" + width + ",resizable=yes,left=" + leftPosition + ",top=" + topPosition + ",screenX=" + leftPosition + ",screenY=" + topPosition + ",toolbar=no,menubar=no,scrollbars=no,location=no,directories=no"); } </code></pre> <p>This seems to return a 404 error when tested. What am i doing wrong?</p> <p>Thanks heaps. </p>
16,183,028
1
3
null
2013-04-24 03:34:42.643 UTC
8
2022-04-08 12:05:54.603 UTC
2013-04-24 03:47:21.827 UTC
null
283,863
null
2,105,885
null
1
11
javascript|html|hyperlink|popup|modal-dialog
73,250
<p><code>function windowpop(url, width, height)</code> The function requires a URL to be returned to it.</p> <p><code>onclick=&quot;return windowpop(545, 433)&quot;</code> You're only returning the <code>width</code> and <code>height</code>.</p> <p>Try returning the URL using <code>this.href</code>:</p> <pre><code>onclick=&quot;return windowpop(this.href, 545, 433)&quot; </code></pre> <pre class="lang-html prettyprint-override"><code>&lt;script&gt; function windowpop(url, width, height) { var left = (screen.width / 2) - (width / 2); var top = (screen.height / 2) - (height / 2); window.open(url, &quot;&quot;, &quot;menubar=no,toolbar=no,status=no,width=&quot; + width + &quot;,height=&quot; + height + &quot;,top=&quot; + top + &quot;,left=&quot; + left); } &lt;/script&gt; </code></pre>
1,216,002
Fractal Encryption
<p>I've heard that one can encrypt data using drawings of the Mandlebrot set, and that this encryption algorithm is quantum-safe (can't be broken with a quantum computer, unlike many commonly-used algorithms). I looked around on Google for more information but I've only come across some articles intended for a more non-technical audience. Does anyone have any sources on this that I could use to learn more about this fascinating subject?</p>
1,250,389
7
7
null
2009-08-01 06:51:33.97 UTC
12
2017-09-13 19:23:02.43 UTC
2017-07-22 15:23:19.103 UTC
null
109,122
null
130,640
null
1
19
algorithm|encryption|fractals
12,487
<p>Here's a general article outlining the process:</p> <p><a href="http://www.techbriefs.com/content/view/2579/32/" rel="noreferrer">http://www.techbriefs.com/content/view/2579/32/</a></p> <p>This is more in-depth, providing an algorithm and examples:</p> <p><a href="http://medwelljournals.com/fulltext/ajit/2007/567-575.pdf" rel="noreferrer">http://medwelljournals.com/fulltext/ajit/2007/567-575.pdf</a><br> (alternate URL): <a href="http://docsdrive.com/pdfs/medwelljournals/ajit/2007/567-575.pdf" rel="noreferrer">http://docsdrive.com/pdfs/medwelljournals/ajit/2007/567-575.pdf</a></p> <p>There is some discussion of it on the sci.crypt group:</p> <p><a href="http://groups.google.com/group/sci.crypt/browse_thread/thread/f7ce14c1f6c0df3f/559895f2f267644?hl=en&amp;ie=UTF-8&amp;q=mandelbrot+fractal+encryption+algorithm" rel="noreferrer">http://groups.google.com/group/sci.crypt/browse_thread/thread/f7ce14c1f6c0df3f/559895f2f267644?hl=en&amp;ie=UTF-8&amp;q=mandelbrot+fractal+encryption+algorithm</a></p> <p>And here's a company in Japan that is offering code and samples (it looks like the package costs $50):</p> <p><a href="http://www.summersoftlabs.com/intro.htm" rel="noreferrer">http://www.summersoftlabs.com/intro.htm</a></p> <p>This was the result of a few minutes poking around, so your mileage may vary. The topic sounds interesting, though. Even if it isn't immediately practical, it's nice that there are researchers thinking of different approaches to the problem.</p>
511,694
Get list of variables whose name matches a certain pattern
<p>In bash </p> <pre><code>echo ${!X*} </code></pre> <p>will print all the names of the variables whose name starts with 'X'.<br> Is it possible to get the same with an arbitrary pattern, e.g. get all the names of the variables whose name contains an 'X' in any position?</p>
511,937
7
0
null
2009-02-04 14:55:40.13 UTC
11
2022-07-09 15:41:37.78 UTC
2019-03-30 21:37:42.19 UTC
null
6,862,601
orsogufo
15,622
null
1
51
bash|variables|scripting
28,252
<p>Use the builtin command compgen:</p> <pre><code>compgen -A variable | grep X </code></pre>
1,302,072
How can I get the HTTP status code out of a ServletResponse in a ServletFilter?
<p>I'm trying to report on every HTTP status code returned from my webapp. However the status code does not appear to be accessible via the ServletResponse, or even if I cast it to a HttpServletResponse. Is there a way to get access to this value within a ServletFilter?</p>
1,302,165
7
0
null
2009-08-19 19:17:17.953 UTC
24
2013-01-03 14:18:44.193 UTC
2011-08-17 08:55:44.17 UTC
null
142,983
null
5,586
null
1
65
java|servlets|servlet-filters|http-status-codes
88,343
<p>First, you need to save the status code in an accessible place. The best to wrap the response with your implementation and keep it there:</p> <pre><code>public class StatusExposingServletResponse extends HttpServletResponseWrapper { private int httpStatus; public StatusExposingServletResponse(HttpServletResponse response) { super(response); } @Override public void sendError(int sc) throws IOException { httpStatus = sc; super.sendError(sc); } @Override public void sendError(int sc, String msg) throws IOException { httpStatus = sc; super.sendError(sc, msg); } @Override public void setStatus(int sc) { httpStatus = sc; super.setStatus(sc); } public int getStatus() { return httpStatus; } } </code></pre> <p>In order to use this wrapper, you need to add a servlet filter, were you can do your reporting:</p> <pre><code>public class StatusReportingFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { StatusExposingServletResponse response = new StatusExposingServletResponse((HttpServletResponse)res); chain.doFilter(req, response); int status = response.getStatus(); // report } public void init(FilterConfig config) throws ServletException { //empty } public void destroy() { // empty } } </code></pre>
1,252,998
How can I compile LaTeX in UTF8?
<p>I did my document in an ISO-standard. It does not support umlaut alphabets, such as ä and ö. I need them. The document gets compiled without UTF8, but not with UTF8. More precisely, the document does not get compiled with the line at the beginning of my main.tex:</p> <pre><code>\usepackage[utf8]{inputenc} </code></pre> <p>How can I compile my LaTeX document in UTF8?</p>
1,253,024
7
0
null
2009-08-10 03:27:21.62 UTC
11
2013-08-12 23:41:44.9 UTC
2010-07-14 13:11:28.517 UTC
null
14,343
null
54,964
null
1
84
latex|utf-8
160,441
<p>I'm not sure whether I got your problem but maybe it helps if you store the source using a UTF-8 encoding. </p> <p>I'm also using <code>\usepackage[utf8]{inputenc}</code> in my LaTeX sources and by storing the files as UTF-8 files everything works just peachy.</p>
548,063
kill a process started with popen
<p>After opening a pipe to a process with <code>popen</code>, is there a way to kill the process that has been started? (Using <code>pclose</code> is not what I want because that will wait for the process to finish, but I need to kill it.)</p>
548,148
8
0
null
2009-02-13 23:16:18.397 UTC
17
2019-09-05 11:14:31.177 UTC
2013-12-21 04:45:39.537 UTC
null
49,485
Ben Alpert
49,485
null
1
23
c|multithreading|kill|popen
27,451
<p>Don't use <code>popen()</code>, write your own wrapper that does what you'd like. </p> <p>It's fairly straightforward to <code>fork()</code>, and then replace <code>stdin</code> &amp; <code>stdout</code> by using <code>dup2()</code>, and then calling <code>exec()</code> on your child.</p> <p>That way, your parent will have the exact child PID, and you can use <code>kill()</code> on that.</p> <p>Google search for "popen2() implementation" for some sample code on how to implement what <code>popen()</code> is doing. It's only a dozen or so lines long. Taken from <a href="http://snippets.dzone.com/posts/show/1134" rel="nofollow noreferrer">dzone.com</a> we can see an example that looks like this:</p> <pre><code>#define READ 0 #define WRITE 1 pid_t popen2(const char *command, int *infp, int *outfp) { int p_stdin[2], p_stdout[2]; pid_t pid; if (pipe(p_stdin) != 0 || pipe(p_stdout) != 0) return -1; pid = fork(); if (pid &lt; 0) return pid; else if (pid == 0) { close(p_stdin[WRITE]); dup2(p_stdin[READ], READ); close(p_stdout[READ]); dup2(p_stdout[WRITE], WRITE); execl("/bin/sh", "sh", "-c", command, NULL); perror("execl"); exit(1); } if (infp == NULL) close(p_stdin[WRITE]); else *infp = p_stdin[WRITE]; if (outfp == NULL) close(p_stdout[READ]); else *outfp = p_stdout[READ]; return pid; } </code></pre> <p>NB: Seems like popen2() is what you want, but my distribution doesn't seem to come with this method. </p>
321,113
How can I pre-set arguments in JavaScript function call? (Partial Function Application)
<p>I am trying to write a JavaScript function that will return its first argument(function) with all the rest of its arguments as preset parameters to that function.</p> <p>So:</p> <pre>function out(a, b) { document.write(a + " " + b); } function setter(...) {...} setter(out, "hello")("world"); setter(out, "hello", "world")(); </pre> <p>Would output "hello world" twice. for some implementation of setter</p> <p>I ran into an issue with manipulating the arguments array on my first try, but it seems there would be a better way to do this.</p>
321,527
8
1
null
2008-11-26 15:33:10.59 UTC
31
2021-07-04 17:18:19.967 UTC
2008-11-26 21:22:21.587 UTC
Jason Bunting
1,790
AlexH
40,397
null
1
53
javascript|functional-programming
26,491
<p>First of all, you need a partial - <a href="https://stackoverflow.com/questions/218025/what-is-the-difference-between-currying-and-partial-application"><strong>there is a difference between a partial and a curry</strong></a> - and here is all you need, <em>without a framework</em>:</p> <pre><code>function partial(func /*, 0..n args */) { var args = Array.prototype.slice.call(arguments, 1); return function() { var allArguments = args.concat(Array.prototype.slice.call(arguments)); return func.apply(this, allArguments); }; } </code></pre> <p>Now, using your example, you can do exactly what you are after:</p> <pre><code>partial(out, "hello")("world"); partial(out, "hello", "world")(); // and here is my own extended example var sayHelloTo = partial(out, "Hello"); sayHelloTo("World"); sayHelloTo("Alex"); </code></pre> <p>The <code>partial()</code> function could be used to implement, but <em>is not</em> currying. Here is a quote from <a href="http://www.uncarved.com/blog/not_currying.mrk" rel="noreferrer"><strong>a blog post on the difference</strong></a>:</p> <blockquote> <p>Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.</p> </blockquote> <p>Hope that helps.</p>
324,053
Find out the size of a .NET object
<p>I'm trying to find out how much memory my objects take to see how many of them are ending up on the <a href="https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/large-object-heap" rel="nofollow noreferrer">Large Object Heap</a> (which is anything over 85,000 bytes).</p> <p>Is it as simple as adding 4 for an int, 8 for a long, 4 (or 8 if you're on 64 bit) for any reference types etc for each object, or are there overheads for methods, properties, etc.?</p>
324,090
8
2
null
2008-11-27 15:38:10.593 UTC
27
2022-01-19 08:00:18.763 UTC
2020-11-21 23:14:58.257 UTC
null
63,550
mat1t
6,713
null
1
57
.net|memory-management|garbage-collection|profiling
55,521
<p>Don't forget that the size of an actual object doesn't include the size of any objects it references.</p> <p>The only things which are likely to end up on the large object heap are arrays and strings - other objects tends to be relatively small in themselves. Even an object with (say) 10 reference type variables (4 bytes each on x86) and 10 GUIDs (16 bytes each) is only going to take up about 208 bytes (there's a bit of overhead for the type reference and sync block).</p> <p>Likewise when thinking about the size of an array, don't forget that if the element type is a reference type, then it's only the size of the <em>references</em> that count for the array itself. In other words, even if you've got an array with 20,000 elements, the size of the array object itself will only be just over 80K (on x86) even if it references a lot more data.</p>
307,512
How do I apply OrderBy on an IQueryable using a string column name within a generic extension method?
<pre><code>public static IQueryable&lt;TResult&gt; ApplySortFilter&lt;T, TResult&gt;(this IQueryable&lt;T&gt; query, string columnName) where T : EntityObject { var param = Expression.Parameter(typeof(T), "o"); var body = Expression.PropertyOrField(param,columnName); var sortExpression = Expression.Lambda(body, param); return query.OrderBy(sortExpression); } </code></pre> <p>Because the type for OrderBy is not inferred from sortExpression I need to specify it something like this at run time:</p> <pre><code>var sortExpression = Expression.Lambda&lt;T, TSortColumn&gt;(body, param); </code></pre> <p>Or</p> <pre><code>return query.OrderBy&lt;T, TSortColumn&gt;(sortExpression); </code></pre> <p>I don't think this is possible however as TSortColumn can only be determined during runtime.</p> <p>Is there a way around this?</p>
307,600
8
2
null
2008-11-21 01:15:44.067 UTC
46
2018-10-04 19:34:14.097 UTC
2012-05-24 12:41:08.983 UTC
JTew
31,532
JTew
25,372
null
1
89
c#|.net|linq|entity-framework|expression-trees
94,145
<p>We did something similar (not 100% the same, but similar) in a LINQ to SQL project. Here's the code:</p> <pre><code>public static IQueryable&lt;T&gt; OrderBy&lt;T&gt;(this IQueryable&lt;T&gt; source, string ordering, params object[] values) { var type = typeof(T); var property = type.GetProperty(ordering); var parameter = Expression.Parameter(type, "p"); var propertyAccess = Expression.MakeMemberAccess(parameter, property); var orderByExp = Expression.Lambda(propertyAccess, parameter); MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp)); return source.Provider.CreateQuery&lt;T&gt;(resultExp); } </code></pre> <p>We didn't actually use a generic, we had a known class, but it should work on a generic (I've put the generic placeholder where it should be).</p> <p><strong>Edit:</strong> For descending order, pass in <code>OrderByDescending</code> instead of "OrderBy":</p> <pre><code>MethodCallExpression resultExp = Expression.Call(typeof(Queryable), "OrderByDescending", new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExp)); </code></pre>
78,497
Design patterns or best practices for shell scripts
<p>Does anyone know of any resources that talk about best practices or design patterns for shell scripts (sh, bash etc.)?</p>
739,034
8
1
null
2008-09-17 00:00:03.273 UTC
185
2017-02-14 15:47:46.553 UTC
2017-02-14 15:47:46.553 UTC
null
3,924,118
null
14,437
null
1
184
design-patterns|bash|shell
75,005
<p>I wrote quite complex shell scripts and my first suggestion is "don't". The reason is that is fairly easy to make a small mistake that hinders your script, or even make it dangerous.</p> <p>That said, I don't have other resources to pass you but my personal experience. Here is what I normally do, which is overkill, but tends to be solid, although <em>very</em> verbose.</p> <p><strong>Invocation</strong></p> <p>make your script accept long and short options. be careful because there are two commands to parse options, getopt and getopts. Use getopt as you face less trouble.</p> <pre><code>CommandLineOptions__config_file="" CommandLineOptions__debug_level="" getopt_results=`getopt -s bash -o c:d:: --long config_file:,debug_level:: -- "$@"` if test $? != 0 then echo "unrecognized option" exit 1 fi eval set -- "$getopt_results" while true do case "$1" in --config_file) CommandLineOptions__config_file="$2"; shift 2; ;; --debug_level) CommandLineOptions__debug_level="$2"; shift 2; ;; --) shift break ;; *) echo "$0: unparseable option $1" EXCEPTION=$Main__ParameterException EXCEPTION_MSG="unparseable option $1" exit 1 ;; esac done if test "x$CommandLineOptions__config_file" == "x" then echo "$0: missing config_file parameter" EXCEPTION=$Main__ParameterException EXCEPTION_MSG="missing config_file parameter" exit 1 fi </code></pre> <p>Another important point is that a program should always return zero if completes successfully, non-zero if something went wrong.</p> <p><strong>Function calls</strong></p> <p>You can call functions in bash, just remember to define them before the call. Functions are like scripts, they can only return numeric values. This means that you have to invent a different strategy to return string values. My strategy is to use a variable called RESULT to store the result, and returning 0 if the function completed cleanly. Also, you can raise exceptions if you are returning a value different from zero, and then set two "exception variables" (mine: EXCEPTION and EXCEPTION_MSG), the first containing the exception type and the second a human readable message.</p> <p>When you call a function, the parameters of the function are assigned to the special vars $0, $1 etc. I suggest you to put them into more meaningful names. declare the variables inside the function as local:</p> <pre><code>function foo { local bar="$0" } </code></pre> <p><strong>Error prone situations</strong></p> <p>In bash, unless you declare otherwise, an unset variable is used as an empty string. This is very dangerous in case of typo, as the badly typed variable will not be reported, and it will be evaluated as empty. use</p> <pre><code>set -o nounset </code></pre> <p>to prevent this to happen. Be careful though, because if you do this, the program will abort every time you evaluate an undefined variable. For this reason, the only way to check if a variable is not defined is the following:</p> <pre><code>if test "x${foo:-notset}" == "xnotset" then echo "foo not set" fi </code></pre> <p>You can declare variables as readonly:</p> <pre><code>readonly readonly_var="foo" </code></pre> <p><strong>Modularization</strong></p> <p>You can achieve "python like" modularization if you use the following code:</p> <pre><code>set -o nounset function getScriptAbsoluteDir { # @description used to get the script path # @param $1 the script $0 parameter local script_invoke_path="$1" local cwd=`pwd` # absolute path ? if so, the first character is a / if test "x${script_invoke_path:0:1}" = 'x/' then RESULT=`dirname "$script_invoke_path"` else RESULT=`dirname "$cwd/$script_invoke_path"` fi } script_invoke_path="$0" script_name=`basename "$0"` getScriptAbsoluteDir "$script_invoke_path" script_absolute_dir=$RESULT function import() { # @description importer routine to get external functionality. # @description the first location searched is the script directory. # @description if not found, search the module in the paths contained in $SHELL_LIBRARY_PATH environment variable # @param $1 the .shinc file to import, without .shinc extension module=$1 if test "x$module" == "x" then echo "$script_name : Unable to import unspecified module. Dying." exit 1 fi if test "x${script_absolute_dir:-notset}" == "xnotset" then echo "$script_name : Undefined script absolute dir. Did you remove getScriptAbsoluteDir? Dying." exit 1 fi if test "x$script_absolute_dir" == "x" then echo "$script_name : empty script path. Dying." exit 1 fi if test -e "$script_absolute_dir/$module.shinc" then # import from script directory . "$script_absolute_dir/$module.shinc" elif test "x${SHELL_LIBRARY_PATH:-notset}" != "xnotset" then # import from the shell script library path # save the separator and use the ':' instead local saved_IFS="$IFS" IFS=':' for path in $SHELL_LIBRARY_PATH do if test -e "$path/$module.shinc" then . "$path/$module.shinc" return fi done # restore the standard separator IFS="$saved_IFS" fi echo "$script_name : Unable to find module $module." exit 1 } </code></pre> <p>you can then import files with the extension .shinc with the following syntax</p> <p>import "AModule/ModuleFile"</p> <p>Which will be searched in SHELL_LIBRARY_PATH. As you always import in the global namespace, remember to prefix all your functions and variables with a proper prefix, otherwise you risk name clashes. I use double underscore as the python dot.</p> <p>Also, put this as first thing in your module</p> <pre><code># avoid double inclusion if test "${BashInclude__imported+defined}" == "defined" then return 0 fi BashInclude__imported=1 </code></pre> <p><strong>Object oriented programming</strong></p> <p>In bash, you cannot do object oriented programming, unless you build a quite complex system of allocation of objects (I thought about that. it's feasible, but insane). In practice, you can however do "Singleton oriented programming": you have one instance of each object, and only one.</p> <p>What I do is: i define an object into a module (see the modularization entry). Then I define empty vars (analogous to member variables) an init function (constructor) and member functions, like in this example code</p> <pre><code># avoid double inclusion if test "${Table__imported+defined}" == "defined" then return 0 fi Table__imported=1 readonly Table__NoException="" readonly Table__ParameterException="Table__ParameterException" readonly Table__MySqlException="Table__MySqlException" readonly Table__NotInitializedException="Table__NotInitializedException" readonly Table__AlreadyInitializedException="Table__AlreadyInitializedException" # an example for module enum constants, used in the mysql table, in this case readonly Table__GENDER_MALE="GENDER_MALE" readonly Table__GENDER_FEMALE="GENDER_FEMALE" # private: prefixed with p_ (a bash variable cannot start with _) p_Table__mysql_exec="" # will contain the executed mysql command p_Table__initialized=0 function Table__init { # @description init the module with the database parameters # @param $1 the mysql config file # @exception Table__NoException, Table__ParameterException EXCEPTION="" EXCEPTION_MSG="" EXCEPTION_FUNC="" RESULT="" if test $p_Table__initialized -ne 0 then EXCEPTION=$Table__AlreadyInitializedException EXCEPTION_MSG="module already initialized" EXCEPTION_FUNC="$FUNCNAME" return 1 fi local config_file="$1" # yes, I am aware that I could put default parameters and other niceties, but I am lazy today if test "x$config_file" = "x"; then EXCEPTION=$Table__ParameterException EXCEPTION_MSG="missing parameter config file" EXCEPTION_FUNC="$FUNCNAME" return 1 fi p_Table__mysql_exec="mysql --defaults-file=$config_file --silent --skip-column-names -e " # mark the module as initialized p_Table__initialized=1 EXCEPTION=$Table__NoException EXCEPTION_MSG="" EXCEPTION_FUNC="" return 0 } function Table__getName() { # @description gets the name of the person # @param $1 the row identifier # @result the name EXCEPTION="" EXCEPTION_MSG="" EXCEPTION_FUNC="" RESULT="" if test $p_Table__initialized -eq 0 then EXCEPTION=$Table__NotInitializedException EXCEPTION_MSG="module not initialized" EXCEPTION_FUNC="$FUNCNAME" return 1 fi id=$1 if test "x$id" = "x"; then EXCEPTION=$Table__ParameterException EXCEPTION_MSG="missing parameter identifier" EXCEPTION_FUNC="$FUNCNAME" return 1 fi local name=`$p_Table__mysql_exec "SELECT name FROM table WHERE id = '$id'"` if test $? != 0 ; then EXCEPTION=$Table__MySqlException EXCEPTION_MSG="unable to perform select" EXCEPTION_FUNC="$FUNCNAME" return 1 fi RESULT=$name EXCEPTION=$Table__NoException EXCEPTION_MSG="" EXCEPTION_FUNC="" return 0 } </code></pre> <p><strong>Trapping and handling signals</strong></p> <p>I found this useful to catch and handle exceptions.</p> <pre><code>function Main__interruptHandler() { # @description signal handler for SIGINT echo "SIGINT caught" exit } function Main__terminationHandler() { # @description signal handler for SIGTERM echo "SIGTERM caught" exit } function Main__exitHandler() { # @description signal handler for end of the program (clean or unclean). # probably redundant call, we already call the cleanup in main. exit } trap Main__interruptHandler INT trap Main__terminationHandler TERM trap Main__exitHandler EXIT function Main__main() { # body } # catch signals and exit trap exit INT TERM EXIT Main__main "$@" </code></pre> <p><strong>Hints and tips</strong></p> <p>If something does not work for some reason, try to reorder the code. Order is important and not always intuitive.</p> <p>do not even consider working with tcsh. it does not support functions, and it's horrible in general. </p> <p>Hope it helps, although please note. If you have to use the kind of things I wrote here, it means that your problem is too complex to be solved with shell. use another language. I had to use it due to human factors and legacy.</p>
354,110
What is the difference between indexOf() and search()?
<p>Being fairly new to JavaScript, I'm unable to discern when to use each of these.</p> <p>Can anyone help clarify this for me?</p>
354,123
8
0
null
2008-12-09 20:25:00.323 UTC
37
2022-06-14 23:21:44.423 UTC
2019-06-16 15:21:41.95 UTC
RoBorg
5,481,342
Colin
30,433
null
1
203
javascript|string
79,706
<p>If your situation requires the use of a regular expression, use the <code>search()</code> method, otherwise; the <code>indexOf()</code> method is more performant.</p>
626,220
How do recommendation systems work?
<p>I've always been curious as to how these systems work. For example, how do netflix or Amazon determine what recommendations to make based on past purchases and/or ratings? Are there any algorithms to read up on?</p> <p>Just so there's no misperceptions here, there's no practical reason for me asking. I'm just asking out of sheer curiosity.</p> <p>(Also, if there's an existing question on this topic, point me to it. "Recommendations system" is a difficult term to search for.)</p>
626,250
9
2
null
2009-03-09 13:27:21.673 UTC
33
2020-01-15 23:41:01.38 UTC
2013-12-09 05:12:23.14 UTC
sblundy
168,868
Jason Baker
2,147
null
1
29
algorithm|recommendation-engine
18,832
<p>This is such a commercially important application that <a href="http://www.netflixprize.com/" rel="noreferrer">Netflix introduced a $1 million prize for improving their recommendations by 10%</a>.</p> <p>After a couple of years people are getting close (I think they're up around 9% now) but it's hard for many, many reasons. Probably the biggest factor or the biggest initial improvement in the Netflix Prize was the use of a statistical technique called <a href="http://en.wikipedia.org/wiki/Singular_value_decomposition" rel="noreferrer">singular value decomposition</a>.</p> <p>I highly recommend you read <a href="http://www.nytimes.com/2008/11/23/magazine/23Netflix-t.html?_r=1&amp;partner=permalink&amp;exprod=permalink" rel="noreferrer">If You Liked This, You’re Sure to Love That</a> for an in-depth discussion of the Netflix Prize in particular and recommendation systems in general.</p> <p>Basically though the principle of Amazon and so on is the same: they look for patterns. If someone bought the Star Wars Trilogy well there's a better than even chance they like Buffy the Vampire Slayer more than the average customer (purely made up example).</p>
233,127
How can I propagate exceptions between threads?
<p>We have a function which a single thread calls into (we name this the main thread). Within the body of the function we spawn multiple worker threads to do CPU intensive work, wait for all threads to finish, then return the result on the main thread.</p> <p>The result is that the caller can use the function naively, and internally it'll make use of multiple cores.</p> <p><em>All good so far..</em></p> <p>The problem we have is dealing with exceptions. We don't want exceptions on the worker threads to crash the application. We want the caller to the function to be able to catch them on the main thread. We must catch exceptions on the worker threads and propagate them across to the main thread to have them continue unwinding from there.</p> <p><strong><em>How can we do this?</em></strong></p> <p>The best I can think of is:</p> <ol> <li>Catch a whole variety of exceptions on our worker threads (std::exception and a few of our own ones).</li> <li>Record the type and message of the exception.</li> <li>Have a corresponding switch statement on the main thread which rethrows exceptions of whatever type was recorded on the worker thread.</li> </ol> <p>This has the obvious disadvantage of only supporting a limited set of exception types, and would need modification whenever new exception types were added.</p>
32,428,427
9
0
null
2008-10-24 11:17:09.483 UTC
47
2018-09-19 11:52:35.273 UTC
null
null
null
pauldoo
755
null
1
118
c++|multithreading|exception
52,994
<p>C++11 introduced the <code>exception_ptr</code> type that allows to transport exceptions between threads:</p> <pre><code>#include&lt;iostream&gt; #include&lt;thread&gt; #include&lt;exception&gt; #include&lt;stdexcept&gt; static std::exception_ptr teptr = nullptr; void f() { try { std::this_thread::sleep_for(std::chrono::seconds(1)); throw std::runtime_error("To be passed between threads"); } catch(...) { teptr = std::current_exception(); } } int main(int argc, char **argv) { std::thread mythread(f); mythread.join(); if (teptr) { try{ std::rethrow_exception(teptr); } catch(const std::exception &amp;ex) { std::cerr &lt;&lt; "Thread exited with exception: " &lt;&lt; ex.what() &lt;&lt; "\n"; } } return 0; } </code></pre> <p>Because in your case you have multiple worker threads, you will need to keep one <code>exception_ptr</code> for each of them.</p> <p>Note that <code>exception_ptr</code> is a shared ptr-like pointer, so you will need to keep at least one <code>exception_ptr</code> pointing to each exception or they will be released.</p> <p>Microsoft specific: if you use SEH Exceptions (<code>/EHa</code>), the example code will also transport SEH exceptions like access violations, which may not be what you want.</p>
710,212
Is there a way to access the "previous row" value in a SELECT statement?
<p>I need to calculate the difference of a column between two lines of a table. Is there any way I can do this directly in SQL? I'm using Microsoft SQL Server 2008.</p> <p>I'm looking for something like this:</p> <pre><code>SELECT value - (previous.value) FROM table </code></pre> <p>Imagining that the "previous" variable reference the latest selected row. Of course with a select like that I will end up with n-1 rows selected in a table with n rows, that's not a probably, actually is exactly what I need.</p> <p>Is that possible in some way?</p>
710,222
9
1
null
2009-04-02 15:28:12.85 UTC
35
2022-07-29 07:18:59.463 UTC
2018-03-28 01:11:11.07 UTC
null
2,826,885
Augusto Radtke
18,623
null
1
131
sql|sql-server|sql-server-2008
430,589
<p>SQL has no built in notion of order, so you need to order by some column for this to be meaningful. Something like this:</p> <pre><code>select t1.value - t2.value from table t1, table t2 where t1.primaryKey = t2.primaryKey - 1 </code></pre> <p>If you know how to order things but not how to get the previous value given the current one (EG, you want to order alphabetically) then I don't know of a way to do that in standard SQL, but most SQL implementations will have extensions to do it.</p> <p>Here is a way for SQL server that works if you can order rows such that each one is distinct: </p> <pre><code>select rank() OVER (ORDER BY id) as 'Rank', value into temp1 from t select t1.value - t2.value from temp1 t1, temp1 t2 where t1.Rank = t2.Rank - 1 drop table temp1 </code></pre> <p>If you need to break ties, you can add as many columns as necessary to the ORDER BY.</p>
466,790
Assembly code vs Machine code vs Object code?
<p>What is the difference between object code, machine code and assembly code?</p> <p>Can you give a visual example of their difference?</p>
466,811
10
3
null
2009-01-21 20:17:27.15 UTC
167
2021-02-25 19:30:38.533 UTC
null
null
null
Simucal
2,635
null
1
267
assembly|machine-code|object-code
178,471
<p><strong>Machine code</strong> is binary (1's and 0's) code that can be executed directly by the CPU. If you open a machine code file in a text editor you would see garbage, including unprintable characters (no, not <em>those</em> unprintable characters ;) ).</p> <p><strong>Object code</strong> is a portion of machine code not yet linked into a complete program. It's the machine code for one particular library or module that will make up the completed product. It may also contain placeholders or offsets not found in the machine code of a completed program. The <strong>linker</strong> will use these placeholders and offsets to connect everything together.</p> <p><strong>Assembly code</strong> is plain-text and (somewhat) human read-able source code that mostly has a direct 1:1 analog with machine instructions. This is accomplished using mnemonics for the actual instructions, registers, or other resources. Examples include <code>JMP</code> and <code>MULT</code> for the CPU's jump and multiplication instructions. Unlike machine code, the CPU does not understand assembly code. You convert assembly code to machine code with the use of an <strong>assembler</strong> or a <strong>compiler</strong>, though we usually think of compilers in association with high-level programming language that are abstracted further from the CPU instructions.</p> <hr /> <p>Building a complete program involves writing <strong>source code</strong> for the program in either assembly or a higher level language like C++. The source code is assembled (for assembly code) or compiled (for higher level languages) to object code, and individual modules are linked together to become the machine code for the final program. In the case of very simple programs the linking step may not be needed. In other cases, such as with an IDE (integrated development environment) the linker and compiler may be invoked together. In other cases, a complicated <strong>make</strong> script or <strong>solution</strong> file may be used to tell the environment how to build the final application.</p> <p>There are also <strong>interpreted languages</strong> that behave differently. Interpreted languages rely on the machine code of a special interpreter program. At the basic level, an interpreter parses the source code and immediately converts the commands to new machine code and executes them. Modern interpreters are now much more complicated: evaluating whole sections of source code at a time, caching and optimizing where possible, and handling complex memory management tasks.</p> <p>One final type of program involves the use of a <strong>runtime-environment</strong> or <strong>virtual machine</strong>. In this situation, a program is first pre-compiled to a lower-level <strong>intermediate language</strong> or <strong>byte code</strong>. The byte code is then loaded by the virtual machine, which just-in-time compiles it to native code. The advantage here is the virtual machine can take advantage of optimizations available at the time the program runs and for that specific environment. A compiler belongs to the developer, and therefore must produce relatively generic (less-optimized) machine code that could run in many places. The runtime environment or virtual machine, however, is located on the end user's computer and therefore can take advantage of all the features provided by that system.</p>
268,629
How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?
<p>I am running my <code>HTTPServer</code> in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.</p> <p>The Python documentation states that <code>BaseHTTPServer.HTTPServer</code> is a subclass of <code>SocketServer.TCPServer</code>, which supports a <code>shutdown</code> method, but it is missing in <code>HTTPServer</code>.</p> <p>The whole <code>BaseHTTPServer</code> module has very little documentation :(</p>
268,660
11
0
null
2008-11-06 13:10:54.26 UTC
13
2021-05-06 06:47:13.187 UTC
2012-06-05 23:16:13.123 UTC
null
331,137
Daren Thomas
2,260
null
1
61
python|http|basehttpserver
90,525
<p>I should start by saying that "I probably wouldn't do this myself, but I have in the past". The serve_forever (from SocketServer.py) method looks like this:</p> <pre><code>def serve_forever(self): """Handle one request at a time until doomsday.""" while 1: self.handle_request() </code></pre> <p>You could replace (in subclass) <code>while 1</code> with <code>while self.should_be_running</code>, and modify that value from a different thread. Something like:</p> <pre><code>def stop_serving_forever(self): """Stop handling requests""" self.should_be_running = 0 # Make a fake request to the server, to really force it to stop. # Otherwise it will just stop on the next request. # (Exercise for the reader.) self.make_a_fake_request_to_myself() </code></pre> <p>Edit: I dug up the actual code I used at the time:</p> <pre><code>class StoppableRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer): stopped = False allow_reuse_address = True def __init__(self, *args, **kw): SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, *args, **kw) self.register_function(lambda: 'OK', 'ping') def serve_forever(self): while not self.stopped: self.handle_request() def force_stop(self): self.server_close() self.stopped = True self.create_dummy_request() def create_dummy_request(self): server = xmlrpclib.Server('http://%s:%s' % self.server_address) server.ping() </code></pre>
62,328
Is there an algorithm that tells the semantic similarity of two phrases
<p>input: phrase 1, phrase 2</p> <p>output: semantic similarity value (between 0 and 1), or the probability these two phrases are talking about the same thing</p>
63,076
11
2
null
2008-09-15 12:26:42.2 UTC
48
2020-06-27 18:40:52.947 UTC
2008-09-15 13:02:35.047 UTC
btw0
1,925,263
btw0
1,925,263
null
1
65
algorithm|nlp|semantics
48,163
<hr> <p>You might want to check out this paper:</p> <p><a href="http://ants.iis.sinica.edu.tw/3BkMJ9lTeWXTSrrvNoKNFDxRm3zFwRR/55/Sentence%20Similarity%20Based%20on%20Semantic%20Nets%20and%20corpus%20statistics.pdf" rel="noreferrer">Sentence similarity based on semantic nets and corpus statistics (PDF)</a></p> <p>I've implemented the algorithm described. Our context was very general (effectively any two English sentences) and we found the approach taken was too slow and the results, while promising, not good enough (or likely to be so without considerable, extra, effort).</p> <p>You don't give a lot of context so I can't necessarily recommend this but reading the paper could be useful for you in understanding how to tackle the problem.</p> <p>Regards,</p> <p>Matt.</p>
6,512
How to implement continuations?
<p>I'm working on a Scheme interpreter written in C. Currently it uses the C runtime stack as its own stack, which is presenting a minor problem with implementing continuations. My current solution is manual copying of the C stack to the heap then copying it back when needed. Aside from not being standard C, this solution is hardly ideal.</p> <p>What is the simplest way to implement continuations for Scheme in C?</p>
6,566
12
0
null
2008-08-09 01:18:37.943 UTC
43
2019-06-26 15:40:34.463 UTC
2011-10-30 15:18:29.767 UTC
null
201,359
Kyle
658
null
1
53
c|lisp|scheme|continuations
9,727
<p>I remember reading an article that may be of help to you: <em><a href="http://home.pipeline.com/~hbaker1/CheneyMTA.html" rel="noreferrer">Cheney on the M.T.A.</a></em> :-)</p> <p>Some implementations of Scheme I know of, such as <a href="http://sisc.sourceforge.net/" rel="noreferrer">SISC</a>, allocate their call frames on the heap.</p> <p>@ollie: You don't need to do the hoisting if all your call frames are on the heap. There's a tradeoff in performance, of course: the time to hoist, versus the overhead required to allocate all frames on the heap. Maybe it should be a tunable runtime parameter in the interpreter. :-P</p>
151,850
Why would you use an assignment in a condition?
<p>In many languages, assignments are legal in conditions. I never understood the reason behind this. Why would you write:</p> <pre><code>if (var1 = var2) { ... } </code></pre> <p>instead of:</p> <pre><code>var1 = var2; if (var1) { ... } </code></pre> <p>?</p>
151,870
12
4
null
2008-09-30 05:24:43.737 UTC
19
2022-06-30 13:47:53.797 UTC
2022-06-30 13:18:53.647 UTC
Blorgbeard
63,550
lajos
3,740
null
1
90
conditional-statements|language-agnostic|variable-assignment
102,810
<p>It's more useful for loops than <em>if</em> statements.</p> <pre><code>while(var = GetNext()) { ...do something with 'var' } </code></pre> <p>Which would otherwise have to be written</p> <pre><code>var = GetNext(); while(var) { ...do something var = GetNext(); } </code></pre>
1,021,007
Should it be "Arrange-Assert-Act-Assert"?
<p>Regarding the classic test pattern of <a href="http://c2.com/cgi/wiki?ArrangeActAssert" rel="noreferrer">Arrange-Act-Assert</a>, I frequently find myself adding a counter-assertion that precedes Act. This way I know that the passing assertion is really passing as the result of the action. </p> <p>I think of it as analogous to the red in red-green-refactor, where only if I've seen the red bar in the course of my testing do I know that the green bar means I've written code that makes a difference. If I write a passing test, then <em>any</em> code will satisfy it; similarly, with respect to Arrange-Assert-Act-Assert, if my first assertion fails, I know that any Act would have passed the final Assert - so that it wasn't actually verifying anything about the Act.</p> <p>Do your tests follow this pattern? Why or why not?</p> <p><strong>Update</strong> Clarification: the initial assertion is essentially the opposite of the final assertion. It's not an assertion that Arrange worked; it's an assertion that Act hasn't yet worked.</p>
1,034,479
14
0
null
2009-06-20 05:16:54.057 UTC
29
2022-01-10 12:28:14.353 UTC
2015-08-08 14:59:47.747 UTC
null
634,576
null
82,118
null
1
100
unit-testing|language-agnostic|arrange-act-assert
24,188
<p>Here's an example.</p> <pre><code>public void testEncompass() throws Exception { Range range = new Range(0, 5); assertFalse(range.includes(7)); range.encompass(7); assertTrue(range.includes(7)); } </code></pre> <p>It could be that I wrote <code>Range.includes()</code> to simply return true. I didn't, but I can imagine that I might have. Or I could have written it wrong in any number of other ways. I would hope and expect that with TDD I actually got it right - that <code>includes()</code> just works - but maybe I didn't. So the first assertion is a sanity check, to ensure that the second assertion is really meaningful. </p> <p>Read by itself, <code>assertTrue(range.includes(7));</code> is saying: "assert that the modified range includes 7". Read in the context of the first assertion, it's saying: "assert that <em>invoking encompass()</em> causes it to include 7. And since encompass is the unit we're testing, I think that's of some (small) value.</p> <p>I'm accepting my own answer; a lot of the others misconstrued my question to be about testing the setup. I think this is slightly different.</p>
93,039
Where are static variables stored in C and C++?
<p>In what segment (.BSS, .DATA, other) of an executable file are static variables stored so that they don't have name collision? For example:</p> <pre><code> foo.c: bar.c: static int foo = 1; static int foo = 10; void fooTest() { void barTest() { static int bar = 2; static int bar = 20; foo++; foo++; bar++; bar++; printf("%d,%d", foo, bar); printf("%d, %d", foo, bar); } } </code></pre> <p>If I compile both files and link it to a main that calls fooTest() and barTest repeatedly, the printf statements increment independently. Makes sense since the foo and bar variables are local to the translation unit.</p> <p>But where is the storage allocated?</p> <p>To be clear, the assumption is that you have a toolchain that would output a file in ELF format. Thus, I <em>believe</em> that there <strong>has</strong> to be some space reserved in the executable file for those static variables.<br> For discussion purposes, lets assume we use the GCC toolchain.</p>
93,411
16
4
null
2008-09-18 14:29:05.937 UTC
152
2021-12-23 04:15:14.543 UTC
2018-09-08 22:30:20.95 UTC
Benoit Lavigne
895,245
Benoit Lavigne
10,703
null
1
208
c++|c|compiler-construction
220,125
<p>Where your statics go depends on whether they are <em>zero-initialized</em>. <em>zero-initialized</em> static data goes in <a href="http://en.wikipedia.org/wiki/.bss" rel="noreferrer">.BSS (Block Started by Symbol)</a>, <em>non-zero-initialized</em> data goes in <a href="http://en.wikipedia.org/wiki/Data_segment" rel="noreferrer">.DATA</a></p>
31,875
Is there a simple, elegant way to define singletons?
<p>There seem to be many ways to define <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="noreferrer">singletons</a> in Python. Is there a consensus opinion on Stack&nbsp;Overflow?</p>
31,887
21
12
null
2008-08-28 09:03:09.827 UTC
240
2022-02-10 18:32:33.63 UTC
2017-02-07 19:44:17.593 UTC
jelovirt
355,230
Jamie
3,363
null
1
516
python|design-patterns|singleton
403,785
<p>I don't really see the need, as a module with functions (and not a class) would serve well as a singleton. All its variables would be bound to the module, which could not be instantiated repeatedly anyway. </p> <p>If you do wish to use a class, there is no way of creating private classes or private constructors in Python, so you can't protect against multiple instantiations, other than just via convention in use of your API. I would still just put methods in a module, and consider the module as the singleton.</p>
162,551
How to find unused/dead code in java projects
<p>What tools do you use to find unused/dead code in large java projects? Our product has been in development for some years, and it is getting very hard to manually detect code that is no longer in use. We do however try to delete as much unused code as possible.</p> <p>Suggestions for general strategies/techniques (other than specific tools) are also appreciated.</p> <p><strong>Edit:</strong> Note that we already use code coverage tools (Clover, IntelliJ), but these are of little help. Dead code still has unit tests, and shows up as covered. I guess an ideal tool would identify clusters of code which have very little other code depending on it, allowing for docues manual inspection.</p>
162,719
21
5
null
2008-10-02 14:22:52.663 UTC
108
2018-12-20 06:53:49.323 UTC
2018-08-04 05:44:19.127 UTC
Soldarnal
214,143
knatten
7,084
null
1
315
java|refactoring|dead-code
171,461
<p>I would instrument the running system to keep logs of code usage, and then start inspecting code that is not used for months or years.</p> <p>For example if you are interested in unused classes, all classes could be instrumented to log when instances are created. And then a small script could compare these logs against the complete list of classes to find unused classes.</p> <p>Of course, if you go at the method level you should keep performance in mind. For example, the methods could only log their first use. I dont know how this is best done in Java. We have done this in Smalltalk, which is a dynamic language and thus allows for code modification at runtime. We instrument all methods with a logging call and uninstall the logging code after a method has been logged for the first time, thus after some time no more performance penalties occur. Maybe a similar thing can be done in Java with static boolean flags...</p>
6,539,459
jQuery - how to write 'if not equal to' (opposite of ==)
<p>I need to reverse of the following code. How can I make the animation run if the width is NOT 500px. </p> <pre><code>$(".image-div").not(this).each(function() { if ($(this).css('width') == '500px') { $(this).animate({ width: '250px' }, 500, function() { // Animation complete. }); } }); </code></pre> <p>In other words, what the opposite of this?: ==</p> <p>Thanks </p>
6,539,478
4
1
null
2011-06-30 18:34:16.667 UTC
4
2019-09-25 11:12:34.07 UTC
null
null
null
null
467,875
null
1
45
jquery
208,432
<p>The opposite of the <code>==</code> compare operator is <code>!=</code>.</p>
15,567,194
How to convert Local time to UTC time in Delphi? and how to convert it back from UTC to local time?
<p>I'm using Delphi and I'm trying to store records using UTC datetime in my database and then restore it back when a client reads it in his local datetime ? any idea how to do this forth back conversion ?</p>
15,567,387
6
0
null
2013-03-22 09:48:22.91 UTC
9
2020-11-02 12:01:26.913 UTC
2020-11-02 11:57:29.053 UTC
null
1,336,118
null
1,336,118
null
1
20
delphi|datetime|time|delphi-xe2|utc
37,417
<p>This is the function that I use to convert from UTC to local.</p> <pre><code>function LocalDateTimeFromUTCDateTime(const UTCDateTime: TDateTime): TDateTime; var LocalSystemTime: TSystemTime; UTCSystemTime: TSystemTime; LocalFileTime: TFileTime; UTCFileTime: TFileTime; begin DateTimeToSystemTime(UTCDateTime, UTCSystemTime); SystemTimeToFileTime(UTCSystemTime, UTCFileTime); if FileTimeToLocalFileTime(UTCFileTime, LocalFileTime) and FileTimeToSystemTime(LocalFileTime, LocalSystemTime) then begin Result := SystemTimeToDateTime(LocalSystemTime); end else begin Result := UTCDateTime; // Default to UTC if any conversion function fails. end; end; </code></pre> <p>As you can see the function transforms the UTC date time as follows:</p> <ul> <li>Date time -> system time</li> <li>System time -> file time</li> <li>File time -> local file time (this is the conversion from UTC to local)</li> <li>Local file time -> system time</li> <li>System time -> date time</li> </ul> <p>It should be obvious how to reverse this.</p> <hr> <p>Note that this conversion treats daylight saving as it is <em>now</em> rather than as it is/was <em>at the time being converted</em>. The <a href="http://docwiki.embarcadero.com/Libraries/en/System.DateUtils.TTimeZone" rel="noreferrer"><code>DateUtils.TTimeZone</code></a> type, introduced in XE, attempts to do just that. The code becomes:</p> <pre><code>LocalDateTime := TTimeZone.Local.ToLocalTime(UniversalDateTime); </code></pre> <p>In the other direction use <code>ToUniversalTime</code>.</p> <p>This class appears to be (loosely) modelled on the .net <a href="http://msdn.microsoft.com/en-us/library/xe5cd9e6%28v=vs.110%29.aspx" rel="noreferrer"><code>TimeZone</code></a> class.</p> <p>A word of warning. Do not expect the <em>attempt</em> to account for daylight savings at the time being converted to be 100% accurate. It is simply impossible to achieve that. At least without a time machine. And that's just considering times in the future. Even times in the past are complex. Raymond Chen discusses the issue here: <a href="http://blogs.msdn.com/b/oldnewthing/archive/2003/10/24/55413.aspx" rel="noreferrer">Why Daylight Savings Time is nonintuitive</a>.</p>
15,961,130
Align printf output in Java
<p>I need to display a list of items with their prices from an array and would like to align the prices. I almost have it working but needs improvements. Below is the code and the output. Any ideas how to make all prices aligned? So far some work but some don't. Thanks in advance.</p> <pre><code>//for loop System.out.printf("%d. %s \t\t $%.2f\n", i + 1, BOOK_TYPE[i], COST[i]); </code></pre> <p>output:</p> <pre><code>1. Newspaper $1.00 2. Paper Back $7.50 3. Hardcover book $10.00 4. Electronic book $2.00 5. Magazine $3.00 </code></pre>
15,961,294
5
1
null
2013-04-12 00:28:29.32 UTC
4
2017-09-21 17:43:30.47 UTC
null
null
null
null
1,781,482
null
1
21
java|alignment|printf|text-align
147,059
<p>You can try the below example. Do use '-' before the width to ensure left indentation. By default they will be right indented; which may not suit your purpose.</p> <pre><code>System.out.printf("%2d. %-20s $%.2f%n", i + 1, BOOK_TYPE[i], COST[i]); </code></pre> <p>Format String Syntax: <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax" rel="noreferrer">http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax</a></p> <p>Formatting Numeric Print Output: <a href="https://docs.oracle.com/javase/tutorial/java/data/numberformat.html" rel="noreferrer">https://docs.oracle.com/javase/tutorial/java/data/numberformat.html</a></p> <p>PS: This could go as a comment to DwB's answer, but i still don't have permissions to comment and so answering it.</p>
15,609,334
How to download intraday stock market data with R
<p>All, </p> <p>I'm looking to download stock data either from Yahoo or Google on 15 - 60 minute intervals for as much history as I can get. I've come up with a crude solution as follows: </p> <pre><code>library(RCurl) tmp &lt;- getURL('https://www.google.com/finance/getprices?i=900&amp;p=1000d&amp;f=d,o,h,l,c,v&amp;df=cpct&amp;q=AAPL') tmp &lt;- strsplit(tmp,'\n') tmp &lt;- tmp[[1]] tmp &lt;- tmp[-c(1:8)] tmp &lt;- strsplit(tmp,',') tmp &lt;- do.call('rbind',tmp) tmp &lt;- apply(tmp,2,as.numeric) tmp &lt;- tmp[-apply(tmp,1,function(x) any(is.na(x))),] </code></pre> <p>Given the amount of data I'm looking to import, I worry that this could be computationally expensive. I also don't for the life of me, understand how the time stamps are coded in Yahoo and Google. </p> <p>So my question is twofold--what's a simple, elegant way to quickly ingest data for a series of stocks into R, and how do I interpret the time stamping on the Google/Yahoo files that I would be using? </p>
15,609,672
4
1
null
2013-03-25 07:00:03.19 UTC
14
2017-08-21 16:22:39.713 UTC
2015-10-15 12:23:21.01 UTC
null
1,315,131
null
375,267
null
1
21
r|finance|stockquotes|quandl
30,425
<p>I will try to answer timestamp question first. Please note this is my interpretation and I could be wrong. </p> <p>Using the link in your example <code>https://www.google.com/finance/getprices?i=900&amp;p=1000d&amp;f=d,o,h,l,c,v&amp;df=cpct&amp;q=AAPL</code> I get following data :</p> <pre><code>EXCHANGE%3DNASDAQ MARKET_OPEN_MINUTE=570 MARKET_CLOSE_MINUTE=960 INTERVAL=900 COLUMNS=DATE,CLOSE,HIGH,LOW,OPEN,VOLUME DATA= TIMEZONE_OFFSET=-300 a1357828200,528.5999,528.62,528.14,528.55,129259 1,522.63,528.72,522,528.6499,2054578 2,523.11,523.69,520.75,522.77,1422586 3,520.48,523.11,519.6501,523.09,1130409 4,518.28,520.579,517.86,520.34,1215466 5,518.8501,519.48,517.33,517.94,832100 6,518.685,520.22,518.63,518.85,565411 7,516.55,519.2,516.55,518.64,617281 ... ... </code></pre> <p>Note the first value of first column <code>a1357828200</code>, my intuition was that this has something to do with <code>POSIXct</code>. Hence a quick check :</p> <pre><code>&gt; as.POSIXct(1357828200, origin = '1970-01-01', tz='EST') [1] "2013-01-10 14:30:00 EST" </code></pre> <p>So my intuition seems to be correct. But the time seems to be off. Now we have one more info in the data. <code>TIMEZONE_OFFSET=-300</code>. So if we offset our timestamps by this amount we should get :</p> <pre><code>as.POSIXct(1357828200-300*60, origin = '1970-01-01', tz='EST') [1] "2013-01-10 09:30:00 EST" </code></pre> <p>Note that I didn't know which day data you had requested. But quick check on google finance reveals, those were indeed price levels on 10th Jan 2013. </p> <p><img src="https://i.stack.imgur.com/2ACN0.png" alt="enter image description here"></p> <p>Remaining values from first column seem to be some sort of offset from first row value. </p>
15,800,121
Why I have to put all the script to index.html in jquery mobile
<p>I have used $.mobile.changepage to do the redirect in my phonegap+jquerymobile projects. However what makes me confused is that I need to put the script of all the pages to the same file index.html. If not, the redirect page can not execute the function in its header.</p> <p>for example, my index.html seem to be <code>$(document).bind("deviceready",function(){$.mobile.changepage("test.html");})</code></p> <p>then, my device will redirect to test.html which seem to be</p> <pre><code>$("#btnTest").click(function(){alert("123");}) &lt;button id="btnTest"&gt;Test&lt;/button&gt; </code></pre> <p>However, the script will never execute in test.html. Then I put the script to index.html, what I expect to be is done. Whatever, if I put all the script to the same page, the project will become harder and harder to be preserved. Appreciated for your help.</p>
15,806,954
3
0
null
2013-04-03 23:38:04.043 UTC
22
2013-07-29 07:46:37.787 UTC
2013-05-21 09:31:38.963 UTC
null
1,848,600
null
1,679,418
null
1
26
javascript|jquery|html|cordova|jquery-mobile
21,956
<h1>Intro</h1> <p>This article can also be found <strong><a href="http://www.gajotres.net/how-jquery-mobile-page-handling-affects-javascript-executions/" rel="noreferrer">HERE</a></strong> as a part of my blog.</p> <h1>How jQuery Mobile handles page changes</h1> <p>To understand this situation you need to understand how jQuery Mobile works. It uses ajax to load other pages.</p> <p>First page is loaded normally. Its <strong><code>HEAD</code></strong> and <strong><code>BODY</code></strong> is loaded into the <strong><code>DOM</code></strong>, and they are there to await other content. When second page is loaded, only its <strong><code>BODY</code></strong> content is loaded into the <strong><code>DOM</code></strong>. To be more precise, even <strong><code>BODY</code></strong> is not fully loaded. Only first div with an attribute data-role=&quot;page&quot; will be loaded, everything else is going to be discarded. Even if you have more pages inside a <strong><code>BODY</code></strong> only first one is going to be loaded. This rule only applies to subsequent pages, if you have more pages in an initial <strong>HTML</strong> all of them will be loaded.</p> <p>That's why your button is show successfully but click event is not working. Same click event whose parent <strong><code>HEAD</code></strong> was disregarded during the page transition.</p> <p>Here's an official documentation: <a href="http://jquerymobile.com/demos/1.2.0/docs/pages/page-links.html" rel="noreferrer">http://jquerymobile.com/demos/1.2.0/docs/pages/page-links.html</a></p> <p>Unfortunately you are not going to find this described in their documentation. Ether they think this is a common knowledge or they forgot to describe this like my other topics. (jQuery Mobile documentation is big but lacking many things).</p> <h1>Solution 1</h1> <p>In your second page, and every other page, move your <strong><code>SCRIPT</code></strong> tag into the <strong><code>BODY</code></strong> content, like this:</p> <pre><code>&lt;body&gt; &lt;div data-role=&quot;page&quot;&gt; // And rest of your HTML content &lt;script&gt; // Your javascript will go here &lt;/script&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>This is a quick solution but still an ugly one.</p> <p>Working example can be found in my other answer here: <strong><a href="https://stackoverflow.com/a/16083870/1848600">Pageshow not triggered after changepage</a></strong></p> <p>Another working example: <a href="https://stackoverflow.com/questions/15430912/page-loaded-differently-with-jquery-mobile-transition/15431229#15431229"><strong>Page loaded differently with jQuery-mobile transition</strong></a></p> <h1>Solution 2</h1> <p>Move all of your javascript into the original first HTML. Collect everything and put it inside a single js file, into a <strong><code>HEAD</code></strong>. Initialize it after jQuery Mobile has been loaded.</p> <pre><code>&lt;head&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi&quot;/&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css&quot; /&gt; &lt;script src=&quot;http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;index.js&quot;&gt;&lt;/script&gt; // Put your code into a new file &lt;/head&gt; </code></pre> <p>In the end I will describe why this is a part of a good solution.</p> <h1>Solution 3</h1> <p>Use <strong>rel=&quot;external&quot;</strong> in your buttons and every elements you are using to change page. Because of it ajax is not going to be used for page loading and your jQuery Mobile app will behave like a normal web application. Unfortunately this is not a good solution in your case. Phonegap should never work as a normal web app.</p> <pre><code>&lt;a href=&quot;#second&quot; class=&quot;ui-btn-right&quot; rel=&quot;external&quot;&gt;Next&lt;/a&gt; </code></pre> <p>Official documentation, look for a chapter: <strong><a href="http://jquerymobile.com/demos/1.2.0/docs/pages/page-links.html" rel="noreferrer">Linking without Ajax</a></strong></p> <h1>Realistic solution</h1> <p>Realistic solution would use <strong>Solution 2</strong>. But unlike solution 2, I would use that same index.js file and initialize it inside a <strong><code>HEAD</code></strong> of every possible other page.</p> <p>Now you can ask me <strong>WHY</strong>?</p> <p><strong><code>Phonegap</code></strong> like jQuery Mobile is buggy, and sooner or later there's going to be an error and your app will fail (including loaded DOM) if your every js content is inside a single HTML file. DOM could be erased and <strong><code>Phonegap</code></strong> will refresh your current page. If that page don't have javascript that it will not work until it is restarted.</p> <h1>Final words</h1> <p>This problem can be easily fixed with a good page architecture. If anyone is interested I have wrote an <strong><a href="http://www.gajotres.net/secrets-of-a-good-jquery-mobile-page-architecture/" rel="noreferrer">ARTICLE</a></strong> about good jQuery Mobile page architecture. In a nut shell I am discussing that knowledge of how jQuery Mobile works is the most important thing you need to know before you can successfully create you first app.</p>
16,020,858
Inline CSV File Editing with Python
<p>Can I modify a CSV file inline using Python's CSV library, or similar technique?</p> <p>Current I am processing a file and updating the first column (a name field) to change the formatting. A simplified version of my code looks like this:</p> <pre><code>with open('tmpEmployeeDatabase-out.csv', 'w') as csvOutput: writer = csv.writer(csvOutput, delimiter=',', quotechar='"') with open('tmpEmployeeDatabase.csv', 'r') as csvFile: reader = csv.reader(csvFile, delimiter=',', quotechar='"') for row in reader: row[0] = row[0].title() writer.writerow(row) </code></pre> <p>The philosophy works, but I am curious if I can do an inline edit so that I'm not duplicating the file.</p> <p>I've tried the follow, but this appends the new records to the end of the file instead of replacing them.</p> <pre><code>with open('tmpEmployeeDatabase.csv', 'r+') as csvFile: reader = csv.reader(csvFile, delimiter=',', quotechar='"') writer = csv.writer(csvFile, delimiter=',', quotechar='"') for row in reader: row[1] = row[1].title() writer.writerow(row) </code></pre>
16,020,923
3
1
null
2013-04-15 17:08:16.103 UTC
19
2022-04-22 20:25:36.58 UTC
2013-04-15 17:21:25.79 UTC
null
411,063
null
411,063
null
1
27
python|csv|file-io
42,845
<p>No, you should not attempt to write to the file you are currently reading from. You <em>can</em> do it if you keep <code>seek</code>ing back after reading a row but it is not advisable, especially if you are writing back more data than you read.</p> <p>The canonical method is to write to a <em>new, temporary</em> file and move that into place over the old file you read from.</p> <pre><code>from tempfile import NamedTemporaryFile import shutil import csv filename = 'tmpEmployeeDatabase.csv' tempfile = NamedTemporaryFile('w+t', newline='', delete=False) with open(filename, 'r', newline='') as csvFile, tempfile: reader = csv.reader(csvFile, delimiter=',', quotechar='&quot;') writer = csv.writer(tempfile, delimiter=',', quotechar='&quot;') for row in reader: row[1] = row[1].title() writer.writerow(row) shutil.move(tempfile.name, filename) </code></pre> <p>I've made use of the <a href="http://docs.python.org/library/tempfile.html" rel="noreferrer"><code>tempfile</code></a> and <a href="http://docs.python.org/library/shutil.html" rel="noreferrer"><code>shutil</code></a> libraries here to make the task easier.</p>
15,833,694
MediaRecorder.stop() stop failed: -1007
<p>I am recording video with MediaRecorder. My code works fine on 2.3.3 but fails on 4.0.3.</p> <p>The issue is following: the code mediaRecorder.stop() throws the RuntimeExeption</p> <pre><code>java.lang.RuntimeException: stop failed. at android.media.MediaRecorder.stop(Native Method) </code></pre> <p>with LogCat message</p> <pre><code>04-05 15:10:51.815: E/MediaRecorder(15709): stop failed: -1007 </code></pre> <p>UPDATE</p> <p>I've found, that MediaPlayer reports an error (via MediaPlayer.OnErrorListener) almost immediately after the start. Error code is 100 (media server died), extra -1007.</p> <p>UPDATE 2 Code to prepare the MediaRecorder</p> <pre><code> c = Camera.open(); ... // Step 1: Unlock and set camera to MediaRecorder camera.unlock(); mediaRecorder.setCamera(camera); // Step 2: Set sources mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER); mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); // Step 3: Set a CamcorderProfile (requires API Level 8 or higher) CamcorderProfile profile = CamcorderProfile .get(CamcorderProfile.QUALITY_HIGH); // manual set up! mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); mediaRecorder.setVideoEncodingBitRate(profile.videoBitRate); mediaRecorder.setVideoFrameRate(profile.videoFrameRate); mediaRecorder.setVideoSize(profile.videoFrameWidth, profile.videoFrameHeight); mediaRecorder.setAudioChannels(profile.audioChannels); mediaRecorder.setAudioEncodingBitRate(profile.audioBitRate); mediaRecorder.setAudioSamplingRate(profile.audioSampleRate); mediaRecorder.setAudioEncoder(profile.audioCodec); //mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP); mediaRecorder.setVideoEncoder(profile.videoCodec); // mediaRecorder.setProfile(profile); // Step 4: Set output file mediaRecorder.setOutputFile("somefile.mp4"); // Step 5: Set the preview output mediaRecorder.setPreviewDisplay(preview.getHolder().getSurface()); // Step 6: Prepare configured MediaRecorder try { mediaRecorder.prepare(); } catch ... { release mediaRecorder} </code></pre> <p>then I simplyCall mediaRecorder.start() please note, that I need video to be encoded into mp4 format. This code works on Samsng Galaxy GIO (android 2.3.3) and fails as described on Acer E305 (android 4.0.2)</p> <p>Any ideas? Thanks.</p>
16,543,157
6
8
null
2013-04-05 12:14:08.8 UTC
7
2021-03-26 17:13:40.21 UTC
2013-04-11 06:57:21.75 UTC
null
184,860
null
184,860
null
1
29
android|video-capture|mediarecorder|android-mediarecorder
27,719
<p>Solved it at last. The issue was setting the preview size before setting the actual preview for the camera. The preview size <strong>MUST</strong> be equal to the selected video size.</p> <pre><code>CamcorderProfile profile = [get required profile]; Camera.Parameters parameters = mCamera.getParameters(); parameters.setPreviewSize(profile.videoFrameWidth,profile.videoFrameHeight); mCamera.setParameters(parameters); mCamera.setPreviewDisplay([surface holder]); mCamera.startPreview(); ... //configure MediaRecorder and call MediaRecorder.start() </code></pre>
36,131,705
Preferred way of using Bootstrap in Webpack
<p>Greetings one and all,</p> <p>I have been playing around with Bootstrap for Webpack, but I'm at the point of tearing my hair out. I have literally gone through loads of blog articles and they either use the 7 months outdated 'bootstrap-webpack' plugin (which, surprisingly does not work out of the box) or.. They include the Bootstrap files through import 'node_modules/*/bootstrap/css/bootstrap.css'.</p> <p>Surely, there must be a cleaner and more efficient way of going about this?</p> <p>This is my current <code>webpack.config.js</code> file:</p> <pre><code>var webpack = require('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var autoprefixer = require('autoprefixer'); var path = require('path'); module.exports = { entry: { app: path.resolve(__dirname, 'src/js/main.js') }, module: { loaders: [{ test: /\.js[x]?$/, loaders: ['babel-loader?presets[]=es2015&amp;presets[]=react'], exclude: /(node_modules|bower_components)/ }, { test: /\.css$/, loaders: ['style', 'css'] }, { test: /\.scss$/, loaders: ['style', 'css', 'postcss', 'sass'] }, { test: /\.sass$/, loader: 'style!css!sass?sourceMap' },{ test: /\.less$/, loaders: ['style', 'css', 'less'] }, { test: /\.woff$/, loader: "url-loader?limit=10000&amp;mimetype=application/font-woff&amp;name=[path][name].[ext]" }, { test: /\.woff2$/, loader: "url-loader?limit=10000&amp;mimetype=application/font-woff2&amp;name=[path][name].[ext]" }, { test: /\.(eot|ttf|svg|gif|png)$/, loader: "file-loader" }] }, output: { path: path.resolve(__dirname, 'dist'), filename: '/js/bundle.js', sourceMapFilename: '/js/bundle.map', publicPath: '/' }, plugins: [ new ExtractTextPlugin('style.css') ], postcss: [ autoprefixer({ browsers: ['last 2 versions'] }) ], resolve: { extensions: ['', '.js', '.sass'], modulesDirectories: ['src', 'node_modules'] }, devServer: { inline: true, contentBase: './dist' } }; </code></pre> <p>I could go and <code>require('bootstrap')</code> (with some way of getting jQuery in it to work), but.. I'm curious to what you all think and do. </p> <p>Thanks in advance :)</p>
42,358,091
3
7
null
2016-03-21 12:59:16.79 UTC
3
2019-06-21 05:47:08.417 UTC
2017-02-20 14:20:19.973 UTC
null
1,235,234
null
1,235,234
null
1
30
javascript|twitter-bootstrap|webpack|vue.js|babeljs
18,349
<p>I am not sure if this is the best way, but following work for me well with <code>vue.js</code> webapp. You can see the working code <a href="https://github.com/mimani/vue-example" rel="noreferrer">here</a>.</p> <p>I have included files required by bootstrap in <a href="https://github.com/mimani/vue-example/blob/master/index.html" rel="noreferrer">index.html</a> like this:</p> <pre><code>&lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Hey&lt;/title&gt; &lt;meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui"&gt; &lt;link rel="stylesheet" href="/static/bootstrap.css" type="text/css"&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.3.7/js/tether.min.js" integrity="sha384-XTs3FgkjiBgo8qjEjBk0tGmf3wPrWtA6coPfQDfFEY8AnYJwjalXCiosYRBIBZX8" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script href="/static/bootstrap.js"&gt;&lt;/script&gt; &lt;/head&gt; </code></pre> <p>And this works, you can execute the repo. Why I went this way was I had to <a href="http://v4-alpha.getbootstrap.com/getting-started/options/" rel="noreferrer">customise</a> some config in <a href="http://v4-alpha.getbootstrap.com/" rel="noreferrer">bootstrap</a> so I had to change the variables file and build the code of bootstrap which outputted me <code>bootstrap.js</code> and <code>bootstrap.css</code>files, which I am using here.</p> <hr> <p>There is an alternative way suggested <a href="https://stackoverflow.com/q/40864747/1610034">here</a> by using the npm package and a webpack customisation.</p> <p>First install bootstrap in your project:</p> <pre><code>npm install [email protected] </code></pre> <p>And make sure you can use sass-loader in your components:</p> <pre><code>npm install sass-loader node-sass --save-dev </code></pre> <p>now go to your webpack config file and add a sassLoader object with the following:</p> <pre><code>sassLoader: { includePaths: [ path.resolve(projectRoot, 'node_modules/bootstrap/scss/'), ], }, </code></pre> <p><code>projectRoot</code> should just point to where you can navigate to <code>node_packages</code> from, in my case this is: <code>path.resolve(__dirname, '../')</code></p> <p>Now you can use bootstrap directly in your .vue files and webpack will compile it for you when you add the following:</p> <pre><code>&lt;style lang="scss"&gt; @import "bootstrap"; &lt;/style&gt; </code></pre>
10,759,099
Difference between object and instance in python?
<p>This happens in python2.7</p> <p>I am working on the idea of meta class in python, almost all the tutorial refer object as instance of a class, in python. However, when playing with the class A(): form of defining a class, I saw this:</p> <pre><code>class ClsDef1(): pass C1 = ClsDef1() print C1 &lt;__main__.ClsDef1 instance at 0x2aea518&gt; class ClsDef2(object): pass C2 = ClsDef2() print C2 &lt;__main__.ClsDef2 object at 0x2ae68d0&gt; </code></pre> <p>This means when create a instance from a class that is not inherent from object, the instance is an instance, but when a class is inherent from object, the instance of the class is an object?</p> <p>Could anyone explain the difference? In real life which one should I use?</p> <p>Thanks!</p>
10,759,244
3
3
null
2012-05-25 17:46:32.147 UTC
11
2020-05-05 02:55:14.273 UTC
2012-05-25 18:06:01.363 UTC
null
620,835
null
620,835
null
1
21
python|oop
21,425
<p>This is the difference between new-style and old-style classes, which is explained in great detail <a href="http://docs.python.org/reference/datamodel.html" rel="noreferrer">in the documentation</a>. Basically, in Python 2.x you should ensure you always inherit from object so that you get a new-style class. In Python 3, old-style classes have gone away completely.</p>
10,786,172
Android getDefaultSharedPreferences
<p>My code is:</p> <pre><code>final String eulaKey = "mykey"; final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); boolean hasBeenShown = prefs.getBoolean(eulaKey, false); </code></pre> <p>Always returns different values depending on os version. Tested in 2.2, 2.3.4, 3.2, 4.0.3 - returns correct value. But for device Zte blade with 2.3.7 with CianogenMod 7.1 - result is always false. I suppose default value for getBoolean.</p> <p>Here is code writing boolean:</p> <pre><code>final String eulaKey = "mykey"; final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean(eulaKey, true); editor.commit(); </code></pre> <p>Does anybody have any idea?</p> <p>Update: Comparing my current code with my previous version of code - there is no difference in code. Only difference is in manifest: code works Ok with minVersion=8 and targetVersion=8 Now I'm compiling with minversion=8 and target=13 /because of Admob/. Maybe some APIs changed, but I found nothing on this.</p> <p>SOLUTION: -Starting app from shortcut and from menu gives me different DefaultSharedPreferences. After removing DefaultSharedPreferences from my code - it works perfect. I can't just say: people don't make shortcuts, so I had to change code.</p>
10,786,739
2
5
null
2012-05-28 14:19:11.25 UTC
15
2021-03-12 11:00:51.447 UTC
2015-04-17 13:29:58.287 UTC
null
973,233
null
973,233
null
1
62
android|sharedpreferences
76,373
<p>Try it this way:</p> <pre><code>final String eulaKey = "mykey"; Context mContext = getApplicationContext(); mPrefs = mContext.getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE); SharedPreferences.Editor editor = mPrefs.edit(); editor.putBoolean(eulaKey, true); editor.commit(); </code></pre> <p>in which case you can specify your own preferences file name (myAppPrefs) and can control access persmission to it. Other operating modes include: </p> <ul> <li>MODE_WORLD_READABLE</li> <li>MODE_WORLD_WRITEABLE</li> <li>MODE_MULTI_PROCESS</li> </ul>
25,004,226
MSI vs nuget packages: which are is better for continuous delivery?
<p>Let's discuss following topic. There is application which currently is being deployed with good to know xcopy method.This approach makes difficult to manage dependencies, file updates etc. There is idea to start application deployment with help of some packages, you know like you do in Linux with help of <a href="http://en.wikipedia.org/wiki/RPM_Package_Manager" rel="noreferrer"><strong>RPM</strong></a>, but for Windows.</p> <p>So I have question: what package system is better to use on windows classic windows installer (<strong>msi</strong>) or <strong>nuget</strong> or something else?</p>
25,005,864
2
4
null
2014-07-28 20:57:20.723 UTC
21
2021-05-28 17:23:00.663 UTC
2018-10-02 21:57:02.847 UTC
null
129,130
null
179,111
null
1
19
.net|wix|nuget|windows-installer|continuous-deployment
31,337
<blockquote> <p><em><strong>Ad-Hoc</strong></em>: <a href="https://stackoverflow.com/questions/45840086/how-do-i-avoid-common-design-flaws-in-my-wix-msi-deployment-solution">How do I avoid common design flaws in my WiX / MSI deployment solution?</a></p> <ul> <li>a very messy and less-than-ideal ad-hoc summary of common problems found in MSI files. Not great. Better than nothing? The stuff that is not in the books (too messy).</li> </ul> </blockquote> <blockquote> <p><em><strong>Important Topic</strong></em>: <a href="https://stackoverflow.com/questions/48311010/how-do-i-avoid-distributing-sensitive-information-in-my-msi-by-accident">How do I avoid distributing sensitive information in my MSI by accident?</a></p> </blockquote> <blockquote> <p><em><strong>Need For Speed</strong></em>: <a href="https://stackoverflow.com/a/63308043/129130"><strong>WiX Quick Start Short Version</strong></a></p> </blockquote> <hr /> <p><em><strong>WiX &amp; MSI</strong></em>:</p> <blockquote> <p><strong>MSI</strong> is the accepted corporate application standard. It has <a href="https://serverfault.com/a/274609/20599"><strong>some major corporate benefits</strong></a> (<a href="https://stackoverflow.com/a/49632260/129130"><strong><code>and the short, concise version</code></strong></a>) compared to legacy deployment techniques. <em><strong>WiX</strong> is the new open source way to create MSI files.</em></p> <ul> <li><a href="http://wixtoolset.org/" rel="noreferrer"><strong>Wix Toolset Download</strong></a> (<strong><code>1)</code></strong> Main <strong>WiX</strong> setup, <strong><code>2)</code></strong> <strong>Votive</strong> - Visual Studio integration setup</li> <li><a href="http://wixtoolset.org/documentation/" rel="noreferrer"><strong>WiX Documentation</strong></a> <ul> <li>After WiX installation locate <strong><code>WiX.chm</code></strong> and <strong><code>msi.chm</code></strong> help files in installation folder &quot;<code>%ProgramFiles(x86)%\WiX Toolset v3.11\doc</code>&quot; for quick access to documentation.</li> </ul> </li> <li>Online: <a href="http://wixtoolset.org/documentation/manual/v3/" rel="noreferrer"><strong><code>WiX Reference Manual v3</code></strong></a>, <a href="https://www.firegiant.com/wix/tutorial/" rel="noreferrer"><strong><code>Official WiX Tutorial</code></strong></a>.</li> <li><a href="https://github.com/wixtoolset" rel="noreferrer"><code>Github</code></a>, <a href="https://github.com/wixtoolset/issues/issues" rel="noreferrer"><code>Bug Tracker</code></a>, <a href="http://windows-installer-xml-wix-toolset.687559.n2.nabble.com/" rel="noreferrer"><code>Mailing List</code></a>, <a href="https://support.firegiant.com/hc/en-us/sections/206730147-WiX-Articles" rel="noreferrer"><code>FireGiant WiX KDB</code></a> (FireGiant is WiX's commercial branch).</li> <li>To get your head around <strong>Wix</strong>, you might want to read a <a href="https://stackoverflow.com/a/12101548/129130"><strong>quick, unofficial summary of the history behind it</strong></a>.</li> <li><a href="https://wixtoolset.org/documentation/manual/v3/msbuild/" rel="noreferrer">MSBuild</a> - using Visual Studio, Votive and MSBuild</li> <li><em><strong>Harvesting</strong></em> (<a href="https://stackoverflow.com/q/56593326/129130">1</a>): WiX has its own tool for generating WiX markup based on an input folder. <ul> <li>The tool is called <a href="https://wixtoolset.org/documentation/manual/v3/overview/heat.html" rel="noreferrer">heat.exe</a>. WiX's commercial branch <a href="https://www.firegiant.com/" rel="noreferrer">FireGiant</a> has a tool called <a href="https://www.firegiant.com/wix/wep-documentation/harvesting/" rel="noreferrer">HeatWave</a> with more features.</li> <li>Largely untested by me is the tool <strong><code>WixHeatATLHarvesterExtension</code></strong>: <a href="https://github.com/nirbar/WixHeatATLHarvesterExtension" rel="noreferrer">https://github.com/nirbar/WixHeatATLHarvesterExtension</a> (a WiX Heat extension to harvest registry information from x64 modules)</li> </ul> </li> </ul> </blockquote> <p><em><strong>Other Tools</strong></em>:</p> <blockquote> <ul> <li>Then you might want to check other ways to deliver an installer, besides Wix by reading: <ul> <li><a href="https://stackoverflow.com/questions/1544292/what-installation-product-to-use-installshield-wix-wise-advanced-installer/1546941#1546941">What installation product to use? InstallShield, WiX, Wise, Advanced Installer, etc</a></li> <li><a href="https://stackoverflow.com/questions/50225031/windows-service-not-shown-in-add-remove-programs-under-control-panel/50229840#50229840">One more quick-list of tools</a></li> </ul> </li> <li><em><strong>Major Tools</strong></em>: <a href="https://www.advancedinstaller.com" rel="noreferrer">Advanced Installer</a>, - <a href="https://www.installshield.com" rel="noreferrer">InstallShield</a>, - <a href="https://pacesuite.com/" rel="noreferrer">PACE Suite</a></li> </ul> </blockquote> <p><em><strong>Hello World &amp; Hello WiX:</strong></em></p> <blockquote> <ul> <li>Finally view a <strong>complete example</strong> of how a Wix source file and its components look like on <a href="http://www.codeproject.com/Tips/105638/A-quick-introduction-Create-an-MSI-installer-with" rel="noreferrer"><strong>Codeproject</strong></a>. This is the <strong>&quot;Hello World&quot;</strong> of Wix.</li> <li><a href="https://stackoverflow.com/a/47972615/129130"><strong>&quot;Hello WiX - step-by-step in Visual Studio&quot;</strong></a>. <ul> <li>This needs <strong>WiX</strong> and <strong>Votive</strong> (WiX Toolset Visual Studio Extension &gt; - WiX's Visual Studio integration so you get Intellisense). <a href="http://wixtoolset.org/releases/" rel="noreferrer"><strong>See download page</strong></a>.</li> <li>Inline comments in bottom markup is probably all you need to get going.</li> <li><a href="https://stackoverflow.com/questions/54763243/how-to-explicitly-remove-dll-during-majorupgrade-using-wix-toolset/54766353#54766353">Small sample of WiX preprocessor variables / defines</a>.</li> </ul> </li> <li><a href="https://stackoverflow.com/questions/60383913/how-do-i-add-c-sharp-methods-to-an-existing-large-wix-script/60384739#60384739"><em><strong>Hello WiX C# Custom Actions</strong></em></a> <ul> <li>How to add C# custom actions to an existing WiX project.</li> </ul> </li> </ul> </blockquote> <p><em><strong>Video Samples</strong></em>:</p> <blockquote> <ul> <li><a href="https://www.youtube.com/watch?v=6Yf-eDsRrnM" rel="noreferrer">How To Create Windows Installer MSI - .Net Core WiX</a></li> <li><a href="https://www.youtube.com/watch?v=-wyUxQux7xY" rel="noreferrer">Create a MSI/Setup package for C# with WiX Toolset</a></li> </ul> </blockquote> <p><em><strong>More Sample Code:</strong></em></p> <blockquote> <p><em><strong>WiX Quick Start</strong></em>: Here are some of the best sample code links that I have found:</p> <ul> <li><a href="https://helgeklein.com/blog/2014/09/real-world-example-wix-msi-application-installer/" rel="noreferrer"><strong>Helge Klein</strong>'s real-world WiX sample</a> - do check this out (<a href="https://web.archive.org/web/20161220161223/https://helgeklein.com/blog/2014/09/real-world-example-wix-msi-application-installer/" rel="noreferrer">Wayback - Archived Version</a>).</li> <li><a href="https://github.com/rstropek/Samples/tree/master/WiXSamples" rel="noreferrer"><strong>Rainer Stropek</strong>'s WiX Samples on Github</a> - can be very helpful.</li> <li><a href="https://blogs.technet.microsoft.com/alexshev/2008/02/10/from-msi-to-wix/" rel="noreferrer">From MSI to WiX by <strong>Alex Schevchuk</strong></a> - aging content, but excellent.</li> <li><a href="https://github.com/iswix-llc/iswix-tutorials" rel="noreferrer"><strong>Chris Painter</strong>'s IsWiX Tutorials</a> - excellent WiX samples.</li> </ul> <p>And finally:</p> <ul> <li><a href="https://stackoverflow.com/users/3261150/phildw"><strong>Phil Wilson</strong></a>'s Github repository for MSI samples: <a href="https://github.com/Apress/def-guide-to-win-installer" rel="noreferrer">https://github.com/Apress/def-guide-to-win-installer</a>. The best content, but aging. General MSI samples, not WiX as such.</li> <li>My experimental site: <a href="http://www.installdude.com" rel="noreferrer">installdude.com</a>.</li> <li><a href="https://github.com/Robs79/How-to-create-a-Windows-Service-MSI-Installer-Using-WiX" rel="noreferrer">How-to-create-a-Windows-Service-MSI-Installer-Using-WiX</a>.</li> <li>WiX Extension: <a href="https://github.com/nirbar/PanelSwWixExtension" rel="noreferrer">https://github.com/nirbar/PanelSwWixExtension</a> (<strong><code>Dism.exe</code></strong>, <strong><code>etc...</code></strong>)</li> </ul> </blockquote> <p><em><strong>Debugging</strong></em>: Always check all <strong>event logs</strong>, <strong>application logs</strong> and <strong>MSI logs</strong> - if available. Just to mention it. And <strong>use any debugging tool available</strong> and <strong>google the exact error message</strong> before doing anything else.</p> <p>And check for any obviously missing runtimes. For example: <strong><code>.Net</code></strong>, <strong><code>.Net Core</code></strong>, <strong><code>Java</code></strong>, <strong><code>Silverlight</code></strong>, <strong><code>Direct X</code></strong>, <strong><code>VC++ Runtime</code></strong>, <strong><code>MS-XML</code></strong> (legacy), <strong><code>etc...</code></strong>.</p> <blockquote> <p><em><strong>Custom Action Debugging</strong></em>:</p> <ul> <li><a href="https://stackoverflow.com/questions/54925087/interrupt-installation-when-custom-action-returns-error"><strong>Common Causes for Custom Action runtime failures</strong></a></li> <li><a href="https://stackoverflow.com/questions/52878332/wixsharp-debug-custom-action-in-console/52880033#52880033"><strong>Debugging Custom Actions</strong></a> <ul> <li>For native code / C++ just attach debugger to <strong><code>msiexec.exe</code></strong></li> <li><a href="https://www.youtube.com/watch?v=ayeBB97_NwA" rel="noreferrer"><strong>Advanced Installer's Debug C# Custom Actions video tutorial</strong></a></li> </ul> </li> </ul> <p><em><strong>MSI logging</strong></em>:</p> <ul> <li><a href="https://stackoverflow.com/questions/54453922/enable-installation-logs-for-msi-installer-without-any-command-line-arguments/54458890#54458890">Overview and summary</a> (how to log, interpreting log file, etc...)</li> <li><a href="http://www.installsite.org/pages/en/msifaq/a/1022.htm" rel="noreferrer">Installsite: MSI log &quot;how-to&quot;</a></li> <li><a href="https://stackoverflow.com/questions/56146456/getting-error-registering-com-application/56147961#56147961">More MSI logging information</a></li> </ul> <p><em><strong>Event Viewer</strong></em>:</p> <ul> <li>Hold down <kbd>Windows Key</kbd>, tap <kbd>R</kbd>, type <code>eventvwr.msc</code> and press <kbd>Enter</kbd>.</li> <li>Go to <code>Windows Logs =&gt; Applications</code>. Look for <code>MsiInstaller events</code>.</li> <li>Check the other logs too (<strong><code>Security</code></strong>, <strong><code>System</code></strong>, <strong><code>Configuration</code></strong>).</li> </ul> <p><em><strong>General Debugging</strong></em>:</p> <ul> <li><p><a href="https://stackoverflow.com/questions/25417893/msi-installation-log-says-note-1-2205-2-3-error/25435817#25435817">&quot;Debugging Light&quot;</a></p> </li> <li><p><a href="https://stackoverflow.com/a/53530377/129130"><strong>Application Launch Problem: Debugging Ideas</strong></a> (torpedoes full spread)</p> </li> <li><p><a href="https://docs.microsoft.com/en-us/sysinternals/downloads/procmon" rel="noreferrer"><strong>ProcMon.exe</strong></a>: The tool of the trade. The one-size-fits-all tool. The bee's knees, the topper-most, the quantum leap, the cat's pajamas. It can be a challenge to use it effectively, but it is the best general-purpose debugging tool that is free (<a href="https://stackoverflow.com/questions/59416186/access-to-path-denied-while-reading-a-dll-from-program-files-which-is-actually-g#comment105024050_59416186">comment link for safekeeping</a>).</p> <ul> <li><a href="https://stackoverflow.com/questions/47746076/registering-a-cpp-dll-into-com-after-installation-using-wix-msi-installer/47792474#47792474">Quick, Rudimentary Sample</a></li> <li><a href="https://www.youtube.com/watch?v=pjKNx41Ubxw" rel="noreferrer">Hanselman's longer video sample</a> (from about 3:50 onwards)</li> </ul> </li> </ul> <p><em><strong>Debugging Tools</strong></em>:</p> <ul> <li><a href="https://stackoverflow.com/questions/51939079/which-winform-project-files-should-be-packed-up-into-the-installer"><strong>Tools to debug dependency issues</strong></a> - <code>ProcMon.exe</code>, <code>VS</code>, <code>Dependency Walker</code>, <code>etc...</code> <ul> <li><a href="https://stackoverflow.com/a/56121116/129130">COM dependency errors</a></li> <li><a href="https://docs.microsoft.com/en-us/dotnet/framework/tools/fuslogvw-exe-assembly-binding-log-viewer" rel="noreferrer">Fuslogvw.exe (Assembly Binding Log Viewer)</a></li> </ul> </li> <li>Essential service debugging tools: <ul> <li><strong><code>Event Viewer</code></strong>, <strong><code>Task Manager</code></strong>, <strong><code>Services.msc</code></strong></li> <li><a href="https://www.coretechnologies.com/blog/windows-services/essential-tools-for-windows-services-process-explorer/" rel="noreferrer"><strong><code>Process Explorer</code></strong></a>, <a href="https://www.coretechnologies.com/blog/windows-services/essential-tools-for-windows-services-net-command/" rel="noreferrer"><strong><code>NET command</code></strong></a>, <a href="https://www.coretechnologies.com/blog/windows-services/essential-tools-windows-services-sc-exe/" rel="noreferrer"><strong><code>SC.exe</code></strong></a></li> <li><a href="https://www.coretechnologies.com/WindowsServices/FAQ.html" rel="noreferrer">Windows Services Frequently Asked Questions (FAQ)</a></li> </ul> </li> </ul> <p><em><strong>Error Code</strong></em>: Looking up error codes and exception messages.</p> <ul> <li><a href="https://www.magnumdb.com/" rel="noreferrer">&quot;The Magic Number Database&quot;</a> - online lookup.</li> <li><a href="https://stackoverflow.com/questions/52572537/msiexec-returns-negative-number/52573312#52573312">Checking Error Codes</a> - several tools and approaches.</li> </ul> </blockquote> <hr /> <blockquote> <p><em><strong>A Deployment Mnemonic</strong></em>: A general mnemonic to think about deployment problems: <strong><code>What is locking</code></strong> (in use, malware), <strong><code>what is blocking</code></strong> (permissions, <a href="https://stackoverflow.com/questions/52977390/wix-bootstrap-prevent-temp-directory-use/52989870#52989870">anti-virus</a>, security tools), <strong><code>what is corrupt</code></strong> (disk, malware, configs, encryption) <strong><code>what are unexpected system states</code></strong> (disk space, time &amp; date settings, language, licensing, windows patch state, path too long, PendingFileRenames, etc...), <strong><code>what are incompatible products</code></strong> (things that can't co-exist), <strong><code>what is unreachable or misconfigured</code></strong> (what points to erroneous locations and resources: network server names, disk paths, URLs, databases, services, UAT environments, PROD environments, etc...) and last but not least: <strong><code>what is missing</code></strong> (runtime, resource image, settings file, etc...)?</p> </blockquote> <hr /> <blockquote> <p><em><strong>NOTE</strong></em>: Always first (step 8 below): <code>Google exact error message</code>.</p> <p><em><strong>Express Failure to Launch Debugging</strong></em>: <strong><code>1)</code></strong> <code>Reboot</code>, <strong><code>2)</code></strong> <a href="https://stackoverflow.com/questions/52977390/wix-bootstrap-prevent-temp-directory-use/52989870#52989870"><code>disable anti-virus</code></a>, <strong><code>3)</code></strong> <code>launch as admin</code> and check, <strong><code>4)</code></strong> Check <code>dependencies and runtimes</code> (<em>Java</em>, <em>VC++ Runtime</em>, <em>.NET</em>, <em>etc...</em>). Then, if need be: <strong><code>5)</code></strong> <code>verbose log</code>, <strong><code>6)</code></strong> <code>event logs</code>, <strong><code>7)</code></strong> <code>Try on a virtual</code> if you still can't get it working? (many virtuals lack essential runtimes - check) Or <code>secondary computer?</code> Also <strong><code>8)</code></strong> <code>google exact error messages</code> and check user comments, <strong><code>9)</code></strong> <code>Run update for the application in question?</code> (new installer could eliminate the error situation). <strong><code>10)</code></strong> Run a full check for <strong><code>malware</code></strong> too? It is all over the place these days. <strong><code>11)</code></strong> Some software (often server software) may need configuration settings sorted out (<code>misconfiguration</code>). Desktop applications may need <code>license</code> to launch at all.</p> </blockquote> <hr /> <blockquote> <p><em><strong>Locks?</strong></em>: With permission and locks you can try to <strong><code>run the tool with elevated rights</code></strong>? You could have disk corruption - <strong><code>disk errors</code></strong>? <code>Faulty ACL permissions</code>? (possible). Your <strong><code>anti-virus suite</code></strong> has locked some file that MSI is trying to put back in place. You can try to disable it temporarily to see. Note that the file can have been <code>quarantined</code> as well (moved somewhere else).</p> </blockquote> <hr /> <h2><em><strong>Generic Tricks?</strong></em> - Consumer issues, <a href="https://stackoverflow.com/questions/61816312/how-can-i-solve-windows-installer-error-2908">failure to install setup.exe</a>:</h2> <ul> <li><a href="https://stackoverflow.com/questions/60369648/bitvise-sh-client-installation-error-createdirectory-failed-windows-error-5/60374125#60374125"><strong>A generic check-list for deployment issues</strong></a> (alternative to list below - recommended).</li> <li><em><strong>Visual Studio Problems</strong></em>: <a href="https://stackoverflow.com/a/62147330/129130">A check list for Visual Studio installation problems</a> - and <a href="https://stackoverflow.com/a/64641913/129130">an updated version</a></li> <li><em><strong>.NET Repair</strong></em>: <a href="https://www.microsoft.com/en-sg/download/details.aspx?id=30135" rel="noreferrer">.Net Framework Repair Tool</a></li> <li><em><strong>Broken Uninstalls</strong></em>: <a href="https://support.microsoft.com/en-us/help/17588/windows-fix-problems-that-block-programs-being-installed-or-removed" rel="noreferrer">MS FixIt: Remove packages that won't uninstall</a></li> <li><em><strong>Log</strong></em>: <a href="http://aka.ms/vscollect" rel="noreferrer">Microsoft Visual Studio and .NET Framework Log Collection Tool</a></li> <li><em><strong>Smartscreen issues</strong></em>: <a href="https://stackoverflow.com/a/63136489/129130">Digital signatures, false positives, tagged downloaded file</a></li> </ul> <p>For setups that won't install properly. A few generic tricks below - in addition to checking <code>event logs</code> and <code>installation-</code> and <code>application logs</code> and <code>googling any error messages</code> (always do that too - perhaps first - but maybe just do a reboot first - before facing all the complexity):</p> <blockquote> <ol> <li><em><strong>Reboot</strong></em>: Reboot first after a failed install to see if that solves locks and pending renames.</li> <li><em><strong>Other Computer</strong></em>: Try installing on another physical machine instead? <ul> <li>Important smoke test of the installation media!</li> </ul> </li> <li><em><strong>Virtual</strong></em>: Try installing on a Virtual machine instead? <ul> <li>Often outdated, check runtimes, check Windows Update.</li> </ul> </li> <li><em><strong>Runtimes</strong></em>: Ensure required runtimes of various types are on there in the required version: <ul> <li><em><strong>Common</strong></em>: <a href="https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads" rel="noreferrer"><code>VCRedist</code></a>, <a href="https://dotnet.microsoft.com/download" rel="noreferrer"><code>.NET</code></a>, <a href="https://dotnet.microsoft.com/download" rel="noreferrer"><code>.NET Core</code></a>, <a href="https://www.java.com/" rel="noreferrer"><code>Java</code></a>, <a href="https://www.microsoft.com/en-us/download/details.aspx?id=35" rel="noreferrer"><code>Direct X</code></a>, <code>etc...</code></li> <li><em><strong>Specific</strong></em>: <code>Python</code>, <code>DBMS systems</code> (<code>PostgreSQL</code>, <a href="https://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="noreferrer"><code>MSSQL</code></a>, <code>etc...</code>)</li> <li><em><strong>Windows Components</strong></em>: <code>IIS</code>, <code>MSMQ - Message Queue</code>, <code>Powershell</code>, <code>etc...</code></li> </ul> </li> <li><em><strong>Secondary Account</strong></em>: Try installing on main box using a different admin account. This can sort out problems caused by errors in the user profile (not at all that uncommon).</li> <li><em><strong>Local Installation Files</strong></em>: Copy installation files locally if they are on the network when invoked (to eliminate network error sources).</li> <li><em><strong>Localization Issues</strong></em>: It is not uncommon for setups delivered in other languages to contain brand new bugs not seen in the original installer (usually English). <ul> <li><em><strong>&quot;Murphy Field&quot;</strong></em>: <em><code>&quot;We have managed to add additional bugs to the internationalized setups beyond the English version&quot;</code></em>. Oh the humanity say! Bummer.</li> <li>Try to download an English setup version and test install?</li> <li>Try the localized setup on an English machine or virtual?</li> <li>Also investigate running with another user account with different language settings.</li> </ul> </li> </ol> </blockquote> <h2>Setup.exe - again - the common &quot;blockers&quot;:</h2> <blockquote> <ol> <li><em><strong>Corrupt Setup File</strong></em>: Corrupt setup file. Re-download to be sure? Get this done as one of the first steps before wasting a whole day? Correct platform bitness? Right CPU-architecture?</li> <li><em><strong>Malware</strong></em>: Malware can cause just about &quot;anything&quot; in terms of problems.</li> <li><em><strong>Security Software</strong></em>: <code>Anti-virus</code>, <code>firewalls</code>, <code>scanners</code>, <code>etc...</code> can interfere with installation. Disable temporarily if possible when required.</li> <li><em><strong>Disk Space</strong></em>: Ensure enough disk space! <ul> <li><a href="https://serverfault.com/questions/642177/how-can-i-eliminate-the-huge-cached-msi-files-in-c-windows-installer/642178#642178">Ways to clear out disk space</a>. <a href="https://stackoverflow.com/questions/49347375/vs-2017-installation-failed/49347648#49347648">Long version</a>.</li> <li>Just run <code>cleanmgr.exe</code> first.</li> </ul> </li> <li><em><strong>Proxy</strong></em>: If there is a network requirement, is there a proxy server that blocks things?</li> <li><em><strong>Policies</strong></em>: There can be policies in effect on managed networks to block certain features making the install impossible. Try on virtual? Usually less restricted.</li> <li><em><strong>Disk Errors</strong></em>: Scan disk to see if it is OK. If not, fix it first. Modern NVMe disks can lose a lot of data with power outages for desktops without UPS.</li> <li><em><strong>Disk Security ACL</strong></em>: Custom security ACL (NTFS access configuration) configuration that leads to runtime errors for Windows components and software alike. Never use custom ACL for Windows directories unless you know what you are doing. <strong>Errors are CERTAIN</strong>.</li> </ol> </blockquote> <p><em><strong>Some Links</strong></em>:</p> <ul> <li><a href="https://stackoverflow.com/questions/48431725/the-setup-process-in-windows-fails-access-denied-when-trying-to-create-uc-micro/48433935#48433935">The setup process in windows fails access denied when trying to create &quot;uc.micro&quot; folder</a></li> <li><a href="https://stackoverflow.com/questions/51489985/sql-server-2017-installation-is-stuck">SQL Server 2017 installation is stuck</a></li> <li><a href="https://stackoverflow.com/questions/49983606/visual-studio-installer-fails-on-aspnetdiagnosticpack-msi/49987350#49987350">Visual Studio installer fails on AspNetDiagnosticPack.msi</a></li> <li><a href="https://stackoverflow.com/questions/49914522/the-installer-has-encountered-an-unexpected-error-installing-this-package-err/49927626#49927626">The installer has encountered an unexpected error installing this package - .Error code 2896</a></li> </ul> <hr /> <p><em><strong>Easy Access</strong></em>:</p> <ul> <li><em><strong>XML Files</strong></em>: <a href="https://stackoverflow.com/questions/49160583/added-new-application-setting-to-app-config-but-msi-wont-install-it-doesnt-ov/49162863#49162863">Installing XML files</a></li> <li><a href="https://stackoverflow.com/questions/52977390/wix-bootstrap-prevent-temp-directory-use/52989870#52989870">False Positives</a></li> <li><a href="https://stackoverflow.com/questions/57269683/windows-service-fails-to-start-on-install-wix-iswix-verify-that-you-have-suffic/57274639#57274639">Installer Class Methods</a> - <a href="https://stackoverflow.com/questions/59076477/wix-installer-based-topshelf-windows-service-fails-to-start/59080738#59080738">More Installer Class Methods</a></li> <li><a href="https://stackoverflow.com/questions/23019329/would-this-method-of-installing-com-work/23022625#23022625">Would this method of installing COM+ work?</a></li> <li><a href="https://docs.microsoft.com/en-us/windows/win32/msi/windows-installer-best-practices" rel="noreferrer">Windows Installer Best Practice</a></li> <li><a href="https://stackoverflow.com/questions/51385973/in-use-files-not-updated-by-msi-installer-visual-studio-installer-project/51387298#51387298">Reboot Manager and Logging</a></li> <li><a href="https://stackoverflow.com/questions/1405100/change-my-component-guid-in-wix/1422121#1422121">Change my component GUID in wix?</a></li> <li><a href="https://stackoverflow.com/a/24769965/129130">Simplify WiX markup</a> - you can leave out a lot of source attributes from your Wix xml file</li> <li><a href="https://stackoverflow.com/a/52451546/129130">Running Legacy Applications</a> (<strong><code>virtuals</code></strong>, <strong><code>compatibility mode</code></strong>, <strong><code>repackaging</code></strong>, <strong><code>etc...</code></strong>)</li> <li><a href="https://stackoverflow.com/questions/24793346/wix-installer-ice03-invalid-language-id/24793670#24793670">What are ICE Rules</a></li> <li><a href="https://stackoverflow.com/a/50452114/129130">Preprocessor versus Localization Variables, and the issue of include files</a></li> <li><a href="https://stackoverflow.com/questions/49449985/wix-installer-setting-component-condition-property-when-doing-a-msiexec-admin/49501700#49501700">WiX Preprocessor</a></li> </ul> <p><em><strong>Repackaging, Application Launch Debugging</strong></em>:</p> <ul> <li><a href="https://stackoverflow.com/questions/59076477/wix-installer-based-topshelf-windows-service-fails-to-start/59080738#59080738"><code>Procmon.exe</code>, <code>capture</code>, <code>repackaging</code>, <code>service installation</code> and <code>installer methods</code></a></li> <li><a href="https://stackoverflow.com/a/62260964/129130">Section on repackaging here</a></li> <li><a href="https://stackoverflow.com/questions/52327442/how-to-run-an-installation-in-silent-mode-with-adjusted-settings/52338626#52338626">How to run an installation in /silent mode with adjusted settings</a></li> <li><a href="https://stackoverflow.com/a/54769767/129130">More on distribution of software</a></li> <li><a href="https://stackoverflow.com/questions/48148875/wix-how-to-run-install-application-without-ui/48157650#48157650">Wix - How to run/install application without UI</a> (embedding setup.exe, silent running setup.exe, application repackaging, bootstrappers / chainers)</li> </ul> <p><em><strong>Upgrades</strong></em>:</p> <ul> <li><a href="https://stackoverflow.com/a/56991527/129130">Causes of major upgrade failures</a></li> <li><a href="https://stackoverflow.com/a/51444047/129130">Some minor upgrade technical restrictions</a></li> </ul> <p><em><strong>Some Other WiX Links</strong></em>:</p> <ul> <li><a href="https://stackoverflow.com/a/54931394/129130">WiX 3 dependency on .NET 3.5</a></li> <li><a href="https://stackoverflow.com/questions/24732761/syntax-for-guids-in-wix/24769965#24769965">Simplify your WiX markup</a>.</li> <li><a href="https://stackoverflow.com/questions/55450950/registering-com-exe-with-wix">Registering COM EXEs with WiX</a>.</li> <li><a href="https://stackoverflow.com/questions/57373835/unable-to-uninstall-the-application-which-is-installed-using-wix-installer/57376073#57376073">Can't uninstall, it fails</a>.</li> <li><a href="https://docs.microsoft.com/en-us/windows/desktop/Msi/dynamic-link-libraries" rel="noreferrer">Dynamic Link Libraries</a>.</li> <li><a href="https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/debuggers-in-the-debugging-tools-for-windows-package" rel="noreferrer">Microsoft Debugging Environments</a>.</li> <li><a href="https://stackoverflow.com/questions/57299450/how-do-i-create-a-prerequisite-package-for-windows-installer/57310696#57310696">How do I create a Prerequisite Package for Windows Installer?</a></li> <li><a href="https://stackoverflow.com/questions/57408269/how-do-i-embed-customaction-ca-dll-in-to-msi">How do I embed CustomAction.CA.dll in to MSI?</a></li> <li><a href="https://stackoverflow.com/questions/57373972/installed-program-is-removed-automatically-everytime-when-server-restarts-from-w/57380860#57380860">Installed program is removed automatically everytime when server restarts from windows server 2012 R2</a></li> </ul> <hr /> <p><em><strong>Procedures</strong></em>:</p> <ul> <li><em><strong>Open Temp folder</strong></em>: <kbd>Windows Key</kbd> =&gt; Tap <kbd>R</kbd> =&gt; Type: <strong><code>%TEMP%</code></strong> =&gt; Press: <kbd>Enter</kbd>.</li> <li><em><strong>ARP</strong></em>: Go <strong>start</strong> <kbd>→</kbd> <strong>run</strong> <kbd>→</kbd> <strong>appwiz.cpl</strong> <kbd>→</kbd> <kbd>ENTER</kbd> in order to open the add/remove programs applet (or click add/ remove programs in the control panel).</li> <li><em><strong>Settings GUI Win8/10</strong></em>: <kbd>Windows Key</kbd> + Tap <kbd>I</kbd> =&gt; <strong><code>Apps &amp; Features</code></strong>. Select entry and uninstall.</li> <li><em><strong>Quick start of Powershell</strong></em>: hold <kbd>Windows key</kbd>, tap <kbd>R</kbd>, type in &quot;powershell&quot; and press <kbd>Enter</kbd>.</li> <li><em><strong>Restart Graphics Driver</strong></em>: <kbd>Windows key</kbd> + <kbd>Ctrl</kbd> + <kbd>Shift</kbd> and tap <kbd>B</kbd>.</li> </ul> <hr /> <p>Some good starting links to learn Wix:</p> <ul> <li><a href="https://stackoverflow.com/a/22550256/129130"><strong>My Wix quick start suggestions</strong></a></li> <li><a href="https://stackoverflow.com/questions/310418/good-resources-for-learning-how-to-create-msi-installers-from-wix">Good resources for learning how to create MSI installers from WiX</a></li> <li><strong><a href="https://stackoverflow.com/questions/114165/how-to-implement-wix-installer-upgrade/3575801#3575801">How to implement WiX installer upgrade?</a></strong> (major upgrade)</li> <li><a href="https://stackoverflow.com/questions/3961750/what-are-limitations-of-wix-and-wix-toolset">What are limitations of WiX and WiX Toolset?</a></li> </ul> <p>Extract Files from <code>Setup.exe</code> WiX Bundle or from an MSI file itself:</p> <ul> <li><a href="https://stackoverflow.com/questions/1547809/extract-msi-from-exe/24987512#24987512">Extract MSI from EXE</a> - including how to extract files embedded in a WiX Burn bundle executable.</li> <li><a href="https://stackoverflow.com/questions/48482545/how-can-i-compare-the-content-of-two-or-more-msi-files/48482546#48482546">How can I compare the content of two (or more) MSI files?</a> - Including how to extract files from an MSI using WiX's <code>dark.exe</code> tool</li> </ul> <p>As I wrote in my suggested &quot;<strong>Wix quick start</strong>&quot; post above: <strong>Wix is hands-on</strong>. <em>Just focus on simple, but complete real-world samples like the one from <a href="http://www.codeproject.com/Tips/105638/A-quick-introduction-Create-an-MSI-installer-with" rel="noreferrer"><strong>Codeproject</strong></a> - reading the documentation alone is likely to be merely confusing</em>.</p> <p>Focus on splitting your application into components and set up a major upgrade. <strong>Use one file per component as a rule of thumb</strong>, and read this answer for a better understanding of component creation: <strong><a href="https://stackoverflow.com/questions/1405100/change-my-component-guid-in-wix/1422121">Change my component GUID in wix?</a></strong></p> <p><strong>A major upgrade</strong> is the most commonly used upgrade mechanism for deployed software (the other common upgrade type is minor upgrade). It is obviously crucial that you can upgrade what you have deployed already. Get upgrade scenarios working before you deploy your first software version so you have confidence in your deployment solution.</p> <p>Once you got your components set up and your upgrade solution is working, the rest of the pieces fall into place as you work your way through your application's deployment requirements and check for samples on the <strong>Wix tutorial site</strong>: <a href="https://www.firegiant.com/wix/tutorial/" rel="noreferrer">https://www.firegiant.com/wix/tutorial/</a>.</p> <p>For those writing Wix code directly (without a GUI editor), I suggest you check this answer for a way to keep your source files terse: <strong><a href="https://stackoverflow.com/questions/24732761/syntax-for-guids-in-wix/24769965#24769965">Syntax for guids in WIX?</a></strong></p> <p><em><strong>Further read</strong></em>:</p> <ul> <li><a href="https://stackoverflow.com/questions/6060281/windows-installer-vs-wix/12101548">Windows Installer and the creation of WiX</a></li> <li><a href="https://stackoverflow.com/questions/2202210/installer-capabilities-wix-vs-installshield-express?rq=1">Installer capabilities, WIX vs InstallShield Express</a></li> <li><a href="https://stackoverflow.com/questions/3156162/installshield-or-wix">Installshield or Wix</a></li> <li><a href="https://github.com/wixtoolset/issues/issues" rel="noreferrer">WiX Bug Tracker</a></li> </ul>
35,487,417
How to stop Form submit if the validation fails
<p>UPDATE: my question is more about <code>How to prevent the form submit if the validation fails</code></p> <p>the link does not solve my problem</p> <p>just re-iterate what I'm doing: I have a form with bunch of input fields and when the user hit the submit button it validate form using attribute <code>required="required"</code> if the form validation fails THEN I want to stop submitting the form as you see the javascript it show the div when the user submit the form.</p> <p>Hope this clears up.</p> <p>END UPDATE</p> <p>How can I stop the form submit to fire if the form validation fails?</p> <pre><code>&lt;input class="form-control" data-val="true" id="SerialNumber" name="SerialNumber" required="required" type="text"&gt; &lt;button type="submit" name="rsubmit" class="btn btn-success"&gt;Submit&lt;/button&gt; //loading message: $("form").submit(function (e) { $("#loading").show(); }); </code></pre>
35,496,374
3
6
null
2016-02-18 16:43:29.623 UTC
6
2016-02-20 18:57:07.077 UTC
2016-02-18 18:15:07.097 UTC
null
275,390
null
275,390
null
1
19
javascript|jquery|forms|model-view-controller
66,437
<p>I able to fixed the problem:</p> <p>First add the ref on your page:</p> <pre><code>&lt;script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"&gt;&lt;/script&gt; &lt;script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js"&gt;&lt;/script&gt; </code></pre> <p>then do this check:</p> <pre><code> $("form").submit(function () { if ($(this).valid()) { //&lt;&lt;&lt; I was missing this check $("#loading").show(); } }); </code></pre>
33,401,767
ImportError: No module named pytesseract
<p>I was following this guide <a href="https://realpython.com/blog/python/setting-up-a-simple-ocr-server/" rel="noreferrer">https://realpython.com/blog/python/setting-up-a-simple-ocr-server/</a> and got to the part where I run cli.py <code>python flask_server/cli.py</code> but I get </p> <pre><code>python cli.py Traceback (most recent call last): File "cli.py", line 3, in &lt;module&gt; import pytesseract ImportError: No module named pytesseract </code></pre> <p>How can I solve this ? </p> <p>I also saw that I have multiple versions of python. I have linux-kali installed with the latest updates. </p> <p>Something else: he runs the command like <code>python flask_server/cli.py</code>- where is that flask_server located ? I simply ran it like <code>python cli.py</code>(I was in some directory in which I created the file).</p>
33,402,041
4
6
null
2015-10-28 21:19:12.7 UTC
4
2019-04-25 19:42:50.33 UTC
2016-10-25 19:09:27.283 UTC
null
508,666
null
4,659,576
null
1
4
python|linux
72,240
<p>Python <code>import</code> errors usually boils down to one of those three cases (whether is is modules you developed; or modules distributed as packages):</p> <ol> <li><p>You did no install the required package. Googling <code>pytesseract</code>tells me its an <a href="https://pypi.python.org/pypi/pytesseract/0.1" rel="noreferrer">OCR</a> that is distributed and installable using Python package manager tool <code>pip</code> by running <code>pip install pytesseract</code> in your favorite shell.</p></li> <li><p>You did install the package, but is is not in your python path.</p></li> <li><p>(Less often) You did install the package, and it is in your python path, but you used a name already in user by Python, and the two are conflicting.</p></li> </ol> <p>In your case, I strongly think this is the first one. Case 2. and 3. can be assessed by calling <code>python -v your_script.py</code>as described in <a href="https://stackoverflow.com/questions/7332299/trace-python-imports">this answer</a>.</p>