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
2,475,329
Steps to Investigate Cause of Web.Config Duplicate Section
<h2>Symptoms</h2> <ul> <li>In IIS 7 and Dot Net 2.0 Integrated app pool: double clicking to view any web.config section results in an error dialog like this:</li> </ul> <p><img src="https://i.stack.imgur.com/z124t.png" alt="&quot;There was an error while performing this operation.... Filename... web.config... Error: There is a duplicate...&quot;"></p> <ul> <li><p>Browsing to the URL displays: <strong>"Http 500.19" internal server error.. There is a duplicate... 'system.web.extensions/scripting/scriptResourceHandler' section defined...."</strong></p></li> <li><p>Running the app from VS 2008 an <strong>"Unable to start debugging on the web server..."</strong> dialog is displayed.</p></li> </ul> <h2>Infrastructure</h2> <ul> <li>Web server: IIS 7 running on Windows 7 x64</li> <li>ASP.Net MVC2</li> <li>Application pool: Dot Net 2.0 integrated</li> <li>VS 2008</li> </ul> <h2>Things Tried</h2> <ul> <li>Checked to see if the problem was occurring in other IIS app directories on the same machine.</li> <li>Removed and re-added the application in IIS.</li> <li>Reverted to prior versions of the web.config file.</li> <li>Checked out a last working version of the source code. Rebuilt the app, added a new app directory for it and tried to view web.config contents from IIS.</li> <li>Looked for web.config files that might have duplicate sections in: <ul> <li>Inetpub root.</li> <li>"C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.config"</li> <li>The "Views" subfolder of the ASP.Net MVC app.</li> </ul></li> <li>Checked out source code to another dev machine. Setup IIS 7 app folder. No problem with Web.config.</li> </ul> <h2>Question</h2> <ul> <li>If the reason for this error is another web.config file where else should I look?</li> <li>Are there other reasons for these symptoms?</li> </ul>
2,478,410
7
2
null
2010-03-19 06:14:57.243 UTC
5
2016-07-08 22:41:56.167 UTC
2016-07-08 22:41:56.167 UTC
null
6,083,675
null
2,669
null
1
41
asp.net|asp.net-mvc|iis-7
30,216
<h2>Add this to the checklist.</h2> <ul> <li>Make sure that the machine.config you check is from the same Dot Net framework as the application pool your application is running under.</li> </ul> <p>In my case the default application pools was changed from Dot Net 2.0 to Dot Net 4.0. This changed the root machine.config to the 4.0 version. This version contains the "scriptResourceHandler" section as well as others. Thus the duplicate section warning.</p>
3,041,011
Is LINQ to SQL deprecated?
<p>Back in late 2008 there was a lot of debate about the future of LINQ to SQL. Many suggested that Microsoft's investments in the Entity Framework in .NET 4.0 were a sign that LINQ to SQL had no future. I figured I'd wait before making my own decision since folks were not in agreement.</p> <p>Fast-forward 18 months and I've got vendors providing solutions that rely on LINQ to SQL and I have personally given it a try and really enjoyed working with it. I figured it was here to stay.</p> <p>But I'm reading a new book (C# 4.0 How-To by Ben Watson) and in chapter 21 (LINQ), he suggests that it "has been more or less deprecated by Microsoft" and suggests using LINQ to Entity Framework.</p> <p>My question to you is whether or not LINQ to SQL is officially deprecated and/or if authoritative entities (Microsoft, Scott Gu, etc.) officially suggest using LINQ to Entities instead of LINQ to SQL.</p>
3,041,035
7
2
null
2010-06-14 21:16:45.877 UTC
16
2019-10-17 20:44:44.647 UTC
2010-06-14 21:30:32.603 UTC
null
148,423
null
148,009
null
1
58
linq|linq-to-sql|linq-to-entities
22,250
<p>For all the <em>"Linq-to-SQL is dead"</em> folks: Scott Guthrie himself clearly mentioned at TechEd Europe that Linq-to-SQL is <strong>FULLY SUPPORTED</strong> in .NET 4, and Damien Guard posted a <a href="http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40" rel="nofollow noreferrer">blog post</a> on what changes and improvements have been made for Linq-to-SQL in .NET 4.</p> <p>To quote Mark Twain: "Reports of my death have been greatly exaggerated"......</p>
2,660,172
How do I set default host for url helpers in rails?
<p>I would like to do something like this</p> <pre><code>config.default_host = 'www.subdomain.example.com' </code></pre> <p>in some of my configuration files, so that <code>object_url</code> helpers (<code>ActionView::Helpers::UrlHelper</code>) produce links beginning with <a href="http://www.subdomain.example.com" rel="noreferrer">http://www.subdomain.example.com</a></p> <p>I have tried to search the docs but I did not find anything except <code>ActionMailer</code> docs and <a href="http://api.rubyonrails.org/classes/Rails/Configuration.html" rel="noreferrer">http://api.rubyonrails.org/classes/Rails/Configuration.html</a> which is not useful for me, because I do not know in which pat to look. Is there a place which describes the whole structure of Rails::Initializer.config?</p>
5,293,143
8
0
null
2010-04-17 21:37:13.49 UTC
10
2021-10-07 18:23:21.083 UTC
2017-02-14 16:27:56.183 UTC
null
4,284,627
null
313,522
null
1
72
ruby-on-rails|url|configuration
77,563
<p><code>asset_host</code> doesn't work for urls</p> <p>You need to override <code>default_url_options</code> in your <code>ApplicationController</code> (at least in Rails 3)</p> <p><a href="http://edgeguides.rubyonrails.org/action_controller_overview.html#default-url-options" rel="noreferrer">http://edgeguides.rubyonrails.org/action_controller_overview.html#default-url-options</a></p> <pre><code>class ApplicationController &lt; ActionController::Base def default_url_options if Rails.env.production? {:host =&gt; "myproduction.com"} else {} end end end </code></pre>
2,843,928
Benefits of arrays
<p>As I see it, the advantages of a list over an array are pretty obvious:</p> <ul> <li>Generics provide more precise typing: <code>List&lt;Integer&gt;, List&lt;? extends Number&gt;, List&lt;? super Integer&gt;</code>.</li> <li>A List interface has a bunch useful methods: <code>addAll</code>, <code>remove</code> etc. While for arrays all standard operations except get/set must be performed in a procedure manner by passing it to a static method.</li> <li>Collections offer different implementations like <code>ArrayList</code>, <code>LinkedList</code>, unmodifieable and synchronized lists, which can be hidden under a common List interface.</li> <li>OOB length control.</li> </ul> <p>As disadvantages I can only mention the absence of syntactic sugar and a runtime type check. At the same time supporting of both structures requires frequent using of <code>asList</code> and <code>toArray</code> methods, which makes code less readable. So I am curious if there are any important benefits of using arrays that I miss.</p>
2,844,151
9
0
null
2010-05-16 13:31:04.323 UTC
6
2010-05-17 10:26:01.32 UTC
2010-05-16 17:58:25.833 UTC
null
288,671
null
288,671
null
1
30
java|arrays|list|arraylist
13,116
<p>Arrays are more efficient, both in terms of processing time and memory footprint. This particularly applies if you are operating on primitive types, such as <code>int</code> or <code>long</code>, since <code>List</code> requires all elements to be wrapped in an <code>Object</code> (such as <code>Integer</code> or <code>Long</code>). While the autoboxing features introduced by Java 5 reduces the amount of code you need for such wrapping and unwrapping, it does not remove the performance issues, as wrapper objects are still being created.</p> <p>However, most applications probably do not have any performance bottlenecks related to these issues, so in most cases, <code>List</code> and other collections should do fine. In these cases, the ease of programming outweighs the increase in memory or CPU usage, and <code>List</code> is the right choice.</p>
2,463,175
How to have Android Service communicate with Activity
<p>I'm writing my first Android application and trying to get my head around communication between services and activities. I have a Service that will run in the background and do some gps and time based logging. I will have an Activity that will be used to start and stop the Service. </p> <p>So first, I need to be able to figure out if the Service is running when the Activity is started. There are some other questions here about that, so I think I can figure that out (but feel free to offer advice).</p> <p>My real problem: if the Activity is running and the Service is started, I need a way for the Service to send messages to the Activity. Simple Strings and integers at this point - status messages mostly. The messages will not happen regularly, so I don't think polling the service is a good way to go if there is another way. I only want this communication when the Activity has been started by the user - I don't want to start the Activity from the Service. In other words, if you start the Activity and the Service is running, you will see some status messages in the Activity UI when something interesting happens. If you don't start the Activity, you will not see these messages (they're not that interesting).</p> <p>It seems like I should be able to determine if the Service is running, and if so, add the Activity as a listener. Then remove the Activity as a listener when the Activity pauses or stops. Is that actually possible? The only way I can figure out to do it is to have the Activity implement Parcelable and build an AIDL file so I can pass it through the Service's remote interface. That seems like overkill though, and I have no idea how the Activity should implement writeToParcel() / readFromParcel().</p> <p>Is there an easier or better way? Thanks for any help.</p> <p><strong>EDIT:</strong> </p> <p>For anyone who's interested in this later on, there is sample code from Google for handling this via AIDL in the samples directory: /apis/app/RemoteService.java</p>
2,463,746
13
0
null
2010-03-17 14:46:48.993 UTC
154
2020-07-19 10:10:38.323 UTC
2018-01-02 14:50:21.43 UTC
null
1,783,163
null
64,193
null
1
267
android|android-activity|android-service
169,463
<p>There are three obvious ways to communicate with services:</p> <ol> <li>Using Intents</li> <li>Using AIDL</li> <li>Using the service object itself (as singleton)</li> </ol> <p>In your case, I'd go with option 3. Make a static reference to the service it self and populate it in onCreate(): </p> <pre><code>void onCreate(Intent i) { sInstance = this; } </code></pre> <p>Make a static function <code>MyService getInstance()</code>, which returns the static <code>sInstance</code>. </p> <p>Then in <code>Activity.onCreate()</code> you start the service, asynchronously wait until the service is actually started (you could have your service notify your app it's ready by sending an intent to the activity.) and get its instance. When you have the instance, register your service listener object to you service and you are set. NOTE: when editing Views inside the Activity you should modify them in the UI thread, the service will probably run its own Thread, so you need to call <code>Activity.runOnUiThread()</code>.</p> <p>The last thing you need to do is to remove the reference to you listener object in <code>Activity.onPause()</code>, otherwise an instance of your activity context will leak, not good.</p> <p>NOTE: This method is only useful when your application/Activity/task is the only process that will access your service. If this is not the case you have to use option 1. or 2.</p>
2,539,069
Can I set text box to readonly when using Html.TextBoxFor?
<p>I have the following tag with a Html.TextBoxFor expression and I want the contents to be read only, is this possible?</p> <pre><code>&lt;%= Html.TextBoxFor(m =&gt; Model.Events.Subscribed[i].Action)%&gt; </code></pre>
2,539,117
15
1
null
2010-03-29 15:20:12.823 UTC
7
2019-09-12 15:32:33.597 UTC
null
null
null
null
91,729
null
1
67
.net|html|asp.net-mvc
155,325
<p>Updated for modern versions of .NET per @1c1cle's suggestion in a comment:</p> <pre><code>&lt;%= Html.TextBoxFor(model =&gt; Model.SomeFieldName, new {{"readonly", "true"}}) %&gt; </code></pre> <p>Do realize that this is not a "secure" way to do this as somebody can inject javascript to change this.</p> <p>Something to be aware of is that if you set that <code>readonly</code> value to <code>false</code>, you actually won't see any change in behavior! So if you need to drive this based on a variable, you cannot simply plug that variable in there. Instead you need to use conditional logic to simply not pass that <code>readonly</code> attribute in.</p> <p>Here is an untested suggestion for how to do this (if there's a problem with this, you can always do an if/else):</p> <pre><code>&lt;%= Html.TextBoxFor(model =&gt; Model.SomeFieldName, shouldBeReadOnlyBoolean ? new {{"readonly", "true"}} : null) %&gt; </code></pre>
2,824,435
UIScrollView not scrolling
<p>I have a <code>UIScrollView</code> which contains many <code>UIImageView</code>s, UILabels, etc... the labels are much longer that the <code>UIScrollView</code>, but when I run the app, I cannot click and scroll down...</p> <p>Why might this be?</p> <p>Thanks</p>
2,833,702
27
1
null
2010-05-13 04:36:15.87 UTC
27
2021-06-03 09:29:25.907 UTC
2019-05-20 14:54:37.763 UTC
null
2,272,431
null
26,310
null
1
135
ios|iphone|ipad|uiscrollview
141,730
<p>It's always good to show a complete working code snippet:</p> <pre><code>// in viewDidLoad (if using Autolayout check note below): UIScrollView *myScrollView; UIView *contentView; // scrollview won't scroll unless content size explicitly set [myScrollView addSubview:contentView];//if the contentView is not already inside your scrollview in your xib/StoryBoard doc myScrollView.contentSize = contentView.frame.size; //sets ScrollView content size </code></pre> <p><strong>Swift 4.0</strong></p> <pre><code>let myScrollView let contentView // scrollview won't scroll unless content size explicitly set myScrollView.addSubview(contentView)//if the contentView is not already inside your scrollview in your xib/StoryBoard doc myScrollView.contentSize = contentView.frame.size //sets ScrollView content size </code></pre> <p>I have not found a way to set contentSize in IB <em>(as of Xcode 5.0)</em>.</p> <p>Note: If you are using Autolayout the best place to put this code is inside the <code>-(void)viewDidLayoutSubviews</code> method .</p>
33,770,549
Viewport vs Window Vs Document
<p>In the below code,</p> <pre><code>document.documentElement.clientWidth 1349 document.documentElement.clientHeight 363 window.innerWidth 1366 window.innerHeight 363 window.screen.height 768 window.screen.width 1366 </code></pre> <p>So, My desktop screen is 1366 px wide and 768 px height.</p> <p>I learnt that, </p> <p>viewport dimensions are referred using <code>document.documentElement.clientWidth</code> and <code>document.documentElement.clientHeight</code>.</p> <p>window dimensions are referred using <code>window.innerWidth</code> and <code>window.innerHeight</code>.</p> <p>1) What is the difference between viewport and document?</p> <p>2) when does <em><code>window.onload</code> Vs <code>document.onload</code></em> get invoked?</p>
33,770,624
3
1
null
2015-11-18 02:02:28.58 UTC
29
2020-05-18 00:02:24.757 UTC
2017-11-24 13:34:19.193 UTC
null
3,317,808
null
3,317,808
null
1
38
javascript|html|css|dom
33,492
<p>Things are different when your page is bigger than your screen. </p> <p>Viewport is the rectangle area where things are visible to you. The document can be larger than that and you'll see scrollbars if so.</p> <p>As for your second question: <a href="https://stackoverflow.com/questions/588040/window-onload-vs-document-onload">window.onload vs document.onload</a></p> <p>Here is a summary.</p> <p><strong>Viewport:</strong> It is your device screen.</p> <p><strong>Window:</strong> It is your browser window. The window can be as big as viewport or smaller.</p> <p><strong>Document:</strong> It is the webpage. It can be bigger than viewport or even bigger than window. </p> <p>Notes: Some websites are for not created for mobiles. Hence the webpage/document is much bigger than the mobile viewport and you have to swipe to see the parts that spill outside the screen. On a desktop, you can make the window of your browser smaller or same as the viewport/monitor.</p>
33,770,902
How to write alternative code "document.querySelector" in Angular 2 (TypeScript)?
<p>I am using Angular 2 (TypeScript). I want to rewrite the code below.</p> <pre><code>&lt;video&gt;&lt;/video&gt; var video = document.querySelector("video"); video.src = URL.createObjectURL(localMediaStream); video.play(); </code></pre> <p>However, I don't know any way to get "video" in Angular 2. This is so far what I did.</p> <pre><code>&lt;video [src]="videoSrc"&gt;&lt;/video&gt; videoSrc:string; … this.videoSrc = URL.createObjectURL(stream); // Since I don't know any way to get "video", // do I have any way to use video.play() here? </code></pre>
33,771,672
1
1
null
2015-11-18 02:37:39.383 UTC
3
2017-04-21 13:41:04.86 UTC
2017-04-21 13:41:04.86 UTC
user663031
null
null
2,000,548
null
1
12
angular|typescript
48,085
<p>You can get a reference to the <code>video</code> element by using a local variable and <code>@ViewChild</code></p> <pre class="lang-js prettyprint-override"><code>@Component({ selector: 'my-app', template : `&lt;video #my-video&gt;&lt;/video&gt;` }) export class App implements AfterViewInit { // myVideo == #my-video @ViewChild('myVideo') myVideo: any; afterViewInit() { let video = this.myVideo.nativeElement; video.src = URL.createObjectURL(yourBlob); video.play(); } </code></pre> <p>Here's a <a href="http://plnkr.co/edit/Na2F8oFmrVm1WgEjoBxM?p=preview" rel="noreferrer">plnkr</a> demonstrating the case (<em>the plnkr differs a little bit, since I couldn't load a video, apparently it's no that simple, instead I load an image as the poster for video tag. You'll get the idea</em>)</p> <p><strong>Update</strong></p> <p>You deleted your last comment, but it was a valid question since the <a href="https://angular.io/docs/js/latest/api/core/ViewChild-var.html" rel="noreferrer">docs only specify one way</a> of using <code>@ViewChild</code>.The docs use the type to query for the children, but you can also use a string. See in <a href="https://github.com/angular/angular/blob/master/modules/angular2/src/core/metadata/di.ts#L347" rel="noreferrer"><code>ViewChildMetadata#L327</code></a> that it accepts a Type (Component/Directive) or a string.</p> <p><strong>Update 2</strong></p> <p>Actually the docs show this alternative, but it's in another part of it. Under <a href="https://angular.io/docs/ts/latest/api/core/Query-var.html" rel="noreferrer"><code>Query</code></a> docs you can see it. Note that <code>Query</code> is deprecated, but the syntax is still valid for <code>ViewChild/ViewChildren</code> and <code>ContentChild/ContentChildren</code>.</p>
42,206,440
java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkArgument
<p>I am trying to run this <a href="https://github.com/grpc/grpc-java/blob/master/examples/src/main/java/io/grpc/examples/helloworld/HelloWorldServer.java" rel="noreferrer">grpc-Java</a> example on my local. Corresponding proto file for the same is <a href="https://github.com/grpc/grpc-java/blob/master/examples/src/main/proto/helloworld.proto" rel="noreferrer">here</a>. When i try to run in on local it throws the following exception from <a href="https://github.com/grpc/grpc-java/blob/master/examples/src/main/java/io/grpc/examples/helloworld/HelloWorldServer.java#L52" rel="noreferrer">here</a> :</p> <pre><code>Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.base.Preconditions.checkArgument(ZLjava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V at io.grpc.ServiceDescriptor.validateMethodNames(ServiceDescriptor.java:129) at io.grpc.ServiceDescriptor.&lt;init&gt;(ServiceDescriptor.java:83) at io.grpc.ServiceDescriptor.&lt;init&gt;(ServiceDescriptor.java:51) at io.grpc.ServiceDescriptor$Builder.build(ServiceDescriptor.java:219) at io.grpc.examples.helloworld.GreeterGrpc.getServiceDescriptor(GreeterGrpc.java:251) at io.grpc.examples.helloworld.GreeterGrpc$GreeterImplBase.bindService(GreeterGrpc.java:84) at io.grpc.internal.AbstractServerImplBuilder.addService(AbstractServerImplBuilder.java:125) at io.grpc.internal.AbstractServerImplBuilder.addService(AbstractServerImplBuilder.java:63) at com.cw.predictive.HelloWorldServer.start(HelloWorldServer.java:56) at com.cw.predictive.HelloWorldServer.main(HelloWorldServer.java:92) </code></pre> <p>This is my pom.xml as mentioned <a href="https://github.com/grpc/grpc-java" rel="noreferrer">here</a> :</p> <pre><code> &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;io.grpc&lt;/groupId&gt; &lt;artifactId&gt;grpc-netty&lt;/artifactId&gt; &lt;version&gt;1.1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;io.grpc&lt;/groupId&gt; &lt;artifactId&gt;grpc-protobuf&lt;/artifactId&gt; &lt;version&gt;1.1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;io.grpc&lt;/groupId&gt; &lt;artifactId&gt;grpc-stub&lt;/artifactId&gt; &lt;version&gt;1.1.2&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre>
47,959,075
3
0
null
2017-02-13 14:27:40.673 UTC
null
2022-07-20 17:16:18.647 UTC
null
null
null
null
2,135,526
null
1
36
java|maven|grpc-java
44,499
<pre><code>**Please add following dependencies in your project.** &lt;dependency&gt; &lt;groupId&gt;com.google.guava&lt;/groupId&gt; &lt;artifactId&gt;guava&lt;/artifactId&gt; &lt;version&gt;23.6-jre&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt; &lt;artifactId&gt;httpcore&lt;/artifactId&gt; &lt;version&gt;4.4.8&lt;/version&gt; &lt;/dependency&gt; </code></pre>
10,781,808
TSQL - how to execute a query as a variable?
<pre><code>DECLARE @query as varchar(200); SET @query = 'SELECT COUNT(*) FROM table'; </code></pre> <p>How can I execute <code>@query</code>, and additionally, is there way to store the query result directly when assigning the variable?</p>
10,781,850
3
0
null
2012-05-28 08:49:41.793 UTC
4
2018-09-19 18:24:55.3 UTC
2015-05-16 16:39:25.993 UTC
null
4,424,636
null
975,843
null
1
20
tsql|variables
79,474
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/ms188001.aspx"><code>sp_executesql</code></a> with an <code>output</code> parameter to retrieve the scalar result.</p> <pre><code>DECLARE @query as nvarchar(200), @count int; SET @query = N'SELECT @count = COUNT(*) FROM table'; EXEC sp_executesql @query, N'@count int OUTPUT', @count = @count OUTPUT SELECT @count AS [@count] </code></pre>
10,766,716
Set font for all textViews in activity?
<p>Is it possible to set the font for all the TextViews in a activity? I can set the font for a single textView by using: </p> <pre><code> TextView tv=(TextView)findViewById(R.id.textView1); Typeface face=Typeface.createFromAsset(getAssets(), "font.ttf"); tv.setTypeface(face); </code></pre> <p>But I would like to change all the textViews at once, instead of setting it manually for every textView, any info would be appreciated!</p>
10,766,791
8
0
null
2012-05-26 13:36:33.36 UTC
18
2020-03-25 16:36:44.217 UTC
null
null
null
null
1,262,576
null
1
52
android|fonts|textview|typeface
41,231
<p>Solution1:: Just call these method by passing parent view as argument.</p> <pre><code>private void overrideFonts(final Context context, final View v) { try { if (v instanceof ViewGroup) { ViewGroup vg = (ViewGroup) v; for (int i = 0; i &lt; vg.getChildCount(); i++) { View child = vg.getChildAt(i); overrideFonts(context, child); } } else if (v instanceof TextView ) { ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "font.ttf")); } } catch (Exception e) { } } </code></pre> <p>Solution2:: you can subclass the TextView class with your custom font and use it instead of textview.</p> <pre><code>public class MyTextView extends TextView { public MyTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public MyTextView(Context context) { super(context); init(); } private void init() { if (!isInEditMode()) { Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font.ttf"); setTypeface(tf); } } } </code></pre>
5,946,529
Scp command syntax for copying a folder from local machine to a remote server
<p>I am using putty for copying files from local machine to remote server.My folder is in <code>C:/site</code> can any one give syntax for copying folder from <code>C:/site</code> to remote server using <code>scp</code></p>
6,040,699
2
3
null
2011-05-10 07:20:22.31 UTC
11
2016-07-20 08:07:55.783 UTC
2016-07-20 08:07:55.783 UTC
null
235,710
null
273,266
null
1
40
linux|scp|putty
116,736
<p>In stall PuTTY in our system and set the environment variable PATH Pointing to putty path. open the command prompt and move to putty folder. Using PSCP command</p> <p><a href="ftp://ftp.zedat.fu-berlin.de/pc/network/putty/putty-0.55/htmldoc/Chapter5.html" rel="nofollow">Please check this</a></p>
19,625,211
Bootstrap linking to a tab with an url
<p>I am working with bootstrap 3, and I am having some problems on linking a url to a specific tab, the panel changes but the activated tab doesnt. So I want the line <code>&lt;a href="#tab2" data-toggle="tab"&gt;link&lt;/a&gt;</code>, to go to the tab2, but it only goes to the panel of the tab2, it doesn't activate the tab.</p> <p>Here is the html:</p> <pre><code>&lt;div class="tabbable"&gt; &lt;ul class="nav nav-tabs"&gt; &lt;li class="active"&gt;&lt;a href="#tab1" data-toggle="tab"&gt;Section 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tab2" data-toggle="tab"&gt;Section 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tab3" data-toggle="tab"&gt;Section 3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="tab-content"&gt; &lt;div class="tab-pane active" id="tab1"&gt; &lt;p&gt;&lt;a href="#tab2" data-toggle="tab"&gt;link&lt;/a&gt;.&lt;/p&gt; &lt;/div&gt; &lt;div class="tab-pane" id="tab2"&gt; &lt;p&gt; I'm in Section 2.&lt;/p&gt; &lt;/div&gt; &lt;div class="tab-pane" id="tab3"&gt; &lt;p&gt;Howdy, I'm in Section 3 &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>You can test this in this link <a href="http://bootply.com/90412" rel="noreferrer">http://bootply.com/90412</a></p>
19,804,343
3
0
null
2013-10-28 00:01:31.75 UTC
5
2017-12-14 02:22:50.16 UTC
2017-10-06 20:06:08.4 UTC
null
4,233,593
null
1,236,751
null
1
9
javascript|twitter-bootstrap-3
53,165
<p>In order to activate the tab you can use jQuery plugin as shown in <a href="http://getbootstrap.com/2.3.2/javascript.html#tabs">bootstrap</a>. So you can add this piece of jQuery code to your program to enable the tab:</p> <pre><code>$(function () { $('#tab1 a').click(function (e) { e.preventDefault(); $('a[href="' + $(this).attr('href') + '"]').tab('show'); }) }); </code></pre> <p>You can check this link: <a href="http://jsfiddle.net/nP2Zk/">Updated code</a></p>
32,322,386
How To Download Multiple Files Sequentially using NSURLSession downloadTask in Swift
<p>I have an app that has to download multiple large files. I want it to download each file one by one sequentially instead of concurrently. When it runs concurrently the app gets overloaded and crashes. </p> <p>So. Im trying to wrap a downloadTaskWithURL inside a NSBlockOperation and then setting the maxConcurrentOperationCount = 1 on the queue. I wrote this code below but it didnt work since both files get downloaded concurrently.</p> <pre><code>import UIKit class ViewController: UIViewController, NSURLSessionDelegate, NSURLSessionDownloadDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. processURLs() } func download(url: NSURL){ let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() let session = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil) let downloadTask = session.downloadTaskWithURL(url) downloadTask.resume() } func processURLs(){ //setup queue and set max conncurrent to 1 var queue = NSOperationQueue() queue.name = "Download queue" queue.maxConcurrentOperationCount = 1 let url = NSURL(string: "http://azspeastus.blob.core.windows.net/azurespeed/100MB.bin?sv=2014-02-14&amp;sr=b&amp;sig=%2FZNzdvvzwYO%2BQUbrLBQTalz%2F8zByvrUWD%2BDfLmkpZuQ%3D&amp;se=2015-09-01T01%3A48%3A51Z&amp;sp=r") let url2 = NSURL(string: "http://azspwestus.blob.core.windows.net/azurespeed/100MB.bin?sv=2014-02-14&amp;sr=b&amp;sig=ufnzd4x9h1FKmLsODfnbiszXd4EyMDUJgWhj48QfQ9A%3D&amp;se=2015-09-01T01%3A48%3A51Z&amp;sp=r") let urls = [url, url2] for url in urls { let operation = NSBlockOperation { () -&gt; Void in println("starting download") self.download(url!) } queue.addOperation(operation) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { //code } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { // } func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { var progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite) println(progress) } } </code></pre> <p>How can write this properly to achieve my goal of only download one file at a time.</p>
32,322,851
5
0
null
2015-09-01 01:50:58.07 UTC
29
2022-01-04 19:28:39.197 UTC
2019-09-18 13:25:37.233 UTC
null
5,175,709
null
1,495,000
null
1
34
ios|swift|multithreading|nsurlsession|nsoperation
30,191
<p>Your code won't work because <code>URLSessionDownloadTask</code> runs asynchronously. Thus the <code>BlockOperation</code> completes before the download is done and therefore while the operations fire off sequentially, the download tasks will continue asynchronously and in parallel.</p> <p>While there are work-arounds one can contemplate (e.g., recursive patterns initiating one request after the prior one finishes, non-zero semaphore pattern on background thread, etc.), the elegant solution is one of the proven asynchronous frameworks.</p> <p>In iOS 15 and later, we would use <code>async</code>-<code>await</code> method <a href="https://developer.apple.com/documentation/foundation/urlsession/3767355-download/" rel="noreferrer"><code>download(from:delegate:)</code></a>, e.g.</p> <pre class="lang-swift prettyprint-override"><code>func downloadFiles() async throws { let folder = try! FileManager.default .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) for url in urls { let (source, _) = try await URLSession.shared.download(from: url) let destination = folder.appendingPathComponent(url.lastPathComponent) try FileManager.default.moveItem(at: source, to: destination) } } </code></pre> <p>Where</p> <pre class="lang-swift prettyprint-override"><code>override func viewDidLoad() { super.viewDidLoad() Task { do { try await downloadFiles() } catch { print(error) } } } </code></pre> <p>That only works in iOS 15 and later. But Xcode 13.2 and later actually lets you use async-await in iOS 13, but you just have to write your own <code>async</code> rendition of <code>download</code>:</p> <pre class="lang-swift prettyprint-override"><code>extension URLSession { @available(iOS, deprecated: 15, message: &quot;Use `download(from:delegate:)` instead&quot;) func download(with url: URL) async throws -&gt; (URL, URLResponse) { try await download(with: URLRequest(url: url)) } @available(iOS, deprecated: 15, message: &quot;Use `download(for:delegate:)` instead&quot;) func download(with request: URLRequest) async throws -&gt; (URL, URLResponse) { let sessionTask = URLSessionTaskActor() return try await withTaskCancellationHandler { Task { await sessionTask.cancel() } } operation: { try await withCheckedThrowingContinuation { continuation in Task { await sessionTask.start(downloadTask(with: request) { location, response, error in guard let location = location, let response = response else { continuation.resume(throwing: error ?? URLError(.badServerResponse)) return } // since continuation can happen later, let's figure out where to store it ... let tempURL = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent(UUID().uuidString) .appendingPathExtension(request.url!.pathExtension) // ... and move it to there do { try FileManager.default.moveItem(at: location, to: tempURL) } catch { continuation.resume(throwing: error) return } continuation.resume(returning: (tempURL, response)) }) } } } } } private extension URLSession { actor URLSessionTaskActor { weak var task: URLSessionTask? func start(_ task: URLSessionTask) { self.task = task task.resume() } func cancel() { task?.cancel() } } } </code></pre> <p>And you would then call this rendition for iOS 13 and later:</p> <pre class="lang-swift prettyprint-override"><code>func downloadFiles() async throws { let folder = try! FileManager.default .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) for url in urls { let (source, _) = try await URLSession.shared.download(with: url) let destination = folder.appendingPathComponent(url.lastPathComponent) try FileManager.default.moveItem(at: source, to: destination) } } </code></pre> <hr /> <p>In iOS versions prior to 13, if you wanted to control the degree of concurrency of a series of asynchronous tasks, we would reach for an asynchronous <a href="https://developer.apple.com/documentation/foundation/operation" rel="noreferrer"><code>Operation</code></a> subclass.</p> <p>Or, in iOS 13 and later, you might also consider <a href="https://developer.apple.com/documentation/combine" rel="noreferrer">Combine</a>. (There are other third-party asynchronous programming frameworks, but I will restrict myself to Apple-provided approaches.)</p> <p>Both of these are described below in my original answer.</p> <hr /> <p><strong>Operation</strong></p> <p>To address this, you can wrap the requests in asynchronous <a href="https://developer.apple.com/documentation/foundation/operation" rel="noreferrer"><code>Operation</code></a> subclass. See <a href="https://developer.apple.com/library/ios/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationObjects/OperationObjects.html#//apple_ref/doc/uid/TP40008091-CH101-SW8" rel="noreferrer">Configuring Operations for Concurrent Execution</a> in the <em>Concurrency Programming Guide</em> for more information.</p> <p>But before I illustrate how to do this in your situation (the delegate-based <code>URLSession</code>), let me first show you the simpler solution when using the completion handler rendition. We'll later build upon this for your more complicated question. So, in Swift 3 and later:</p> <pre><code>class DownloadOperation : AsynchronousOperation { var task: URLSessionTask! init(session: URLSession, url: URL) { super.init() task = session.downloadTask(with: url) { temporaryURL, response, error in defer { self.finish() } guard let httpResponse = response as? HTTPURLResponse, 200..&lt;300 ~= httpResponse.statusCode else { // handle invalid return codes however you'd like return } guard let temporaryURL = temporaryURL, error == nil else { print(error ?? &quot;Unknown error&quot;) return } do { let manager = FileManager.default let destinationURL = try manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) .appendingPathComponent(url.lastPathComponent) try? manager.removeItem(at: destinationURL) // remove the old one, if any try manager.moveItem(at: temporaryURL, to: destinationURL) // move new one there } catch let moveError { print(&quot;\(moveError)&quot;) } } } override func cancel() { task.cancel() super.cancel() } override func main() { task.resume() } } </code></pre> <p>Where</p> <pre><code>/// Asynchronous operation base class /// /// This is abstract to class emits all of the necessary KVO notifications of `isFinished` /// and `isExecuting` for a concurrent `Operation` subclass. You can subclass this and /// implement asynchronous operations. All you must do is: /// /// - override `main()` with the tasks that initiate the asynchronous task; /// /// - call `completeOperation()` function when the asynchronous task is done; /// /// - optionally, periodically check `self.cancelled` status, performing any clean-up /// necessary and then ensuring that `finish()` is called; or /// override `cancel` method, calling `super.cancel()` and then cleaning-up /// and ensuring `finish()` is called. class AsynchronousOperation: Operation { /// State for this operation. @objc private enum OperationState: Int { case ready case executing case finished } /// Concurrent queue for synchronizing access to `state`. private let stateQueue = DispatchQueue(label: Bundle.main.bundleIdentifier! + &quot;.rw.state&quot;, attributes: .concurrent) /// Private backing stored property for `state`. private var rawState: OperationState = .ready /// The state of the operation @objc private dynamic var state: OperationState { get { return stateQueue.sync { rawState } } set { stateQueue.sync(flags: .barrier) { rawState = newValue } } } // MARK: - Various `Operation` properties open override var isReady: Bool { return state == .ready &amp;&amp; super.isReady } public final override var isExecuting: Bool { return state == .executing } public final override var isFinished: Bool { return state == .finished } // KVO for dependent properties open override class func keyPathsForValuesAffectingValue(forKey key: String) -&gt; Set&lt;String&gt; { if [&quot;isReady&quot;, &quot;isFinished&quot;, &quot;isExecuting&quot;].contains(key) { return [#keyPath(state)] } return super.keyPathsForValuesAffectingValue(forKey: key) } // Start public final override func start() { if isCancelled { finish() return } state = .executing main() } /// Subclasses must implement this to perform their work and they must not call `super`. The default implementation of this function throws an exception. open override func main() { fatalError(&quot;Subclasses must implement `main`.&quot;) } /// Call this function to finish an operation that is currently executing public final func finish() { if !isFinished { state = .finished } } } </code></pre> <p>Then you can do:</p> <pre><code>for url in urls { queue.addOperation(DownloadOperation(session: session, url: url)) } </code></pre> <p>So that's one very easy way to wrap asynchronous <code>URLSession</code>/<code>NSURLSession</code> requests in asynchronous <code>Operation</code>/<code>NSOperation</code> subclass. More generally, this is a useful pattern, using <code>AsynchronousOperation</code> to wrap up some asynchronous task in an <code>Operation</code>/<code>NSOperation</code> object.</p> <p>Unfortunately, in your question, you wanted to use delegate-based <code>URLSession</code>/<code>NSURLSession</code> so you could monitor the progress of the downloads. This is more complicated.</p> <p>This is because the &quot;task complete&quot; <code>NSURLSession</code> delegate methods are called at the session object's delegate. This is an infuriating design feature of <code>NSURLSession</code> (but Apple did it to simplify background sessions, which isn't relevant here, but we're stuck with that design limitation).</p> <p>But we have to asynchronously complete the operations as the tasks finish. So we need some way for the session to figure out which operation to complete when <code>didCompleteWithError</code> is called. Now you could have each operation have its own <code>NSURLSession</code> object, but it turns out that this is pretty inefficient.</p> <p>So, to handle that, I maintain a dictionary, keyed by the task's <code>taskIdentifier</code>, which identifies the appropriate operation. That way, when the download finishes, you can &quot;complete&quot; the correct asynchronous operation. Thus:</p> <pre><code>/// Manager of asynchronous download `Operation` objects class DownloadManager: NSObject { /// Dictionary of operations, keyed by the `taskIdentifier` of the `URLSessionTask` fileprivate var operations = [Int: DownloadOperation]() /// Serial OperationQueue for downloads private let queue: OperationQueue = { let _queue = OperationQueue() _queue.name = &quot;download&quot; _queue.maxConcurrentOperationCount = 1 // I'd usually use values like 3 or 4 for performance reasons, but OP asked about downloading one at a time return _queue }() /// Delegate-based `URLSession` for DownloadManager lazy var session: URLSession = { let configuration = URLSessionConfiguration.default return URLSession(configuration: configuration, delegate: self, delegateQueue: nil) }() /// Add download /// /// - parameter URL: The URL of the file to be downloaded /// /// - returns: The DownloadOperation of the operation that was queued @discardableResult func queueDownload(_ url: URL) -&gt; DownloadOperation { let operation = DownloadOperation(session: session, url: url) operations[operation.task.taskIdentifier] = operation queue.addOperation(operation) return operation } /// Cancel all queued operations func cancelAll() { queue.cancelAllOperations() } } // MARK: URLSessionDownloadDelegate methods extension DownloadManager: URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { operations[downloadTask.taskIdentifier]?.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { operations[downloadTask.taskIdentifier]?.urlSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite) } } // MARK: URLSessionTaskDelegate methods extension DownloadManager: URLSessionTaskDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { let key = task.taskIdentifier operations[key]?.urlSession(session, task: task, didCompleteWithError: error) operations.removeValue(forKey: key) } } /// Asynchronous Operation subclass for downloading class DownloadOperation : AsynchronousOperation { let task: URLSessionTask init(session: URLSession, url: URL) { task = session.downloadTask(with: url) super.init() } override func cancel() { task.cancel() super.cancel() } override func main() { task.resume() } } // MARK: NSURLSessionDownloadDelegate methods extension DownloadOperation: URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { guard let httpResponse = downloadTask.response as? HTTPURLResponse, 200..&lt;300 ~= httpResponse.statusCode else { // handle invalid return codes however you'd like return } do { let manager = FileManager.default let destinationURL = try manager .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent(downloadTask.originalRequest!.url!.lastPathComponent) try? manager.removeItem(at: destinationURL) try manager.moveItem(at: location, to: destinationURL) } catch { print(error) } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite) print(&quot;\(downloadTask.originalRequest!.url!.absoluteString) \(progress)&quot;) } } // MARK: URLSessionTaskDelegate methods extension DownloadOperation: URLSessionTaskDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { defer { finish() } if let error = error { print(error) return } // do whatever you want upon success } } </code></pre> <p>And then use it like so:</p> <pre><code>let downloadManager = DownloadManager() override func viewDidLoad() { super.viewDidLoad() let urlStrings = [ &quot;http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/s72-55482.jpg&quot;, &quot;http://spaceflight.nasa.gov/gallery/images/apollo/apollo10/hires/as10-34-5162.jpg&quot;, &quot;http://spaceflight.nasa.gov/gallery/images/apollo-soyuz/apollo-soyuz/hires/s75-33375.jpg&quot;, &quot;http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-134-20380.jpg&quot;, &quot;http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-140-21497.jpg&quot;, &quot;http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-148-22727.jpg&quot; ] let urls = urlStrings.compactMap { URL(string: $0) } let completion = BlockOperation { print(&quot;all done&quot;) } for url in urls { let operation = downloadManager.queueDownload(url) completion.addDependency(operation) } OperationQueue.main.addOperation(completion) } </code></pre> <p>See <a href="https://stackoverflow.com/revisions/32322851/4">revision history</a> for Swift 2 implementation.</p> <hr /> <p><strong>Combine</strong></p> <p>For <a href="https://developer.apple.com/documentation/combine" rel="noreferrer">Combine</a>, the idea would be to create a <code>Publisher</code> for <code>URLSessionDownloadTask</code>. Then you can do something like:</p> <pre><code>var downloadRequests: AnyCancellable? /// Download a series of assets func downloadAssets() { downloadRequests = downloadsPublisher(for: urls, maxConcurrent: 1).sink { completion in switch completion { case .finished: print(&quot;done&quot;) case .failure(let error): print(&quot;failed&quot;, error) } } receiveValue: { destinationUrl in print(destinationUrl) } } /// Publisher for single download /// /// Copy downloaded resource to caches folder. /// /// - Parameter url: `URL` being downloaded. /// - Returns: Publisher for the URL with final destination of the downloaded asset. func downloadPublisher(for url: URL) -&gt; AnyPublisher&lt;URL, Error&gt; { URLSession.shared.downloadTaskPublisher(for: url) .tryCompactMap { let destination = try FileManager.default .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent(url.lastPathComponent) try FileManager.default.moveItem(at: $0.location, to: destination) return destination } .receive(on: RunLoop.main) .eraseToAnyPublisher() } /// Publisher for a series of downloads /// /// This downloads not more than `maxConcurrent` assets at a given time. /// /// - Parameters: /// - urls: Array of `URL`s of assets to be downloaded. /// - maxConcurrent: The maximum number of downloads to run at any given time (default 4). /// - Returns: Publisher for the URLs with final destination of the downloaded assets. func downloadsPublisher(for urls: [URL], maxConcurrent: Int = 4) -&gt; AnyPublisher&lt;URL, Error&gt; { Publishers.Sequence(sequence: urls.map { downloadPublisher(for: $0) }) .flatMap(maxPublishers: .max(maxConcurrent)) { $0 } .eraseToAnyPublisher() } </code></pre> <p>Now, unfortunately, Apple supplies a <code>DataTaskPublisher</code> (which loads the full asset into memory which is not acceptable solution for large assets), but one can refer to <a href="https://github.com/apple/swift/blob/88b093e9d77d6201935a2c2fb13f27d961836777/stdlib/public/Darwin/Foundation/Publishers%2BURLSession.swift" rel="noreferrer">their source code</a> and adapt it to create a <code>DownloadTaskPublisher</code>:</p> <pre><code>// DownloadTaskPublisher.swift // // Created by Robert Ryan on 9/28/20. // // Adapted from Apple's `DataTaskPublisher` at: // https://github.com/apple/swift/blob/88b093e9d77d6201935a2c2fb13f27d961836777/stdlib/public/Darwin/Foundation/Publishers%2BURLSession.swift import Foundation import Combine // MARK: Download Tasks @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) extension URLSession { /// Returns a publisher that wraps a URL session download task for a given URL. /// /// The publisher publishes temporary when the task completes, or terminates if the task fails with an error. /// /// - Parameter url: The URL for which to create a download task. /// - Returns: A publisher that wraps a download task for the URL. public func downloadTaskPublisher(for url: URL) -&gt; DownloadTaskPublisher { let request = URLRequest(url: url) return DownloadTaskPublisher(request: request, session: self) } /// Returns a publisher that wraps a URL session download task for a given URL request. /// /// The publisher publishes download when the task completes, or terminates if the task fails with an error. /// /// - Parameter request: The URL request for which to create a download task. /// - Returns: A publisher that wraps a download task for the URL request. public func downloadTaskPublisher(for request: URLRequest) -&gt; DownloadTaskPublisher { return DownloadTaskPublisher(request: request, session: self) } public struct DownloadTaskPublisher: Publisher { public typealias Output = (location: URL, response: URLResponse) public typealias Failure = URLError public let request: URLRequest public let session: URLSession public init(request: URLRequest, session: URLSession) { self.request = request self.session = session } public func receive&lt;S: Subscriber&gt;(subscriber: S) where Failure == S.Failure, Output == S.Input { subscriber.receive(subscription: Inner(self, subscriber)) } private typealias Parent = DownloadTaskPublisher private final class Inner&lt;Downstream: Subscriber&gt;: Subscription, CustomStringConvertible, CustomReflectable, CustomPlaygroundDisplayConvertible where Downstream.Input == Parent.Output, Downstream.Failure == Parent.Failure { typealias Input = Downstream.Input typealias Failure = Downstream.Failure private let lock: NSLocking private var parent: Parent? // GuardedBy(lock) private var downstream: Downstream? // GuardedBy(lock) private var demand: Subscribers.Demand // GuardedBy(lock) private var task: URLSessionDownloadTask! // GuardedBy(lock) var description: String { return &quot;DownloadTaskPublisher&quot; } var customMirror: Mirror { lock.lock() defer { lock.unlock() } return Mirror(self, children: [ &quot;task&quot;: task as Any, &quot;downstream&quot;: downstream as Any, &quot;parent&quot;: parent as Any, &quot;demand&quot;: demand, ]) } var playgroundDescription: Any { return description } init(_ parent: Parent, _ downstream: Downstream) { self.lock = NSLock() self.parent = parent self.downstream = downstream self.demand = .max(0) } // MARK: - Upward Signals func request(_ d: Subscribers.Demand) { precondition(d &gt; 0, &quot;Invalid request of zero demand&quot;) lock.lock() guard let p = parent else { // We've already been cancelled so bail lock.unlock() return } // Avoid issues around `self` before init by setting up only once here if self.task == nil { let task = p.session.downloadTask( with: p.request, completionHandler: handleResponse(location:response:error:) ) self.task = task } self.demand += d let task = self.task! lock.unlock() task.resume() } private func handleResponse(location: URL?, response: URLResponse?, error: Error?) { lock.lock() guard demand &gt; 0, parent != nil, let ds = downstream else { lock.unlock() return } parent = nil downstream = nil // We clear demand since this is a single shot shape demand = .max(0) task = nil lock.unlock() if let location = location, let response = response, error == nil { _ = ds.receive((location, response)) ds.receive(completion: .finished) } else { let urlError = error as? URLError ?? URLError(.unknown) ds.receive(completion: .failure(urlError)) } } func cancel() { lock.lock() guard parent != nil else { lock.unlock() return } parent = nil downstream = nil demand = .max(0) let task = self.task self.task = nil lock.unlock() task?.cancel() } } } } </code></pre> <p>Now, unfortunately, that isn’t using <code>URLSession</code> delegate pattern, but rather the completion handler rendition. But one could conceivably adapt it for delegate pattern.</p> <p>Also, this will stop downloads when one fails. If you don't want it to stop just because one fails, you could conceivably define it to <code>Never</code> fail, and instead <code>replaceError</code> with <code>nil</code>:</p> <pre><code>/// Publisher for single download /// /// Copy downloaded resource to caches folder. /// /// - Parameter url: `URL` being downloaded. /// - Returns: Publisher for the URL with final destination of the downloaded asset. Returns `nil` if request failed. func downloadPublisher(for url: URL) -&gt; AnyPublisher&lt;URL?, Never&gt; { URLSession.shared.downloadTaskPublisher(for: url) .tryCompactMap { let destination = try FileManager.default .url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent(url.lastPathComponent) try FileManager.default.moveItem(at: $0.location, to: destination) return destination } .replaceError(with: nil) .receive(on: RunLoop.main) .eraseToAnyPublisher() } /// Publisher for a series of downloads /// /// This downloads not more than `maxConcurrent` assets at a given time. /// /// - Parameters: /// - urls: Array of `URL`s of assets to be downloaded. /// - maxConcurrent: The maximum number of downloads to run at any given time (default 4). /// - Returns: Publisher for the URLs with final destination of the downloaded assets. func downloadsPublisher(for urls: [URL], maxConcurrent: Int = 4) -&gt; AnyPublisher&lt;URL?, Never&gt; { Publishers.Sequence(sequence: urls.map { downloadPublisher(for: $0) }) .flatMap(maxPublishers: .max(maxConcurrent)) { $0 } .eraseToAnyPublisher() } </code></pre> <hr /> <p>Perhaps needless to say, I would generally discourage the downloading of assets/files sequentially. You should allow them to run concurrently, but control the degree of concurrency so your app is not overloaded. All of the patterns outlined above constrain the degree of concurrency to something reasonable.</p>
32,774,520
why matplotlib give the error [<matplotlib.lines.Line2D object at 0x0392A9D0>]?
<p>I am using python 2.7.9 on win8. When I tried to plot using matplotlib, the following error showed up:</p> <blockquote> <p>from pylab import *<br> plot([1,2,3,4])</p> <p><strong>[matplotlib.lines.Line2D object at 0x0392A9D0]</strong></p> </blockquote> <p>I tried the test code "python simple_plot.py --verbose-helpful", and the following warning showed up:</p> <blockquote> <p>$HOME=C:\Users\XX matplotlib data path C:\Python27\lib\site-packages\matplotlib\mpl-data</p> <hr> <p>You have the following UNSUPPORTED LaTeX preamble customizations:</p> <p>Please do not ask for support with these customizations active.</p> <hr> <p>loaded rc file C:\Python27\lib\site-packages\matplotlib\mpl-data\matplotlibrc matplotlib version 1.4.3 verbose.level helpful interactive is False platform is win32 CACHEDIR=C:\Users\XX.matplotlib Using fontManager instance from C:\Users\XX.matplotlib\fontList.cache backend TkAgg version 8.5 findfont: Matching :family=sans-serif:style=normal:variant=normal:weight=normal:stretch=normal:size=medium to Bitstream Vera Sans (u'C:\Python27\lib\site-packages\matplotlib\mpl-data\fonts\ttf\Vera.ttf') with score of 0.000000</p> </blockquote> <p>What does this mean? How could I get matplotlib working?</p>
32,774,547
5
0
null
2015-09-25 03:54:33.557 UTC
10
2021-10-19 04:26:09.46 UTC
2019-12-05 21:46:23.873 UTC
null
1,839,439
null
5,374,665
null
1
28
python|matplotlib
65,201
<p>That isn't an error. That has created a plot object but you need to show the window. That's done using <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show" rel="noreferrer"><code>pyplot.show()</code></a>. As stated in the comments, please do not use <code>pylab</code>, but use <code>matplotlib.pyplot</code> instead as <code>pylab</code> has been deprecated. As such, all you have to do is call:</p> <pre><code>plt.show() </code></pre> <p>Just for reproducibility, here's a trace from the Python REPL (using IPython):</p> <pre><code>In [1]: import matplotlib.pyplot as plt In [2]: plt.plot([1,2,3,4]) Out[2]: [&lt;matplotlib.lines.Line2D at 0x123245290&gt;] In [3]: plt.show() </code></pre> <p>We get:</p> <p><a href="https://i.stack.imgur.com/snnS0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/snnS0.png" alt="enter image description here" /></a></p> <hr /> <h1>What about in a Jupyter notebook?</h1> <p>If you are using this in a Jupyter notebook, instead of having to use <code>show()</code>, you can place the following in a separate cell after you import <code>matplotlib.pyplot</code>:</p> <pre><code>%matplotlib inline </code></pre> <p>This will automatically draw the figure once you create it and you will not have to use <code>show()</code> after you're done.</p>
21,537,782
How to set fixed continuous colour values in ggplot2
<p>I'm plotting a lot of graphics and I'd like for all of them to have the same colour scale so I can compare one to another. Here's my code:</p> <pre><code>myPalette &lt;- colorRampPalette(rev(brewer.pal(11, "Spectral"))) print(ggplot(mydata, aes(x= X, y= Y, colour= Z)) + geom_point(alpha=.5,size = 6) + scale_colour_gradientn(colours = myPalette(100)) + ylim(.1,.4) + xlim(1.5,2) + ggtitle(title)) </code></pre> <p>Is there a way to set this colour scale?</p>
21,538,521
3
0
null
2014-02-03 21:07:12.16 UTC
15
2018-11-20 19:47:43.57 UTC
2014-02-04 08:10:06.96 UTC
null
1,627,235
null
1,208,142
null
1
28
r|ggplot2
66,475
<p>Do I understand this correctly? You have two plots, where the values of the color scale are being mapped to different colors on different plots because the plots don't have the same values in them.</p> <pre><code>library("ggplot2") library("RColorBrewer") ggplot(subset(mtcars, am==0), aes(x=wt, y=mpg, colour=carb)) + geom_point(size=6) </code></pre> <p><img src="https://i.stack.imgur.com/cp9JZ.png" alt="enter image description here"> </p> <pre><code>ggplot(subset(mtcars, am==1), aes(x=wt, y=mpg, colour=carb)) + geom_point(size=6) </code></pre> <p><img src="https://i.stack.imgur.com/bwqEH.png" alt="enter image description here"> </p> <p>In the top one, dark blue is 1 and light blue is 4, while in the bottom one, dark blue is (still) 1, but light blue is now 8.</p> <p>You can fix the ends of the color bar by giving a <code>limits</code> argument to the scale; it should cover the whole range that the data can take in any of the plots. Also, you can assign this scale to a variable and add that to all the plots (to reduce redundant code so that the definition is only in one place and not in every plot).</p> <pre><code>myPalette &lt;- colorRampPalette(rev(brewer.pal(11, "Spectral"))) sc &lt;- scale_colour_gradientn(colours = myPalette(100), limits=c(1, 8)) ggplot(subset(mtcars, am==0), aes(x=wt, y=mpg, colour=carb)) + geom_point(size=6) + sc </code></pre> <p><img src="https://i.stack.imgur.com/gzF3U.png" alt="enter image description here"> </p> <pre><code>ggplot(subset(mtcars, am==1), aes(x=wt, y=mpg, colour=carb)) + geom_point(size=6) + sc </code></pre> <p><img src="https://i.stack.imgur.com/eI4Rz.png" alt="enter image description here"></p>
55,907,526
Angular mat-form-field center alignment
<p>Everywhere you can find how to center the text and even placeholder and labels and everything but I can't center the whole form-field and it looks ugly as hell.</p> <pre><code>&lt;div class="mat-app-background basic-container"&gt; &lt;div layout-gt-sm="column" style="min-width: 350px; max-width: 450px; margin:auto"&gt; &lt;mat-card flex-gt-sm class="push"&gt; &lt;div style="text-align:center;"&gt; &lt;mat-card-title&gt;Login&lt;/mat-card-title&gt; &lt;/div&gt; &lt;div style="text-align:center;"&gt; &lt;mat-card-content&gt; &lt;form [formGroup]="loginForm" class="form" (ngSubmit)="login()"&gt; &lt;table cellspacing="0"&gt; &lt;tr&gt; &lt;td&gt; &lt;mat-form-field&gt; &lt;div style="text-align:center;"&gt; &lt;input matInput placeholder="{{ 'LOGIN.USERNAME' | translate }}" name="username" formControlName="username" type="name" /&gt; &lt;mat-error *ngIf="formErrors.username" class="form__error"&gt;{{ formErrors.username }} &lt;/mat-error&gt; &lt;/div&gt; &lt;/mat-form-field&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>I hope this code needs. If not I will post the rest of the html. But it's just about centering the fields. Didn't used CSS here.</p> <p><a href="https://i.stack.imgur.com/VxmOh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VxmOh.png" alt=""></a></p>
55,908,020
2
2
null
2019-04-29 16:37:36.163 UTC
3
2021-06-29 02:30:09.623 UTC
null
null
null
null
10,565,504
null
1
8
angular|angular-material
38,221
<p>I would recommend you to use <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/" rel="noreferrer">flexbox</a>.</p> <p>I am also not sure why do you need to put it inside a , but I have removed it to simplify the demo. </p> <pre><code>&lt;div class="parent"&gt; &lt;mat-form-field&gt; &lt;div style="text-align:center;"&gt; &lt;input matInput placeholder="{{ 'LOGIN.USERNAME' | translate }}" name="username" formControlName="username" type="name" /&gt; &lt;mat-error *ngIf="formErrors.username" class="form__error"&gt;{{ formErrors.username }} &lt;/mat-error&gt; &lt;/div&gt; &lt;/mat-form-field&gt; &lt;/div&gt; </code></pre> <p>And on your CSS,</p> <pre><code>.parent { display: flex; justify-content: center; align-items: center; flex-direction: column; } </code></pre> <p>The properties <code>justify-content</code> and <code>align-items</code> with the value of <code>center</code> will center the flex children along the line and in the cross-axis respectively, thus placing them on the centre of the page. The property <code>flex-direction</code> with the value of <code>column</code> aligns the children (form fields) from top to bottom.</p>
54,299,273
Uploading Android App Bundle to Google Play Console - key signing error
<p>I'm trying to upload a brand new .aab file to the Google Play Console, but keep getting this error:</p> <blockquote> <p><strong>Upload failed</strong><br> You uploaded an APK or Android App Bundle that is signed with a key that is also used to sign APKs that are delivered to users. Because you are enrolled in App Signing by Google Play, you should sign your APK or Android App Bundle with a new key before you upload it.</p> </blockquote> <p>I'm completely stumped, as I generated a new key for this app bundle at the time of generating the app bundle, i.e. through the Build > Generate Signed Bundle / APK... menu item in Android Studio, so it is a brand new key, unused by other apps.<br> I've even tried creating a whole new keystore with a new key in it, but always get the same error. Is this some quirk someone else has come across? </p> <p>When enrolling for App Signing by Google Play for this app, I chose the <strong>"Let Google manage and protect your app signing key (recommended)"</strong> option, and from all the documentation I've read, the key that you use to sign the app with first becomes the "Upload Key", so it seems like I'm doing everything correctly, but no dice. </p> <p>Does anyone have any advice, or past experience on this?</p>
54,381,614
14
0
null
2019-01-21 23:37:09.407 UTC
7
2022-04-26 09:22:31.397 UTC
2020-12-31 10:46:06.413 UTC
null
6,296,561
null
845,205
null
1
59
android|google-play-console
73,719
<p>Well, after a lot of screaming and shouting, including reaching out to Google Play Console support in chat (they're only first level support, so... not much help) and email (who put me in the too hard basket and said they can't offer support for app development - what? the problem is to do with uploading an app to Play Console, not app dev!), I discovered this self answered question <a href="https://stackoverflow.com/a/54359729/845205">https://stackoverflow.com/a/54359729/845205</a>. </p> <p>Basically, make sure you're doing a Clean &amp; Rebuild Project whenever doing <em>anything</em> to do with signing in Android Studio. For some reason it thought my new app was using the key from my old app and kept signing with that. (I guess the solution was app development support after all!)</p>
19,227,243
Write a data frame to csv file without column header in R
<p>I would like to store the contents of my data frame into a .csv file without the names of columns. I use the following piece of code,</p> <pre><code>write.csv(cur_data,new_file, row.names = F, col.names=F) </code></pre> <p>The resulting file looks like this,</p> <pre><code>"V1","V2" -0.02868862,5.442283e-11 -0.03359281,7.669754e-12 -0.03801883,-1.497323e-10 -0.04320051,-6.557672e-11 </code></pre> <p>However I would like to have the file in the following format,</p> <pre><code>-0.02868862,5.442283e-11 -0.03359281,7.669754e-12 -0.03801883,-1.497323e-10 -0.04320051,-6.557672e-11 </code></pre> <p>I don't understand why the the col.names parameter in the code is not taken into consideration</p>
19,227,265
1
0
null
2013-10-07 14:18:37.123 UTC
4
2013-10-07 14:30:37.787 UTC
2013-10-07 14:19:07.917 UTC
null
1,315,767
null
2,834,604
null
1
56
r|col
83,319
<p>Dont use <code>write.csv</code>, use <code>write.table</code></p> <pre><code> write.table( &lt;yourdf&gt;, sep=",", col.names=FALSE) </code></pre> <p>You cannot change many settings in <code>write.csv</code> -- the arguments are just there as a reminder to the user. From the documentation: </p> <blockquote> <p>These wrappers are deliberately inflexible: they are designed to ensure that the correct conventions are used to write a valid file. Attempts to change append, col.names, sep, dec or qmethod are ignored</p> </blockquote>
8,889,679
how to create a cookie and add to http response from inside my service layer?
<p>I am creating a custom authentication service in my spring mvc application:</p> <pre><code>@Service public class AuthenticationServiceImpl implements AuthenticationService { @Autowired UserService userService; @Override public void login(String email, String password) { boolean isValid = userService.isValidLogin(email, password); if(isValid) { // ??? create a session cookie and add to http response } } } </code></pre> <p>How can I create and add the cookie to the response?</p>
8,890,865
4
0
null
2012-01-17 04:32:26.907 UTC
3
2017-12-10 14:00:25.497 UTC
null
null
null
null
39,677
null
1
21
java|spring|cookies|spring-mvc
124,703
<p>In Spring MVC you get the HtppServletResponce object by default .</p> <pre><code> @RequestMapping("/myPath.htm") public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{ //Do service call passing the response return new ModelAndView("CustomerAddView"); } //Service code Cookie myCookie = new Cookie("name", "val"); response.addCookie(myCookie); </code></pre>
8,898,020
Taking the record with the max date
<p>Let's assume I extract some set of data.</p> <p>i.e.</p> <pre><code>SELECT A, date FROM table </code></pre> <p>I want just the record with the max date (for each value of A). I could write </p> <pre><code>SELECT A, col_date FROM TABLENAME t_ext WHERE col_date = (SELECT MAX (col_date) FROM TABLENAME t_in WHERE t_in.A = t_ext.A) </code></pre> <p><strong>But my query is really long... is there a more compact way using ANALYTIC FUNCTION to do the same?</strong></p>
8,898,142
7
0
null
2012-01-17 16:19:08.24 UTC
13
2021-07-31 05:46:51.137 UTC
2019-03-21 13:20:27.193 UTC
null
2,753,501
null
196,210
null
1
34
oracle|date|max|analytic-functions
209,158
<p>The analytic function approach would look something like</p> <pre><code>SELECT a, some_date_column FROM (SELECT a, some_date_column, rank() over (partition by a order by some_date_column desc) rnk FROM tablename) WHERE rnk = 1 </code></pre> <p>Note that depending on how you want to handle ties (or whether ties are possible in your data model), you may want to use either the <code>ROW_NUMBER</code> or the <code>DENSE_RANK</code> analytic function rather than <code>RANK</code>.</p>
8,858,584
How to wrap text in a JTextArea
<p>I have a JTextArea in Java. When I place a large amount of text in it, the text area provides horizontal scrolling.</p> <p>How can I make my text area wrap instead?</p>
8,858,616
5
0
null
2012-01-13 23:21:23.38 UTC
3
2022-05-28 20:35:53.193 UTC
2012-01-13 23:58:26.663 UTC
null
714,968
null
1,030,885
null
1
35
java|swing|jtextarea|word-wrap
81,614
<p>Use the <a href="http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html#setLineWrap(boolean)" rel="noreferrer"><code>JTextArea#setLineWrap</code></a> method. This is also illustrated in the <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/textarea.html" rel="noreferrer">Swing <code>JTextArea</code> tutorial</a></p>
968,904
ASP.NET MVC: url routing vs querystring
<p>I have a page routed like <code>/Comments/Search/3</code> where i search and display all the comments of the thread "3".</p> <p>I'm adding a sort function (by date, author etc). What is the best way to handle it? <code>/Comments/Search/3/Sort/Author</code> or <code>/Comments/Search/3?sort=author</code> ?</p> <p>How do I automatically handle the querystring sort=author as a parameter in MVC?</p> <p>Thanks</p>
968,927
3
0
null
2009-06-09 08:42:46.503 UTC
15
2009-06-20 07:05:00.753 UTC
2009-06-20 07:05:00.753 UTC
null
63,756
null
42,636
null
1
42
asp.net-mvc|routing|query-string
42,804
<p>I prefer: /Comments/Search/3?sort=author. The querystring is a good place to pass in programmatic parameters, especially if the parameter (like in this case) is not important for SEO purposes. If the parameter had some semantic meaning as a search term, the first URL would be better.</p> <p>In a controller method you can use something like this:</p> <pre><code>public ActionResult Search(int id, string sort) </code></pre> <p>ASP.NET MVC will automatically wire up querystring values to the parameters of your method.</p> <p>Use the following route</p> <pre><code>routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Comments", action = "Search", id = "" } // Parameter defaults ); </code></pre> <p>/Comments/Search/3?sort=author will call Search(3, "author") </p> <p>/Comments/Search/3 will call Search(3, null)</p> <p>Keep in mind that id is mandatory so this url will fail: /Comments/Search</p>
51,969
How to detect READ_COMMITTED_SNAPSHOT is enabled?
<p>In Microsoft SQL Server, is there a way to detect whether a database has had its isolation level set via the T-SQL command <code>ALTER DATABASE &lt;database&gt; SET READ_COMMITTED_SNAPSHOT ON;</code>?</p> <p>I cannot find a simple way to detect this in either T-SQL or via the Management Studio's GUI.</p>
51,977
3
0
null
2008-09-09 14:07:11.823 UTC
36
2022-02-01 13:31:02.123 UTC
2022-02-01 13:28:51.513 UTC
null
8,839,059
Chris Driver
5,217
null
1
138
sql-server|isolation-level|read-committed-snapshot
125,283
<pre><code>SELECT is_read_committed_snapshot_on FROM sys.databases WHERE name= 'YourDatabase' </code></pre> <p>Return value:</p> <ul> <li><strong>1</strong>: <code>READ_COMMITTED_SNAPSHOT</code> option is <strong>ON</strong>. Read operations under the <code>READ COMMITTED</code> isolation level are based on snapshot scans and do not acquire locks.</li> <li><strong>0</strong> (default): <code>READ_COMMITTED_SNAPSHOT</code> option is <strong>OFF</strong>. Read operations under the <code>READ COMMITTED</code> isolation level use <a href="https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms175519(v=sql.105)" rel="nofollow noreferrer">Shared (S) locks</a>.</li> </ul>
39,703,048
Does Spark support true column scans over parquet files in S3?
<p>One of the great benefits of the Parquet data storage format is that <a href="https://stackoverflow.com/a/36831549/189336">it's columnar</a>. If I've got a 'wide' dataset with hundreds of columns, but my query only touches a few of those, then it's possible read only the data that stores those few columns, and skip the rest.</p> <p>Presumably this feature works by reading a bit of metadata at the head of a parquet file that indicates the locations on the filesystem for each column. The reader can then seek on disk to read in only the necessary columns.</p> <p>Does anyone know whether spark's default parquet reader correctly implements this kind of selective seeking on S3? I think <a href="https://stackoverflow.com/questions/36436057/s3-how-to-do-a-partial-read-seek-without-downloading-the-complete-file">it's supported by S3</a>, but there's a big difference between theoretical support and an implementation that properly exploits that support.</p>
47,671,804
4
1
null
2016-09-26 12:37:40.147 UTC
13
2018-03-13 11:21:15.223 UTC
2017-11-29 14:36:25.803 UTC
null
1,305,344
null
189,336
null
1
35
apache-spark|amazon-s3|apache-spark-sql|parquet
4,130
<p>This needs to be broken down</p> <ol> <li>Does the Parquet code get the predicates from spark (yes)</li> <li>Does parquet then attempt to selectively read only those columns, using the Hadoop <code>FileSystem</code> <code>seek()</code> + <code>read()</code> or <code>readFully(position, buffer, length)</code> calls? Yes</li> <li>Does the S3 connector translate these File Operations into efficient HTTP GET requests? In Amazon EMR: Yes. In Apache Hadoop, you need hadoop 2.8 on the classpath and set the properly <code>spark.hadoop.fs.s3a.experimental.fadvise=random</code> to trigger random access.</li> </ol> <p>Hadoop 2.7 and earlier handle the aggressive seek() round the file badly, because they always initiate a GET offset-end-of-file, get surprised by the next seek, have to abort that connection, reopen a new TCP/HTTPS 1.1 connection (slow, CPU heavy), do it again, repeatedly. The random IO operation hurts on bulk loading of things like .csv.gz, but is critical to getting ORC/Parquet perf.</p> <p>You don't get the speedup on Hadoop 2.7's hadoop-aws JAR. If you need it you need to update hadoop*.jar and dependencies, or build Spark up from scratch against Hadoop 2.8</p> <p>Note that Hadoop 2.8+ also has a nice little feature: if you call <code>toString()</code> on an S3A filesystem client in a log statement, it prints out all the filesystem IO stats, including how much data was discarded in seeks, aborted TCP connections &amp;c. Helps you work out what's going on.</p> <p><strong>2018-04-13 warning:</strong>: Do not try to drop the Hadoop 2.8+ <code>hadoop-aws</code> JAR on the classpath along with the rest of the hadoop-2.7 JAR set and expect to see any speedup. All you will see are stack traces. You need to update all the hadoop JARs and their transitive dependencies.</p>
35,279,933
Update Table Using Laravel Model
<p>I've got a table for a sports team. The record shows the team selection and some other information. I want to update the record with the team selection. My model is thus:</p> <pre><code>class Selection extends Model { protected $table = "selection"; protected $fillable = [ 'loose', 'hooker', 'tight', 'secrow1', 'secrow2', 'blindflank', 'openflank', 'eight', 'scrum', 'fly', 'leftwing', 'rightwing', 'fullback', 'sub1', 'sub2', 'sub3', 'sub4', 'sub5' ]; </code></pre> <p>}</p> <p>So I have a form which gives all the data for the positions and gives the id for the record in the DB. In my controller, I've got:</p> <pre><code>public function storeFirstTeam() { $input = Request::all(); Selection::update($input-&gt;id,$input); return redirect('first-team'); } </code></pre> <p>But I get the following error:</p> <blockquote> <p>Non-static method Illuminate\Database\Eloquent\Model::update() should not be called statically, assuming $this from incompatible context</p> </blockquote> <p>Can anyone point out my silly error?</p>
35,280,064
4
2
null
2016-02-08 21:43:51.653 UTC
4
2022-07-06 09:02:32.21 UTC
null
null
null
null
3,436,996
null
1
33
laravel|model|eloquent
82,491
<p>Please check the code below and this would solve your problem: </p> <pre><code>Selection::whereId($id)-&gt;update($request-&gt;all()); </code></pre>
59,375,668
How to install Nuget package using windows command line in C# project?
<p>I have downloaded NuGet version - 5.1.0 and tried to install one of the package - log4net using cmd. it failed. below is error -</p> <blockquote> <p>Microsoft Windows [Version 10.0.19042.1348] (c) Microsoft Corporation. All rights reserved.</p> <p>D:\Personal\ConsoleApplication1\ClassLibrary1&gt;&quot;D:\Personal\ConsoleApplication1\nuget_1\nuget.exe&quot; install-package log4net Unknown command: 'install-package' NuGet.CommandLine.CommandLineException: Unknown command: 'install-package' at NuGet.CommandLine.CommandManager.GetCommand(String commandName) at NuGet.CommandLine.CommandLineParser.ParseCommandLine(IEnumerable`1 commandLineArgs) at NuGet.CommandLine.Program.MainCore(String workingDirectory, String[] args)</p> <p>D:\Personal\ConsoleApplication1\ClassLibrary1&gt;</p> </blockquote> <p>Here, ClassLibrary1 is C# project where I have to add log4net package. I don't want to use NuGet Package Manager Console option available in Visual Studio.</p> <p>Did I write correct command?</p>
59,375,752
3
2
null
2019-12-17 13:48:21.633 UTC
2
2021-11-27 06:08:43.663 UTC
2021-11-27 06:08:43.663 UTC
null
2,638,841
null
2,638,841
null
1
4
c#|visual-studio-2017|nuget|nuget-package
42,046
<p>Install-Package is how you install via Visual Studio. The cmdlet to install a package via the CLI is <code>nuget install &lt;Package-Name&gt;</code>.</p> <p>Please see this Microsoft Doc for reference: <a href="https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-nuget-cli" rel="noreferrer">https://docs.microsoft.com/en-us/nuget/consume-packages/install-use-packages-nuget-cli</a></p>
6,120,465
How to retrieve an Oracle directory path?
<p>I created the following Oracle Directory <code>csvDir</code>:</p> <pre><code>create or replace directory csvDir as 'd:\oracle\oradata\external_data\downloadedFiles'; </code></pre> <p>Now, how can I retrieve the path from this <code>csvDir</code> alias?</p> <p>There should be some system table that stores this path.</p>
6,120,502
3
0
null
2011-05-25 06:36:20.07 UTC
3
2014-11-17 10:21:49.607 UTC
2011-05-25 06:38:03.12 UTC
null
135,152
null
607,874
null
1
26
oracle|directory
163,089
<p>That would be the ALL_DIRECTORIES view:</p> <p><a href="http://download.oracle.com/docs/cd/B28359_01/server.111/b28320/statviews_1075.htm#i1576965">http://download.oracle.com/docs/cd/B28359_01/server.111/b28320/statviews_1075.htm#i1576965</a></p>
5,938,802
Are "(function ( ) { } ) ( )" and "(function ( ) { } ( ) )" functionally equal in JavaScript?
<p>Both of these code blocks below alert <code>foo</code> then <code>bar</code>. The only difference is <code>})()</code> and <code>}())</code>.</p> <p>Code 1:</p> <pre><code>(function() { bar = 'bar'; alert('foo'); })(); alert(bar); </code></pre> <p>Code 2:</p> <pre><code>(function() { bar = 'bar'; alert('foo'); }()); alert(bar); </code></pre> <p>So is there any difference, apart from the syntax?</p>
5,938,845
3
2
null
2011-05-09 15:07:22.523 UTC
42
2013-01-15 15:07:43.713 UTC
2011-06-01 00:25:55.72 UTC
null
34,397
null
224,004
null
1
57
javascript|function
6,308
<p>No; they are identical</p> <hr /> <p>However, if you add <code>new</code> beforehand and <code>.something</code> afterwards, they will be different.</p> <h1>Code 1</h1> <pre><code>new (function() { this.prop = 4; }) ().prop; </code></pre> <p>This code creates a new instance of this function's class, then gets the <code>prop</code> property of the new instance.<br /> It returns <code>4</code>.</p> <p>It's equivalent to</p> <pre><code>function MyClass() { this.prop = 4; } new MyClass().prop; </code></pre> <hr /> <h1>Code 2</h1> <pre><code>new ( function() { return { Class: function() { } }; }() ).Class; </code></pre> <p>This code calls <code>new</code> on the <code>Class</code> property.<br /> Since the parentheses for the function call are inside the outer set of parentheses, they aren't picked up by the <code>new</code> expression, and instead call the function normally, returning its return value.<br /> The <code>new</code> expression parses up to the <code>.Class</code> and instantiates that. (the parentheses after <code>new</code> are optional)</p> <p>It's equivalent to</p> <pre><code>var namespace = { Class: function() { } }; function getNamespace() { return namespace; } new ( getNamespace() ).Class; //Or, new namespace.Class; </code></pre> <p>Without the parentheses around the call to <code>getNamespace()</code>, this would be parsed as <code>(new getNamespace()).Class</code> — it would call instantiate the <code>getNamespace</code> class and return the <code>Class</code> property of the new instance.</p>
1,598,351
emacs, etags and using emacs as an IDE
<p>My usual tools are Emacs with g++ on a Linux system to implement my research algorithms. For the last some years, I have used emacs in a fairly basic way. I open C or C++ files, edit them with a syntax highlighting scheme of my choice and compile and do other stuff from within emacs (or maybe from a terminal), including using gdb within emacs for debugging. I know about etags and ctags and have played a bit with etags and emacs but don't seem to find that "sweet spot" with the tools.</p> <p>I was wondering, what do others do to configure emacs just so that it meshes nicely with etags and other tools? What tweaks does one need to do to emacs to make it a better IDE?</p>
1,598,678
2
0
null
2009-10-21 01:51:51.673 UTC
12
2016-08-21 00:34:35.553 UTC
2016-08-21 00:34:35.553 UTC
null
2,395,796
null
193,272
null
1
13
c++|c|emacs|ide|ctags
13,711
<p>For just tagging info, I also recommend <a href="http://www.gnu.org/software/global/" rel="noreferrer">GNU Global</a>. CScope can do a lot also. In both cases, they provide a way to find the location of a tag by name, and also the uses of a particular tag.</p> <p>For "IDE Stuff" there is more to it than just a tagging system. For that, I recommend the <a href="http://cedet.sf.net" rel="noreferrer">CEDET</a> set of tools for Emacs. This provides a project management system (EDE) which can create Makefiles to compile your code for you. There is also a parsing and code analysis part (Semantic) which provides smart completion. There is a template / code generation system (SRecode) which can convert tags from semantic back into code. There is even a UML diagram editor (COGRE) which can generate code from a class diagram that you draw in Emacs.</p> <p>Most people using CEDET only use the parser and smart completion systems, possibly in combination with <a href="http://ecb.sf.net" rel="noreferrer">ECB</a>, and it is ok to use only a subset of CEDET.</p> <p>For good measure CEDET will also integrate with GNU Global databases so you can reference symbol uses in addition to tag locations along with the regular GNU Global interface for Emacs.</p>
1,439,564
iPhone - getting unique values from NSArray object
<p>I have an <code>NSArray</code> formed with objects of a custom class. The class has 3 (city, state, zip) string properties. I would like to get all unique state values from the <code>array</code>.</p> <p>I did read through the <code>NSPredicate</code> class but couldn't make much of how to use it in this case. The only examples I could find were for string operations.</p> <p>Can someone please help me out?</p>
1,439,635
2
0
null
2009-09-17 15:24:39.033 UTC
37
2013-06-07 11:52:14.66 UTC
2013-06-07 11:52:14.66 UTC
null
1,355,704
null
46,297
null
1
55
iphone|nsarray|nspredicate
39,990
<p>The totally simple one liner:</p> <pre><code>NSSet *uniqueStates = [NSSet setWithArray:[myArrayOfCustomObjects valueForKey:@"state"]]; </code></pre> <p>The trick is the <code>valueForKey:</code> method of <code>NSArray</code>. That will iterate through your array (<code>myArrayOfCustomObjects</code>), call the <code>-state</code> method on each object, and build an array of the results. We then create an <code>NSSet</code> with the resulting array of states to remove duplicates.</p> <hr> <p>Starting with iOS 5 and OS X 10.7, there's a new class that can do this as well: <code>NSOrderedSet</code>. The advantage of an ordered set is that it will remove any duplicates, but also maintain relative order.</p> <pre><code>NSArray *states = [myArrayOfCustomObjects valueForKey:@"state"]; NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:states]; NSSet *uniqueStates = [orderedSet set]; </code></pre>
2,190,056
NSDictionary - Need to check whether dictionary contains key-value pair or not
<p>I just need to ask something as follow. Suppose I am having a dictionary.</p> <pre><code>NSMutableDictionary *xyz=[[NSMutableDictionary alloc] init]; [xyz setValue:@"sagar" forKey:@"s"]; [xyz setValue:@"amit" forKey:@"a"]; [xyz setValue:@"nirav" forKey:@"n"]; [xyz setValue:@"abhishek" forKey:@"a"]; [xyz setValue:@"xrox" forKey:@"x"]; </code></pre> <p>Now, I need to check as follows</p> <p>[xyz does contains key "b" value ?? pair or not?</p> <p>Question is How? </p> <p>The other question is How to just count total key-value pair?</p> <p>Say for example <code>NSInteger mCount=[xyz keyCounts];</code></p>
2,190,068
2
0
null
2010-02-03 06:13:03.723 UTC
9
2017-12-20 06:18:31.89 UTC
2016-01-04 07:05:44.53 UTC
null
3,908,884
null
140,765
null
1
99
ios|objective-c|nsdictionary
106,924
<p>Just ask it for the <code>objectForKey:@"b"</code>. If it returns <code>nil</code>, no object is set at that key.</p> <pre><code>if ([xyz objectForKey:@"b"]) { NSLog(@"There's an object set for key @\"b\"!"); } else { NSLog(@"No object set for key @\"b\""); } </code></pre> <p><strong>Edit</strong>: As to your edited second question, it's simply <code>NSUInteger mCount = [xyz count];</code>. Both of these answers are documented well and easily found in the <a href="https://developer.apple.com/documentation/foundation/nsdictionary" rel="noreferrer">NSDictionary</a> class reference (<a href="https://developer.apple.com/documentation/foundation/nsdictionary/1414347-objectforkey?language=objc" rel="noreferrer">[1]</a> <a href="https://developer.apple.com/documentation/foundation/nsdictionary/1409628-count?language=objc" rel="noreferrer">[2]</a>). </p>
57,263,525
useEffect not being called and not updating state when api is fetched
<p>I'm fetching data from a weather api using useEffect hook and declaring the dependency correctly as well. My state is still not being updated and I get errors in my render function because of that. I've pretty much tried everything from getting rid of the dependency array to declaring multiples in the dependency array. I don't know what's wrong with my function. The API's JSON response is in this format: </p> <pre><code>{ location: { name: "Paris", region: "Ile-de-France", }, current: { last_updated_epoch: 1564279222, last_updated: "2019-07-28 04:00", temp_c: 16, temp_f: 60.8, is_day: 0, condition: { text: "Clear", icon: "//cdn.apixu.com/weather/64x64/night/113.png", code: 1000 }, wind_mph: 6.9, wind_kph: 11.2 } } </code></pre> <p>and this is what my code looks like: </p> <pre><code>const Weather = ({ capital }) =&gt; { const [weather, setWeather] = useState(null); useEffect(() =&gt; { console.log("useEffect called"); const getWeather = async () =&gt; { try { const res = await axios.get( `http://api.apixu.com/v1/current.json?key=53d601eb03d1412c9c004840192807&amp;q=${capital}` ); setWeather(res.data); } catch (e) { console.log(e); } }; getWeather(); }, [capital]); console.log(weather); return ( &lt;Card style={{ width: "18rem", marginTop: "25px" }}&gt; &lt;Card.Img variant="top" src={weather.current.condition.icon} /&gt; &lt;Card.Header style={{ textAlign: "center", fontSize: "25px" }}&gt; Weather in {capital} &lt;/Card.Header&gt; &lt;/Card&gt; ) } </code></pre> <p>I expect to get to be shown image of the icon but I get this error message in my render function:</p> <pre><code>TypeError: Cannot read property 'current' of null Weather src/components/Weather.js:26 23 | 24 | return ( 25 | &lt;Card style={{ width: "18rem", marginTop: "25px" }}&gt; 26 | &lt;Card.Img variant="top" src={weather.current.condition.icon} /&gt; | ^ 27 | 28 | &lt;Card.Header style={{ textAlign: "center", fontSize: "25px" }}&gt; 29 | Weather in {capital} </code></pre> <p>and my <code>console.log(weather)</code> return null, the original state even though its being called after useEffect() and <code>console.log(useEffect called)</code> does not log at all which mean useEffect is not being called.</p>
57,263,556
3
2
null
2019-07-30 02:22:45.36 UTC
2
2021-12-15 16:12:20.043 UTC
2021-04-20 07:50:42.997 UTC
null
5,714,933
null
11,275,845
null
1
10
javascript|reactjs|react-hooks|use-effect
40,512
<p>The error message gives it away, <code>Cannot read property 'current' of null</code>, the only place where <code>current</code> is called is in <code>weather.current</code> in the <code>src</code> of <code>Card.Img</code>, so we deduce that <code>weather</code> was <code>null</code> during the render.</p> <p>The reason this happens is because the api call is asynchronus, it doesn't populate the state immediately, so the render happens first and tries to read <code>.current</code> from the initial weather state <code>null</code>.</p> <p>Solution: in your <code>render</code> method, make sure not to read <code>weather.current</code> while <code>weather</code> is <code>null</code>.</p> <p>You can for example use <code>{weather &amp;&amp; &lt;Card&gt;...&lt;/Card}</code> to hide the whole card until the data is loaded and show a loading indicator, or you can use <code>src={weather &amp;&amp; weather.current.condition.icon}</code> as a quick workaround.</p> <pre><code>const Weather = ({capital}) =&gt; { const [weather, setWeather] = useState(null); useEffect(() =&gt; { console.log(&quot;useEffect called&quot;); const getWeather = async () =&gt; { try { const res = await axios.get( `http://api.apixu.com/v1/current.json?key=53d601eb03d1412c9c004840192807&amp;q=${capital}`, ); setWeather(res.data); } catch (e) { console.log(e); } }; getWeather(); }, [capital]); console.log(weather); return ( &lt;Card style={{width: &quot;18rem&quot;, marginTop: &quot;25px&quot;}}&gt; &lt;Card.Img variant=&quot;top&quot; src={weather &amp;&amp; weather.current.condition.icon} /&gt; &lt;Card.Header style={{textAlign: &quot;center&quot;, fontSize: &quot;25px&quot;}}&gt; Weather in {capital} &lt;/Card.Header&gt; &lt;/Card&gt; ); }; </code></pre>
28,916,917
SQL count rows in a table
<p>I need to send a SQL query to a database that tells me how many rows there are in a table. I could get all the rows in the table with a SELECT and then count them, but I don't like to do it this way. Is there some other way to ask the number of the rows in a table to the SQL server?</p>
28,916,930
6
1
null
2015-03-07 16:11:58.077 UTC
15
2021-12-15 17:36:42.513 UTC
2015-03-07 16:17:09.06 UTC
null
437,818
null
4,229,007
null
1
89
sql-server|count|rows|database-table
287,455
<p>Yes, <code>SELECT COUNT(*) FROM TableName</code></p>
50,365,598
Typescript runtime error: cannot read property of undefined (enum)
<p>I have the following interface and enum in a file <em>RESTConfig.ts</em>:</p> <pre><code>export const enum RESTMethod { POST = "POST", GET = "GET" } export interface RESTConfig { url: string; method: RESTMethod; data: any; } </code></pre> <p>I want to import and use the enum in another class as such:</p> <pre><code>import { RESTConfig, RESTMethod } from './RESTConfig'; class Pipelines { ... private someMethod() { let rest: RESTConfig = { url: "", method: RESTMethod.POST, data: {} } ... } ... } </code></pre> <p>Linting and transpiling works fine, but at runtime I get the following error:</p> <blockquote> <p>TypeError: Cannot read property 'POST' of undefined</p> </blockquote> <p>on the line "method: RESTMethod.POST".</p> <p>Can someone tell me what I'm doing wrong?</p>
53,232,849
7
2
null
2018-05-16 08:13:41.38 UTC
5
2021-12-01 09:31:51.64 UTC
null
null
null
null
1,764,970
null
1
47
typescript|enums|undefined
20,542
<p>In Typescript there are 2 kinds of enums:</p> <ul> <li><em>Classic</em> <code>enum</code>: </li> </ul> <p>During TS to JS transpilation they are converted to real objects, so they exist at runtime.</p> <pre><code>enum Response { No = 0, Yes = 1, } const yes = Response.Yes; // Works at runtime const nameOfYes = Response[yes]; // Also works at runtime because a reverse mapping is also generated during transpilation </code></pre> <ul> <li><code>const enum</code> (the one you are using):</li> </ul> <p>Const enums are removed during transpilation in JS so you can not use them at runtime. As per <a href="https://www.typescriptlang.org/docs/handbook/enums.html" rel="noreferrer">TS doc</a> const enums exists to <em>avoid paying the cost of extra generated code and additional indirection when accessing enum values</em>.</p> <pre><code>const enum Response { No = 0, Yes = 1, } const yes = Response.Yes; // At runtime: ReferenceError: Response is not defined const nameOfYes = Response[yes]; // During transpilation: TS2476: A const enum member can only be accessed using a string literal. </code></pre> <hr> <p>So just change your <code>const enum</code> to <code>enum</code> and your runtime error will be gone. </p>
5,885,739
Why are some textboxes not accepting Control + A shortcut to select all by default
<p>I have found a few textboxes here and there in my program that accepts Control+A shortcut to select the entire text "by default" with "no coding". </p> <p>I don't know what additional information I have to give here to enable it for all of them, as I find absolutely no difference between these textboxes. They are all simple dragged and dropped textboxes.</p> <p>Note: I'm not talking about this piece of code:</p> <pre><code>if (e.Control &amp;&amp; e.KeyCode == Keys.A) { textBox1.SelectAll(); } </code></pre> <p>I want selection by default... or is there anyway to change textbox property so that textboxes accept all default windows shortcuts?</p> <p>Everything else (<code>Control + Z</code>, <code>Control + X</code>, <code>Control + C</code>, <code>Control + V</code>) works by default! Why not <code>Control + A</code>?</p> <p><strong>Update:</strong> The text boxes that accepted <code>Ctrl+A</code> by default were <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox%28v=vs.80%29.aspx" rel="nofollow noreferrer">masked textboxes</a>, not the regular one. And at that point I was with .NET 2.0. But <em>I guess</em> the original problem was something else, as I can see <code>Ctrl+A</code> working fine by default in .NET 2.0 code.</p>
5,893,879
5
5
null
2011-05-04 15:17:07.633 UTC
9
2019-03-01 17:00:41.15 UTC
2019-03-01 17:00:41.15 UTC
null
661,933
null
661,933
null
1
43
c#|select|textbox|.net-2.0
25,123
<p>You might be looking for the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.shortcutsenabled.aspx" rel="nofollow noreferrer">ShortcutsEnabled</a> property. Setting it to <code>true</code> would allow your text boxes to implement the <kbd>Ctrl</kbd>+<kbd>A</kbd> shortcut (among others). From the documentation:</p> <blockquote> <p>Use the <code>ShortcutsEnabled</code> property to enable or disable the following shortcut key combinations:</p> <ul> <li><p><kbd>CTRL</kbd>+<kbd>Z</kbd></p></li> <li><p><kbd>CTRL</kbd>+<kbd>E</kbd></p></li> <li><p><kbd>CTRL</kbd>+<kbd>C</kbd></p></li> <li><p><kbd>CTRL</kbd>+<kbd>Y</kbd></p></li> <li><p><kbd>CTRL</kbd>+<kbd>X</kbd></p></li> <li><p><kbd>CTRL</kbd>+<kbd>BACKSPACE</kbd></p></li> <li><p><kbd>CTRL</kbd>+<kbd>V</kbd></p></li> <li><p><kbd>CTRL</kbd>+<kbd>DELETE</kbd></p></li> <li><p><kbd>CTRL</kbd>+<kbd>A</kbd></p></li> <li><p><kbd>SHIFT</kbd>+<kbd>DELETE</kbd></p></li> <li><p><kbd>CTRL</kbd>+<kbd>L</kbd></p></li> <li><p><kbd>SHIFT</kbd>+<kbd>INSERT</kbd></p></li> <li><p><kbd>CTRL</kbd>+<kbd>R</kbd></p></li> </ul> </blockquote> <p>However, the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.shortcutsenabled.aspx" rel="nofollow noreferrer">documentation</a> states:</p> <blockquote> <p>The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox.aspx" rel="nofollow noreferrer">TextBox</a> control does not support the <kbd>CTRL</kbd>+<kbd>A</kbd> shortcut key when the <a href="http://msdn.microsoft.com/en-us/library/12w624ff.aspx" rel="nofollow noreferrer">Multiline</a> property value is true.</p> </blockquote> <p>You will probably have to use another subclass of <code>TextBoxBase</code>, such as <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.aspx" rel="nofollow noreferrer">RichTextBox</a>, for that to work.</p>
5,964,118
Git - working on wrong branch - how to copy changes to existing topic branch
<p>I've been working on a project, but unfortunately, I <em>forgot</em> to switch to my branch, and as such have been working on master</p> <p>How can I copy the work (3 files) I've done here from master, to my branch (called, for example <em>branch123</em>) without comitting to master?</p>
5,964,168
5
0
null
2011-05-11 12:21:15.707 UTC
99
2022-08-04 19:01:05.28 UTC
2014-02-27 18:47:41.063 UTC
null
674,039
null
131,809
null
1
417
git
119,575
<p>Sounds like all you need is the following:</p> <pre><code>git stash git checkout branch123 git stash apply </code></pre> <p>Then you should be back on your own branch without touching the master branch.</p>
5,780,280
How can I see which wakelocks are active
<p>For some reason my Android phone won't go to sleep. I assume that a wakelock is keeping it awake, but there is no way to tell which wakelocks are active. The running services doesn't list anything suspicious, and certainly nothing different from usual. So my questions are:</p> <ol> <li><p>Does Android definitely release wakelocks when a process ends? Is it possible an app was badly written and didn't release a wakelock before exiting?</p></li> <li><p>Is there any way to see the active wakelocks?</p></li> </ol> <p>This is what <code>dumpsys power</code> shows:</p> <pre><code>$ dumpsys power Power Manager State: mIsPowered=true mPowerState=0 mScreenOffTime=226093 ms mPartialCount=0 mWakeLockState= mUserState= mPowerState= mLocks.gather= mNextTimeout=91922738 now=92136117 -213s from now mDimScreen=true mStayOnConditions=0 mScreenOffReason=3 mUserState=0 mBroadcastQueue={-1,-1,-1} mBroadcastWhy={0,0,0} mPokey=1 mPokeAwakeonSet=false mKeyboardVisible=false mUserActivityAllowed=false mKeylightDelay=6000 mDimDelay=47000 mScreenOffDelay=7000 mPreventScreenOn=false mScreenBrightnessOverride=-1 mButtonBrightnessOverride=-1 mScreenOffTimeoutSetting=60000 mMaximumScreenOffTimeout=2147483647 mLastScreenOnTime=0 mBroadcastWakeLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=false) mStayOnWhilePluggedInScreenDimLock=UnsynchronizedWakeLock(mFlags=0x6 mCount=0 mHeld=false) mStayOnWhilePluggedInPartialLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=false) mPreventScreenOnPartialLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=false) mProximityPartialLock=UnsynchronizedWakeLock(mFlags=0x1 mCount=0 mHeld=false) mProximityWakeLockCount=0 mProximitySensorEnabled=false mProximitySensorActive=false mProximityPendingValue=-1 mLastProximityEventTime=0 mLightSensorEnabled=false mLightSensorValue=-1.0 mLightSensorPendingValue=-1.0 mLightSensorScreenBrightness=35 mLightSensorButtonBrightness=255 mLightSensorKeyboardBrightness=0 mUseSoftwareAutoBrightness=true mAutoBrightessEnabled=false mScreenBrightness: animating=false targetValue=-1 curValue=0.0 delta=-1.3333334 mLocks.size=0: mPokeLocks.size=1: poke lock 'PhoneApp': POKE_LOCK_IGNORE_CHEEK_EVENTS </code></pre>
25,992,687
8
0
null
2011-04-25 16:01:38.83 UTC
24
2019-01-07 18:13:39.197 UTC
2014-01-22 19:10:11.663 UTC
null
321,731
null
265,521
null
1
28
android|process|wakelock
56,089
<p>In new versions of Android you can see list of wakelocks here:</p> <pre><code>adb shell "cat /sys/kernel/debug/wakeup_sources" </code></pre>
6,094,962
Android: How to set password property in an edit text?
<p>I need to create a login form with 'username' 'password' fields and two buttons 'login' and 'cancel' in my android application. </p> <p>I am using an alert dialog with edittext inside that. </p> <p>This is the code I used to create password edittext..</p> <pre><code> final EditText Password = new EditText(this); Password.setGravity(Gravity.CENTER); Password.setHint("Password"); Password.setWidth(200); Password.setTransformationMethod(new PasswordTransformationMethod()); login_alert.addView(Password); </code></pre> <p>My issue is that, plain text is shown instead of 'dots' when i open a softkeypad to edit the password. (It is shown as dots when not in softkeypad mode)</p> <p>Can anyone suggest a solution? </p>
6,095,222
9
3
null
2011-05-23 08:56:03.313 UTC
7
2017-07-05 13:52:40.93 UTC
2011-05-29 06:22:22.973 UTC
null
750,987
null
180,908
null
1
51
android|android-edittext
126,714
<pre><code>Password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); </code></pre> <p>This one works for me.<br> But you have to look at Octavian Damiean's comment, he's right.</p>
46,407,490
"No such file or directory" or "No such host is known" when running migrations
<p>I deleted the <code>migrations</code> table from a Laravel 5.4 database named <code>laravel</code>. When I run <code>php artisan migrate:install</code>, I get this error:</p> <pre class="lang-none prettyprint-override"><code>[Illuminate\Database\QueryException] SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from information_schema.tables where table_schema = laravel and table_name = migrations) </code></pre> <p>I deleted and recreated the database. I also ran <code>composer update</code>. No luck. I can run the command in phpMyAdmin and create the table manually.</p> <p>This problem sometimes also manifests itself with similar 2002 errors:</p> <pre class="lang-none prettyprint-override"><code>[Illuminate\Database\QueryException] SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known. (SQL: select * from information_schema.tables where table_schema = laravel and table_name = migrations and table_type = 'BASE TABLE') </code></pre> <pre class="lang-none prettyprint-override"><code>[Illuminate\Database\QueryException] SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known (SQL: select * from information_schema.tables where table_schema = laravel and table_name = migrations and table_type = 'BASE TABLE') </code></pre>
46,407,584
8
2
null
2017-09-25 14:19:03.937 UTC
13
2022-06-08 09:20:17.087 UTC
2020-12-11 21:55:14.223 UTC
null
1,255,289
null
1,905,056
null
1
36
php|mysql|laravel|laravel-artisan
66,359
<p>If you are using <code>localhost</code> as your <code>DATABASE_HOST</code> in the <code>.env</code> file, change it to <code>127.0.0.1</code>, then run <code>php artisan config:clear</code> and now try <code>php artisan migrate:install</code> again.</p>
5,446,522
data type not understood
<p>I'm trying to use a matrix to compute stuff. The code is this</p> <pre><code>import numpy as np # some code mmatrix = np.zeros(nrows, ncols) print mmatrix[0, 0] </code></pre> <p>but I get 'data type not understood', and it works if I do it from terminal.</p>
5,446,579
1
0
null
2011-03-27 01:10:10.913 UTC
16
2011-03-27 01:24:39.793 UTC
null
null
null
null
464,277
null
1
103
python|matrix|numpy
179,843
<p>Try:</p> <pre><code>mmatrix = np.zeros((nrows, ncols)) </code></pre> <p>Since the shape parameter has to be an int or sequence of ints</p> <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html" rel="noreferrer">http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html</a></p> <p>Otherwise you are passing <code>ncols</code> to <code>np.zeros</code> as the dtype.</p>
44,427,382
What does ".()" mean in Kotlin?
<p>I've seen examples where a function has an argument given by ClassName.() This doesn't seem to be an extension function, which is ClassName.Function()</p> <p>An example is <a href="https://github.com/JakeWharton/kotterknife/blob/master/src/main/kotlin/kotterknife/ButterKnife.kt#L82" rel="noreferrer">Kotterknife</a>:</p> <pre><code>private val View.viewFinder: View.(Int) -&gt; View? get() = { findViewById(it) } </code></pre> <p>Which I don't quite know the function of,</p> <p>and <a href="https://github.com/zsmb13/MaterialDrawerKt/blob/master/library/src/main/java/co/zsmb/materialdrawerkt/builders/DrawerBuilderKt.kt#L26" rel="noreferrer">MaterialDrawerKt</a></p> <pre><code>fun Activity.drawer(setup: DrawerBuilderKt.() -&gt; Unit = {}): Drawer { val builder = DrawerBuilderKt(this) builder.setup() return builder.build() } </code></pre> <p>Where the code allows you to directly call </p> <pre><code>drawer { ... } </code></pre> <p>rather than give it arguments surrounded by the parentheses.</p> <p>Is there any documentation on this anywhere?</p>
44,427,835
4
2
null
2017-06-08 05:35:07.577 UTC
18
2022-06-12 17:08:43.297 UTC
2019-08-30 05:23:41.047 UTC
null
820,861
null
4,407,321
null
1
55
android|object|kotlin|navigation-drawer|higher-order-functions
9,415
<p>A function that takes in nothing and returns nothing in Kotlin looks like:</p> <pre class="lang-kotlin prettyprint-override"><code>var function : () -&gt; Unit </code></pre> <p>The difference is that the function in your code takes in nothing, returns nothing, <strong>but is invoked on an object</strong>.</p> <p>For example,</p> <pre class="lang-kotlin prettyprint-override"><code>class Builder (val multiplier: Int) { fun invokeStuff(action: (Builder.() -&gt; Unit)) { this.action() } fun multiply(value: Int) : Int { return value * multiplier } } </code></pre> <p>The important bit here is the way we've declared the type of <code>action</code></p> <pre class="lang-kotlin prettyprint-override"><code>action: (Builder.() -&gt; Unit) </code></pre> <p>This is a function that returns nothing, takes in nothing but <strong>is invoked on an object of type <code>Builder</code></strong>.</p> <p>This means when we use this builder like so</p> <pre class="lang-kotlin prettyprint-override"><code>var builder = Builder(10) builder.invokeStuff({ var result = multiply(1) println(result) }) </code></pre> <p>The context of <code>this</code> has been set to the builder object and we can invoke functions declared within the builder.</p> <p><strong><a href="http://codeofrob.com/entries/looking-at-kotlin---fun-with-functions.html" rel="noreferrer">Refer more here</a></strong>.</p>
33,221,425
How do I group my date variable into month/year in R?
<p>I have a "date" vector, that contains dates in mm/dd/yyyy format:</p> <pre><code> head(Entered_Date,5) [1] 1/5/1998 1/5/1998 1/5/1998 1/5/1998 1/5/1998 </code></pre> <p>I am trying to plot a frequency variable against the date, but I want to group the dates that it is by month or year. As it is now, there is a frequency per day, but I want to plot the frequency by month or year. So instead of having a frequency of 1 for 1/5/1998, 1 for 1/7/1998, and 3 for 1/8/1998, I would like to display it as 5 for 1/1998. It is a relatively large data set, with dates from 1998 to present, and I would like to find some automated way to accomplish this.</p> <pre><code>&gt; dput(head(Entered_Date)) structure(c(260L, 260L, 260L, 260L, 260L, 260L), .Label = c("1/1/1998", "1/1/1999", "1/1/2001", "1/1/2002", "1/10/2000", "1/10/2001", "1/10/2002", "1/10/2003", "1/10/2005", "1/10/2006", "1/10/2007", "1/10/2008", "1/10/2011", "1/10/2012", "1/10/2013", "1/11/1999", "1/11/2000", "1/11/2001", "1/11/2002", "1/11/2005", "1/11/2006", "1/11/2008", "1/11/2010", "1/11/2011", "1/11/2012", "1/11/2013", "1/12/1998", "1/12/1999", "1/12/2001", "1/12/2004", "1/12/2005", ... </code></pre>
33,221,885
8
2
null
2015-10-19 18:30:30.827 UTC
16
2022-06-16 20:48:23.667 UTC
2021-04-16 15:52:51.693 UTC
null
792,066
null
5,372,441
null
1
48
r
102,728
<p>Here is an example using <code>dplyr</code>. You simply use the corresponding date format string for month <code>%m</code> or year <code>%Y</code> in the <code>format</code> statement.</p> <pre><code>set.seed(123) df &lt;- data.frame(date = seq.Date(from =as.Date("01/01/1998", "%d/%m/%Y"), to=as.Date("01/01/2000", "%d/%m/%Y"), by="day"), value = sample(seq(5), 731, replace = TRUE)) head(df) date value 1 1998-01-01 2 2 1998-01-02 4 3 1998-01-03 3 4 1998-01-04 5 5 1998-01-05 5 6 1998-01-06 1 library(dplyr) df %&gt;% mutate(month = format(date, "%m"), year = format(date, "%Y")) %&gt;% group_by(month, year) %&gt;% summarise(total = sum(value)) Source: local data frame [25 x 3] Groups: month [?] month year total (chr) (chr) (int) 1 01 1998 105 2 01 1999 91 3 01 2000 3 4 02 1998 74 5 02 1999 77 6 03 1998 96 7 03 1999 86 8 04 1998 91 9 04 1999 95 10 05 1998 93 .. ... ... ... </code></pre>
9,172,737
how to get beans from view scope
<p>I want to ask if i place my managed bean in session scope, then it is stored in session' Like if i have a bean like this</p> <pre><code>@ManagedBean @SessionScoped public class SessionScopedBean implements Serializable { ....... } //end of class SessionScopedBean </code></pre> <p>Then it stored in the session, and during my session i can get it using</p> <pre><code>session.getAttribut("SessionScopedBean"); </code></pre> <p>This will give me the SessionScopedBean Object, and when session will get destroy, i will get null. Now i want to ask if i have my bean in view Scope, then how can i get it. Like</p> <pre><code>@ManagedBean @ViewScoped public class ViewScopedBean implements Serializable { ....... } //end of class ViewScopedBean </code></pre> <p>Now if the view is persist then this bean is in the view state, and when view changes, this bean will get destroy.Now i want to ask how can i get this bean from view state, if the view persist. Like</p> <pre><code>view.getAttrubute("ViewScopedBean"); //just a code. No actual implementation. </code></pre> <p>Thanks</p>
9,177,769
1
0
null
2012-02-07 07:57:43.213 UTC
10
2016-02-08 09:53:02.157 UTC
null
null
null
null
1,000,510
null
1
13
jsf-2
19,680
<p>They're stored in the view map as available by <a href="http://docs.oracle.com/javaee/7/api/javax/faces/component/UIViewRoot.html#getViewMap%28%29" rel="noreferrer"><code>UIViewRoot#getViewMap()</code></a>:</p> <pre><code>Map&lt;String, Object&gt; viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap(); ViewScopedBean viewScopedBean = (ViewScopedBean) viewMap.get("viewScopedBean"); // ... </code></pre> <p>Equivalently, you should be using the session map abstraction as well which is available by <a href="http://docs.oracle.com/javaee/7/api/javax/faces/context/ExternalContext.html#getSessionMap%28%29" rel="noreferrer"><code>ExternalContext#getSessionMap()</code></a> (you ultimately want to have <strong>zero</strong> <code>javax.servlet</code> import declarations throughout your JSF code):</p> <pre><code>Map&lt;String, Object&gt; sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap(); SessionScopedBean sessionScopedBean = (SessionScopedBean) sessionMap.get("sessionScopedBean"); // ... </code></pre> <h3>See also:</h3> <ul> <li><a href="https://stackoverflow.com/questions/2633112/jsf-get-managed-bean-by-name">Get JSF managed bean by name in any Servlet related class</a></li> </ul> <hr> <p><strong>Unrelated</strong> to the concrete problem, this may not be the best way. Look at <a href="http://docs.oracle.com/javaee/7/api/javax/faces/bean/ManagedProperty.html" rel="noreferrer"><code>@ManagedProperty</code></a> if possible.</p>
9,472,871
parse arguments after getopts
<p>I want to call a bash script like this</p> <pre><code>$ ./scriptName -o -p -t something path/to/file </code></pre> <p>This is as far as I get</p> <pre><code>#!/bin/bash o=false p=false while getopts ":opt:" options do case $options in o ) opt1=true ;; p ) opt2=true ;; t ) opt3=$OPTARG ;; esac done </code></pre> <p>but how do I get the <code>path/to/file</code>?</p>
9,472,919
2
0
null
2012-02-27 21:51:13.18 UTC
9
2018-10-08 18:45:45.55 UTC
null
null
null
null
263,589
null
1
36
bash|command-line-arguments|arguments|getopts
24,701
<p>You can do something like:</p> <pre><code>shift $(($OPTIND - 1)) first_arg=$1 second_arg=$2 </code></pre> <p>after the loop has run.</p>
9,597,001
How to set the working directory of a command in a Windows batch file?
<p>Let's say I have these commands:</p> <pre><code>Prog1.exe D:\SomeDir\Prog2.exe Prog3.exe </code></pre> <p>Now, say for the second line, I would like the working directory to be D:\SomeDir, but in Prog1.exe and Prog3.exe I want the default working directory (normally, where my .bat file is). If I try this</p> <pre><code>Prog1.exe cd D:\SomeDir D:\SomeDir\Prog2.exe Prog3.exe </code></pre> <p>Apparently Prog3 will be executed in SomeDir, which is not what I want.</p>
9,598,440
3
0
null
2012-03-07 06:51:12.49 UTC
6
2019-07-21 19:02:32.493 UTC
2015-07-11 22:49:20.35 UTC
null
63,550
null
385,387
null
1
49
windows|batch-file|working-directory
109,003
<p>You could use the pushd/popd commands (help with <code>pushd /?</code>)</p> <pre><code>Prog1.exe Pushd D:\SomeDir Prog2.exe popd Prog3.exe </code></pre>
30,127,580
Docker daemon flags ignored
<h1>Environment:</h1> <ul> <li><strong>OS</strong>: debian 8.0.0-amd64, ubuntu-15.04, 16.04</li> <li><strong>Docker</strong>: 1.x.x</li> </ul> <h1>Procedure:</h1> <p>I changed <code>/etc/default/docker</code> to add a private docker registry, then I restarted docker service and finally tried to pull some image.</p> <pre><code>$ cat /etc/default/docker DOCKER_OPTS="--insecure-registry mydocker-registry.net:5000" $ service docker restart $ docker pull mydocker-registry.net:5000/testdb FATA[0000] Error: v1 ping attempt failed with error: Get https://mydocker- registry.net:5000/v1/_ping: dial tcp: lookup mydocker-registry.net: no such host. If this private registry supports only HTTP or HTTPS with an unknown CA certificate, please add `--insecure-registry mydocker- registry.net:5000` to the daemon's arguments. In the case of HTTPS, if you have access to the registry's CA certificate, no need for the flag; simply place the CA certificate at /etc/docker/certs.d/mydocker- registry.net:5000/ca.crt </code></pre> <p>A <code>ps</code> output shows nothing about DOCKER_OPTS environment var.</p> <pre><code>$ ps auxwww|grep docker root 6919 0.0 0.1 331076 19984 ? Ssl 10:14 0:00 /usr/bin/docker -d -H fd:// </code></pre> <h1>Question:</h1> <p>According to docker documentation the way to use a private registry is through DOCKER_OPTS in <code>/etc/default/docker</code>. Why, after doing that, it does not take effect in this environment?</p> <h1>Notes:</h1> <ul> <li>The private registry hostname is correctly resolved by the DNS.</li> </ul>
30,219,552
6
3
null
2015-05-08 15:31:33.19 UTC
14
2019-05-20 17:24:22.59 UTC
2017-08-09 15:31:08.307 UTC
null
766,855
null
766,855
null
1
23
ubuntu|docker|debian
16,499
<h1>Recommended Way Docker 17.xx +</h1> <p>There are a number of ways to configure the daemon flags and environment variables for your Docker daemon. The <a href="https://docs.docker.com/engine/reference/commandline/dockerd//#daemon-configuration-file" rel="noreferrer">recommended way</a> is to use the platform-independent <code>daemon.json</code> file, which is located in <code>/etc/docker/</code> on Linux by default.</p> <p>So, for configuring insecure registries, do the following:</p> <ol> <li><p>Set the following flag in the <code>/etc/docker/daemon.json</code> file:</p> <pre><code>{ "insecure-registries": ["mydocker-registry.net:5000"] } </code></pre></li> <li><p>Restart Docker </p> <pre><code> $ sudo systemctl restart docker </code></pre></li> </ol> <p>Easier each time!</p> <hr> <h1>Previously Recommended Way with Docker 1.12</h1> <p>According to <a href="https://docs.docker.com/engine/admin/systemd/" rel="noreferrer">docker documentation</a>, The recommended way to configure the daemon flags and environment variables for your Docker daemon is to use a <strong>systemd</strong> <em>drop-in file</em>. </p> <p>So, for this specific case, do the following:</p> <ol> <li><p>Create a file called <code>/etc/systemd/system/docker.service.d/private-registry.conf</code> with the following content:</p> <blockquote> <p>If not exists, create directory <code>/etc/systemd/system/docker.service.d</code></p> </blockquote> <pre><code>[Service] ExecStart= ExecStart=/usr/bin/dockerd --insecure-registry mydocker-registry.net:5000 </code></pre></li> <li><p>Flush changes:</p> <pre><code>$ sudo systemctl daemon-reload </code></pre></li> <li><p>Restart Docker:</p> <pre><code> $ sudo systemctl restart docker </code></pre></li> </ol> <p>Voila!</p> <hr> <h1>Not recommended way</h1> <p>Edit file <code>/lib/systemd/system/docker.service</code> </p> <pre><code>... [Service] ExecStart=/usr/bin/docker -d -H fd:// $DOCKER_OPTS ... EnvironmentFile=-/etc/default/docker ... </code></pre> <p>Then execute</p> <pre><code>systemctl daemon-reload systemctl restart docker </code></pre> <p>Verify that <code>/etc/default/docker</code> is loaded</p> <pre><code>ps auxwww | grep docker root 4989 0.8 0.1 265540 16608 ? Ssl 10:37 0:00 /usr/bin/docker -d -H fd:// --insecure-registry </code></pre> <p>That's it. </p>
10,464,611
JavaScript - Split A String
<p>I have a variable that holds the value 'website.html'.</p> <p>How can I split that variable so it only gives me the 'website'?</p> <p>Thanks</p>
10,464,617
3
1
null
2012-05-05 18:11:37.85 UTC
2
2018-04-18 09:37:31.33 UTC
null
null
null
null
1,029,969
null
1
16
javascript|split|substring
60,964
<pre><code>var a = "website.html"; var name = a.split(".")[0]; </code></pre> <p>If the file name has a dot in the name, you could try...</p> <pre><code>var a = "website.old.html"; var nameSplit = a.split("."); nameSplit.pop(); var name = nameSplit.join("."); </code></pre> <p>But if the file name is something like <code>my.old.file.tar.gz</code>, then it will think <code>my.old.file.tar</code> is the file name </p>
7,106,211
Entity Framework - Why explicitly set entity state to modified?
<p>The official documentation says to modify an entity I retrieve a DbEntityEntry object and either work with the property functions or I set its state to modified. It uses the following example</p> <pre><code>Department dpt = context.Departments.FirstOrDefault(); DbEntityEntry entry = context.Entry(dpt); entry.State = EntityState.Modified; </code></pre> <p>I don't understand the purpose of the 2nd and 3rd statement. If I ask the framework for an entity like the 1st statement does and then modify the POCO as in</p> <pre><code>dpt.Name = "Blah" </code></pre> <p>If I then ask EF to SaveChanges(), the entity <em>has</em> a status of MODIFIED (I'm guessing via snapshot tracking, this isn't a proxy) and the changes are persisted without the need to manually set the state. Am I missing something here?</p>
7,106,328
2
0
null
2011-08-18 10:51:03.967 UTC
11
2019-01-22 10:02:44.167 UTC
2011-08-18 12:27:28.157 UTC
null
771,698
null
771,698
null
1
61
entity-framework
45,653
<p>In your scenario you indeed don't have to set the state. It is purpose of change tracking to find that you have changed a value on attached entity and put it to modified state. Setting state manually is important in case of detached entities (entities loaded without change tracking or created outside of the current context).</p>
31,486,232
How do I xcodebuild a static library with Bitcode enabled?
<p>Xcode 7 introduces <a href="https://developer.apple.com/library/prerelease/ios/documentation/IDEs/Conceptual/AppDistributionGuide/AppThinning/AppThinning.html#//apple_ref/doc/uid/TP40012582-CH35-SW3">Bitcode</a>, which is some sort of LLVM intermediate binary that means Apple's servers can recompile my app for different architectures without my involvement.</p> <p>At Lookback, I distribute a static archive framework with our library. It seems that when you build with anything but a "Build &amp; Archive", bitcode is not actually emitted into my library, and anyone who links with my library in their app and tries to do a Build &amp; Archive with Bitcode enabled will get one of two warnings:</p> <ul> <li><code>ld: 'Lookback(Lookback.o)' does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target.</code> (if lib is built with Xcode 6)</li> <li><code>ld: warning: full bitcode bundle could not be generated because 'Lookback(Lookback.o)' was built only with bitcode marker. The library must be generated from Xcode archive build with bitcode enabled (Xcode setting ENABLE_BITCODE)</code> (if lib is built with Xcode 7 with a normal xcodebuild)</li> </ul> <p>I have a build script that builds a device+simulator universal binary, so I can't use Build &amp; Archive, but rather, I run <code>xcodebuild</code> from commandline from my script. How can I make <code>xcodebuild</code> generate a proper bitcode-enabled library?</p>
31,486,233
4
2
null
2015-07-17 23:37:34.007 UTC
55
2019-12-24 11:29:38.727 UTC
2015-08-03 18:05:04.163 UTC
null
102,008
null
48,125
null
1
93
ios|xcode|xcode7|bitcode
51,962
<p>Bitcode is a compile-time feature (not a link-time feature) which means that every .o file should contain an extra section called __bitcode when built with bitcode. You can confirm whether your binary is bitcode-compatible by running <code>otool -l (my .o or .a file) | grep __LLVM</code>.</p> <p>When you build normally, Xcode adds the build flag <code>-fembed-bitcode-marker</code> to any clang invocation. This seems to be some sort of 'this is where bitcode would go, if bitcode was enabled' thing, and doesn't actually enable bitcode.</p> <p>When you "Build &amp; Archive", this flag is replaced by <code>-fembed-bitcode</code>, which really does build a Bitcode-enabled binary.</p> <p>There seems to be two ways to make <code>xcodebuild</code> use <code>-fembed-bitcode</code>:</p> <ul> <li>Use the 'archive' action, as in <code>xcodebuild -target LookbackSDK archive</code> instead of <code>xcodebuild -target LookbackSDK build</code>. This has the side-effect of putting binaries in your Xcode Organizer instead of the <code>build/</code> folder, though you can work around that by using <code>-exportArchive -archivePath ./build</code> (thanks <a href="https://twitter.com/jensayton/status/622349580986916864" rel="noreferrer">@JensAyton</a>)</li> <li>Force usage of the flag by adding Other C Flags with <code>OTHER_CFLAGS="-fembed-bitcode"</code>. Your <code>xcodebuild</code> invocation would look something like <code>xcodebuild OTHER_CFLAGS="-fembed-bitcode" -target LookbackSDK build</code>.</li> </ul> <p>The latter is what I chose so that I don't have to change my build system, but it will generate warnings for every file, since now both <code>-fembed-bitcode-marker</code> and <code>-fembed-bitcode</code> are sent to clang. Luckilly the latter wins, generating a Bitcode-enabled library!</p> <h3>Resources</h3> <ul> <li><a href="https://forums.developer.apple.com/message/7038" rel="noreferrer">Apple DevForums: Bitcode and Assembly?</a></li> <li><a href="https://stackoverflow.com/questions/31233395/ios-library-to-bitcode">SO: iOS library to BitCode</a></li> </ul>
31,477,319
Excel VBA Loop Rows Until Empty Cell
<p>I have an excel document with some plain text in a row. A1:A5 contains text, then several houndred rows down, there's another few rows with text. Cells between are empty. I've set up a <code>Do Until</code> loop which is supposed to copy cells with text, and then stop when an empty cell appears. My loop counts&amp;copies 136 cells includingthe 5 with text. So my question is why? The bottom line: <strong>Hello</strong> ends up on line 136, and then there's a huge gap of empty cells until next area with text. Do the 131 white cells contain any hidden formating causing this? I've tried "Clear Formats" and "Clear All" Code-snippet found below:</p> <pre><code>Sub CopyTags_Click() Dim assets As Workbook, test As Workbook Dim x As Integer, y As Integer Set assets = Workbooks.Open("file-path.xlsx") Set test = Workbooks.Open("File-path.xlsx") x = 1 y = 1 Do Until assets.Worksheets(1).Range("A" &amp; x) = "" test.Worksheets(1).Range("A" &amp; y) = assets.Worksheets(1).Range("A" &amp; x) x = x + 1 y = y + 1 Loop test.Worksheets(1).Range("A" &amp; x).Value = "Hello" End Sub </code></pre> <p>Ive also tried using <code>vbNullString</code> instead of " "</p>
31,477,895
1
4
null
2015-07-17 13:45:15.07 UTC
1
2015-07-17 14:14:00.727 UTC
null
null
null
null
4,056,587
null
1
5
excel|vba|loops
43,915
<p>Use a <a href="https://msdn.microsoft.com/en-us/library/5z06z1kb.aspx" rel="noreferrer">For Next Statement</a> terminating in the last used cell in column A. Only increment <em>y</em> if there has been a value found and transferred and let the For ... Next increment <em>x</em>.</p> <pre><code>Sub CopyTags_Click() Dim assets As Workbook, test As Workbook Dim x As Long, y As Long Set assets = Workbooks.Open("file-path.xlsx") Set test = Workbooks.Open("File-path.xlsx") x = 1 y = 1 with assets.Worksheets(1) for x = 1 to .cells(rows.count, 1).end(xlup).row if cbool(len(.Range("A" &amp; x).value2)) then test.Worksheets(1).Range("A" &amp; y) = assets.Worksheets(1).Range("A" &amp; x) y = y + 1 end if next x test.Worksheets(1).Range("A" &amp; y).Value = "Hello" end with End Sub </code></pre>
31,324,384
Import C# Class
<p>I'm (very) new to C#, and I need to know how to import classes.</p> <p>In Java, I could just say:</p> <pre><code>package com.test; class Test {} </code></pre> <p>And then in some other class:</p> <pre><code>package com.test2; import com.test.Test; </code></pre> <p>How could I do this in C#?</p>
31,324,482
2
5
null
2015-07-09 17:28:53.823 UTC
null
2021-05-03 04:45:29.79 UTC
null
null
null
null
4,984,735
null
1
7
c#|import
44,292
<p>Importing namespaces is accomplished in C# with the <code>using</code> directive:</p> <pre><code>using com.test; </code></pre> <p>However, there is no way, currently, to import a class. Importing classes, however <em>is</em> a new feature which is being <a href="http://blogs.msdn.com/b/csharpfaq/archive/2014/11/20/new-features-in-c-6.aspx" rel="noreferrer">introduced in C# 6</a> (which will come with Visual Studio 2015).</p> <p>In C#, namespaces are the semi-equivalent of Java's packages. To declare the namespace, you just need to do something like this:</p> <pre><code>namespace com.test { class Test {} } </code></pre> <p>If the class is declared in a separate assembly (such as a class library), simply adding the <code>using</code> directive is not enough. You must also add a reference to the other assembly.</p>
18,016,503
AspectJ "around" and "proceed" with "before / after"
<p>Let's say you have three advices: <strong>around</strong>, <strong>before</strong> and <strong>after</strong>.</p> <p>1) Are <strong>before/after</strong> called when <strong>proceed</strong> is called in the <strong>around</strong> advice, or are they called <strong>before/after</strong> the <strong>around</strong> advice as a whole?</p> <p>2) If my <strong>around</strong> advice does not call <strong>proceed</strong>, will the <strong>before/after</strong> advice be run anyway?</p>
18,054,605
2
2
null
2013-08-02 12:07:02.917 UTC
5
2019-09-23 13:03:39.217 UTC
2016-05-27 14:40:18.077 UTC
null
4,478,411
null
755,938
null
1
32
java|aop|aspectj
32,682
<p>With this Test</p> <pre><code>@Aspect public class TestAspect { private static boolean runAround = true; public static void main(String[] args) { new TestAspect().hello(); runAround = false; new TestAspect().hello(); } public void hello() { System.err.println("in hello"); } @After("execution(void aspects.TestAspect.hello())") public void afterHello(JoinPoint joinPoint) { System.err.println("after " + joinPoint); } @Around("execution(void aspects.TestAspect.hello())") public void aroundHello(ProceedingJoinPoint joinPoint) throws Throwable { System.err.println("in around before " + joinPoint); if (runAround) { joinPoint.proceed(); } System.err.println("in around after " + joinPoint); } @Before("execution(void aspects.TestAspect.hello())") public void beforeHello(JoinPoint joinPoint) { System.err.println("before " + joinPoint); } } </code></pre> <p>i have following output</p> <ol> <li>in around before execution(void aspects.TestAspect.hello()) </li> <li>before execution(void aspects.TestAspect.hello()) </li> <li>in hello</li> <li>after execution(void aspects.TestAspect.hello())</li> <li>in around after execution(void aspects.TestAspect.hello())</li> <li>in around before execution(void aspects.TestAspect.hello())</li> <li>in around after execution(void aspects.TestAspect.hello())</li> </ol> <p>so you can see before/after are not called when <strong>proceed</strong> is called from within <code>@Around</code> annotation.</p>
17,735,994
Automatically refresh ICollectionView Filter
<p>Is there any way to automatically update a filter on an <code>ICollectionView</code> without having to call <code>Refresh()</code> when a relevant change has been made?</p> <p>I have the following:</p> <pre><code>[Notify] public ICollectionView Workers { get; set; } </code></pre> <p>The [Notify] attribute in this property just implements <code>INotifyPropertyChanged</code> but it doesn't seem to be doing anything in this situation.</p> <pre><code>Workers = new CollectionViewSource { Source = DataManager.Data.Workers }.View; Workers.Filter = w =&gt; { Worker worker = w as Worker; if (w == null) return false; return worker.Employer == this; }; </code></pre> <p>In XAML:</p> <pre><code>&lt;TextBlock x:Name="WorkersTextBlock" DataContext="{Binding PlayerGuild}" FontFamily="Pericles" Text="{Binding Workers.Count, StringFormat=Workers : {0}, FallbackValue=Workers : 99}" /&gt; </code></pre> <p><strong>Update:</strong> It looks like using <code>ICollectionView</code> is going to be necessary for me, so I'd like to revisit this topic. I'm adding a bounty to this question, the recipient of which will be any person who can provide some insight on how to implement a 'hands-off' <code>ICollectionView</code> that doesn't need to be manually refreshed. At this point I'm open to any ideas.</p>
17,906,474
2
7
null
2013-07-18 23:59:35.637 UTC
11
2013-07-29 08:26:15.633 UTC
2013-07-25 08:07:36.287 UTC
null
885,920
null
1,667,020
null
1
19
c#|wpf|icollectionview
19,642
<p>AFAIK there is no inbuilt support in <code>ICollectionView</code> to refresh collection on any property change in underlying source collection.</p> <p>But you can subclass <code>ListCollectionView</code> to give it your own implementation to <code>refresh collection on any property changed</code>. Sample -</p> <pre><code>public class MyCollectionView : ListCollectionView { public MyCollectionView(IList sourceCollection) : base(sourceCollection) { foreach (var item in sourceCollection) { if (item is INotifyPropertyChanged) { ((INotifyPropertyChanged)item).PropertyChanged += (s, e) =&gt; Refresh(); } } } } </code></pre> <p>You can use this in your project like this -</p> <pre><code>Workers = new MyCollectionView(DataManager.Data.Workers); </code></pre> <p>This can be reused across your project without having to worry to refresh collection on every <code>PropertyChanged</code>. <code>MyCollectionView</code> will do that <code>automatically</code> for you.</p> <p><strong>OR</strong></p> <p>If you are using <strong>.Net4.5</strong> you can go with <code>ICollectionViewLiveShaping</code> implementation as described <a href="http://www.jonathanantoine.com/2011/10/05/wpf-4-5-%E2%80%93-part-10-live-shaping/" rel="noreferrer">here</a>.</p> <p>I have posted the implementation part for your problem here - <a href="https://stackoverflow.com/questions/17865202/implementing-icollectionviewliveshaping/17906815#17906815">Implementing ICollectionViewLiveShaping</a>.</p> <p>Working code from that post -</p> <pre><code>public ICollectionViewLiveShaping WorkersEmployed { get; set; } ICollectionView workersCV = new CollectionViewSource { Source = GameContainer.Game.Workers }.View; ApplyFilter(workersCV); WorkersEmployed = workersCV as ICollectionViewLiveShaping; if (WorkersEmployed.CanChangeLiveFiltering) { WorkersEmployed.LiveFilteringProperties.Add("EmployerID"); WorkersEmployed.IsLiveFiltering = true; } </code></pre>
3,321,611
Specify max and min for Random.nextInt()?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/363681/java-generating-random-number-in-a-range">Java: generating random number in a range</a> </p> </blockquote> <p>I want to generate a random int in a logical range. So, say for example, I'm writing a program to "roll" a dice with a specified number of sides.</p> <pre>public int rollDice() { Random generator = new Random(); return generator.nextInt(sides); }</pre> <p>Now the problem becomes that this will return values between sides and zero, <em>inclusive</em>, which makes no sense because most dice go from 1 to 6, 9, etc. So how can I specify that nextInt should work between 1 and the number of sides?</p>
3,321,685
1
4
null
2010-07-23 19:17:01.677 UTC
5
2010-07-23 19:25:30.35 UTC
2017-05-23 11:54:47.663 UTC
null
-1
null
399,815
null
1
17
java|random
40,300
<p>To generate a random int value (uniform distribution) between <em>from</em> and <em>to</em> (inclusive) use:</p> <pre><code>from + rndGenerator.nextInt(to - from + 1) </code></pre> <p>In your case (1..sides):</p> <pre><code>1 + rndGenerator.nextInt(sides) </code></pre>
21,091,766
Mp4 Download causes browser to play file instead of download
<p>In my website I stream users mp4 content. I also allow users to download. However in Chrome it seems to automatically play the file in an internal player instead of downloading the file.</p> <p>How do I force the browser to download the file instead.</p> <p>Regards and thanks Craig</p>
21,309,940
6
2
null
2014-01-13 12:50:15.697 UTC
4
2022-09-09 13:26:02.177 UTC
null
null
null
null
379,972
null
1
13
google-chrome|browser|download|streaming
49,828
<p>You have to use the HTTP header "<strong>Content-Disposition</strong>" and '<strong>Content-Type: application/force-download</strong>' which will force browser to download the content instead of displaying it there. </p> <p>Depending upon the server side language you are having the implementation differs. In case of </p> <p>PHP: </p> <pre><code> header('Content-Disposition: attachment; filename="'.$nameOfFile.'"'); </code></pre> <p>will do the job for you. </p> <p>Ofcourse to simplify and generalize this for all your files, you may need to write a method which will route a link to downloadable content. </p> <p>The link you can show in the html will be like: </p> <pre><code>&lt;a href="http://yoursite.com/downloadFile?id=1234"&gt;Click here to Download Hello.mp4&lt;/a&gt; </code></pre> <p>And in the server side, you need a script which is being called on /downloadFile (depending on your routing), get the file by id and send it to user as an attachment. </p> <pre><code>&lt;?php $fileId = $_POST['id']; // so for url http://yoursite.com/downloadFile?id=1234 will download file // /pathToVideoFolder/1234.mp4 $filePath = "/pathToVideoFolder/".$fileId."mp4"; $fileName = $fileId."mp4"; //or a name from database like getFilenameForID($id) //Assume that $filename and $filePath are correclty set. header('Content-Description: File Transfer'); header('Content-Disposition: attachment; filename="'.$filename.'"'); header('Content-Type: application/force-download'); readfile($filePath); </code></pre> <p>Here 'Content-Type: application/force-download' will force the browser to show the download option no matter what's the default setting is for a mime-type. </p> <p>No matter what your server side technology is, the headers to look out for are: </p> <pre><code>'Content-Description: File Transfer' 'Content-Type: application/force-download' 'Content-Disposition: attachment; filename="myfile.mp4" </code></pre>
21,108,793
Can't open Outlook e-mail message from Windows 7 search results
<p>When I type something into the Windows 7 search box and choose <strong>See more results</strong> a list of found emails and files appears (I've customised my index to include my C drive too). So far, so good. I can open other file types by double-clicking, but there is no right-mouse menu for Outlook files, and double-clicking doesn't do anything.</p> <p>On previous computers this has worked fine. I've been through all sorts of links on Google, but none of them has the right answer (at least for me). I'm running Windows 7 on a 64-bit computer, but running MS Office 2010 as a 32-bit application. </p> <p>Any suggestions, wonderful people at StackOverflow?</p>
22,702,050
5
2
null
2014-01-14 08:23:21.377 UTC
1
2015-04-22 07:01:59.377 UTC
2015-04-22 07:01:59.377 UTC
null
1,009,479
null
601,622
null
1
3
windows|email|search|outlook
38,116
<p>This procedure worked in my case:</p> <pre><code>Control Panel -&gt; All Control Panel Items -&gt; Programs and Features then click on "Microsoft Office Professional Plus 2010" then select "Change" and click "Yes" to allow the change then select "Repair" from the list. </code></pre> <p>It will require a reboot to complete the process.</p>
18,269,181
Unaligned access causes error on ARM Cortex-M4
<p>I have an object that has an address that is not 4-byte aligned. This causes a HardFault error in the cpu when there is a STR instruction saving 2 registers.</p> <p>This is the generated code:</p> <pre><code> 00000000 &lt;_ZN8BaseAreaC1EPcmm&gt;: 0: b510 push {r4, lr} 2: 4604 mov r4, r0 4: 6042 str r2, [r0, #4] 6: e9c4 3102 strd r3, r1, [r4, #8] a: 2001 movs r0, #1 c: 7420 strb r0, [r4, #16] e: b921 cbnz r1, 1a &lt;_ZN8BaseAreaC1EPcmm+0x1a&gt; </code></pre> <p>These are the registers when at line &quot;4: 6042...&quot;</p> <pre><code>R0 08738B82 R8 0 R1 08738BAE R9 0 R2 0 R10 082723E0 R3 2FCC R11 0 R4 08738B82 R12 0 R5 20007630 R13 2000CB38 </code></pre> <p>As seen the target register for STR-instructions are not aligned on 4-byte. The instruction <code>STR r2, [r0, #4]</code> is executed fine. But it HardFaults on the next <code>STRD r3, r1, [r4, #8]</code>. If I manually change register R4 to <code>08738B80</code> it does not hardfault.</p> <p>This is the C++ code that generates the above asm:</p> <pre><code>BaseArea::BaseArea(char * const pAddress, unsigned long startOffset, unsigned long endOffset) : m_pAddress(pAddress), m_start(startOffset), m_end(endOffset), m_eAreaType(BASE_AREA) { </code></pre> <p>And <code>m_start</code> is the first variable in the class and has the same address as <code>this</code> (<code>0x08738B82</code>), <code>m_end</code> follows after on <code>0x08738B86</code>.</p> <p>How do I get the object aligned on 4-byte? Anyone have some other solution to this?</p>
18,269,440
2
4
null
2013-08-16 08:39:15.953 UTC
8
2021-10-04 10:40:43.57 UTC
2021-10-04 10:40:43.57 UTC
null
10,669,875
null
479,807
null
1
9
c++|c|arm|memory-alignment|cortex-m
14,110
<p>On ARM-based systems you frequently cannot address a 32-bit word that is not aligned to a 4-byte boundary (as your error is telling you). On x86 you can access non-aligned data, however there is a huge hit on performance. Where an ARM part does support unaligned accesses (e.g. single word normal load), there is a performance penalty <em>and</em> there should be a configurable exception trap.</p> <p>Example of boundary error on ARM (<a href="https://stackoverflow.com/questions/1237963/alignment-along-4-byte-boundaries">here</a>), TLDR: storing a pointer to an <code>unsigned char</code> and then attempting to convert it to a <code>double *</code> (double pointer).</p> <p>To solve your problem, you would need to request a block of memory that is 4-byte aligned and copy the non-aligned bytes + fill it with garbage bytes to ensure it is 4 byte-aligned (hence perform data structure alignment manually). Then, you can interpret that object as 4-byte aligned from its new address.</p> <p>From TurboJ in comments, the explicit error:</p> <blockquote> <p>Cortex-M3 and M4 allow unaligned access by default. But they do not allow unalinged access with the STRD instruction, hence the fault.</p> </blockquote> <p>You may also find it helpful to look into <a href="http://sourceware.org/binutils/docs/as/Align.html#Align" rel="nofollow noreferrer">this</a> for forcing data structure alignment on ARM.</p>
1,656,901
varargs and the '...' argument
<p>Consider the method declaration:</p> <pre><code>String.format(String, Object ...) </code></pre> <p>The <code>Object ...</code> argument is just a reference to an array of <code>Object</code>s. <strong>Is there a way to use this method with a reference to an actual <code>Object</code> array?</strong> If I pass in an <code>Object</code> array to the <code>...</code> argument - will the resultant argument value be a two-dimensional array - because an <code>Object[]</code> is itself an <code>Object</code>:</p> <pre><code>Object[] params = ....; // Make the array (for example based on user-input) String s = String.format("%S has %.2f euros", params); </code></pre> <p>So the first component of the array (Which is used in the <code>String.format</code> method), will be an array and he will generate:</p> <pre><code>[class.getName() + "@" + Integer.toHexString(hashCode())] </code></pre> <p>and then an error because the array size is 1.</p> <p>The <strong>bold</strong> sequence is the real question.<br> This is a second question: <strong>Does a <code>...</code> array/parameter have a name?</strong></p>
1,656,918
3
1
null
2009-11-01 11:11:52.117 UTC
12
2017-12-14 17:24:10.727 UTC
2017-12-14 17:24:10.727 UTC
null
1,033,581
null
155,137
null
1
47
java|arrays|parameters|variadic-functions
44,705
<p>From the <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html" rel="noreferrer">docs on varargs</a>:</p> <blockquote> <p>The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.</p> </blockquote> <p>So you can pass multiple arguments or an array.</p> <p>The following works just fine:</p> <pre><code>class VarargTest { public static void main(String[] args) { Object[] params = {"x", 1.2345f}; String s = String.format("%s is %.2f", params); System.out.println(s); // Output is: x is 1.23 } } </code></pre>
8,762,007
What's the difference between "Push..." and "Push to upstream..." in Eclipse
<p>When using "Push to upstream..." in Eclipse, the new "local" commits are pushed to remote repository and the remote branch ref is updated in the local repository (so <code>master</code> and <code>origin/master</code> reference the same commit).</p> <p>When using "Push..." and adding a push ref on master in the wizard window (<code>refs/heads/*</code>), the new "local" commits are pushed to remote repository (like previously) but the remote branch ref is not updated in the local repository (so <code>master</code> reference the last commit but <code>origin/master</code> didn't moved).</p> <p>What's the difference between these two ways of working? Is it useful for particular decentralized work flows? What would be the corresponding git commands of these two approaches?</p>
8,762,966
3
1
null
2012-01-06 17:38:09.04 UTC
9
2013-08-23 23:29:05.427 UTC
null
null
null
null
946,487
null
1
35
eclipse|git|egit
57,031
<p>Push to Upstream.. pushes your branch as you would expect for a remote-tracking branch.</p> <p>Push... opens a dialog and lets you specify which refspecs you should push up, including tags, special cases like HEAD:refs/heads/master, etc.</p> <p>That it doesn't update origin/master seems like a bug to me, or maybe they're waiting for the next fetch to update origin. I'd open a bug at <a href="https://bugs.eclipse.org/bugs/enter_bug.cgi?product=EGit&amp;component=UI">https://bugs.eclipse.org/bugs/enter_bug.cgi?product=EGit&amp;component=UI</a></p> <p>PW</p>
664,631
Disable backspace and delete key with javascript in IE
<p>Anyone know how can I disable backspace and delete key with Javascript in IE? This is my code below, but seems it's not work for IE but fine for Mozilla.</p> <pre><code>onkeydown="return isNumberKey(event,this)" function isNumberKey(evt, obj) { var charCode = (evt.which) ? evt.which : evt.keyCode if (charCode == 8 || charCode == 46) return false; return true; } </code></pre>
664,648
4
1
null
2009-03-20 01:07:39.83 UTC
4
2015-02-07 11:18:55.623 UTC
2009-03-20 01:32:23.47 UTC
Jin Yong
52,745
Jin Yong
52,745
null
1
13
javascript
43,809
<p>This event handler works in all the major browsers.</p> <pre><code>function onkeyup(e) { var code; if (!e) var e = window.event; // some browsers don't pass e, so get it from the window if (e.keyCode) code = e.keyCode; // some browsers use e.keyCode else if (e.which) code = e.which; // others use e.which if (code == 8 || code == 46) return false; } </code></pre> <p>You can attach the event to this function like:</p> <pre><code>&lt;input onkeyup="return onkeyup()" /&gt; </code></pre>
283,922
What are the best Java social networking frameworks?
<p>I would like to create a private customized social networking for my company employees and partners so that they can collaborate, exchange messages, share experiences (events, book references, etc) and be grouped into communities. Does anybody know good Java framework for start developing this? </p> <p>I would be looking for something that would contain basic components such as Profile, Friend List, Community, Events, Messages, etc. Each of this component could be extended to implement domain specific features. It would be nice if it also supports OpenSocial.</p>
284,071
4
3
null
2008-11-12 13:28:58.763 UTC
22
2011-10-06 11:14:37.453 UTC
2008-11-12 14:02:54.263 UTC
Otavio
1,134,977
null
1,134,977
null
1
19
java|social-networking|opensocial
39,726
<p>Shindig is in incubation at Apache :<br> <a href="http://incubator.apache.org/projects/shindig.html" rel="noreferrer">http://incubator.apache.org/projects/shindig.html</a></p> <p>YouTube Link About Shindig :<br> <a href="http://www.youtube.com/watch?v=ZcWszaReqXI" rel="noreferrer">http://www.youtube.com/watch?v=ZcWszaReqXI</a></p> <hr> <p>A List of Open Source Social Networking >Applications&lt; Written in Java: <a href="http://www.manageability.org/blog/stuff/java-open-source-social-network" rel="noreferrer">http://www.manageability.org/blog/stuff/java-open-source-social-network</a></p>
953,112
Should I explicitly cast malloc()'s return value?
<p>I wanted to ask about the following case:</p> <pre><code>char *temp; temp = malloc(10); </code></pre> <p>Since the return type of <code>malloc</code> is <code>void*</code>, will the pointer returned by the <code>malloc</code> be implicitly cast to <code>char*</code> type before being assigned to temp? What does the standard say in this regard?</p> <p>If our pointer variable is some struct type for example:</p> <pre><code>struct node *temp; temp = (struct node *)malloc(sizeof(struct node)); </code></pre> <p>If we allocate memory to temp without casting it to <code>struct node*</code> type, will it be implicitly cast to <code>struct node*</code> type or is it necessary to explicitly cast it to <code>struct node*</code> type?</p>
953,123
4
3
null
2009-06-04 21:09:01.673 UTC
22
2012-06-27 08:31:03.493 UTC
2012-06-27 08:31:03.493 UTC
null
1,459,996
null
90,575
null
1
54
c|pointers|casting
17,516
<p>A void pointer in C can be assigned to any pointer without an explicit cast.</p>
67,791,029
Nullable Array Notation
<p>I am new to nullable.</p> <p>Is there a meaningful difference between the possible notations? <code>string?[] str</code> <code>string[]? str</code> and even <code>string?[]? str</code> seems to all be valid</p>
67,791,211
1
2
null
2021-06-01 14:45:20.45 UTC
3
2021-06-02 19:16:06.82 UTC
2021-06-02 19:16:06.82 UTC
null
2,319,407
null
14,933,279
null
1
31
c#|arrays|nullable-reference-types
1,857
<p>When we put <code>?</code> after <a href="https://docs.microsoft.com/en-us/dotnet/csharp/nullable-references" rel="noreferrer">reference type</a> we allow the instance to be <code>null</code>. So we have</p> <ul> <li><code>string?[]</code> - string array where we allow the items to be <code>null</code> (but array itself can't be <code>null</code>)</li> <li><code>string[]?</code> - string array which can be <code>null</code> itself (but it can't have <code>null</code> items)</li> <li><code>string?[]?</code> - both array and its items allowed to be <code>null</code></li> </ul>
54,063,041
Package a non-modular JavaFX application
<p>I have a Java 8 application, that uses JavaFX and where the main class extends <em>javafx.application.Application</em> . Currently, I deliver it as a fat jar and it runs fine on Oracle Java 8.</p> <p>Now I want it to be able to run on OpenJDK 11. To add JavaFX, I already added the artifacts from org.openjfx to the classpath and am including them in the fat jar. If I start my jar from the command line, I get</p> <pre><code>Error: JavaFX runtime components are missing, and are required to run this application </code></pre> <p>I found two possible ways around this problem:</p> <ol> <li>The dirty one: Write a special launcher that does not extend Application and circumvent the module check. See <a href="http://mail.openjdk.java.net/pipermail/openjfx-dev/2018-June/021977.html" rel="noreferrer">http://mail.openjdk.java.net/pipermail/openjfx-dev/2018-June/021977.html</a></li> <li>The clean one: Add --module-path and --add-modules to my command line. The problem with this solution is, that I want my end users to be able to just launch the application by double clicking it.</li> </ol> <p>While I could go with 1. as a workaround, I wonder what is currently (OpenJDK 11) the intended way to build/deliver executable fat jars of non-modular JavaFX applications. Can anyone help?</p>
54,065,502
1
1
null
2019-01-06 15:30:42.807 UTC
20
2019-01-06 20:11:39.77 UTC
2019-01-06 15:49:15.61 UTC
null
1,746,118
null
4,496,194
null
1
22
java|maven|javafx|javafx-11|openjfx
13,777
<p>These are a few options for packaging/distributing a (non-modular) JavaFX 11 end application. Most of them are explained in the official OpenJFX <a href="https://openjfx.io/openjfx-docs/#modular" rel="noreferrer">docs</a>.</p> <p>I'll use <a href="https://github.com/openjfx/samples/tree/master/CommandLine/Non-modular/Gradle" rel="noreferrer">this sample</a> as reference. I'll also use Gradle. Similar can be done with Maven (different plugins), and even without build tools (but this is not recommended...). Build tools are a must nowadays.</p> <h1>Fat Jar</h1> <p>This is still a valid option, but not the preferred one, as it breaks the modular design and bundles everything all together, and it is not cross-platform unless you take care of that.</p> <p>For the given sample, you have a build.gradle file like this:</p> <pre><code>plugins { id 'application' id 'org.openjfx.javafxplugin' version '0.0.5' } repositories { mavenCentral() } dependencies { } javafx { modules = [ 'javafx.controls' ] } mainClassName = 'hellofx.HelloFX' jar { manifest { attributes 'Main-Class': 'hellofx.Launcher' } from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } } </code></pre> <p>Note the use of a <code>Launcher</code> class. As mentioned by the OP or explained <a href="https://stackoverflow.com/a/52571719/3956070">here</a>, a launcher class that not extends from <code>Application</code> is required now to create a fat jar.</p> <p>Running <code>./gradlew jar</code> produces a fat jar (~8 MB) that includes the JavaFX classes, and the native libraries of <em>your</em> current platform.</p> <p>You can run <code>java -jar build/libs/hellofx.jar</code> as usual, but only in the same platform.</p> <p>As explained in the OpenJFX docs or <a href="https://stackoverflow.com/questions/52653836/maven-shade-javafx-runtime-components-are-missing/52654791#52654791">here</a>, you can still create a cross-platform jar.</p> <p>In this case, we can include the three graphics jars, as those are the ones that have platform-dependent code and libraries. Base, controls and fxml modules are the platform-independent.</p> <pre><code>dependencies { compile "org.openjfx:javafx-graphics:11.0.1:win" compile "org.openjfx:javafx-graphics:11.0.1:linux" compile "org.openjfx:javafx-graphics:11.0.1:mac" } </code></pre> <p><code>./gradlew jar</code> will produce a fat jar (19 MB) now that can be distributed to these three platforms.</p> <p>(Note Media and Web have also platform-dependent code/native libraries).</p> <p>So this works as it used to on Java 8. But as I said before, it breaks how modules work, and it doesn't align on how libraries and apps are distributed nowadays. </p> <p>And don't forget that the users of these jars will still have to install a JRE.</p> <h1>jlink</h1> <p>So what about distributing a custom image with your project, that already includes a native JRE and a launcher?</p> <p>You will say that if you have a non-modular project, that won't work. True. But let's examine two options here, before talking about jpackage.</p> <h2>runtime-plugin</h2> <p>The <a href="https://github.com/beryx/badass-runtime-plugin" rel="noreferrer">badass-runtime-plugin</a> is a Gradle plugin that creates runtime images from non-modular projects.</p> <p>With this build.gradle:</p> <pre><code>plugins { id 'org.openjfx.javafxplugin' version '0.0.5' id 'org.beryx.runtime' version '1.0.0' id "com.github.johnrengelman.shadow" version "4.0.3" } repositories { mavenCentral() } dependencies { } javafx { modules = [ 'javafx.controls' ] } mainClassName = 'hellofx.Launcher' runtime { options = ['--strip-debug', '--compress', '2', '--no-header-files', '--no-man-pages'] } </code></pre> <p>When you run <code>./gradlew runtime</code> it will create a runtime, with its launcher, so you can run:</p> <pre><code>cd build/image/hellofx/bin ./hellofx </code></pre> <p>Note it relies on the shadow plugin, and it requires a Launcher class as well. </p> <p>If you run <code>./gradlew runtimeZip</code>, you can get a zip for this custom image of about 32.5 MB.</p> <p>Again, you can distribute this zip to any user with the same platform, but now there is no need of an installed JRE.</p> <p>See <a href="https://badass-runtime-plugin.beryx.org/releases/latest/#_methods" rel="noreferrer"><code>targetPlatform</code></a> for building images for other platforms.</p> <h2>Going Modular</h2> <p>We keep thinking that we have non-modular project, and that can't be changed... but what if we do change it?</p> <p><em>Going modular</em> is not that big of a change: you add a <code>module-info.java</code> descriptor, and you include the required modules on it, even if those are non-modular jars (based on automatic names).</p> <p>Based on the same sample, I'll add a descriptor:</p> <pre><code>module hellofx { requires javafx.controls; exports hellofx; } </code></pre> <p>And now I can use <code>jlink</code> on command line, or use a plugin for it. The <a href="https://github.com/beryx/badass-jlink-plugin" rel="noreferrer">badass-gradle-plugin</a> is a gradle plugin, from the same author as the one mentioned before, that allows creating a custom runtime.</p> <p>With this build file:</p> <pre><code>plugins { id 'org.openjfx.javafxplugin' version '0.0.5' id 'org.beryx.jlink' version '2.3.0' } repositories { mavenCentral() } dependencies { } javafx { modules = [ 'javafx.controls' ] } mainClassName = 'hellofx/hellofx.HelloFX' </code></pre> <p>you can run now:</p> <pre><code>./gradlew jlink cd build/image/bin/hellofx ./hellofx </code></pre> <p>or <code>./gradlew jlinkZip</code> for a zipped version (31 MB) that can be distributed and run in machines, of the same platform, even if there is no JRE installed.</p> <p>As you can see, no need for shadow plugin or Launcher class. You can also target other platforms, or include non-modular dependencies, like in this <a href="https://stackoverflow.com/a/53764547/3956070">question</a>. </p> <h2>jpackage</h2> <p>Finally, there is a new tool to create executable installers that you can use to distribute your application.</p> <p>So far there is no GA version yet (probably we'll have to wait for Java 13), but there are two options to use it now with Java 11 or 12:</p> <p>With Java/JavaFX 11 there is a back port from the initial work on the JPackager on Java 12 that you can find <a href="https://mail.openjdk.java.net/pipermail/openjfx-dev/2018-September/022500.html" rel="noreferrer">here</a>. There is a nice article about using it <a href="https://medium.com/@adam_carroll/java-packager-with-jdk11-31b3d620f4a8" rel="noreferrer">here</a>, and a gradle project to use it <a href="https://github.com/Santulator/Santulator/tree/master/package" rel="noreferrer">here</a>.</p> <p>With Java/JavaFX 12 there is already a <a href="https://jdk.java.net/jpackage/" rel="noreferrer">build 0 version</a> of the <code>jpackage</code> tool that will be available with Java 13.</p> <p>This is a very preliminary use of the tool:</p> <pre><code>plugins { id 'org.openjfx.javafxplugin' version '0.0.5' } repositories { mavenCentral() } dependencies { } javafx { version = "12-ea+5" modules = [ 'javafx.controls' ] } mainClassName = 'hellofx/hellofx.HelloFX' def java_home = '/Users/&lt;user&gt;/Downloads/jdk-12.jdk/Contents/Home' def installer = 'build/installer' def appName = 'HelloFXApp' task copyDependencies(type: Copy) { dependsOn 'build' from configurations.runtime into "${buildDir}/libs" } task jpackage(type: Exec) { dependsOn 'clean' dependsOn 'copyDependencies' commandLine "${java_home}/bin/jpackage", 'create-installer', "dmg", '--output', "${installer}", "--name", "${appName}", '--verbose', '--echo-mode', '--module-path', 'build/libs', '--add-modules', "${moduleName}", '--input', 'builds/libraries', '--class', "${mainClassName}", '--module', "${mainClassName}" } </code></pre> <p>Now running <code>./gradlew jpackage</code> generates a dmg (65 MB), that I can distribute to be installed:</p> <p><a href="https://i.stack.imgur.com/lQUU1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lQUU1.png" alt="installer"></a></p> <h2>Conclusion</h2> <p>While you can stick to classic fat jars, when moving to Java 11 and beyond, everything is supposed to be modular. The new (soon to be) available tools and plugins, including the IDE support, are helping during this transition.</p> <p>I know I've presented here the simplest use case, and that when trying more complex real cases, there will be several issues... But we should better work on solving those issues rather than keep using outdated solutions. </p>
38,063,657
pyspark: merge (outer-join) two data frames
<p>I have the following two data frames:</p> <pre><code>DF1: Id | field_A | field_B | field_C | field_D 1 | cat | 12 | black | 11 2 | dog | 128 | white | 19 3 | dog | 35 | yellow | 20 4 | dog | 21 | brown | 4 5 | bird | 10 | blue | 7 6 | cow | 99 | brown | 34 </code></pre> <p>and</p> <pre><code>DF2: Id | field_B | field_C | field_D | field_E 3 | 35 | yellow | 20 | 123 5 | 10 | blue | 7 | 454 6 | 99 | brown | 34 | 398 </code></pre> <p>And I am hoping to get the new_DF as</p> <pre><code> Id | field_A | field_B | field_C | field_D | field_E 1 | cat | 12 | black | 11 | 2 | dog | 128 | white | 19 | 3 | dog | 35 | yellow | 20 | 123 4 | dog | 21 | brown | 4 | 5 | bird | 10 | blue | 7 | 454 6 | cow | 99 | brown | 34 | 398 </code></pre> <hr> <p>Could this be achieved by data frame operations? Thanks!</p>
38,063,734
1
0
null
2016-06-27 21:36:52.8 UTC
3
2017-10-29 22:12:59.003 UTC
2017-10-29 22:12:59.003 UTC
null
5,741,205
null
3,993,270
null
1
20
python|apache-spark|pyspark|spark-dataframe
55,135
<p>try this:</p> <pre><code>new_df = df1.join(df2, on=['field_B', 'field_C', 'field_D'], how='left_outer') </code></pre>
33,631,482
React: this is null in event handler
<p>I have a LoginForm component. I want to check before submit, that both <code>loginName</code> and <code>password</code> is set. I tried with this code (a lot of stuff omitted):</p> <pre><code>class LoginForm extends Component { constructor() { super(); this.state = { error: "", loginName: "", password: "", remember: true }; } submit(e) { e.preventDefault(); if(!this.state.loginName || !this.state.password) { //this is null this.setState({ error: "Fill in both fields" }); } else { console.log("submitting form"); } } render() { return ( &lt;div className="col-xs-12 col-sm-6 col-md-4"&gt; &lt;form className="login" onSubmit={this.submit}&gt; &lt;button type="submit" className="btn btn-default"&gt;Sign in&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; ); } } export default LoginForm; </code></pre> <p>however, i get a <code>TypeError</code> in the event handler, saying that <code>this</code> is null.</p> <p>What should I be doing?</p>
33,631,520
4
0
null
2015-11-10 13:46:09.12 UTC
7
2018-08-21 08:42:47.83 UTC
2017-01-07 11:22:41.503 UTC
null
1,173,529
null
1,173,529
null
1
39
javascript|reactjs|this
18,566
<p>You need set <code>this</code> for <code>submit</code> method because now <code>this</code> is <code>undefined</code>, for this operation you can use <code>.bind</code></p> <pre><code>onSubmit={ this.submit.bind(this) } </code></pre> <p><a href="https://jsfiddle.net/_alexander_/69z2wepo/20407/"><code>Example</code></a></p> <p>or you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function</a></p> <pre><code>onSubmit={ (e) =&gt; this.submit(e) } </code></pre> <p><a href="https://jsfiddle.net/_alexander_/69z2wepo/31122/"><code>Example</code></a></p>
36,753,819
Conditionally add RouterLink or other attribute directives to an element in Angular 2
<p>In Angular 2 if I have an element like <code>&lt;button&gt;&lt;/button&gt;</code> how can I conditionally add an attribute directive like <code>[routerLink]="['SomeRoute']</code> to it?</p>
36,754,176
9
0
null
2016-04-20 19:50:57.893 UTC
6
2022-06-20 12:58:56.073 UTC
null
null
null
null
300,744
null
1
74
angular
63,035
<p>As far as I know, there is no straight way to do this. There are some workarounds... I used something like this:</p> <pre><code>&lt;button *ngIf=&quot;condition&quot; [routerLink]=&quot;['SomeRoute']&quot;&gt;&lt;/button&gt; &lt;button *ngIf=&quot;!condition&quot;&gt;&lt;/button&gt; </code></pre> <p>There is an similar discussion here: <a href="https://github.com/angular/angular/issues/6576" rel="noreferrer">link</a></p>
19,269,507
Accept only digits for h:inputText value
<p>Is there a way to confirm the value of an <code>h:inputText</code> in JSF, which should accepts only digits. Means it can be an <code>Integer</code> or the <code>float</code>. </p> <p>If I type <code>12s3a562.675</code> , <code>a5678s12</code> , <code>68712haf.563345</code> or any other such kind of values, then it should show an error. Otherwise it accepts and proceeds.</p>
29,963,409
11
0
null
2013-10-09 10:29:15.933 UTC
6
2020-06-14 09:53:44.81 UTC
2015-08-05 13:28:25.597 UTC
null
157,882
null
1,312,477
null
1
19
validation|jsf|jsf-2|input|decimal
102,912
<p>Just bind the input value to a <code>Double</code>, or better, <code>BigDecimal</code> property instead of <code>String</code>.</p> <pre><code>private BigDecimal number; // Double can also, but beware floating-point-gui.de </code></pre> <pre><code>&lt;h:inputText value="#{bean.number}" /&gt; </code></pre> <p>JSF has <a href="https://docs.oracle.com/javaee/7/api/javax/faces/convert/package-summary.html">builtin converters</a> for those types which will kick in automatically. You can customize the converter message as below:</p> <pre><code>&lt;h:inputText value="#{bean.number}" converterMessage="Please enter digits only." /&gt; </code></pre>
26,667,112
Optionally inject Content Script
<p>Content Script can be injected programatically or permanently by declaring in Extension manifest file. Programatic injection require host permission, which is generally grant by browser or page action.</p> <p>In my use case, I want to inject gmail, outlook.com and yahoo mail web site without user action. I can do by declaring all of them manifest, but by doing so require all data access to those account. Some use may want to grant only outlook.com, but not gmail. Programatic injection does not work because I need to know when to inject. Using tabs permission is also require another permission.</p> <p>Is there any good way to optionally inject web site? </p>
26,677,279
3
0
null
2014-10-31 03:28:30.73 UTC
12
2022-06-13 07:17:14.107 UTC
null
null
null
null
824,275
null
1
21
google-chrome-extension|content-script
6,405
<p>You cannot run code on a site without the appropriate permissions. Fortunately, you can add the host permissions to <a href="https://developer.chrome.com/extensions/permissions#manifest" rel="noreferrer"><code>optional_permissions</code></a> in the manifest file to declare them optional and still allow the extension to use them.</p> <p>In response to a user gesture, you can use <a href="https://developer.chrome.com/extensions/permission#method-request" rel="noreferrer"><code>chrome.permission.request</code></a> to request additional permissions. This API can only be used in extension pages (background page, popup page, options page, ...). As of Chrome 36.0.1957.0, the required user gesture also carries over from content scripts, so if you want to, you could add a click event listener from a content script and use <a href="https://developer.chrome.com/extensions/runtime#method-sendMessage" rel="noreferrer"><code>chrome.runtime.sendMessage</code></a> to send the request to the background page, which in turn calls <a href="https://developer.chrome.com/extensions/permissions#method-request" rel="noreferrer"><code>chrome.permissions.request</code></a>.</p> <h3>Optional code execution in tabs</h3> <p>After obtaining the host permissions (optional or mandatory), you have to somehow inject the content script (or CSS style) in the matching pages. There are a few options, in order of my preference:</p> <ol> <li><p>Use the <a href="https://developer.chrome.com/extensions/declarativeContent#type-RequestContentScript" rel="noreferrer"><code>chrome.declarativeContent.RequestContentScript</code></a> action to insert a content script in the page. Read <a href="https://developer.chrome.com/extensions/declarativeContent" rel="noreferrer">the documentation</a> if you want to learn how to use this API.</p></li> <li><p>Use the <a href="https://developer.chrome.com/extensions/webNavigation" rel="noreferrer"><code>webNavigation</code></a> API (e.g. <a href="https://developer.chrome.com/extensions/webNavigation#event-onCommitted" rel="noreferrer"><code>chrome.webNavigation.onCommitted</code></a>) to detect when the user has navigated to the page, then use <a href="https://developer.chrome.com/extensions/tabs#method-executeScript" rel="noreferrer"><code>chrome.tabs.executeScript</code></a> to insert the content script in the tab (or <a href="https://developer.chrome.com/extensions/tabs#method-insertCSS" rel="noreferrer"><code>chrome.tabs.insertCSS</code></a> to insert styles).</p></li> <li><p>Use the <a href="https://developer.chrome.com/extensions/tabs" rel="noreferrer"><code>tabs</code></a> API (<a href="https://developer.chrome.com/extensions/tabs#event-onUpdated" rel="noreferrer"><code>chrome.tabs.onUpdated</code></a>) to detect that a page might have changed, and insert a content script in the page using <code>chrome.tabs.executeScript</code>.</p></li> </ol> <p>I strongly recommend option 1, because it was specifically designed for this use case. Note: This API was added in Chrome 38, but only worked with optional permissions <a href="https://crbug.com/429944" rel="noreferrer" title="Issue 429944: declarativeContent.RequestContentScript not injected with optional permissions">since Chrome 39</a>. Despite the "<a href="https://developer.chrome.com/extensions/declarativeContent#type-RequestContentScript" rel="noreferrer">WARNING: This action is still experimental and is not supported on stable builds of Chrome.</a>" in the documentation, the API is actually supported on stable. Initially the idea was to <a href="https://crbug.com/409147" rel="noreferrer" title="declarativeContent.RequestContentScript has reached stable channel">wait for a review before publishing the API on stable</a>, but that review never came and so now this API has been working fine for almost two years.</p> <p>The second and third options are similar. The difference between the two is that using the <code>webNavigation</code> API adds an additional permission warning ("Read your browsing history"). For this warning, you get an API that can efficiently filter the navigations, so the number of <code>chrome.tabs.executeScript</code> calls can be minimized.</p> <p>If you don't want to put this extra permission warning in your permission dialog, then you could blindly try to inject on every tab. If your extension has the permission, then the injection will succeed. Otherwise, it fails. This doesn't sound very efficient, and it is not... ...on the bright side, this method does not require any additional permissions.</p> <p>By using either of the latter two methods, your content script must be designed in such a way that it can handle multiple insertions (e.g. <a href="https://stackoverflow.com/a/18423519">with a guard</a>). Inserting in frames is also supported (<code>allFrames:true</code>), but only if your extension is allowed to access the tab's URL (or the frame's URL if <a href="https://developer.chrome.com/extensions/tabs#property-details-frameId" rel="noreferrer"><code>frameId</code></a> is set).</p>
36,223,157
Set weight and bias tensors of tensorflow conv2d operation
<p>I have been given a trained neural network in torch and I need to rebuild it exactly in tensorflow. I believe I have correctly defined the network's architecture in tensorflow but I am having trouble transferring the weight and bias tensors. Using a third party package, I converted all the weight and bias tensors from the torch network to numpy arrays then wrote them to disk. I can load them back into my python program but I cannot figure out a way to assign them to the corresponding layers in my tensorflow network. </p> <p>For instance, I have a convolution layer defined in tensorflow as</p> <pre><code>kernel_1 = tf.Variable(tf.truncated_normal([11,11,3,64], stddev=0.1)) conv_kernel_1 = tf.nn.conv2d(input, kernel_1, [1,4,4,1], padding='SAME') biases_1 = tf.Variable(tf.zeros[64]) bias_layer_1 = tf.nn_add(conv_kernel_1, biases_1) </code></pre> <p>According to the tensorflow documentation, the tf.nn.conv2d operation uses the shape defined in the kernel_1 variable to construct the weight tensor. However, I cannot figure out how to access that weight tensor to set it to the weight array I have loaded from file. </p> <p><strong>Is it possible to explicitly set the weight tensor? And if so, how?</strong> </p> <p>(The same question applies to bias tensor.)</p>
36,223,553
1
0
null
2016-03-25 15:45:42.937 UTC
8
2016-03-25 16:06:43.547 UTC
null
null
null
null
6,114,511
null
1
13
python|numpy|tensorflow
16,355
<p>If you have the weights and biases in a NumPy array, it should be easy to connect them into your TensorFlow network:</p> <pre><code>weights_1_array = ... # ndarray of weights for layer 1 biases_1_array = ... # ndarray of biases for layer 1 conv_kernel_1 = tf.nn.conv2d(input, weights_1_array, [1, 4, 4, 1], padding='SAME') bias_layer_1 = tf.nn.bias_add(conv_kernel_1, biases_1_array) </code></pre> <p>Note that you must ensure that <code>weights_1_array</code> and <code>biases_1_array</code> are in the correct data format. See the documentation for <a href="https://www.tensorflow.org/versions/master/api_docs/python/nn.html#conv2d" rel="noreferrer"><code>tf.nn.conv2d()</code></a> for an explanation of the required filter shape.</p>
27,533,193
Android HCE: are there rules for AID?
<p>I'm trying to use an ACR122 NFC reader to select an application emulated in one Nexus 5 using Android Host Card Emulation. However, small AIDs are not recognized.</p> <p>My goal is to use a three byte long AID, as I do in a DESfire card. My first goal is only to be able to do a SELECT command.</p> <p>My test app uses the following configuration for AIDs:</p> <pre><code>&lt;host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android" android:description="@string/service_descr" android:requireDeviceUnlock="false" &gt; &lt;aid-group android:category="other" android:description="@string/aid_descr" &gt; &lt;aid-filter android:name="A0A1A2" /&gt; &lt;aid-filter android:name="B0B1B2B3" /&gt; &lt;aid-filter android:name="C0C1C2C3C4" /&gt; &lt;aid-filter android:name="D0D1D2D3D4D5" /&gt; &lt;aid-filter android:name="E0E1E2E3E4E5E6" /&gt; &lt;/aid-group&gt; &lt;/host-apdu-service&gt; </code></pre> <p>If I run the following APDUs:</p> <pre><code>00 a4 04 00 03 a0 a1 a2 00 00 a4 04 00 04 b0 b1 b2 b3 00 00 a4 04 00 05 c0 c1 c2 c3 c4 00 00 a4 04 00 06 d0 d1 d2 d3 d4 d5 00 00 a4 04 00 07 e0 e1 e2 e3 e4 e5 e6 00 </code></pre> <p>I always get the following responses:</p> <pre><code>=&gt; 00 a4 04 00 03 a0 a1 a2 00 &lt;= 6f 00 =&gt; 00 a4 04 00 04 b0 b1 b2 b3 00 &lt;= 6a 82 =&gt; 00 a4 04 00 05 c0 c1 c2 c3 c4 00 &lt;= 90 00 =&gt; 00 a4 04 00 06 d0 d1 d2 d3 d4 d5 00 &lt;= 90 00 =&gt; 00 a4 04 00 07 e0 e1 e2 e3 e4 e5 e6 00 &lt;= 90 00 </code></pre> <p>So, only AIDs with length greater than 5 bytes will work with Android? Or am I doing something really wrong?</p>
27,620,724
2
0
null
2014-12-17 19:20:19.413 UTC
9
2017-06-14 15:32:34.643 UTC
2017-06-14 15:32:34.643 UTC
null
2,425,802
null
3,240,124
null
1
8
android|nfc|mifare|apdu|hce
11,918
<p>The rules for smartcard application identifiers (AIDs) are defined in ISO/IEC 7816-4. An AID may consist of up to 16 bytes. Based on the first 4 bits, AIDs are divided into different groups. The most relevant groups defined in ISO/IEC 7816-4 are:</p> <ul> <li>AIDs starting with <code>'A'</code>: internationally registered AIDs</li> <li>AIDs starting with <code>'D'</code>: nationally registered AIDs</li> <li>AIDs starting with <code>'F'</code>: proprietary AIDs (no registration)</li> </ul> <p>For (inter)nationally registered AIDs, the AID is split into two parts, a 5-byte mandatory RID (registered application provider identifier), and an optional PIX (proprietary application identifier extension) of up to 11 bytes.</p> <p>For proprietary AIDs (<code>F...</code>) ISO/IEC 7816-4 does not clearly mandate any minimum length requirements.</p> <p>In addition to this, when it comes to HCE and routing of card emulation communication from the NFC controller to secure elements or the application processor, there is the NFC Forum NCI specification. This specification mandates an AID (used in AID-based routing entries) to be between 5 and 16 bytes. Btw. the same limitation applies to smartcards following the Java Card specifications.</p> <p>When it comes to Android, there is a hard-coded requirement that AIDs received in a SELECT command consist of at least 5 bytes:</p> <ul> <li>In method <code>resolveAid()</code> in <a href="https://android.googlesource.com/platform/packages/apps/Nfc/+/android-5.0.0_r7/src/com/android/nfc/cardemulation/RegisteredAidCache.java#142">RegisteredAidCache.java on line 142</a></li> <li>In method <code>findSelectAid()</code> in <a href="https://android.googlesource.com/platform/packages/apps/Nfc/+/android-5.0.0_r7/src/com/android/nfc/cardemulation/HostEmulationManager.java#390">HostEmulationManager.java on line 390</a> (which actually causes the odd behavior that the 4 byte AID is rejected with a "File or application not found" (<code>6A82</code>) status word as the check does not properly account for the Le byte)</li> </ul>
40,097,488
Saving npm @types typings with --save or --save-dev
<p>TypeScript 2 recommends using npm for types. In <a href="https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/" rel="noreferrer">The Future of Declaration Files</a>.</p> <p>the example is:</p> <pre><code>npm install --save @types/lodash </code></pre> <p>My question is whether --save-dev should be used in an application, because TypeScript is transpiled and not deployed? Some comments on the article mention similar, but there is no answer I could see.</p> <p>Perhaps --save is useful in a library to drag around the types when others install your library?</p> <p>Am I missing something else this is useful for and what is the best practice? Thanks.</p>
40,600,860
1
1
null
2016-10-18 00:02:51.13 UTC
2
2016-11-15 02:05:28.253 UTC
2016-11-15 02:05:28.253 UTC
null
162,698
null
2,800,482
null
1
39
typescript-typings|typescript2.0
6,866
<p>From <a href="https://github.com/Microsoft/types-publisher/issues/81" rel="noreferrer">Microsoft/types-publisher #81</a>: </p> <blockquote> <p>Using --save-dev is fine when you're writing a simple application, and it won't be used as a library. The problem comes along when you might have dependencies. If you stored your type declarations in your devDependencies, your consumers would not automatically get your type declarations. They'd then have to manually add your declaration file dependencies as their devDependencies.</p> <p>Given that breaking consumers is a worse problem than slightly-larger packages, we've made --save the default in our documentation.</p> </blockquote>
39,890,849
What exactly is Field Injection and how to avoid it?
<p>I read in some posts about Spring MVC and Portlets that <em>field injection</em> is not recommended. As I understand it, <em>field injection</em> is when you inject a Bean with <code>@Autowired</code> like this:</p> <pre><code>@Component public class MyComponent { @Autowired private Cart cart; } </code></pre> <p>During my research I also read about <em>constructor injection</em>:</p> <pre><code>@Component public class MyComponent { private final Cart cart; @Autowired public MyComponent(Cart cart){ this.cart = cart; } } </code></pre> <p>What are the advantages and the disadvantages of both of these types of injections?</p> <hr> <p><strong>EDIT 1:</strong> As this question is marked as duplicate of <a href="https://stackoverflow.com/questions/7779509/setter-di-vs-constructor-di-in-spring">this question</a> i checked it. Cause there aren't any code examples neither in the question nor in the answers it's not clear to me if i'm correct with my guess which injection type i'm using. </p>
39,892,204
4
2
null
2016-10-06 08:12:05.453 UTC
171
2021-08-31 15:04:59.013 UTC
2020-02-05 23:49:02.387 UTC
null
1,371,329
null
5,444,891
null
1
264
java|spring-mvc|dependency-injection|portlet|autowired
147,598
<p><strong>Injection types</strong></p> <p>There are three options for how dependencies can be injected into a bean:</p> <ol> <li>Through a constructor</li> <li>Through setters or other methods</li> <li>Through reflection, directly into fields</li> </ol> <p>You are using option 3. That is what is happening when you use <code>@Autowired</code> directly on your field.</p> <hr> <p><strong>Injection guidelines</strong></p> <p>A general guideline, <a href="http://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/beans.html" rel="noreferrer">which is recommended by Spring</a> (see the sections on <a href="https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/beans.html#beans-constructor-injection" rel="noreferrer">Constructor-based DI</a> or <a href="https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/beans.html#beans-setter-injection" rel="noreferrer">Setter-based DI</a>) is the following:</p> <ul> <li>For mandatory dependencies or when aiming for immutability, use constructor injection</li> <li>For optional or changeable dependencies, use setter injection</li> <li>Avoid field injection in most cases</li> </ul> <hr> <p><strong>Field injection drawbacks</strong></p> <p>The reasons why field injection is frowned upon are as follows:</p> <ul> <li>You cannot create immutable objects, as you can with constructor injection</li> <li>Your classes have tight coupling with your DI container and cannot be used outside of it</li> <li>Your classes cannot be instantiated (for example in unit tests) without reflection. You need the DI container to instantiate them, which makes your tests more like integration tests</li> <li>Your real dependencies are hidden from the outside and are not reflected in your interface (either constructors or methods)</li> <li>It is really easy to have like ten dependencies. If you were using constructor injection, you would have a constructor with ten arguments, which would signal that something is fishy. But you can add injected fields using field injection indefinitely. Having too many dependencies is a red flag that the class usually does more than one thing, and that it may violate the Single Responsibility Principle.</li> </ul> <hr> <p><strong>Conclusion</strong></p> <p>Depending on your needs, you should primarily use constructor injection or some mix of constructor and setter injection. Field injection has many drawbacks and should be avoided. The only advantage of field injection is that it is more convenient to write, which does not outweigh all the cons.</p> <hr> <p><strong>Further reading</strong></p> <p>I wrote a blog article about why field injection is usually not recommended: <a href="http://vojtechruzicka.com/field-dependency-injection-considered-harmful/" rel="noreferrer">Field Dependency Injection Considered Harmful</a>.</p>
37,194,653
Fragment replacing in RecyclerView item
<p>In my RecyclerView I need replace part of my item to my fragment. But replacing <strong>only first item</strong> in recycler view. What I am doing is wrong?</p> <p>My container (in recycler view item):</p> <pre><code>... &lt;FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/container" /&gt; ... </code></pre> <p>My update code in RecyclerView adapter:</p> <pre><code>... @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ... MyFragment fragment = MyFragment.newInstance("fragment1"); fragmentManager.beginTransaction().replace(R.id.container, fragment).commit(); ... } ... </code></pre>
37,212,091
2
1
null
2016-05-12 18:20:28.163 UTC
10
2020-05-08 13:34:05.973 UTC
null
null
null
null
4,866,667
null
1
10
android|android-fragments|android-recyclerview
20,393
<p>I finnaly found solution. The problem is I set a common container id. But in recycler view need to set <strong>unique container id</strong> for each item.</p> <p>So, my code now this:</p> <pre><code>MyFragment fragment = MyFragment.newInstance("fragment1"); fragmentManager.beginTransaction().replace(UNIQUE_CONTAINER_ID, fragment).commit(); </code></pre> <p>If someone will be useful, here is my complete code (implementation fragment in recycler view):</p> <pre><code>public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ... // Delete old fragment int containerId = holder.mediaContainer.getId();// Get container id Fragment oldFragment = fragmentManager.findFragmentById(containerId); if(oldFragment != null) { fragmentManager.beginTransaction().remove(oldFragment).commit(); } int newContainerId = View.generateViewId();// Generate unique container id holder.mediaContainer.setId(newContainerId);// Set container id // Add new fragment MyFragment fragment = MyFragment.newInstance("fragment1"); fragmentManager.beginTransaction().replace(newContainerId, fragment).commit(); ... } </code></pre> <p><strong>Upd.:</strong> Instead of using your own method to generate a unique id, it is recommended to use <code>View.generateViewId()</code></p>
48,365,252
How to find element using type in Selenium and Python
<p>I have the below html code.</p> <pre><code>&lt;div align="center"&gt; &lt;input type="file" name="filePath"&gt;&lt;br&gt; &lt;input type="Submit" value="Upload File"&gt;&lt;br&gt; &lt;/div&gt; </code></pre> <p>I am trying to find the two elements "file" and "submit" using Selenium with Python. Below is the code I have tried to use.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys # create a new Firefox session driver = webdriver.Chrome() # Maximize the browser window driver.maximize_window() # Enter the url to load driver.get("&lt;&lt;MY PAGE TO LOAD&gt;&gt;") # Wait for the page to load driver.implicitly_wait(5) # find the upload file type and pass a test value upload_field = driver.find_element_by_partial_link_text('file') upload_field.clear() upload_field.send_keys("test") </code></pre> <p>When I run this code, I am able to load the page successfully in the Chrome browser but I get the below exception.</p> <pre><code># Exception when trying to get element by type Traceback (most recent call last): File "C:\Users\TEST\Desktop\Test.py", line 33, in &lt;module&gt; upload_field = driver.find_element_by_partial_link_text('file') File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 453, in find_element_by_partial_link_text return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text) File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 955, in find_element 'value': value})['value'] File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 312, in execute self.error_handler.check_response(response) File "C:\Python\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 237, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"partial link text","selector":"file"} (Session info: chrome=63.0.3239.132) (Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.14393 x86_64) </code></pre> <p>I looked at the solution provided <a href="https://sqa.stackexchange.com/questions/15509/selenium-how-to-identify-an-object-by-its-type">here</a> but this too is throwing an error. I am currently using Python 3.6.4 x64 with Selenium 3.8.1. My OS is Windows 7 x64 bit. How can I get elements with 'type' in html?</p>
48,365,300
3
2
null
2018-01-21 09:07:02.93 UTC
8
2019-02-19 15:43:46.137 UTC
null
null
null
null
8,741,108
null
1
23
python|python-3.x|selenium|selenium-webdriver|selenium-chromedriver
62,486
<p>Checkout <a href="http://selenium-python.readthedocs.io/locating-elements.html" rel="noreferrer">the docs</a> on finding elements. I find xpaths or css selectors particularly powerful because they are extremely generalizable.</p> <h3>xpath</h3> <pre><code>upload_field = driver.find_element_by_xpath("//input[@type='file']") </code></pre> <h3>css selector</h3> <pre><code>upload_field = driver.find_element_by_css_selector("input[name='filePath'][type='file']") </code></pre>
25,812,331
Alter column default value
<p>I know you can change the default value of an existing column like <a href="https://stackoverflow.com/questions/6791675/how-to-set-a-default-value-for-an-existing-column">this</a>: </p> <pre><code>ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn; </code></pre> <p>But according to <a href="http://msdn.microsoft.com/en-us/library/ms187742%28v=sql.110%29.aspx" rel="noreferrer">this</a> my query supposed to work: </p> <pre><code>ALTER TABLE MyTable ALTER COLUMN CreateDate DATETIME NOT NULL CONSTRAINT DF_Constraint DEFAULT GetDate() </code></pre> <p>So here I'm trying to make my column Not Null and also set the Default value. But getting Incoorect Syntax Error near CONSTRAINT. Am I missing sth?</p>
25,813,306
5
1
null
2014-09-12 16:00:51.633 UTC
7
2021-02-25 00:53:24.733 UTC
2017-05-23 12:26:13.973 UTC
null
-1
null
713,847
null
1
30
sql|sql-server|default-value|notnull
116,006
<p>I think issue here is with the confusion between <code>Create Table</code> and <code>Alter Table</code> commands. If we look at <code>Create table</code> then we can add a default value and default constraint at same time as:</p> <pre><code>&lt;column_definition&gt; ::= column_name &lt;data_type&gt; [ FILESTREAM ] [ COLLATE collation_name ] [ SPARSE ] [ NULL | NOT NULL ] [ [ CONSTRAINT constraint_name ] DEFAULT constant_expression ] | [ IDENTITY [ ( seed,increment ) ] [ NOT FOR REPLICATION ] ] [ ROWGUIDCOL ] [ &lt;column_constraint&gt; [ ...n ] ] [ &lt;column_index&gt; ] ex: CREATE TABLE dbo.Employee ( CreateDate datetime NOT NULL CONSTRAINT DF_Constraint DEFAULT (getdate()) ) ON PRIMARY; </code></pre> <p>you can check for complete definition here: <a href="http://msdn.microsoft.com/en-IN/library/ms174979.aspx" rel="noreferrer">http://msdn.microsoft.com/en-IN/library/ms174979.aspx</a></p> <p>but if we look at the <code>Alter Table</code> definition then with <code>ALTER TABLE ALTER COLUMN</code> you cannot add <code>CONSTRAINT</code> the options available for <code>ADD</code> are:</p> <pre><code> | ADD { &lt;column_definition&gt; | &lt;computed_column_definition&gt; | &lt;table_constraint&gt; | &lt;column_set_definition&gt; } [ ,...n ] </code></pre> <p>Check here: <a href="http://msdn.microsoft.com/en-in/library/ms190273.aspx" rel="noreferrer">http://msdn.microsoft.com/en-in/library/ms190273.aspx</a></p> <p>So you will have to write two different statements one for Altering column as:</p> <pre><code>ALTER TABLE MyTable ALTER COLUMN CreateDate DATETIME NOT NULL; </code></pre> <p>and another for altering table and add a default constraint</p> <p><code>ALTER TABLE MyTable ADD CONSTRAINT DF_Constraint DEFAULT GetDate() FOR CreateDate;</code></p> <p>Hope this helps!!!</p>
20,482,375
Use Active Directory with Web API for SPA
<p>I am building single page application and I would like to know user's identity. We have Active Directory in our intranet but I don't know much about it. I am able to use code like this to verify username and password.</p> <pre><code>using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN")) { bool isValid = pc.ValidateCredentials("myuser", "mypassword"); } </code></pre> <p>In fact that is everything I need from the Active Directory side of thing. So I could create some AuthorizationFilter with this code but this would mean that username and password must be in every request. I would like to send username and password only once and then use some token for authorization. So there should be some token provider inside my server-side application.</p> <p>I am building this application from scratch so I can use the latest .net technologies. I found that there are some Owin middlewares which are handling tokens, cookies and OAuth. Could anything of that help me?</p>
20,502,594
2
1
null
2013-12-09 22:40:47.063 UTC
13
2016-10-14 19:17:05.64 UTC
null
null
null
null
332,148
null
1
18
c#|active-directory|asp.net-web-api|single-page-application|owin
24,644
<p>When I was searching for something completely different, I found this incredible project on CodePlex: <a href="https://angularapp.codeplex.com/" rel="noreferrer">https://angularapp.codeplex.com/</a> It is exactly what I was looking for.</p> <p><strong>Update:</strong></p> <p>The part of this app which was useful to me is the DomainUserLoginProvider</p> <pre><code>public class DomanUserLoginProvider : ILoginProvider { public bool ValidateCredentials(string userName, string password, out ClaimsIdentity identity) { using (var pc = new PrincipalContext(ContextType.Domain, _domain)) { bool isValid = pc.ValidateCredentials(userName, password); if (isValid) { identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType); identity.AddClaim(new Claim(ClaimTypes.Name, userName)); } else { identity = null; } return isValid; } } public DomanUserLoginProvider(string domain) { _domain = domain; } private readonly string _domain; } </code></pre> <p>LoginProvider is used in AccountController's action to verify the credentials. Also the AccessToken is created here.</p> <pre><code>[HttpPost, Route("Token")] public IHttpActionResult Token(LoginViewModel login) { ClaimsIdentity identity; if (!_loginProvider.ValidateCredentials(login.UserName, login.Password, out identity)) { return BadRequest("Incorrect user or password"); } var ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); var currentUtc = new SystemClock().UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30)); return Ok(new LoginAccessViewModel { UserName = login.UserName, AccessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket) }); } </code></pre> <p>Last but not least, add the correct middleware to Owin pipeline.</p> <pre><code>public partial class Startup { static Startup() { OAuthOptions = new OAuthAuthorizationServerOptions(); } public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } public static void ConfigureAuth(IAppBuilder app) { app.UseOAuthBearerTokens(OAuthOptions); } } </code></pre> <p>On the client side you just send the request with credentials to the Token action of AccountController and you'll get the authentication token. Save this token in browser ("Remember me" feature) and set the Angular's $http service to attach token to each request. </p> <pre><code>services.factory('$auth', ['$q', '$http', '$path', function ($q, $http, $path) { var tokenUrl = $path('api/Account/Token'); function setupAuth(accessToken, remember) { var header = 'Bearer ' + accessToken; delete $http.defaults.headers.common['Authorization']; $http.defaults.headers.common['Authorization'] = header; sessionStorage['accessToken'] = accessToken; if (remember) { localStorage['accessToken'] = accessToken; } return header; } var self = {}; self.login = function(user, passw, rememberMe) { var deferred = $q.defer(); $http.post(tokenUrl, { userName: user, password: passw }) .success(function (data) { var header = setupAuth(data.accessToken, rememberMe); deferred.resolve({ userName: data.userName, Authorization: header }); }) .error(function() { deferred.reject(); }); return deferred.promise; }; return self; }]); </code></pre>
20,772,476
When to use pthread condition variables?
<p>pthread question:</p> <p>it appears that a condition variable only works if pthread_cond_wait is called before the other thread calls pthread_cond_notify. If notify somehow happens before wait then wait will be stuck.</p> <p>My question is: <strong><em>when should condition variables be used?</em></strong></p> <p>The scheduler can preempt threads and a notify may happen before wait. </p> <p>Waiting on semaphores does not have this problem -- these have a counter.</p> <p>When is a conditional variable better than a semaphore?</p> <p>Here is a test: </p> <h3>File condvar.c</h3> <pre class="lang-c prettyprint-override"><code>#include &lt;pthread.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; // test of conditional variables; // if cond-var is notified before wait starts, then wait never wakes up !!! // better to use semaphores than this crap. pthread_mutex_t cond_var_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER; int wait_first = 1; void *tfunc(void *arg) { (void) arg; if (!wait_first) sleep(1); fprintf(stderr,"on enter cond_var_lock %lx\n", pthread_self()); pthread_mutex_lock( &amp;cond_var_lock); fprintf(stderr,"before pthread_cond_wait %lx\n", pthread_self()); pthread_cond_wait( &amp;cond_var, &amp;cond_var_lock); fprintf(stderr,"after pthread_cond_wait %lx\n", pthread_self()); pthread_mutex_unlock( &amp;cond_var_lock); fprintf(stderr,"after exit cond_var_lock %lx\n", pthread_self()); return 0; } int main(int argc, char *argv[]) { pthread_t th; if (argc &gt; 0) wait_first = atoi( argv[1] ); if (wait_first) { fprintf(stderr,"********* Wait first ***********\n"); } else { fprintf(stderr,"********* Notify first *********\n"); } pthread_create( &amp;th, 0, tfunc, 0 ); if (wait_first) { sleep(1); } fprintf(stderr, "! on enter cond_var_lock %lx\n", pthread_self()); pthread_mutex_lock( &amp;cond_var_lock); fprintf(stderr, "! before pthread_cond_signal %lx\n", pthread_self()); pthread_cond_signal( &amp;cond_var ); fprintf(stderr, "! after pthread_cond_signal %lx\n", pthread_self()); pthread_mutex_unlock( &amp;cond_var_lock); fprintf(stderr, "! after exit cond_var_lock %lx\n", pthread_self()); sleep(5); return 0; } </code></pre> <h3>File test.sh</h3> <pre><code>#!/bin/sh set -e set -x gcc condvar.c -o condvar -lpthread ./condvar 1 ./condvar 0 </code></pre> <h3>Test output</h3> <pre><code>Output: + gcc condvar.c -o condvar -lpthread + ./condvar 1 ********* Wait first *********** on enter cond_var_lock b7779b70 before pthread_cond_wait b7779b70 ! on enter cond_var_lock b777a6c0 ! before pthread_cond_signal b777a6c0 ! after pthread_cond_signal b777a6c0 ! after exit cond_var_lock b777a6c0 after pthread_cond_wait b7779b70 after exit cond_var_lock b7779b70 + ./condvar 0 ********* Notify first ********* ! on enter cond_var_lock b785c6c0 ! before pthread_cond_signal b785c6c0 ! after pthread_cond_signal b785c6c0 ! after exit cond_var_lock b785c6c0 on enter cond_var_lock b785bb70 before pthread_cond_wait b785bb70 </code></pre>
20,772,586
1
1
null
2013-12-25 11:50:50.323 UTC
9
2019-11-12 07:56:43.353 UTC
2019-11-12 07:56:43.353 UTC
null
608,639
null
3,034,482
null
1
31
c|linux|pthreads
61,081
<p>Condition variables should be used as a place to wait and be notified. They are not the condition itself and they are not events. The condition is contained in the surrounding programming logic. The typical usage pattern of condition variables is</p> <pre><code>// safely examine the condition, prevent other threads from // altering it pthread_mutex_lock (&amp;lock); while ( SOME-CONDITION is false) pthread_cond_wait (&amp;cond, &amp;lock); // Do whatever you need to do when condition becomes true do_stuff(); pthread_mutex_unlock (&amp;lock); </code></pre> <p>On the other hand, a thread, signaling the condition variable, typically looks like</p> <pre><code>// ensure we have exclusive access to whathever comprises the condition pthread_mutex_lock (&amp;lock); ALTER-CONDITION // Wakeup at least one of the threads that are waiting on the condition (if any) pthread_cond_signal (&amp;cond); // allow others to proceed pthread_mutex_unlock (&amp;lock) </code></pre>
51,588,009
Vue.js - Configuring WebStorm to set @ in path files to the src folder
<p>In Vue.js you have the possibility to use the <code>@</code> in a path file as a shortcut to your <code>src</code> folder. It is nice because all your files have an absolute path.</p> <p>However I don't manage to find a way to configure WebStorm to understand that and allow me to follow and check if the file exist when using it.</p> <p>Example :</p> <pre><code>import Business from '@/components/Business/Business' </code></pre> <p>Writing that I want WebStorm to tell me if the file does not exists and to allow me to go to that file directly.</p> <p>I did not manage to find any answer about it and neither managed to find a way to do it in the IDE.</p>
51,593,112
4
2
null
2018-07-30 06:19:07.007 UTC
10
2021-03-31 07:05:13.877 UTC
2018-07-30 07:59:02.953 UTC
null
783,119
null
7,477,752
null
1
17
vue.js|ide|webstorm
11,017
<p>For vue-cli3, you need to specify a full path to <code>node_modules/@vue/cli-service/webpack.config.js</code> as a webpack configuration file in <strong>Settings | Languages &amp; Frameworks | JavaScript | Webpack</strong>.</p> <p>Note that this only works for JavaScript; webpack aliases are not resolved when using components written in TypeScript, <a href="https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping" rel="noreferrer">path mappings</a> in <code>tsconfig.json</code> should be used instead</p>
55,078,484
Open Jupyter Notebook from a Drive Other than C Drive
<p>I have a machine learning project in drive D. It contains python notebook files. But when I launch jupyter notebook through command prompt, it only shows directories inside drive C. How can I navigate to a drive other than C drive without changing jupyter notebook startup path?. I'm using windows 10 operating system. All the solutions I found, trying to change notebook startup path.</p>
55,369,484
13
4
null
2019-03-09 14:43:30.297 UTC
54
2022-03-10 05:29:57.093 UTC
null
null
null
null
8,855,629
null
1
92
python|jupyter-notebook
152,660
<p>You can launch it from any drive/location you want with the <code>--notebook-dir</code> option.</p> <p>For example:</p> <pre class="lang-sh prettyprint-override"><code>jupyter notebook --notebook-dir=D:/ </code></pre>
15,511,367
Mysql fetch all rows and echo as json
<p>I've got a database with 5 columns and multiple rows. I want to fetch the first 3 rows and echo them as an array. So far I can only get the first row (I'm new to PHP and mysql). Here's my PHP so far:</p> <pre><code>//==== FETCH DATA $result = mysql_query("SELECT * FROM $tableName"); $array = mysql_fetch_row($result); //==== ECHO AS JSON echo json_encode($array); </code></pre> <p>Help would be much appreciated.</p>
15,511,447
5
3
null
2013-03-19 22:02:39.853 UTC
2
2017-12-31 14:46:51.987 UTC
null
null
null
null
3,575,029
null
1
3
php|mysql|json
39,211
<p>You need to loop through the results. <code>mysql_fetch_row</code> gets them one at a time.</p> <p><a href="http://php.net/manual/en/function.mysql-fetch-row.php">http://php.net/manual/en/function.mysql-fetch-row.php</a></p> <p>The code would end up like:</p> <pre><code>$jsonData = array(); while ($array = mysql_fetch_row($result)) { $jsonData[] = $array; } echo json_encode($jsonData); //json_encode() </code></pre> <p><strong>PLEASE NOTE</strong> The mysql extension is deprecated in PHP 5.5, as stated in the comments you should use mysqli or PDO. You would just substitute <code>mysqli_fetch_row</code> in the code above. <a href="http://www.php.net/manual/en/mysqli-result.fetch-row.php">http://www.php.net/manual/en/mysqli-result.fetch-row.php</a></p>
25,360,893
Convert char* to uint8_t
<p>I transfer <strong>message trough a CAN protocol</strong>.</p> <p>To do so, the <strong>CAN message needs data of uint8_t type</strong>. So I need to convert my char* to uint8_t. With my research on this site, I produce this code :</p> <pre><code> char* bufferSlidePressure = ui-&gt;canDataModifiableTableWidget-&gt;item(6,3)-&gt;text().toUtf8().data();//My char* /* Conversion */ uint8_t slidePressure [8]; sscanf(bufferSlidePressure,"%c", &amp;slidePressure[0]); </code></pre> <p>As you may see, my <code>char*</code> must fit in <code>sliderPressure[0]</code>.</p> <p>My problem is that even if I have no error during compilation, <strong>the data in slidePressure are totally incorrect</strong>. Indeed, I test it with a <code>char* = 0</code> and I 've got unknow characters ... So I think the problem must come from conversion.</p> <p>My datas can be <code>Bool, Uchar, Ushort and float</code>.</p> <p>Thanks for your help.</p>
25,360,996
4
3
null
2014-08-18 10:13:50.557 UTC
2
2019-07-22 21:46:32.23 UTC
2014-08-18 13:03:05.99 UTC
null
2,812,789
null
2,812,789
null
1
11
c++|char|data-conversion|uint8t
79,117
<p>Is your string an integer? E.g. <code>char* bufferSlidePressure = "123";</code>?</p> <p>If so, I would simply do:</p> <pre><code>uint8_t slidePressure = (uint8_t)atoi(bufferSlidePressure); </code></pre> <p>Or, if you need to put it in an array:</p> <pre><code>slidePressure[0] = (uint8_t)atoi(bufferSlidePressure); </code></pre> <p>Edit: Following your comment, if your data could be anything, I guess you would have to copy it into the buffer of the new data type. E.g. something like:</p> <pre><code>/* in case you'd expect a float*/ float slidePressure; memcpy(&amp;slidePressure, bufferSlidePressure, sizeof(float)); /* in case you'd expect a bool*/ bool isSlidePressure; memcpy(&amp;isSlidePressure, bufferSlidePressure, sizeof(bool)); /*same thing for uint8_t, etc */ /* in case you'd expect char buffer, just a byte to byte copy */ char * slidePressure = new char[ size ]; // or a stack buffer memcpy(slidePressure, (const char*)bufferSlidePressure, size ); // no sizeof, since sizeof(char)=1 </code></pre>
25,247,565
Difference between "maxlength" & "size" attribute in html?
<p>I am little bit confused about the difference between the <code>maxlength</code> and the <code>size</code> attribute.</p> <pre><code>&lt;input type="text" name="telephone" maxlength="30" size="34"&gt; </code></pre> <p>I know that <code>maxlength</code> is used to control the input data. So what is the reason for using both attributes at once?</p>
25,248,436
5
3
null
2014-08-11 16:03:13.033 UTC
13
2022-07-11 18:26:23.883 UTC
2015-05-05 15:29:40.717 UTC
null
957,829
null
3,807,259
null
1
41
html|forms|web
40,157
<p>The <a href="http://www.w3.org/TR/html5/forms.html#the-maxlength-and-minlength-attributes" rel="nofollow noreferrer"><code>maxlength</code></a> (not <code>max-length</code>) attribute specifies the maximum length of the input string in characters or, more exactly, in code units. The browser is expected to enforce this, by refusing to accept more characters. However, this is not meant to act as a security measure, since it can be overridden trivially. Rather, it tells the user that no more characters will be accepted in processing the data. This is useful when you have to set an upper limit, e.g. your database can store only a fixed number of characters fpr some information, and also when there is a logical limit on the length (e.g., if the data is a two-letter code for a US state, it has the logical upper limit of 2).</p> <p>The <code>maxlength</code> attribute is thus logical, and it is expected to work even in non-visual user interface. It is not meant to affect the visual appearance of the input field in any way.</p> <p>The <a href="http://www.w3.org/TR/html5/forms.html#the-size-attribute" rel="nofollow noreferrer"><code>size</code></a> attribute, in contrast, is for visual rendering only. It suggests a visible width for the field, in terms of “average” characters. This vague concept has not been clarified in specifications, and browsers implement it inconsistently. It works best when a monospace font is used. This attribute does not limit the amount of characters entered, but it affects usability: it is difficult to enter, say, a 30 characters long string in a field that lets you see only 10 characters at a time. The width of a field is also a signal to the user: it indicates the expected maximum width of the input.</p> <p>It is often suitable to use both attributes, often with the same value. For example, if the field is for a 5-digit postal code, <code>size=5 maxlength=5</code> is suitable, especially if you also set <code>font-family: monospace</code>, so that the actual width is more or less exactly five digits.</p> <p>However, the values may differ. E.g., when asking for a line in a postal address, you might set <code>size=30</code>, since this is normally sufficient for a line, but <code>maxlength=80</code>, if this corresponds to the limitations set by your database or data processing and you have no particular reason not to allow such long lines.</p> <p>The <code>size</code> attribute can in principle be replaced by <strong>CSS</strong>, since it deals with visual rendering only. However, the width is usually best set in characters, and there is no universally supported unit for the average width of a character in <strong>CSS</strong>; the new <a href="https://meyerweb.com/eric/thoughts/2018/06/28/what-is-the-css-ch-unit/" rel="nofollow noreferrer"><code>ch</code></a> unit comes close, but isn’t quite the same and isn’t supported by old browsers.</p>
38,985,624
Alternative of Object.assign(...array)
<p>Assume we have array of objects. </p> <p>Calling <code>Object.assign(...array)</code> makes an inheritance among those objects where object with index <code>i</code> override existing properties in object with index <code>i-1</code></p> <p>For example:</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-js lang-js prettyprint-override"><code>var array=[{interf:'IPerson',name:'Someone'},{clss:'Person',name:'Ahmed'},{student:true}]; console.log( Object.assign(...array) // Object.assign(array[0],array[1],array[2]) )</code></pre> </div> </div> </p> <p>Now, using Babel with the proposed object spread syntax, we can do this statically : </p> <pre><code>{...array[0],...array[1],...array[2]} // spread used for each object not for array </code></pre> <p><strong>How to do that dynamically?</strong></p> <p>There is overlap of context of "spread syntax". I mean how to use spread syntax for both:</p> <ul> <li>For the Array to spread elements. </li> <li>For the output literal object <code>{}</code> to make inheritance </li> </ul> <p>?</p> <p>I tried <code>{...array}</code> and it returns <code>{0:&lt;array[0]&gt;,1:&lt;array[1]&gt;,2:&lt;array[2]&gt;}</code> which is <strong>not</strong> the same output as <code>Object.assign(...array)</code>.</p>
38,985,682
4
5
null
2016-08-16 22:47:15.577 UTC
7
2021-11-19 02:49:55.953 UTC
2016-08-16 23:23:33.973 UTC
null
218,196
null
747,579
null
1
34
javascript|babeljs|ecmascript-next
94,014
<p>You are looking for</p> <pre><code>var obj = Object.assign({}, ...array) </code></pre> <p>that creates a new object instead of mutating <code>array[0]</code>.</p>
20,125,196
Difference between OnActionExecuted and OnResultExecuting
<p>What is the difference between OnActionExecuted and OnResultExecuting? Do they both get fired right after each other once the action has been processed or does something happen in between these two methods. Like the initialisation of the View Engine, ...</p>
20,125,845
4
1
null
2013-11-21 15:36:10.953 UTC
3
2021-09-11 15:51:08.32 UTC
2013-11-21 15:50:53.397 UTC
null
1,741,011
null
1,741,011
null
1
48
c#|asp.net-mvc
22,035
<p>They have a different context. </p> <p><code>OnActionExecuted</code> has a <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.actionexecutedcontext%28v=vs.100%29.aspx">ActionExecutedContext</a> in which you can view the result produced by the action. You can also see whether the action encountered an Exception and see if the exception was handled.</p> <p><code>OnResultExecuting</code> has a <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.resultexecutingcontext%28v=vs.100%29.aspx">ResultExecutingContext</a>. This method gets called just before the <code>ActionResult</code> instance is invoked. You can examine the result of the method and possibly cancel the execution of the result. This will usually result in a blank response with status code 200. (you can't do this in the OnActionExecuted method).</p>
7,406,523
Excel VBA call function with variable name
<p>I'm trying to call a function with a variable name that is generated at run time based upon a combo box value. This is straightforward in most languages but I can't seem to figure it out in Excel VBA, I suspect this is because I don't really understand how the compiler works. I've found several posts that are close but don't quite seem to do the trick. The code below is wrong but should give an idea of what I want.</p> <p>Thanks</p> <pre><code>Sub main() 'run formatting macros for each institution on format button click Dim fn As String Dim x As Boolean 'create format function name from CB value fn = "format_" &amp; CBinst.Value 'run function that returns bool x = Eval(fn) ... End Sub </code></pre>
7,406,851
4
0
null
2011-09-13 18:16:25.197 UTC
8
2017-07-04 11:02:49.04 UTC
2018-07-09 18:41:45.953 UTC
null
-1
null
824,823
null
1
12
excel|vba
43,804
<p><a href="https://msdn.microsoft.com/VBA/Language-Reference-VBA/articles/callbyname-function" rel="noreferrer"><code>CallByName</code></a> is what you'll need to accomplish the task.</p> <p>example: Code in Sheet1</p> <pre><code>Option Explicit Public Function Sum(ByVal x As Integer, ByVal y As Integer) As Long Sum = x + y End Function </code></pre> <p>Code is Module1 (bas module)</p> <pre><code>Option Explicit Sub testSum() Dim methodToCall As String methodToCall = "Sum" MsgBox CallByName(Sheet1, methodToCall, VbMethod, 1, 2) End Sub </code></pre> <p>Running the method <code>testSum</code> calls the method <code>Sum</code> using the name of the method given in a string variable, passing 2 parameters (1 and 2). The return value of the call to function is returned as output of <code>CallByName</code>.</p>
24,380,456
How can I make CMake use GCC instead of Clang on Mac OS X?
<p>I can't find any info on it, but only the other way around (e.g., how to set CMake to use clang).</p> <p>I've installed gcc-4.8 using brew, setup all dependencies, headers, etc, and now CMake refuses to use gcc.</p> <p>I've set my bash profile with both aliases and actual entries:</p> <pre><code>export CC=/usr/bin/gcc export CXX=/usr/bin/g++ alias gcc='gcc-4.8' alias cc='gcc-4.8' alias g++='g++-4.8' alias c++='c++-4.8' </code></pre> <p>Yet CMake stubbornly refuses to use gcc and instead reverts back to clang:</p> <pre><code>air:build alex$ cmake -DCMAKE_BUILD_TYPE=DEBUG .. -- The C compiler identification is Clang 5.1.0 -- The CXX compiler identification is Clang 5.1.0 -- Check for working C compiler: /usr/bin/gcc -- Check for working C compiler: /usr/bin/gcc -- works </code></pre>
24,380,618
5
1
null
2014-06-24 07:09:26.703 UTC
28
2022-04-27 15:24:17.71 UTC
2014-06-24 07:52:35.28 UTC
null
623,133
null
499,699
null
1
75
c++|cmake
104,725
<p>CMake doesn't (always) listen to <code>CC</code> and <code>CXX</code>. Instead use <code>CMAKE_C_COMPILER</code> and <code>CMAKE_CXX_COMPILER</code>:</p> <pre><code>cmake -DCMAKE_C_COMPILER=/usr/bin/gcc -DCMAKE_CXX_COMPILER=/usr/bin/g++ ... </code></pre> <p>See also the <a href="https://gitlab.kitware.com/cmake/community/-/wikis/doc/cmake/Useful-Variables#compilers-and-tools" rel="noreferrer">documentation</a>.</p> <p>Alternatively, you can provide a <a href="https://cmake.org/cmake/help/latest/manual/cmake-toolchains.7.html" rel="noreferrer">toolchain file</a>, but that might be overkill in this case.</p>
24,105,479
Scala case class update value
<p>I have a case class with 2 String members. I would like to update The second member later, so first I create an instance with String and None and later I load the data to the class and would like to update the second member with some value.</p> <p>How can I do it?</p>
24,105,728
3
2
null
2014-06-08 11:01:21.687 UTC
3
2022-09-03 18:14:30.203 UTC
2022-09-03 18:14:30.203 UTC
null
3,744,182
null
298,627
null
1
30
scala|option-type|case-class
35,635
<p>Define the case class so that the second member is a <code>var</code>:</p> <pre><code>case class Stuff(name: String, var value: Option[String]) </code></pre> <p>Now you can create an instance of <code>Stuff</code> and modify the second value:</p> <pre><code>val s = Stuff("bashan", None) s.value = Some("hello") </code></pre> <p>However, making case classes mutable is probably not a good idea. You should prefer working with immutable data structures. Instead of creating a mutable case class, make it immutable, and use the <code>copy</code> method to create a new instance with modified values. For example:</p> <pre><code>// Immutable Stuff case class Stuff(name: String, value: Option[String]) val s1 = Stuff("bashan", None) val s2 = s1.copy(value = Some("hello")) // s2 is now: Stuff("bashan", Some("hello")) </code></pre>
10,300,769
How to load packages in R automatically?
<p>Could you suggest me a way for loading packages in R automatically? I mean, I want to start a session in R without needing to use <code>library('package name')</code> several times. Suppose I downloaded all packages I'll want to use the next time I start R.</p>
10,300,829
4
2
null
2012-04-24 15:10:05.933 UTC
35
2021-01-03 18:08:39.567 UTC
2018-02-19 13:14:53.577 UTC
null
2,204,410
null
1,303,333
null
1
67
r|loading|r-package|r-faq|defaults
60,483
<p>Put <code>library(foo)</code> in your <code>.Rprofile</code> file or set <code>R_DEFAULT_PACKAGES</code>: see <code>?Rprofile</code> ...</p> <p>In particular (because <code>?Rprofile</code> is long and potentially intimidating):</p> <blockquote> <p>If you want a different set of packages than the default ones when you start, insert a call to ‘options’ in the ‘.Rprofile’ or ‘Rprofile.site’ file. For example, ‘options(defaultPackages = character())’ will attach no extra packages on startup (only the ‘base’ package) (or set ‘R_DEFAULT_PACKAGES=NULL’ as an environment variable before running R). Using ‘options(defaultPackages = "")’ or ‘R_DEFAULT_PACKAGES=""’ enforces the R <em>system</em> default.</p> </blockquote> <p>Since you probably <em>do</em> want all of the default packages loaded, and then extra ones in addition (rather than, say, not loading some of the default packages), you can either put</p> <pre><code>library("mypackage1") library("mypackage2") [etc.] </code></pre> <p>or using <code>options(defaultPackages=...)</code>:</p> <pre><code>options(defaultPackages=c(getOption("defaultPackages"), "mypackage1","mypackage2", ... [etc.])) </code></pre> <p>in your <code>.Rprofile</code> to <em>append</em> your desired packages to the standard defaults.</p> <p><strong>edit</strong> (copied from comment) re getting this to work in <a href="http://www.rstudio.org" rel="noreferrer" title="Rstudio">Rstudio</a>: <a href="http://rstudio.org/docs/using/workspaces" rel="noreferrer">http://rstudio.org/docs/using/workspaces</a> suggests that Rstudio executes <code>.Rprofile</code> and then "Performs the other actions described in R Startup [ <a href="http://stat.ethz.ch/R-manual/R-patched/library/base/html/Startup.html" rel="noreferrer">http://stat.ethz.ch/R-manual/R-patched/library/base/html/Startup.html</a> ]" (which is the same as <code>?Rprofile</code>). It is ambiguous whether it looks at <code>Rprofile.site</code> or not. </p> <p><strong>edit #2</strong>: according to comment below, it does work with a recent version of Rstudio.</p>
26,125,095
Can't load Image source in QML Image
<p>This seems really basic but for some reason I can't get the image source to work in the ultra-simple QML app below. </p> <p>FYI, I'm running Mac OS-X 10.9.5, Qt Creator 3.2.1 based on Qt 5.3.2. </p> <pre><code>import QtQuick 2.3 import QtQuick.Controls 1.2 ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("Test") Image { id: image1 x: 10 y: 10 width: 100 height: 100 source: "testImage.png" } } </code></pre> <p>I get the following error:</p> <pre><code>qrc:/main.qml:10:5: QML Image: Cannot open: qrc:/testImage.png </code></pre> <p>The application window is created but no image is displayed. I've also tried wrapping the image within a Rectangle but this doesn't help.</p> <p>What am I doing wrong here?</p> <p>The "testImage.png" is in the project directory and I've tried all sorts of ways to specify the image path using resources, absolute, relative, and even specifying the image source manually with the QML UI designer.</p> <p>I'll also mention that to get Qt 5.3.2 to work I followed the modification suggested <a href="https://stackoverflow.com/questions/23667088/qtquick-dynamic-images-and-c/">HERE</a>.</p> <p>Thanks.</p>
26,125,159
6
1
null
2014-09-30 15:55:24.817 UTC
6
2020-08-05 11:21:13.423 UTC
2017-05-23 12:02:14.477 UTC
null
-1
null
1,103,012
null
1
24
image|qt|qml
52,989
<p>I suppose that your <code>qml</code> file is in resources, so try place your <code>testImage.png</code> image in resources too. Recompile app, run it and check is image works properly.</p> <p>All should be together. For example:</p> <p><img src="https://i.stack.imgur.com/h2rPB.png" alt="enter image description here"></p> <p>My code:</p> <pre><code>Image { source: "images/earth.png" </code></pre> <p>If I delete this image from resources, I'll get this error too, but image still in the correct place in file system.</p> <p>When <code>qml</code> source placed in the resource, then all files, which loads from <code>qml</code> should be in resource too (Qt searchs this files in the resources, not in the file system).</p>
7,014,052
Ruby multidimensional array
<p>Maybe it's just my lack of abilities to find stuff here that is the problem, but I can't find anything about how to create multidimensional arrays in Ruby.</p> <p>Could someone please give me an example on how to do it? </p>
7,014,092
10
0
null
2011-08-10 16:06:36.803 UTC
10
2021-06-13 01:56:41.817 UTC
2011-08-10 18:21:09.03 UTC
null
104,219
null
460,448
null
1
51
ruby|multidimensional-array
81,349
<p>Strictly speaking it is not possible to create multi dimensional arrays in Ruby. But it is possible to put an array in another array, which is almost the same as a multi dimensional array.</p> <p>This is how you could create a 2D array in Ruby:</p> <pre><code>a = [[1,2,3], [4,5,6], [7,8,9]] </code></pre> <p><hr/> As stated in the comments, you could also use <a href="http://masa16.github.io/narray/" rel="noreferrer">NArray</a> which is a Ruby numerical array library:</p> <pre><code>require 'narray' b = NArray[ [1,2,3], [4,5,6], [7,8,9] ] </code></pre> <hr/> <p>Use <code>a[i][j]</code> to access the elements of the array. Basically <code>a[i]</code> returns the 'sub array' stored on position <code>i</code> of <code>a</code> and thus <code>a[i][j]</code> returns element number <code>j</code> from the array that is stored on position <code>i</code>.</p>
7,569,444
How to test abstract class in Java with JUnit?
<p>I am new to Java testing with JUnit. I have to work with Java and I would like to use unit tests.</p> <p>My problem is: I have an abstract class with some abstract methods. But there are some methods which are not abstract. How can I test this class with JUnit? Example code (very simple):</p> <pre><code>abstract class Car { public Car(int speed, int fuel) { this.speed = speed; this.fuel = fuel; } private int speed; private int fuel; abstract void drive(); public int getSpeed() { return this.speed; } public int getFuel() { return this.fuel; } } </code></pre> <p>I want to test <code>getSpeed()</code> and <code>getFuel()</code> functions.</p> <p>Similar question to this problem is <a href="https://stackoverflow.com/questions/3604721/how-to-test-a-method-in-an-abstract-class-with-abstract-methods">here</a>, but it is not using JUnit.</p> <p>In JUnit FAQ section, I found <a href="http://c2.com/cgi/wiki?AbstractTestCases" rel="noreferrer">this link</a>, but I don't understand what the author want to say with this example. What does this line of code mean?</p> <pre><code>public abstract Source getSource() ; </code></pre>
7,569,581
12
4
null
2011-09-27 12:53:24.44 UTC
13
2022-05-31 09:10:00.523 UTC
2017-08-02 14:08:40 UTC
null
1,988,304
null
765,579
null
1
91
java|junit|abstract-class
122,368
<p>If you have no concrete implementations of the class and the methods aren't <code>static</code> whats the point of testing them? If you have a concrete class then you'll be testing those methods as part of the concrete class's public API. </p> <p>I know what you are thinking "I don't want to test these methods over and over thats the reason I created the abstract class", but my counter argument to that is that the point of unit tests is to allow developers to make changes, run the tests, and analyze the results. Part of those changes could include overriding your abstract class's methods, both <code>protected</code> and <code>public</code>, which could result in fundamental behavioral changes. Depending on the nature of those changes it could affect how your application runs in unexpected, possibly negative ways. If you have a good unit testing suite problems arising from these types changes should be apparent at development time.</p>
13,857,734
Redirect User to different Website Based on Location (IP Address)
<p>How to redirect user visiting my sites to location specific sites using the IP Address.<br> I have 3 location specific sites.<br> 1. Europe.<br> 2. US.<br> 3. Asia.<br> In short I wanted to find the location of the client using his IP Address. The solution needs to use Google APIs.</p>
13,858,729
5
9
null
2012-12-13 10:22:25.567 UTC
10
2022-08-15 12:50:17.653 UTC
2016-02-12 17:52:31.483 UTC
null
5,816,509
null
1,439,333
null
1
9
javascript|html|location
54,508
<p>I got the solution using <strong>"google.loader.ClientLocation"</strong><br> here is the code for that if somebody needs it.</p> <p>Check this JSFiddle</p> <blockquote> <p><a href="http://jsfiddle.net/kvishnudev/7Ut65/1/" rel="noreferrer">http://jsfiddle.net/kvishnudev/7Ut65/1/</a></p> </blockquote> <pre><code> &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Get web visitor's location&lt;/title&gt; &lt;meta name="robots" value="none" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="yourinfo"&gt;&lt;/div&gt; &lt;script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAAp04yNttlQq-7b4aZI_jL5hQYPm-xtd00hTQOC0OXpAMO40FHAxQMnH50uBbWoKVHwgpklyirDEregg"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var Continent = {"AD":"Europe","AE":"Asia","AF":"Asia","AG":"North America","AI":"North America","AL":"Europe","AM":"Asia","AN":"North America","AO":"Africa","AQ":"Antarctica","AR":"South America","AS":"Australia","AT":"Europe","AU":"Australia","AW":"North America","AZ":"Asia","BA":"Europe","BB":"North America","BD":"Asia","BE":"Europe","BF":"Africa","BG":"Europe","BH":"Asia","BI":"Africa","BJ":"Africa","BM":"North America","BN":"Asia","BO":"South America","BR":"South America","BS":"North America","BT":"Asia","BW":"Africa","BY":"Europe","BZ":"North America","CA":"North America","CC":"Asia","CD":"Africa","CF":"Africa","CG":"Africa","CH":"Europe","CI":"Africa","CK":"Australia","CL":"South America","CM":"Africa","CN":"Asia","CO":"South America","CR":"North America","CU":"North America","CV":"Africa","CX":"Asia","CY":"Asia","CZ":"Europe","DE":"Europe","DJ":"Africa","DK":"Europe","DM":"North America","DO":"North America","DZ":"Africa","EC":"South America","EE":"Europe","EG":"Africa","EH":"Africa","ER":"Africa","ES":"Europe","ET":"Africa","FI":"Europe","FJ":"Australia","FK":"South America","FM":"Australia","FO":"Europe","FR":"Europe","GA":"Africa","GB":"Europe","GD":"North America","GE":"Asia","GF":"South America","GG":"Europe","GH":"Africa","GI":"Europe","GL":"North America","GM":"Africa","GN":"Africa","GP":"North America","GQ":"Africa","GR":"Europe","GS":"Antarctica","GT":"North America","GU":"Australia","GW":"Africa","GY":"South America","HK":"Asia","HN":"North America","HR":"Europe","HT":"North America","HU":"Europe","ID":"Asia","IE":"Europe","IL":"Asia","IM":"Europe","IN":"Asia","IO":"Asia","IQ":"Asia","IR":"Asia","IS":"Europe","IT":"Europe","JE":"Europe","JM":"North America","JO":"Asia","JP":"Asia","KE":"Africa","KG":"Asia","KH":"Asia","KI":"Australia","KM":"Africa","KN":"North America","KP":"Asia","KR":"Asia","KW":"Asia","KY":"North America","KZ":"Asia","LA":"Asia","LB":"Asia","LC":"North America","LI":"Europe","LK":"Asia","LR":"Africa","LS":"Africa","LT":"Europe","LU":"Europe","LV":"Europe","LY":"Africa","MA":"Africa","MC":"Europe","MD":"Europe","ME":"Europe","MG":"Africa","MH":"Australia","MK":"Europe","ML":"Africa","MM":"Asia","MN":"Asia","MO":"Asia","MP":"Australia","MQ":"North America","MR":"Africa","MS":"North America","MT":"Europe","MU":"Africa","MV":"Asia","MW":"Africa","MX":"North America","MY":"Asia","MZ":"Africa","NA":"Africa","NC":"Australia","NE":"Africa","NF":"Australia","NG":"Africa","NI":"North America","NL":"Europe","NO":"Europe","NP":"Asia","NR":"Australia","NU":"Australia","NZ":"Australia","OM":"Asia","PA":"North America","PE":"South America","PF":"Australia","PG":"Australia","PH":"Asia","PK":"Asia","PL":"Europe","PM":"North America","PN":"Australia","PR":"North America","PS":"Asia","PT":"Europe","PW":"Australia","PY":"South America","QA":"Asia","RE":"Africa","RO":"Europe","RS":"Europe","RU":"Europe","RW":"Africa","SA":"Asia","SB":"Australia","SC":"Africa","SD":"Africa","SE":"Europe","SG":"Asia","SH":"Africa","SI":"Europe","SJ":"Europe","SK":"Europe","SL":"Africa","SM":"Europe","SN":"Africa","SO":"Africa","SR":"South America","ST":"Africa","SV":"North America","SY":"Asia","SZ":"Africa","TC":"North America","TD":"Africa","TF":"Antarctica","TG":"Africa","TH":"Asia","TJ":"Asia","TK":"Australia","TM":"Asia","TN":"Africa","TO":"Australia","TR":"Asia","TT":"North America","TV":"Australia","TW":"Asia","TZ":"Africa","UA":"Europe","UG":"Africa","US":"North America","UY":"South America","UZ":"Asia","VC":"North America","VE":"South America","VG":"North America","VI":"North America","VN":"Asia","VU":"Australia","WF":"Australia","WS":"Australia","YE":"Asia","YT":"Africa","ZA":"Africa","ZM":"Africa","ZW":"Africa"}; if(google.loader.ClientLocation) { visitor_lat = google.loader.ClientLocation.latitude; visitor_lon = google.loader.ClientLocation.longitude; visitor_city = google.loader.ClientLocation.address.city; visitor_region = google.loader.ClientLocation.address.region; visitor_country = google.loader.ClientLocation.address.country; visitor_countrycode = google.loader.ClientLocation.address.country_code; if(visitor_countrycode!= null) { var Cont = Continent[visitor_countrycode]; //alert(Cont); } // document.getElementById('yourinfo').innerHTML = '&lt;p&gt;Lat/Lon: ' + visitor_lat + ' / ' + visitor_lon + '&lt;/p&gt;&lt;p&gt;Location: ' + visitor_city + ', ' + visitor_region +', Continent : ' + Cont + ', ' + visitor_country + ' (' + visitor_countrycode + ')&lt;/p&gt;'; } else { document.getElementById('yourinfo').innerHTML = '&lt;p&gt;Whoops!&lt;/p&gt;'; } &lt;/script&gt; &lt;/body&gt; </code></pre> <p></p>
14,272,051
Appending a key value pair to a json object
<p>This is the <strong>json object</strong> I am working with </p> <pre><code>{ "name": "John Smith", "age": 32, "employed": true, "address": { "street": "701 First Ave.", "city": "Sunnyvale, CA 95125", "country": "United States" }, "children": [ { "name": "Richard", "age": 7 }, { "name": "Susan", "age": 4 }, { "name": "James", "age": 3 } ] } </code></pre> <p>I want this as another key-value pair :</p> <pre><code>"collegeId": { "eventno": "6062", "eventdesc": "abc" }; </code></pre> <p>I tried concat but that gave me the result with || symbol and I cdnt iterate. I used spilt but that removes only commas.</p> <pre><code>concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2))); </code></pre> <p>How do I add a key pair value to an existing json object ? I am working in javascript.</p>
14,273,082
4
2
null
2013-01-11 05:07:29.593 UTC
4
2017-06-29 14:22:23.107 UTC
2013-01-11 05:13:51.25 UTC
null
1,337,742
null
1,337,742
null
1
12
json
42,454
<p>This is the easiest way and it's working to me.</p> <pre><code>var testJson = { "name": "John Smith", "age": 32, "employed": true, "address": { "street": "701 First Ave.", "city": "Sunnyvale, CA 95125", "country": "United States" }, "children": [ { "name": "Richard", "age": 7 }, { "name": "Susan", "age": 4 }, { "name": "James", "age": 3 } ] }; testJson.collegeId = {"eventno": "6062","eventdesc": "abc"}; </code></pre>
13,836,978
Maven skip compile
<p>I want to use Maven to execute a certain plug-in that only needs the source code but I do not want Maven to compile anything (mostly because the project just doesn't compile).</p> <p>How do I tell Maven to skip the compile step and just launch its plug-in and then package the generated resources together in a nice JAR? (The procedure of the last step is already known to me.)</p> <p><strong>Additional Info:</strong></p> <p>So we tried a lot of things right now, e.g.:</p> <pre class="lang-xml prettyprint-override"><code>&lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.0&lt;/version&gt; &lt;configuration&gt; &lt;excludes&gt; &lt;exclude&gt;**/*&lt;/exclude&gt; &lt;/excludes&gt; &lt;source&gt;1.7&lt;/source&gt; &lt;target&gt;1.7&lt;/target&gt; &lt;/configuration&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;deploy&lt;/phase&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre> <p>Though when we do a <code>mvn package</code> we get this:</p> <pre class="lang-none prettyprint-override"><code>[INFO] --- maven-compiler-plugin:3.0:compile (default-compile) @ project --- [INFO] Changes detected - recompiling the module! [INFO] Compiling ALOTOF source files to /home/myname/dir/dir/project/target/classes </code></pre> <p>message edited ofc.</p>
29,002,704
5
0
null
2012-12-12 09:48:04.68 UTC
3
2021-06-14 09:50:33.73 UTC
2017-02-03 10:31:18.553 UTC
null
452,775
null
1,264,768
null
1
39
java|maven|compilation
56,983
<pre><code>&lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;default-compile&lt;/id&gt; &lt;phase&gt;compile&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;compile&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;skipMain&gt;true&lt;/skipMain&gt; &lt;--Skip &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre> <blockquote> <p>Set this to 'true' to bypass compilation of main sources. Its use is NOT RECOMMENDED, but quite convenient on occasion. User property is: maven.main.skip.</p> </blockquote> <p><code>mvn package -Dmaven.main.skip</code></p>
14,102,416
Python Requests requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol
<p>I'm on Ubuntu 12.10 with OpenSSL 1.0.1c, python 2.7.3, <a href="http://www.python-requests.org/en/latest/">Requests</a> 1.0.3 and 1.0.4 (tried both), and when attempting to connect to the website in the url variable with the following code.</p> <pre><code>def SendInitialRequest(xmlmessage, redirecturl): url = 'https://centineltest.cardinalcommerce.com/maps/txns.asp' payload = 'cmpi_msg=' + ET.tostring(xmlmessage) headers = { 'Content-Type': 'application/x-www-form-urlencoded', } r = requests.post(url, data=payload, headers=headers, verify=None) print r.text </code></pre> <p>It throws the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "clams/libs/centinel/thinclient.py", line 134, in SendInitialRequest r = requests.post(url, data=payload, headers=headers, verify=None) File "/home/jasonamyers/.virtualenv/clams/lib/python2.7/site-packages/requests/api.py", line 87, in post return request('post', url, data=data, **kwargs) File "/home/jasonamyers/.virtualenv/clams/lib/python2.7/site-packages/requests/api.py", line 44, in request return session.request(method=method, url=url, **kwargs) File "/home/jasonamyers/.virtualenv/clams/lib/python2.7/site-packages/requests/sessions.py", line 269, in request resp = self.send(prep, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies) File "/home/jasonamyers/.virtualenv/clams/lib/python2.7/site-packages/requests/sessions.py", line 364, in send r = adapter.send(request, **kwargs) File "/home/jasonamyers/.virtualenv/clams/lib/python2.7/site-packages/requests/adapters.py", line 163, in send raise SSLError(e) requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol </code></pre> <p>Attempting the connection with openssl returns the following:</p> <pre><code>$ openssl s_client -connect centineltest.cardinalcommerce.com:443 CONNECTED(00000003) 140019346777760:error:140790E5:SSL routines:SSL23_WRITE:ssl handshake failure:s23_lib.c:177: --- no peer certificate available --- No client certificate CA names sent --- SSL handshake has read 0 bytes and written 226 bytes --- New, (NONE), Cipher is (NONE) Secure Renegotiation IS NOT supported Compression: NONE Expansion: NONE --- </code></pre> <p>If I force it to use tls1 it works (output truncated):</p> <pre><code>$ openssl s_client -tls1 -connect centineltest.cardinalcommerce.com:443 CONNECTED(00000003) depth=2 C = US, O = "thawte, Inc.", OU = Certification Services Division, OU verify error:num=20:unable to get local issuer certificate verify return:0 --- </code></pre> <p>I've seen numerous <a href="https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/965371">bug reports</a> for this; however, I've not found a way to get around it using the python requests library. Any assistance would be greatly appreciated.</p>
14,146,031
10
4
null
2012-12-31 13:51:58.67 UTC
21
2020-07-09 21:50:48.073 UTC
2013-01-03 16:48:31.79 UTC
null
95,735
null
1,231,488
null
1
65
python|openssl|httprequest|python-requests|ubuntu-12.10
138,371
<p>Reposting this here for others from <a href="https://github.com/kennethreitz/requests/issues/1083#issuecomment-11853729" rel="noreferrer">the requests issue page</a>:</p> <p>Requests' does not support doing this before version 1. Subsequent to version 1, you are expected to subclass the HTTPAdapter, like so:</p> <pre><code>from requests.adapters import HTTPAdapter from requests.packages.urllib3.poolmanager import PoolManager import ssl class MyAdapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1) </code></pre> <p>When you've done that, you can do this:</p> <pre><code>import requests s = requests.Session() s.mount('https://', MyAdapter()) </code></pre> <p>Any request through that session object will then use TLSv1.</p>
14,001,963
Finish all activities at a time
<p>I have an application with multiple pages i.e., multiple activities and some of them remain open. </p> <p>Is there a way to close all activities at once?</p>
14,002,030
21
1
null
2012-12-22 10:18:35.4 UTC
26
2020-11-11 12:23:56.643 UTC
2016-05-21 19:44:40.26 UTC
null
4,717,992
null
1,915,437
null
1
72
android|android-activity|activity-finish
139,650
<p>Whenever you wish to exit all open activities, you should press a button which loads the <strong>first Activity</strong> that runs when your application starts then clear all the other activities, then have the last remaining activity finish. to do so apply the following code in ur project</p> <pre><code>Intent intent = new Intent(getApplicationContext(), FirstActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("EXIT", true); startActivity(intent); </code></pre> <p>The above code finishes all the activities except for FirstActivity. Then we need to finish the FirstActivity's Enter the below code in Firstactivity's oncreate</p> <pre><code>if (getIntent().getBooleanExtra("EXIT", false)) { finish(); } </code></pre> <p>and you are done....</p>
33,980,224
How to check if two paths are equal in Bash?
<p>What's the best way to check if two paths are equal in Bash? For example, given the directory structure</p> <pre><code>~/ Desktop/ Downloads/ (symlink to ~/Downloads) Downloads/ photo.png </code></pre> <p>and assuming that the current directory is the home directory, all of the following would be equivalent:</p> <pre><code>./ and ~ ~/Desktop and /home/you/Desktop ./Downloads and ~/Desktop/Downloads ./Downloads/photo.png and ~/Downloads/photo.png </code></pre> <p>Is there a native Bash way to do this?</p>
33,980,885
5
3
null
2015-11-29 06:51:00.733 UTC
5
2015-11-29 08:34:36.96 UTC
null
null
null
null
4,077,294
null
1
30
linux|bash|shell|unix|sh
15,740
<p>Bash's test commands have a <code>-ef</code> operator for this purpose</p> <pre><code>if [[ ./ -ef ~ ]]; then ... if [[ ~/Desktop -ef /home/you/Desktop ]]; then ... </code></pre> <p>etc...</p> <pre><code>$ help test | grep -e -ef FILE1 -ef FILE2 True if file1 is a hard link to file2. </code></pre>