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
1,523,479
What does the variable $this mean in PHP?
<p>I see the variable <code>$this</code> in PHP all the time and I have no idea what it's used for. I've never personally used it. </p> <p>Can someone tell me how the variable <code>$this</code> works in PHP?</p>
1,523,484
11
0
null
2009-10-06 03:45:08.45 UTC
44
2020-12-13 17:02:07.023 UTC
2019-11-18 13:34:23.207 UTC
null
2,370,483
null
89,334
null
1
123
php|class|oop|this
247,173
<p>It's a reference to the current object, it's most commonly used in object oriented code.</p> <ul> <li>Reference: <a href="http://www.php.net/manual/en/language.oop5.basic.php" rel="noreferrer">http://www.php.net/manual/en/language.oop5.basic.php</a></li> <li>Primer: <a href="http://www.phpro.org/tutorials/Object-Oriented-Programming-with-PHP.html" rel="noreferrer">http://www.phpro.org/tutorials/Object-Oriented-Programming-with-PHP.html</a></li> </ul> <p>Example:</p> <pre><code>&lt;?php class Person { public $name; function __construct( $name ) { $this-&gt;name = $name; } }; $jack = new Person('Jack'); echo $jack-&gt;name; </code></pre> <p>This stores the 'Jack' string as a property of the object created.</p>
1,938,614
In what case would I use a tuple as a dictionary key?
<p>I was studying the <a href="https://docs.python.org/3/faq/design.html#why-are-there-separate-tuple-and-list-data-types" rel="noreferrer">difference between lists and tuples</a> (in Python). An obvious one is that tuples are immutable (the values cannot be changed after initial assignment), while lists are mutable.</p> <p>A sentence in the article got me: </p> <blockquote> <p>Only immutable elements can be used as dictionary keys, and hence only tuples and not lists can be used as keys.</p> </blockquote> <p>I have a hard time thinking of a situation where I would like to use a tuple as a dictionary key. Can you provide an example problem where this would be the natural, efficient, elegant, or obvious solution?</p> <p><strong>Edit:</strong></p> <p>Thanks for your examples. So far I take that a very important application is the caching of function values.</p>
1,938,638
12
1
null
2009-12-21 07:01:29.587 UTC
23
2022-02-14 00:33:46.21 UTC
2018-05-16 08:36:54.643 UTC
null
9,298,629
null
104,427
null
1
99
python|list|dictionary|tuples
98,382
<p>Classic Example: You want to store point value as tuple of (x, y) </p>
1,441,562
Detect language from string in PHP
<p>In PHP, is there a way to detect the language of a string? Suppose the string is in UTF-8 format.</p>
1,441,575
18
5
null
2009-09-17 22:06:44.5 UTC
16
2022-09-24 15:27:29.553 UTC
2014-03-14 11:33:27.907 UTC
null
1,598,477
null
156,153
null
1
35
php|language-detection
67,983
<p>You can not detect the language from the character type. And there are no foolproof ways to do this.</p> <p>With any method, you're just doing an educated guess. There are available some math related <a href="http://tnlessone.wordpress.com/2007/05/13/how-to-detect-which-language-a-text-is-written-in-or-when-science-meets-human/" rel="noreferrer">articles</a> out there</p>
33,942,849
Border Position
<p>I want to try and achieve something in CSS using borders but they don't seem to have something I want. In Photoshop, when you add a Stroke (border), you select the position. Outside, Inside, or Center. Outside being where the entire border wraps around the object. Inside is where it sits on the inside (obviously), and center being half and half.</p> <p>I want a <code>2px</code> border that's positioned in the center. So it shows 1px outside and <code>1px</code> inside. Is there anyway to do this with CSS? I imagine I can do it with a <code>box-shadow</code> of some kind but I'm horrendous at shadows in CSS.</p> <p>There's also the issue of having to be pure CSS so I can't lay an image over it. Can someone possibly help me out with this.</p> <p>Thanks.</p>
33,943,318
3
3
null
2015-11-26 16:04:13.38 UTC
3
2018-02-19 23:18:44.113 UTC
2015-11-26 16:12:51.1 UTC
null
2,081,719
null
2,179,057
null
1
5
css
60,418
<p>There's a work around, since <code>border</code> represents outer stroke for you, you can make use of <code>outline</code> css property with <code>outline-offset</code> set to negative value to have the inner <code>1px</code> stroke<sup>( 1 )</sup> <a href="http://jsfiddle.net/Mi_Creativity/2bx6jL9s/2/" rel="noreferrer"><strong>JS Fiddle</strong></a></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { padding-top: 10px; } #test { width: 250px; height: 200px; background-color: orange; margin: 0 auto; border: 1px navy solid; /* outer stroke */ outline: 1px navy solid; /* inner stroke */ outline-offset: -2px; /* negative border width + outline width */ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="test"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <hr> <p><sup>( 1 )</sup> As the above fiddle might not demonstrate the explanation good enough, here's the same example with two colored strokes and <code>4px</code> for each stroke instead of <code>1px</code> <a href="http://jsfiddle.net/Mi_Creativity/2bx6jL9s/1/" rel="noreferrer"><strong>Demo Fiddle</strong></a></p> <p><strong>Resources:</strong></p> <p><a href="http://caniuse.com/#search=outline" rel="noreferrer">http://caniuse.com/#search=outline</a> </p> <p><a href="https://developer.mozilla.org/en/docs/Web/CSS/outline-offset" rel="noreferrer">https://developer.mozilla.org/en/docs/Web/CSS/outline-offset</a></p> <p><a href="http://www.w3schools.com/cssref/css3_pr_outline-offset.asp" rel="noreferrer">http://www.w3schools.com/cssref/css3_pr_outline-offset.asp</a></p> <p><a href="https://davidwalsh.name/outline-offset" rel="noreferrer">https://davidwalsh.name/outline-offset</a></p>
8,497,103
What are the naming conventions in C#?
<blockquote> <p>There are a few questions on this, but they all seemed to be targeting a specific part of the language;</p> <ul> <li><a href="https://stackoverflow.com/questions/1228478/what-are-the-most-common-naming-conventions-in-c">What are the most common naming conventions in C#?</a> - Asking specifically about getters/setters.</li> <li><a href="https://stackoverflow.com/questions/2109171/c-sharp-naming-conventions">C# naming conventions for acronyms</a> - Asking more specifically about short uppercase suffixes.</li> </ul> </blockquote> <p>I'm just starting out in C# with a friend on a venture to create games for XBOX Live Arcade. I've developed a number of games using ActionScript 2 and 3 but want to start exploring more powerful languages and devices.</p> <p>I want to ensure that I don't peeve people that I start working with (if I get to that) or even just people on here when I run into trouble and ask a question with seriously disturbing / "incorrect" naming of methods, etc.</p> <p>I've found it confusing in the example code that I've seen because there seems to be from my current point of view some flaws. I doubt that a flawed naming convention would be used, so I realize that I'm just having trouble understanding.</p> <p>As far as I can tell so far, there are these conventions:</p> <ul> <li><code>public Type SomeMethod()</code></li> <li><code>private Type SomeMethod()</code> - no underscore or anything?</li> <li><code>public static Type SomeMethod()</code></li> <li><code>private static Type _SomeMethod()</code> - this one just seems odd..</li> <li><code>public Type someProperty</code> - switching it up to camel casing for properties?</li> <li><code>public static Type SomeProperty</code> - and then going back to pascal casing for static..</li> </ul> <p>In ActionScript 3, I have developed and strictly stick to these conventions:</p> <ul> <li><code>private var _someVar</code></li> <li><code>public var someVar</code></li> <li><code>private function _someMethod()</code></li> <li><code>public function someMethod()</code></li> <li><code>public static var SomeStaticVar</code></li> <li><code>public static function SomeStaticMethod()</code></li> <li><code>public const SOME_CONSTANT</code></li> </ul> <p>Is there a complete list of naming conventions with reasoning behind each so that I can get my head around them? The reversal of syntax (i.e. <code>public Type method()</code> instead of AS3's <code>public function method():Type</code>) is throwing me out enough at the moment that I know I need to keep an eye on how I'm naming things, otherwise I'll forget and develop bad habits, which I'd rather nail and avoid now.</p>
8,497,240
4
2
null
2011-12-13 22:27:32.443 UTC
16
2020-03-11 14:03:42.99 UTC
2017-05-23 12:18:24.66 UTC
null
-1
null
699,632
null
1
47
c#|naming-conventions
50,824
<p>There is the <a href="http://www.scribd.com/doc/56782158/All-In-One-Code-Framework-Coding-Standards" rel="nofollow noreferrer">All-In-One Code Framework Coding Standards</a> from Microsoft which contains a complete set of rules and guidelines. (also used to be available <a href="https://web.archive.org/web/20170305071831/http://1code.codeplex.com/wikipage?title=All-In-One%20Code%20Framework%20Coding%20Standards" rel="nofollow noreferrer">here</a>)</p> <blockquote> <p>This document describes the coding style guideline for native C++ and .NET (C# and VB.NET) programming used by the Microsoft All-In-One Code Framework project team.</p> </blockquote>
46,288,170
Is it possible to mix --class-path and --module-path in javac (JDK 9)?
<p>When I compile a module that depends on other modules I've compiled previously I have to specify the <code>--module-path &lt;directory&gt;</code> option. This makes modules I depend on visible. </p> <p>But at the same time I would also like to make some non-modular Jar files visible. However if don't make them automatic modules and just specify the <code>--class-path some.jar</code> right next to <code>--module-path &lt;directory&gt;</code>, then <strong>javac</strong> seems to ignore the claspath and throws "package yyy not found" and other "not found" errors. </p> <p>I can understand that using <code>--class-path</code> and <code>--module-path</code> at the same (compile) time is illegal, but <strong>javac</strong> does not warn me against it in any way.</p>
46,289,257
2
3
null
2017-09-18 21:02:57.377 UTC
15
2021-05-06 16:34:06.98 UTC
2021-05-06 16:34:06.98 UTC
null
1,746,118
null
509,276
null
1
31
java|classpath|java-9|java-platform-module-system|module-path
24,214
<p>You can use class path and module path in parallel, but there are a few details to consider.</p> <h1>Dependency Module Path ~> Class Path</h1> <p>Explicit modules (JARs with a module descriptor on the module path) can not read the unnamed module (JARs on the class path) - that was done on purpose to prevent modular JARs from depending on "the chaos of the class path".</p> <p>Since a module must require all of its dependencies and those can only be fulfilled by other named modules (i.e. not JARs on the class path) all dependencies of a modular JAR must be placed on the module path. Yes, even non-modular JARs, which will then get turned into <a href="http://openjdk.java.net/projects/jigsaw/spec/sotms/#automatic-modules" rel="noreferrer">automatic modules</a>.</p> <p>The interesting thing is that automatic modules <em>can</em> read the unnamed module, so <em>their</em> dependencies can go on the class path.</p> <h1>Dependency Class Path ~> Module Path</h1> <p>If you compile non-modular code or launch an application from a non-modular JAR, the module system is still in play and because non-modular code does not express any dependencies, it will not resolve modules from the module path.</p> <p>So if non-modular code depends on artifacts on the module path, you need to add them manually with <a href="https://blog.codefx.org/java/five-command-line-options-to-hack-the-java-9-module-system/#Extending-The-Module-Graph-With--add-modules" rel="noreferrer">the <code>--add-modules</code> option</a>. Not necessarily all of them, just those that you directly depend on (the module system will pull in transitive dependencies) - or you can use <code>ALL-MODULE-PATH</code> (check the linked post, it explains this in more detail).</p>
46,312,956
Why can't I connect AWS RDS instance from EC2 instance in another VPC after peering
<p>I am running Tableau Server on our EC2 instance in VPC A. Meanwhile, I created a postgres RDS in another VPC B. Now I want to establish the connection between the Tableau Server and RDS. CIDR of RDS VPC is 172.31.0.0/16 and that of EC2 VPC is 10.0.0.0/16.</p> <p>According to <a href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.Scenarios.html" rel="noreferrer">A DB Instance in a VPC Accessed by an EC2 Instance in a Different VPC</a>, I created peering between VPC A and VPC B, pcx-xyz123. Besides, I also created the following route tables for the VPCs.</p> <pre><code>RDS VPC Destination Target 172.31.0.0/16 local 10.0.0.0/16 pcx-xyz123 EC2 VPC Destination Target 10.0.0.0/16 local 172.31.0.0/16 pcx-xyz123 </code></pre> <p>Both route tables are main. Each has 0 Subnets though (not sure if this matters).</p> <p>However I still can't connect RDS from Tableau Server. </p> <p>The two instances are created by same account. They are both listed under US East(Ohio). So I assume they are in the same region. Plus both have <code>us-east-2</code> in their hostnames. From my PC, I can connect to RDS with psql command or pgAdmin.</p> <p>Why can't I connect the two instances? </p> <p><strong>EDIT</strong>: I've created another EC2 Linux instance within the same subnet of the same VPC as the Tableau Server just for debugging purposes. I configured the peering and route table same way and also associate the subnets to the route tables. However, I still can't connect to RDS on the EC2 Linux instance.</p>
46,331,624
7
5
null
2017-09-20 03:46:31.3 UTC
8
2021-12-31 01:21:41.443 UTC
2018-06-05 21:16:30.383 UTC
null
174,777
null
3,358,927
null
1
19
amazon-web-services|amazon-ec2|amazon-rds|amazon-vpc
14,476
<p>VPC Peering works much the same way as how Public Subnets connect to the Internet Gateway -- the <strong>Route Tables</strong> define how traffic goes in/out of the Subnets.</p> <p>For VPC Peering to work:</p> <ul> <li><strong>Invite &amp; Accept</strong> the peering connection (Done)</li> <li>Create a <strong>Route table</strong> in each VPC that points to the Peering connection for the other VPC's IP range (Done)</li> <li><strong>Associate each subnet</strong> that you want able to peer to the Route Table</li> <li>Alternatively, edit <strong>existing route tables</strong> to include the peering entry</li> <li>If your RDS database is public, and you are attempting to connect using the public DNS of the database, then you will need to <strong>edit the DNS settings</strong> of <a href="https://stackoverflow.com/questions/21089582/amazon-rds-endpoint-internal">your peering connection</a> to allow DNS resolution.</li> </ul> <p>The routing works as follows:</p> <ul> <li>When traffic leaves a subnet, the Route Table is consulted to determine where to send the traffic</li> <li>The most restrictive (eg /24) is evaluated first, through to the least restrictive (eg /0)</li> <li>The traffic is routed according to the appropriate Route Table entry</li> </ul> <p>This means that you can configure <em>some</em> of the subnets to peer, rather than having to include all of them. Traditionally, it is the <strong>Private subnets</strong> that peer and possibly only <em>specific</em> Private subnets -- but that is totally your choice.</p> <p>Think of it as directions on a roadmap, telling traffic where it should be directed.</p>
41,946,156
Strange diagonal lines in Chrome/Chromium (bug?)
<p>When I use CSS filters, shadows, transformations, SVG (or similar), my Chrome/Chromium shows a strange diagonal lines:</p> <pre><code> filter:drop-shadow(0px 0px 10px #dce810); transform:skew(-15deg); </code></pre> <p><a href="https://i.stack.imgur.com/pfPL4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pfPL4.png" alt="Diagonal lines error Chrome/Chromium"></a></p> <p>No error in Firefox (Windows) / Canary Chrome 58. Error on Chrome 56 and Chromium 58 (Windows).</p> <p>In this pen, ocurrs this error (at end, when switch on title): <a href="https://codepen.io/manz/pen/jyYKJo" rel="noreferrer">https://codepen.io/manz/pen/jyYKJo</a></p> <p>Does anyone know if it's a known bug or some problem that is solved by disabling any option?</p>
44,545,448
3
3
null
2017-01-30 22:00:19.603 UTC
8
2017-10-14 13:35:53.287 UTC
null
null
null
null
500,214
null
1
27
google-chrome|webkit|chromium|blink
3,402
<p>It's almost certainly this Chrome/Chromium rasterization bug, which appears to be specific to certain NVidia GPUs: </p> <blockquote> <p><A href="https://bugs.chromium.org/p/chromium/issues/detail?id=691262" rel="noreferrer">Issue 691262 Corrupted background with GPU rasterization</a>.</p> </blockquote>
44,589,738
Angular2 - Error: The selector "app-root" did not match any elements
<p>I am learning Angular 2, without prior experience of Angular. I was following this tutorial: <a href="https://www.barbarianmeetscoding.com/blog/2016/03/25/getting-started-with-angular-2-step-by-step-1-your-first-component/" rel="noreferrer">https://www.barbarianmeetscoding.com/blog/2016/03/25/getting-started-with-angular-2-step-by-step-1-your-first-component/</a>.</p> <p>And after adding new component "app-people-list" and updating the same in index.html, i get below exception. What went wrong?</p> <pre><code> Unhandled Promise rejection: The selector "app-root" did not match any elements ; Zone: &lt;root&gt; ; Task: Promise.then ; Value: Error: The selector "app-root" did not match any elements at DefaultDomRenderer2.webpackJsonp.../../../platform-browser/@angular/platform-browser.es5.js.DefaultDomRenderer2.selectRootElement (platform-browser.es5.js:2808) at DebugRenderer2.webpackJsonp.../../../core/@angular/core.es5.js.DebugRenderer2.selectRootElement (core.es5.js:13710) at createElement (core.es5.js:9259) at createViewNodes (core.es5.js:12225) at createRootView (core.es5.js:12154) at callWithDebugContext (core.es5.js:13535) at Object.debugCreateRootView [as createRootView] (core.es5.js:12852) at ComponentFactory_.webpackJsonp.../../../core/@angular/core.es5.js.ComponentFactory_.create (core.es5.js:9945) at ComponentFactoryBoundToModule.webpackJsonp.../../../core/@angular/core.es5.js.ComponentFactoryBoundToModule.create (core.es5.js:3333) at ApplicationRef_.webpackJsonp.../../../core/@angular/core.es5.js.ApplicationRef_.bootstrap (core.es5.js:4822) Error: The selector "app-root" did not match any elements at DefaultDomRenderer2.webpackJsonp.../../../platform-browser/@angular/platform-browser.es5.js.DefaultDomRenderer2.selectRootElement (http://localhost:4200/vendor.bundle.js:70399:19) at DebugRenderer2.webpackJsonp.../../../core/@angular/core.es5.js.DebugRenderer2.selectRootElement (http://localhost:4200/vendor.bundle.js:57800:49) at createElement (http://localhost:4200/vendor.bundle.js:53349:23) at createViewNodes (http://localhost:4200/vendor.bundle.js:56315:44) at createRootView (http://localhost:4200/vendor.bundle.js:56244:5) at callWithDebugContext (http://localhost:4200/vendor.bundle.js:57625:42) at Object.debugCreateRootView [as createRootView] (http://localhost:4200/vendor.bundle.js:56942:12) at ComponentFactory_.webpackJsonp.../../../core/@angular/core.es5.js.ComponentFactory_.create (http://localhost:4200/vendor.bundle.js:54035:46) at ComponentFactoryBoundToModule.webpackJsonp.../../../core/@angular/core.es5.js.ComponentFactoryBoundToModule.create (http://localhost:4200/vendor.bundle.js:47423:29) at ApplicationRef_.webpackJsonp.../../../core/@angular/core.es5.js.ApplicationRef_.bootstrap (http://localhost:4200/vendor.bundle.js:48912:57) api.onUnhandledError @ zone.js:643 handleUnhandledRejection @ zone.js:667 _loop_1 @ zone.js:658 api.microtaskDrainDone @ zone.js:662 drainMicroTaskQueue @ zone.js:592 zone.js:645 Error: Uncaught (in promise): Error: The selector "app-root" did not match any elements Error: The selector "app-root" did not match any elements at DefaultDomRenderer2.webpackJsonp.../../../platform-browser/@angular/platform-browser.es5.js.DefaultDomRenderer2.selectRootElement (platform-browser.es5.js:2808) at DebugRenderer2.webpackJsonp.../../../core/@angular/core.es5.js.DebugRenderer2.selectRootElement (core.es5.js:13710) at createElement (core.es5.js:9259) at createViewNodes (core.es5.js:12225) at createRootView (core.es5.js:12154) at callWithDebugContext (core.es5.js:13535) at Object.debugCreateRootView [as createRootView] (core.es5.js:12852) at ComponentFactory_.webpackJsonp.../../../core/@angular/core.es5.js.ComponentFactory_.create (core.es5.js:9945) at ComponentFactoryBoundToModule.webpackJsonp.../../../core/@angular/core.es5.js.ComponentFactoryBoundToModule.create (core.es5.js:3333) at ApplicationRef_.webpackJsonp.../../../core/@angular/core.es5.js.ApplicationRef_.bootstrap (core.es5.js:4822) at DefaultDomRenderer2.webpackJsonp.../../../platform-browser/@angular/platform-browser.es5.js.DefaultDomRenderer2.selectRootElement (platform-browser.es5.js:2808) at DebugRenderer2.webpackJsonp.../../../core/@angular/core.es5.js.DebugRenderer2.selectRootElement (core.es5.js:13710) at createElement (core.es5.js:9259) at createViewNodes (core.es5.js:12225) at createRootView (core.es5.js:12154) at callWithDebugContext (core.es5.js:13535) at Object.debugCreateRootView [as createRootView] (core.es5.js:12852) at ComponentFactory_.webpackJsonp.../../../core/@angular/core.es5.js.ComponentFactory_.create (core.es5.js:9945) at ComponentFactoryBoundToModule.webpackJsonp.../../../core/@angular/core.es5.js.ComponentFactoryBoundToModule.create (core.es5.js:3333) at ApplicationRef_.webpackJsonp.../../../core/@angular/core.es5.js.ApplicationRef_.bootstrap (core.es5.js:4822) at resolvePromise (zone.js:770) at zone.js:696 at zone.js:712 at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:391) at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.run (zone.js:141) at zone.js:818 at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424) at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:191) at drainMicroTaskQueue (zone.js:584) at &lt;anonymous&gt; </code></pre> <p>All the code is exactly as per the tutorial link above. But i am still adding some details below.</p> <p>index.html:</p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Calui&lt;/title&gt; &lt;base href="/"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link rel="icon" type="image/x-icon" href="favicon.ico"&gt; &lt;/head&gt; &lt;body&gt; &lt;app-people-list&gt;&lt;/app-people-list&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>app.component.spec.ts:</p> <pre><code>import { TestBed, async } from '@angular/core/testing'; import { AppComponent } from './app.component'; describe('AppComponent', () =&gt; { beforeEach(async(() =&gt; { TestBed.configureTestingModule({ declarations: [ AppComponent ], }).compileComponents(); })); it('should create the app', async(() =&gt; { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app).toBeTruthy(); })); it(`should have as title 'app'`, async(() =&gt; { const fixture = TestBed.createComponent(AppComponent); const app = fixture.debugElement.componentInstance; expect(app.title).toEqual('app'); })); it('should render title in a h1 tag', async(() =&gt; { const fixture = TestBed.createComponent(AppComponent); fixture.detectChanges(); const compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!!'); })); }); </code></pre> <p>app.component.ts:</p> <pre><code>import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; } </code></pre> <p>app.module.ts:</p> <pre><code>import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { AppComponent } from './app.component'; import { PeopleListComponent } from './people-list/people-list.component'; @NgModule({ declarations: [ AppComponent, PeopleListComponent ], imports: [ BrowserModule, FormsModule, HttpModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } </code></pre> <p>people-list.component.spec.ts:</p> <pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { PeopleListComponent } from './people-list.component'; describe('PeopleListComponent', () =&gt; { let component: PeopleListComponent; let fixture: ComponentFixture&lt;PeopleListComponent&gt;; beforeEach(async(() =&gt; { TestBed.configureTestingModule({ declarations: [ PeopleListComponent ] }) .compileComponents(); })); beforeEach(() =&gt; { fixture = TestBed.createComponent(PeopleListComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () =&gt; { expect(component).toBeTruthy(); }); }); </code></pre> <p>people-list.component.ts:</p> <pre><code>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-people-list', template: ` &lt;p&gt; people-list Works! &lt;/p&gt; `, styleUrls: ['./people-list.component.css'] }) export class PeopleListComponent implements OnInit { constructor() { } ngOnInit() { } } </code></pre>
44,625,753
7
10
null
2017-06-16 12:52:43.347 UTC
3
2021-09-25 08:11:14.493 UTC
2017-06-17 14:19:18.893 UTC
null
1,730,904
null
1,730,904
null
1
34
angular
63,022
<p>Angular starts with a root component. When you give</p> <pre><code>bootstrap: [ AppComponent ] </code></pre> <p>in your <code>app.modules.ts</code>, angular searches for first instance of <code>app-root</code> in your HTML and replaces that tag with angular application. So, your AppComponent <code>selector</code> should match to the root component in HTML .</p> <p>You need to add other component code <em>inside</em> <code>app.component.html</code> , so that angular can display them . It follows <code>tree</code> structure where <code>app-root</code> is at the top .</p>
41,053,901
How to display base64 encoded image in html
<p>I have image URL, so I downloaded the image and converted image into base 64 by online converter.</p> <p>base 64 code:</p> <pre><code>iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MEVBMTczNDg3QzA5MTFFNjk3ODM5NjQyRjE2RjA3QTkiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MEVBMTczNDk3QzA5MTFFNjk3ODM5NjQyRjE2RjA3QTkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDowRUExNzM0NjdDMDkxMUU2OTc4Mzk2NDJGMTZGMDdBOSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDowRUExNzM0NzdDMDkxMUU2OTc4Mzk2NDJGMTZGMDdBOSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PjjUmssAAAGASURBVHjatJaxTsMwEIbpIzDA6FaMMPYJkDKzVYU+QFeEGPIKfYU8AETkCYI6wANkZQwIKRNDB1hA0Jrf0rk6WXZ8BvWkb4kv99vn89kDrfVexBSYgVNwDA7AN+jAK3gEd+AlGMGIBFDgFvzouK3JV/lihQTOwLtOtw9wIRG5pJn91Tbgqk9kSk7GViADrTD4HCyZ0NQnomi51sb0fUyCMQEbp2WpU67IjfNjwcYyoUDhjJVcZBjYBy40j4wXgaobWoe8Z6Y80CJBwFpunepIzt2AUgFjtXXshNXjVmMh+K+zzp/CMs0CqeuzrxSRpbOKfdCkiMTS1VBQ41uxMyQR2qbrXiiwYN3ACh1FDmsdK2Eu4J6Tlo31dYVtCY88h5ELZIJJ+IRMzBHfyJINrigNkt5VsRiub9nXICdsYyVd2NcVvA3ScE5t2rb5JuEeyZnAhmLt9NK63vX1O5Pe8XaPSuGq1uTrfUgMEp9EJ+CQvr+BJ/AAKvAcCiAR+bf9CjAAluzmdX4AEIIAAAAASUVORK5CYII= </code></pre> <p>So may I use this big size in or some other way is there?</p>
41,053,963
1
3
null
2016-12-09 05:49:31.843 UTC
2
2018-09-06 11:52:02.877 UTC
null
null
null
null
6,333,230
null
1
10
html|image|base64
74,307
<p>You can use a <a href="https://en.wikipedia.org/wiki/Data_URI_scheme" rel="noreferrer">data URI</a>:</p> <pre class="lang-html prettyprint-override"><code>&lt;img src="data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MEVBMTczNDg3QzA5MTFFNjk3ODM5NjQyRjE2RjA3QTkiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MEVBMTczNDk3QzA5MTFFNjk3ODM5NjQyRjE2RjA3QTkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDowRUExNzM0NjdDMDkxMUU2OTc4Mzk2NDJGMTZGMDdBOSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDowRUExNzM0NzdDMDkxMUU2OTc4Mzk2NDJGMTZGMDdBOSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PjjUmssAAAGASURBVHjatJaxTsMwEIbpIzDA6FaMMPYJkDKzVYU+QFeEGPIKfYU8AETkCYI6wANkZQwIKRNDB1hA0Jrf0rk6WXZ8BvWkb4kv99vn89kDrfVexBSYgVNwDA7AN+jAK3gEd+AlGMGIBFDgFvzouK3JV/lihQTOwLtOtw9wIRG5pJn91Tbgqk9kSk7GViADrTD4HCyZ0NQnomi51sb0fUyCMQEbp2WpU67IjfNjwcYyoUDhjJVcZBjYBy40j4wXgaobWoe8Z6Y80CJBwFpunepIzt2AUgFjtXXshNXjVmMh+K+zzp/CMs0CqeuzrxSRpbOKfdCkiMTS1VBQ41uxMyQR2qbrXiiwYN3ACh1FDmsdK2Eu4J6Tlo31dYVtCY88h5ELZIJJ+IRMzBHfyJINrigNkt5VsRiub9nXICdsYyVd2NcVvA3ScE5t2rb5JuEeyZnAhmLt9NK63vX1O5Pe8XaPSuGq1uTrfUgMEp9EJ+CQvr+BJ/AAKvAcCiAR+bf9CjAAluzmdX4AEIIAAAAASUVORK5CYII="&gt; </code></pre>
5,010,754
Do collaborators have commit access on GitHub?
<p>One thing I noticed: Using the GitHub UI, I added a collaborator to a repository. I saw that they committed changes without any authority / approval from me. It was a private repository.</p> <p>With private repositories, how do I give someone read access versus write access?</p>
5,010,789
2
0
null
2011-02-15 23:29:11.377 UTC
3
2016-07-03 06:24:58.393 UTC
2016-07-03 06:23:58.623 UTC
null
63,550
null
129,774
null
1
42
git|github
34,445
<blockquote> <p>With private repositories, how do I give someone read access versus write access?</p> </blockquote> <p>This kind of permission is not available for simple accounts. When you add an user as a collaborator, he gains read/write permissions.</p> <p>The story changes if you own an <a href="https://github.com/blog/674-introducing-organizations" rel="nofollow">Organization</a>. Organizations contains teams and each team can have different level of access, including read-only. You can assign users to a specific read-only group, and they will only have pull access to the repositories.</p>
492,627
Change border color on <select> HTML form
<p>Is it possible to change the border color on a <code>&lt;select/&gt;</code> element in an HTML form?</p> <p>The <code>border-color</code> style works in Firefox but not IE.</p> <p>I could find no real answers on Google.</p>
492,670
7
1
null
2009-01-29 17:34:15.65 UTC
4
2020-06-29 05:44:41.08 UTC
2013-06-06 19:41:58.93 UTC
null
2,156,756
Too embarrassed to say
null
null
1
20
html|css|html-select
151,770
<p>I would consinder enclosing that select block within a div block and setting the border property like this:</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-html lang-html prettyprint-override"><code>&lt;div style="border: 2px solid blue;"&gt; &lt;select style="width: 100%;"&gt; &lt;option value="Sal"&gt;Sal&lt;/option&gt; &lt;option value="Awesome"&gt;Awesome!&lt;/option&gt; &lt;/select&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>You should be able to play with that to accomplish what you need.</p>
724,857
How to find JavaScript variable by its name
<p>Is there a way to find JavaScript variable on the page (get it as an object) by its name? Variable name is available as a string constant.</p>
724,906
7
1
null
2009-04-07 09:43:47.033 UTC
11
2018-08-29 09:32:37.947 UTC
null
null
null
null
59,713
null
1
40
javascript
54,864
<pre><code>&lt;script&gt; var a ="test"; alert(a); alert(window["a"]); alert(eval("a")); &lt;/script&gt; </code></pre>
324,045
Windows temporary files behaviour - are they deleted by the system?
<p>Using the .net framework you have the option to create temporary files with</p> <pre><code>Path.GetTempFileName(); </code></pre> <p>The MSDN doesn't tell us what happens to temporary files. I remember reading somewhere that they are deleted by the OS when it gets a restart. Is this true?</p> <p>If the files aren't deleted by the OS, why are they called temporary? They are normal files in a normal directory. </p>
324,345
7
1
null
2008-11-27 15:34:21.163 UTC
5
2016-07-15 12:49:21.1 UTC
2008-11-27 15:40:18.64 UTC
Bogdan Gavril
21,634
Bogdan Gavril
21,634
null
1
43
.net|windows|file
13,852
<p>The short answer: they don't get deleted.</p> <p>The long answer: The managed <a href="http://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename.aspx" rel="noreferrer"><code>Path.GetTempFileName()</code></a> method calls the native Win32API <a href="http://msdn.microsoft.com/en-us/library/aa364991.aspx" rel="noreferrer"><code>GetTempFileName()</code></a> method, like this: </p> <pre><code>//actual .NET 2.0 decompiled code // .NET Reflector rocks for looking at plumbing public static string GetTempFileName() { string tempPath = GetTempPath(); new FileIOPermission(FileIOPermissionAccess.Write, tempPath).Demand(); StringBuilder tmpFileName = new StringBuilder(260); if (Win32Native.GetTempFileName(tempPath, "tmp", 0, tmpFileName) == 0) { __Error.WinIOError(); } return tmpFileName.ToString(); } </code></pre> <p>The documentation for the native method states:</p> <blockquote> <p><img src="https://stackoverflow.com/Content/img/wmd/blockquote.png" alt=""> Temporary files whose names have been created by this function are not automatically deleted. To delete these files call DeleteFile.</p> </blockquote> <p>I have found a great article called <a href="https://web.archive.org/web/20071020031505/http://dotnet.org.za/markn/archive/2006/04/15/51594.aspx" rel="noreferrer">"Those pesky temp files"</a> (Archived Oct. 2007) that starts from basics and touches some less obvious problems of handling temporary files, like:</p> <ul> <li>How to make sure the file is deleted (even if the app crashes! hint: <a href="http://msdn.microsoft.com/en-us/library/system.io.fileoptions.aspx" rel="noreferrer"><code>FileOption.DeleteOnClose</code></a> and let the kernel deal with it)</li> <li>How to get the correct caching policy for the file, to improve performance (hint: <a href="http://msdn.microsoft.com/en-us/library/system.io.fileattributes.aspx" rel="noreferrer"><code>FileAttributes.Temporary</code></a>)</li> <li>How to make sure the contents of the file stay secure, because: <ul> <li>the file name is even more predictable with the managed method than with the unmanaged one</li> <li>the temp file is created, then <em>closed</em>, then you get the path to it (only to open it again), thus leaving a small window of opportunity for malicious code/users to hijack the file. </li> </ul></li> </ul> <p>C# Code from article:</p> <pre><code>using System; using System.IO; using System.Security.Permissions; using System.Security.Principal; using System.Security.AccessControl; public static class PathUtility { private const int defaultBufferSize = 0x1000; // 4KB #region GetSecureDeleteOnCloseTempFileStream /// &lt;summary&gt; /// Creates a unique, randomly named, secure, zero-byte temporary file on disk, which is automatically deleted when it is no longer in use. Returns the opened file stream. /// &lt;/summary&gt; /// &lt;remarks&gt; /// &lt;para&gt;The generated file name is a cryptographically strong, random string. The file name is guaranteed to be unique to the system's temporary folder.&lt;/para&gt; /// &lt;para&gt;The &lt;see cref="GetSecureDeleteOnCloseTempFileStream"/&gt; method will raise an &lt;see cref="IOException"/&gt; if no unique temporary file name is available. Although this is possible, it is highly improbable. To resolve this error, delete all uneeded temporary files.&lt;/para&gt; /// &lt;para&gt;The file is created as a zero-byte file in the system's temporary folder.&lt;/para&gt; /// &lt;para&gt;The file owner is set to the current user. The file security permissions grant full control to the current user only.&lt;/para&gt; /// &lt;para&gt;The file sharing is set to none.&lt;/para&gt; /// &lt;para&gt;The file is marked as a temporary file. File systems avoid writing data back to mass storage if sufficient cache memory is available, because an application deletes a temporary file after a handle is closed. In that case, the system can entirely avoid writing the data. Otherwise, the data is written after the handle is closed.&lt;/para&gt; /// &lt;para&gt;The system deletes the file immediately after it is closed or the &lt;see cref="FileStream"/&gt; is finalized.&lt;/para&gt; /// &lt;/remarks&gt; /// &lt;returns&gt;The opened &lt;see cref="FileStream"/&gt; object.&lt;/returns&gt; public static FileStream GetSecureDeleteOnCloseTempFileStream() { return GetSecureDeleteOnCloseTempFileStream(defaultBufferSize, FileOptions.DeleteOnClose); } /// &lt;summary&gt; /// Creates a unique, randomly named, secure, zero-byte temporary file on disk, which is automatically deleted when it is no longer in use. Returns the opened file stream with the specified buffer size. /// &lt;/summary&gt; /// &lt;remarks&gt; /// &lt;para&gt;The generated file name is a cryptographically strong, random string. The file name is guaranteed to be unique to the system's temporary folder.&lt;/para&gt; /// &lt;para&gt;The &lt;see cref="GetSecureDeleteOnCloseTempFileStream"/&gt; method will raise an &lt;see cref="IOException"/&gt; if no unique temporary file name is available. Although this is possible, it is highly improbable. To resolve this error, delete all uneeded temporary files.&lt;/para&gt; /// &lt;para&gt;The file is created as a zero-byte file in the system's temporary folder.&lt;/para&gt; /// &lt;para&gt;The file owner is set to the current user. The file security permissions grant full control to the current user only.&lt;/para&gt; /// &lt;para&gt;The file sharing is set to none.&lt;/para&gt; /// &lt;para&gt;The file is marked as a temporary file. File systems avoid writing data back to mass storage if sufficient cache memory is available, because an application deletes a temporary file after a handle is closed. In that case, the system can entirely avoid writing the data. Otherwise, the data is written after the handle is closed.&lt;/para&gt; /// &lt;para&gt;The system deletes the file immediately after it is closed or the &lt;see cref="FileStream"/&gt; is finalized.&lt;/para&gt; /// &lt;/remarks&gt; /// &lt;param name="bufferSize"&gt;A positive &lt;see cref="Int32"/&gt; value greater than 0 indicating the buffer size.&lt;/param&gt; /// &lt;returns&gt;The opened &lt;see cref="FileStream"/&gt; object.&lt;/returns&gt; public static FileStream GetSecureDeleteOnCloseTempFileStream(int bufferSize) { return GetSecureDeleteOnCloseTempFileStream(bufferSize, FileOptions.DeleteOnClose); } /// &lt;summary&gt; /// Creates a unique, randomly named, secure, zero-byte temporary file on disk, which is automatically deleted when it is no longer in use. Returns the opened file stream with the specified buffer size and file options. /// &lt;/summary&gt; /// &lt;remarks&gt; /// &lt;para&gt;The generated file name is a cryptographically strong, random string. The file name is guaranteed to be unique to the system's temporary folder.&lt;/para&gt; /// &lt;para&gt;The &lt;see cref="GetSecureDeleteOnCloseTempFileStream"/&gt; method will raise an &lt;see cref="IOException"/&gt; if no unique temporary file name is available. Although this is possible, it is highly improbable. To resolve this error, delete all uneeded temporary files.&lt;/para&gt; /// &lt;para&gt;The file is created as a zero-byte file in the system's temporary folder.&lt;/para&gt; /// &lt;para&gt;The file owner is set to the current user. The file security permissions grant full control to the current user only.&lt;/para&gt; /// &lt;para&gt;The file sharing is set to none.&lt;/para&gt; /// &lt;para&gt;The file is marked as a temporary file. File systems avoid writing data back to mass storage if sufficient cache memory is available, because an application deletes a temporary file after a handle is closed. In that case, the system can entirely avoid writing the data. Otherwise, the data is written after the handle is closed.&lt;/para&gt; /// &lt;para&gt;The system deletes the file immediately after it is closed or the &lt;see cref="FileStream"/&gt; is finalized.&lt;/para&gt; /// &lt;para&gt;Use the &lt;paramref name="options"/&gt; parameter to specify additional file options. You can specify &lt;see cref="FileOptions.Encrypted"/&gt; to encrypt the file contents using the current user account. Specify &lt;see cref="FileOptions.Asynchronous"/&gt; to enable overlapped I/O when using asynchronous reads and writes.&lt;/para&gt; /// &lt;/remarks&gt; /// &lt;param name="bufferSize"&gt;A positive &lt;see cref="Int32"/&gt; value greater than 0 indicating the buffer size.&lt;/param&gt; /// &lt;param name="options"&gt;A &lt;see cref="FileOptions"/&gt; value that specifies additional file options.&lt;/param&gt; /// &lt;returns&gt;The opened &lt;see cref="FileStream"/&gt; object.&lt;/returns&gt; public static FileStream GetSecureDeleteOnCloseTempFileStream(int bufferSize, FileOptions options) { FileStream fs = GetSecureFileStream(Path.GetTempPath(), bufferSize, options | FileOptions.DeleteOnClose); File.SetAttributes(fs.Name, File.GetAttributes(fs.Name) | FileAttributes.Temporary); return fs; } #endregion #region GetSecureTempFileStream public static FileStream GetSecureTempFileStream() { return GetSecureTempFileStream(defaultBufferSize, FileOptions.None); } public static FileStream GetSecureTempFileStream(int bufferSize) { return GetSecureTempFileStream(bufferSize, FileOptions.None); } public static FileStream GetSecureTempFileStream(int bufferSize, FileOptions options) { FileStream fs = GetSecureFileStream(Path.GetTempPath(), bufferSize, options); File.SetAttributes(fs.Name, File.GetAttributes(fs.Name) | FileAttributes.NotContentIndexed | FileAttributes.Temporary); return fs; } #endregion #region GetSecureTempFileName public static string GetSecureTempFileName() { return GetSecureTempFileName(false); } public static string GetSecureTempFileName(bool encrypted) { using (FileStream fs = GetSecureFileStream(Path.GetTempPath(), defaultBufferSize, encrypted ? FileOptions.Encrypted : FileOptions.None)) { File.SetAttributes(fs.Name, File.GetAttributes(fs.Name) | FileAttributes.NotContentIndexed | FileAttributes.Temporary); return fs.Name; } } #endregion #region GetSecureFileName public static string GetSecureFileName(string path) { return GetSecureFileName(path, false); } public static string GetSecureFileName(string path, bool encrypted) { using (FileStream fs = GetSecureFileStream(path, defaultBufferSize, encrypted ? FileOptions.Encrypted : FileOptions.None)) { return fs.Name; } } #endregion #region GetSecureFileStream public static FileStream GetSecureFileStream(string path) { return GetSecureFileStream(path, defaultBufferSize, FileOptions.None); } public static FileStream GetSecureFileStream(string path, int bufferSize) { return GetSecureFileStream(path, bufferSize, FileOptions.None); } public static FileStream GetSecureFileStream(string path, int bufferSize, FileOptions options) { if (path == null) throw new ArgumentNullException("path"); if (bufferSize &lt;= 0) throw new ArgumentOutOfRangeException("bufferSize"); if ((options &amp; ~(FileOptions.Asynchronous | FileOptions.DeleteOnClose | FileOptions.Encrypted | FileOptions.RandomAccess | FileOptions.SequentialScan | FileOptions.WriteThrough)) != FileOptions.None) throw new ArgumentOutOfRangeException("options"); new FileIOPermission(FileIOPermissionAccess.Write, path).Demand(); SecurityIdentifier user = WindowsIdentity.GetCurrent().User; FileSecurity fileSecurity = new FileSecurity(); fileSecurity.AddAccessRule(new FileSystemAccessRule(user, FileSystemRights.FullControl, AccessControlType.Allow)); fileSecurity.SetAccessRuleProtection(true, false); fileSecurity.SetOwner(user); // Attempt to create a unique file three times before giving up. // It is highly improbable that there will ever be a name clash, // therefore we do not check to see if the file first exists. for (int attempt = 0; attempt &lt; 3; attempt++) { try { return new FileStream(Path.Combine(path, Path.GetRandomFileName()), FileMode.CreateNew, FileSystemRights.FullControl, FileShare.None, bufferSize, options, fileSecurity); } catch (IOException) { if (attempt == 2) throw; } } // This code can never be reached. // The compiler thinks otherwise. throw new IOException(); } #endregion } </code></pre>
542,705
How do I combine 2 select statements into one?
<p>I am a noob when it comes to SQL syntax. </p> <p>I have a table with lots of rows and columns of course :P Lets say it looks like this:</p> <pre><code> AAA BBB CCC DDD ----------------------- Row1 | 1 A D X Row2 | 2 B C X Row3 | 3 C D Z </code></pre> <p>Now I want to create an advanced select statement that gives me this combined (pseudo SQLish here):</p> <pre><code>select 'Test1', * from TABLE Where CCC='D' AND DDD='X' select 'Test2', * from TABLE Where CCC&lt;&gt;'D' AND DDD='X' </code></pre> <p>The output would be:</p> <pre><code>Test1, 1, A, D, X Test2, 2, B, C, X </code></pre> <p>How would I combine those two select statements into one nice select statement?</p> <p>Would it work if I complicated the SQL like below (because my own SQL statement contains an exists statement)? I just want to know how I can combine the selects and then try to apply it to my somewhat more advanced SQL.</p> <pre><code>select 'Test1', * from TABLE Where CCC='D' AND DDD='X' AND exists(select ...) select 'Test2', * from TABLE Where CCC&lt;&gt;'D' AND DDD='X' AND exists(select ...) </code></pre> <p><br> <br> <br> My REAL SQL statement is this one:</p> <pre><code>select Status, * from WorkItems t1 where exists (select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) ) AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01) AND TimeStamp&gt;'2009-02-12 18:00:00' </code></pre> <p>which gives me a result. But I want to combine it with a copy of this select statement with an added AND on the end and the 'Status' field would be changed with a string like 'DELETED'.</p> <pre><code>select 'DELETED', * from WorkItems t1 where exists (select 1 from workitems t2 where t1.TextField01=t2.TextField01 AND (BoolField05=1) ) AND TimeStamp=(select max(t2.TimeStamp) from workitems t2 where t2.TextField01=t1.TextField01) AND TimeStamp&gt;'2009-02-12 18:00:00' AND NOT (BoolField05=1) </code></pre>
542,735
8
1
null
2009-02-12 18:41:39.093 UTC
18
2017-07-03 10:06:00.643 UTC
2013-05-04 10:44:21.317 UTC
null
635,608
Wolf5
37,643
null
1
59
sql|select|conditional
326,898
<p>You have two choices here. The first is to have two result sets which will set 'Test1' or 'Test2' based on the condition in the <code>WHERE</code> clause, and then <code>UNION</code> them together:</p> <pre><code>select 'Test1', * from TABLE Where CCC='D' AND DDD='X' AND exists(select ...) UNION select 'Test2', * from TABLE Where CCC&lt;&gt;'D' AND DDD='X' AND exists(select ...) </code></pre> <p>This might be an issue, because you are going to effectively scan/seek on TABLE twice.</p> <p>The other solution would be to select from the table once, and set 'Test1' or 'Test2' based on the conditions in TABLE:</p> <pre><code>select case when CCC='D' AND DDD='X' AND exists(select ...) then 'Test1' when CCC&lt;&gt;'D' AND DDD='X' AND exists(select ...) then 'Test2' end, * from TABLE Where (CCC='D' AND DDD='X' AND exists(select ...)) or (CCC&lt;&gt;'D' AND DDD='X' AND exists(select ...)) </code></pre> <p>The catch here being that you will have to duplicate the filter conditions in the <code>CASE</code> statement and the <code>WHERE</code> statement.</p>
1,169,248
Test if a vector contains a given element
<p>How to check if a vector contains a given value?</p>
1,169,262
8
7
null
2009-07-23 02:20:53.34 UTC
149
2022-07-16 18:43:31.497 UTC
2018-05-09 09:33:59.3 UTC
null
680,068
null
2,002,705
null
1
609
r|vector|r-faq
882,574
<p>Both the <code>match()</code> (returns the first appearance) and <code>%in%</code> (returns a Boolean) functions are designed for this.</p> <pre><code>v &lt;- c('a','b','c','e') 'b' %in% v ## returns TRUE match('b',v) ## returns the first location of 'b', in this case: 2 </code></pre>
644,975
Deleting a LOT of data in Oracle
<p>I am not a database person, exactly, and most of my db work has been with MySQL, so forgive me if something in this question is incredibly naïve.</p> <p>I need to delete 5.5 million rows from an Oracle table that has about 100 million rows. I have all the IDs of the rows I need to delete in a temporary table. If it were a just a few thousand rows, I'd do this:</p> <pre><code>DELETE FROM table_name WHERE id IN (SELECT id FROM temp_table); COMMIT; </code></pre> <p>Is there anything I need to be aware of, and/or do differently, because it's 5.5 million rows? I thought about doing a loop, something like this:</p> <pre><code>DECLARE vCT NUMBER(38) := 0; BEGIN FOR t IN (SELECT id FROM temp_table) LOOP DELETE FROM table_name WHERE id = t.id; vCT := vCT + 1; IF MOD(vCT,200000) = 0 THEN COMMIT; END IF; END LOOP; COMMIT; END; </code></pre> <p>First of all - is this doing what I think it is - batching commits of 200,000 at a time? Assuming it is, I'm still not sure if it's better to generate 5.5 million SQL statements, and commit in batches of 200,000, or to have one SQL statement and commit all at once.</p> <p>Ideas? Best practices?</p> <p><strong>EDIT</strong>: I ran the first option, the single delete statement, and it only took 2 hours to complete in development. Based on that, it's queued to be run in production. </p>
645,021
9
1
null
2009-03-13 23:31:02.24 UTC
6
2016-09-23 20:23:40.08 UTC
2016-09-23 20:23:40.08 UTC
Sarah Mei
4,370,109
Sarah Mei
66,801
null
1
15
sql|oracle|plsql
55,011
<p>The first approach is better, because you give the query optimizer a clear picture of what you are trying to do, instead of trying to hide it. The database engine might take a different approach to deleting 5.5m (or 5.5% of the table) internally than to deleting 200k (or 0.2%). </p> <p>Here is also an <a href="http://www.devx.com/dbzone/10MinuteSolution/22191" rel="noreferrer">article</a> about massive DELETE in Oracle which you might want to read.</p>
283,749
The VB.NET 'With' Statement - embrace or avoid?
<p>At work, I'm frequently working on projects where numerous properties of certain objects have to be set during their construction or early during their lifetime. For the sake of convenience and readability, I often use the <code>With</code> statement to set these properties. I find that</p> <pre><code>With Me.Elements .PropertyA = True .PropertyB = "Inactive" ' And so on for several more lines End With </code></pre> <p>Looks much better than</p> <pre><code>Me.Elements.PropertyA = True Me.Elements.PropertyB = "Inactive" ' And so on for several more lines </code></pre> <p>for very long statements that simply set properties.</p> <p>I've noticed that there are some issues with using <code>With</code> while debugging; however, <strong>I was wondering if there were any compelling reasons to avoid using <code>With</code> in practice</strong>? I've always assumed the code generated via the compiler for the above two cases is basically the same which is why I've always chosen to write what I feel to be more readable. </p>
283,820
10
1
null
2008-11-12 12:09:32.713 UTC
13
2017-08-17 14:39:48.467 UTC
2009-11-09 20:47:30.373 UTC
Tom
20
Tom
20
null
1
72
vb.net|with-statement
61,028
<p>If you have long variablenames and would end up with:</p> <pre><code>UserHandler.GetUser.First.User.FirstName="Stefan" UserHandler.GetUser.First.User.LastName="Karlsson" UserHandler.GetUser.First.User.Age="39" UserHandler.GetUser.First.User.Sex="Male" UserHandler.GetUser.First.User.Occupation="Programmer" UserHandler.GetUser.First.User.UserID="0" ....and so on </code></pre> <p>then I would use WITH to make it more readable:</p> <pre><code>With UserHandler.GetUser.First.User .FirstName="Stefan" .LastName="Karlsson" .Age="39" .Sex="Male" .Occupation="Programmer" .UserID="0" end with </code></pre> <p>In the later example there are even performance benefit over the first example because in the first example Im fetching the user every time I access a user property and in the WITH-case I only fetch the user one time.</p> <p>I can get the performance gain without using with, like this:</p> <pre><code>dim myuser as user =UserHandler.GetUser.First.User myuser.FirstName="Stefan" myuser.LastName="Karlsson" myuser.Age="39" myuser.Sex="Male" myuser.Occupation="Programmer" myuser.UserID="0" </code></pre> <p>But I would go for the WITH statement instead, it looks cleaner.</p> <p>And I just took this as an example so dont complain over a class with many keywords, another example could be like: WITH RefundDialog.RefundDatagridView.SelectedRows(0) </p>
603,785
Environment variables in Mac OS X
<p>Update: The link below <em>does not have a complete answer</em>. Having to set the path or variable in two places (one for GUI and one for shell) is lame.</p> <p><strong>Not Duplicate of</strong>: <a href="https://stackoverflow.com/questions/135688/setting-environment-variables-in-os-x">Setting environment variables in OS X?</a></p> <hr> <p>Coming from a Windows background where it's very easy to set and modify environment variables (just go to System Properties > Advanced > Environment Variables), it does not seem to be that straight forward on Mac OS 10.5. Most references say I should update /etc/profile or ~/.profile. Are those the equivalent of System Variables and User Variables? For example, where should I set my <code>JAVA_HOME</code> variable?</p> <hr> <p>EDIT:</p> <p>I want to be able to access the variable from the terminal as well as an app like Eclipse. Also, I hope I don't have to restart/logout to make this take effect.</p>
3,756,674
10
1
null
2009-03-02 20:07:20.46 UTC
176
2022-01-10 08:29:44.683 UTC
2017-05-23 12:26:37.537 UTC
Abdullah Jibaly
-1
Abdullah Jibaly
47,110
null
1
203
macos|environment-variables
246,773
<p>There's no need for duplication. You can set environment variables used by launchd (and child processes, i.e. anything you start from Spotlight) using <code>launchctl setenv</code>.</p> <p>For example, if you want to mirror your current path in launchd after setting it up in <code>.bashrc</code> or wherever:</p> <pre><code>PATH=whatever:you:want launchctl setenv PATH $PATH </code></pre> <p>Environment variables are not automatically updated in running applications. You will need to relaunch applications to get the updated environment variables (although you can just set variables in your shell, e.g. <code>PATH=whatever:you:want</code>; there's no need to relaunch the terminal).</p>
4,371
How do I retrieve my MySQL username and password?
<p>I lost my MySQL username and password. How do I retrieve it?</p>
4,376
11
0
null
2008-08-07 03:54:14.593 UTC
63
2022-07-03 11:14:22.733 UTC
2022-05-14 20:46:50.21 UTC
null
12,492,890
null
131
null
1
180
mysql|mysql-workbench
744,650
<blockquote> <p>Stop the MySQL process.</p> <p>Start the MySQL process with the --skip-grant-tables option.</p> <p>Start the MySQL console client with the -u root option.</p> </blockquote> <p>List all the users;</p> <pre><code>SELECT * FROM mysql.user; </code></pre> <p>Reset password;</p> <pre><code>UPDATE mysql.user SET Password=PASSWORD('[password]') WHERE User='[username]'; </code></pre> <hr /> <p>But <strong>DO NOT FORGET</strong> to</p> <blockquote> <p>Stop the MySQL process</p> <p>Start the MySQL Process normally (i.e. without the --skip-grant-tables option)</p> </blockquote> <p>when you are finished. Otherwise, your database's security could be compromised.</p>
927,006
LINQ to SQL -- Can't modify return type of stored procedure
<p>When I drag a particular stored procedure into the VS 2008 dbml designer, it shows up with Return Type set to "none", and it's read only so I can't change it. The designer code shows it as returning an int, and if I change that manually, it just gets undone on the next build. </p> <p>But with another (nearly identical) stored procedure, I can change the return type just fine (from "Auto Generated Type" to what I want.) </p> <p>I've run into this problem on two separate machines. Any idea what's going on? </p> <p>Here's the stored procedure that works:</p> <pre><code>USE [studio] GO /****** Object: StoredProcedure [dbo].[GetCourseAnnouncements] Script Date: 05/29/2009 09:44:51 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER OFF GO CREATE PROCEDURE [dbo].[GetCourseAnnouncements] @course int AS SELECT * FROM Announcements WHERE Announcements.course = @course RETURN </code></pre> <p>And this one doesn't: </p> <pre><code>USE [studio] GO /****** Object: StoredProcedure [dbo].[GetCourseAssignments] Script Date: 05/29/2009 09:45:32 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER OFF GO CREATE PROCEDURE [dbo].[GetCourseAssignments] @course int AS SELECT * FROM Assignments WHERE Assignments.course = @course ORDER BY date_due ASC RETURN </code></pre>
928,319
12
1
null
2009-05-29 16:48:39.373 UTC
15
2019-01-31 14:26:51.05 UTC
2013-08-24 15:46:48.46 UTC
null
861,716
null
113,435
null
1
21
linq-to-sql|stored-procedures|asp.net-3.5
27,980
<p>Okay, I found the problem... kind of. I had changed the name of the table "Assignments" and forgot to update the stored procudure, so the DBML designer was confused. BUT even after I updated the stored procedure, deleted it from the DBML designer and readded it, it wasn't working! </p> <p>This is nearly the same problem discussed here: <a href="http://forums.asp.net/t/1231821.aspx" rel="noreferrer">http://forums.asp.net/t/1231821.aspx</a>.</p> <p>It only worked when I deleted the stored procedure from the database and recreated it, and deleted it from the DBML designer, recompiled, restarted Visual Studio, and added it again. This is the second time I've run into "refresh" problems with the Visual Studio DBML designer...</p>
1,160,004
Setup Factory Girl with Test::Unit and Shoulda
<p>I'm trying to set up Factory Girl with Test::Unit and Shoulda in Ruby on Rails. I have installed the gem, created my factory file under the test/factories directory, and created my spec file under the test/models directory. The current error I'm getting is 'ArgumentError: No such factory: test', which leads me to believe that the test_factory.rb file is not being loaded? Any idea as to what I should change?</p> <p>Here are my files.</p> <pre><code>#test/factories/test_factory.rb Factory.define :test do |t| t.name 'test_spotlight' t.label 'test spotlight label' end </code></pre> <p>and</p> <pre><code>#test/modes/test_spec.rb require 'test_helper' require 'factory_girl' class TestTest &lt; Test::Unit::TestCase def setup @test = Factory.build(:test) end context "A test" do should "save with the minimum requirements" do assert @test.save end end end </code></pre>
1,359,180
13
0
null
2009-07-21 15:38:18.363 UTC
10
2011-09-19 14:50:48.367 UTC
2009-07-21 16:12:08.497 UTC
null
141,615
null
141,615
null
1
16
ruby-on-rails|ruby|shoulda|factory-bot|testunit
14,465
<p>I've run into this problem on one of my projects too. I'm not sure precisely what's causing the initialization code to be skipped but you can force load the factory definitions like this: </p> <pre><code>require 'factory_girl' Factory.find_definitions </code></pre> <p>Hope this helps.</p>
985,725
Tools for JPEG optimization?
<p>Do you know of any tools (preferrably command-line) to automatically and losslessly optimize JPEGs that I could integrate into our build environment? For PNGs I'm currently using <a href="http://www.advsys.net/ken/util/pngout.htm" rel="noreferrer">PNGOUT</a>, and it generally saves around 40% bandwidth/image size.</p> <p>At the very least, I would like a tool that can strip metadata from the JPGs - I noticed a strange case where I tried to make thumbnail from a photograph, and couldn't get it smaller than 34 kB. After investigating more, I found that the EXIF data was still part of the image, and the thumbnail was 3 kB after removing the metadata.</p> <p>And beyond that - is it possible to further optimize JPGs losslessly? The PNG optimizer tries different compression strategies, random initialization of the Huffmann encoding etc. </p> <p>I am aware that most savings come from the JPEG quality parameter, and that it's a rather subjective measure. I'm only looking for a tool that can be run as a build step and that losslessly squeezes a few bytes from the images.</p>
986,642
14
6
null
2009-06-12 09:03:05.827 UTC
56
2017-04-07 12:34:10.097 UTC
null
null
null
null
108,655
null
1
115
optimization|jpeg
65,618
<p>I use libjpeg for lossless operations. It contains a command-line tool <a href="http://en.wikipedia.org/wiki/Jpegtran" rel="noreferrer"><strong>jpegtran</strong></a> that can do all you want. With the commandline option <code>-copy none</code> all the metadata is stripped, and <code>-optimize</code> does a lossless optimization of the Huffmann compression. You can also convert the images to progressive mode with <code>-progressive</code>, but that might cause compatibility problems (does anyone know more about that?)</p>
70,303
How do you implement GetHashCode for structure with two string, when both strings are interchangeable
<p>I have a structure in C#:</p> <pre><code>public struct UserInfo { public string str1 { get; set; } public string str2 { get; set; } } </code></pre> <p>The only rule is that <code>UserInfo(str1="AA", str2="BB").Equals(UserInfo(str1="BB", str2="AA"))</code></p> <p>How to override the GetHashCode function for this structure? </p>
70,375
15
2
null
2008-09-16 08:17:43.553 UTC
9
2021-05-10 11:48:17.053 UTC
2014-09-24 11:28:56.553 UTC
aku
3,834
Ngu Soon Hui
3,834
null
1
72
c#|hashtable
44,180
<p><a href="http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx" rel="noreferrer">MSDN</a>:</p> <p>A hash function must have the following properties:</p> <blockquote> <ul> <li>If two objects compare as equal, the <code>GetHashCode</code> method for each object must return the same value. However, if two objects do not compare as equal, the <code>GetHashCode</code> methods for the two object do not have to return different values.</li> <li>The <code>GetHashCode</code> method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's <code>Equals</code> method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.</li> <li>For the best performance, a hash function must generate a random distribution for all input. </li> </ul> </blockquote> <p>Taking it into account correct way is:</p> <pre><code>return str1.GetHashCode() ^ str2.GetHashCode() </code></pre> <p><code>^</code> can be substituted with other commutative operation</p>
436,411
Where should I put <script> tags in HTML markup?
<p>When embedding JavaScript in an HTML document, where is the proper place to put the <code>&lt;script&gt;</code> tags and included JavaScript? I seem to recall that you are not supposed to place these in the <code>&lt;head&gt;</code> section, but placing at the beginning of the <code>&lt;body&gt;</code> section is bad, too, since the JavaScript will have to be parsed before the page is rendered completely (or something like that). This seems to leave the <em>end</em> of the <code>&lt;body&gt;</code> section as a logical place for <code>&lt;script&gt;</code> tags.</p> <p>So, where <em>is</em> the right place to put the <code>&lt;script&gt;</code> tags?</p> <p>(This question references <a href="https://stackoverflow.com/questions/436154/why-does-the-call-to-this-jquery-function-fail-in-firefox">this question</a>, in which it was suggested that JavaScript function calls should be moved from <code>&lt;a&gt;</code> tags to <code>&lt;script&gt;</code> tags. I'm specifically using jQuery, but more general answers are also appropriate.)</p>
24,070,373
21
4
null
2009-01-12 18:15:54.57 UTC
909
2022-07-29 00:56:57.257 UTC
2022-07-29 00:56:57.257 UTC
null
7,941,251
mipadi
28,804
null
1
1,795
javascript|html|script-tag
735,480
<p>Here's what happens when a browser loads a website with a <code>&lt;script&gt;</code> tag on it:</p> <ol> <li>Fetch the HTML page (e.g. <em>index.html</em>)</li> <li>Begin parsing the HTML</li> <li>The parser encounters a <code>&lt;script&gt;</code> tag referencing an external script file.</li> <li>The browser requests the script file. Meanwhile, the parser blocks and stops parsing the other HTML on your page.</li> <li>After some time the script is downloaded and subsequently executed.</li> <li>The parser continues parsing the rest of the HTML document.</li> </ol> <p>Step #4 causes a bad user experience. Your website basically stops loading until you've downloaded all scripts. If there's one thing that users hate it's waiting for a website to load.</p> <h2>Why does this even happen?</h2> <p>Any script can insert its own HTML via <code>document.write()</code> or other DOM manipulations. This implies that the parser has to wait until the script has been downloaded and executed before it can safely parse the rest of the document. After all, the script <em>could</em> have inserted its own HTML in the document.</p> <p>However, most JavaScript developers no longer manipulate the DOM <em>while</em> the document is loading. Instead, they wait until the document has been loaded before modifying it. For example:</p> <pre><code>&lt;!-- index.html --&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;My Page&lt;/title&gt; &lt;script src=&quot;my-script.js&quot;&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;user-greeting&quot;&gt;Welcome back, user&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>JavaScript:</p> <pre><code>// my-script.js document.addEventListener(&quot;DOMContentLoaded&quot;, function() { // this function runs when the DOM is ready, i.e. when the document has been parsed document.getElementById(&quot;user-greeting&quot;).textContent = &quot;Welcome back, Bart&quot;; }); </code></pre> <p>Because your browser does not know <em>my-script.js</em> isn't going to modify the document until it has been downloaded and executed, the parser stops parsing.</p> <h2>Antiquated recommendation</h2> <p>The old approach to solving this problem was to put <code>&lt;script&gt;</code> tags at the bottom of your <code>&lt;body&gt;</code>, because this ensures the parser isn't blocked until the very end.</p> <p>This approach has its own problem: the browser cannot start downloading the scripts until the entire document is parsed. For larger websites with large scripts and stylesheets, being able to download the script as soon as possible is very important for performance. If your website doesn't load within 2 seconds, people will go to another website.</p> <p>In an optimal solution, the browser would start downloading your scripts as soon as possible, while at the same time parsing the rest of your document.</p> <h2>The modern approach</h2> <p>Today, browsers support the <code>async</code> and <code>defer</code> attributes on scripts. These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.</p> <h3>async</h3> <pre><code>&lt;script src=&quot;path/to/script1.js&quot; async&gt;&lt;/script&gt; &lt;script src=&quot;path/to/script2.js&quot; async&gt;&lt;/script&gt; </code></pre> <p>Scripts with the async attribute are executed asynchronously. This means the script is executed as soon as it's downloaded, without blocking the browser in the meantime. This implies that it's possible that script 2 is downloaded and executed before script 1.</p> <p>According to <a href="http://caniuse.com/#feat=script-async" rel="noreferrer">http://caniuse.com/#feat=script-async</a>, 97.78% of all browsers support this.</p> <h3>defer</h3> <pre><code>&lt;script src=&quot;path/to/script1.js&quot; defer&gt;&lt;/script&gt; &lt;script src=&quot;path/to/script2.js&quot; defer&gt;&lt;/script&gt; </code></pre> <p>Scripts with the defer attribute are executed in order (i.e. first script 1, then script 2). This also does not block the browser.</p> <p>Unlike async scripts, defer scripts are only executed after the entire document has been loaded.</p> <p>According to <a href="http://caniuse.com/#feat=script-defer" rel="noreferrer">http://caniuse.com/#feat=script-defer</a>, 97.79% of all browsers support this. 98.06% support it at least partially.</p> <p>An important note on browser compatibility: in some circumstances, Internet Explorer 9 and earlier may execute deferred scripts out of order. If you need to support those browsers, please read <a href="https://github.com/h5bp/lazyweb-requests/issues/42" rel="noreferrer">this</a> first!</p> <p><em>(To learn more and see some really helpful visual representations of the differences between async, defer and normal scripts check the first two links at the references section of this answer)</em></p> <h1>Conclusion</h1> <p>The current state-of-the-art is to put scripts in the <code>&lt;head&gt;</code> tag and use the <code>async</code> or <code>defer</code> attributes. This allows your scripts to be downloaded ASAP without blocking your browser.</p> <p>The good thing is that your website should still load correctly on the 2% of browsers that do not support these attributes while speeding up the other 98%.</p> <h2>References</h2> <ul> <li><a href="https://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html" rel="noreferrer">async vs defer attributes</a></li> <li><a href="https://flaviocopes.com/javascript-async-defer/" rel="noreferrer">Efficiently load JavaScript with defer and async</a></li> <li><a href="https://developers.google.com/speed/docs/insights/BlockingJS" rel="noreferrer">Remove Render-Blocking JavaScript</a></li> <li><a href="https://gist.github.com/jakub-g/385ee6b41085303a53ad92c7c8afd7a6#visual-representation" rel="noreferrer">Async, Defer, Modules: A Visual Cheatsheet</a></li> </ul>
914,895
How to change credentials for SVN repository in Eclipse?
<p>I have Eclipse 3.4.2 installed on Windows with subclipse. Another developer added an SVN repository with his credentials and selected 'Save password'. Now every time I do anything with SVN his cached credentials are used. How can I change them to mine?</p> <p>I have already checked the 'workspace/.metadata/.plugins/org.tigris...' folders, and could not find any way to reset those cached credentials.</p>
914,926
21
0
null
2009-05-27 09:53:40.243 UTC
39
2021-05-19 10:04:47.32 UTC
2013-01-04 19:24:28.727 UTC
null
543,738
null
112,971
null
1
124
eclipse|svn|subclipse|subversive
262,083
<p><a href="http://subclipse.tigris.org/wiki/PluginFAQ#head-d507c29676491f4419997a76735feb6ef0aa8cf8" rel="noreferrer">http://subclipse.tigris.org/wiki/PluginFAQ#head-d507c29676491f4419997a76735feb6ef0aa8cf8</a>:</p> <blockquote> <p><strong>Usernames and passwords</strong></p> <p>Subclipse does not collect or store username and password credentials when defining a repository. This is because the JavaHL and SVNKit client adapters are intelligent enough to prompt you for this information when they need to -- including when your password has changed.</p> <p>You can also allow the adapter to cache this information and a common question is how do you delete this cached information so that you can be prompted again? We have an open request to have an API added to JavaHL so that we could provide a UI to do this. Currently, you have to manually delete the cache. The location of the cache varies based on the client adapter used.</p> <p>JavaHL caches the information in the same location as the command line client -- in the Subversion runtime configuration area. On Windows this is located in %APPDATA%\Subversion\auth. On Linux and OSX it is located in ~/.subversion/auth. Just find and delete the file with the cached information.</p> <p>SVNKit caches information in the Eclipse keyring. By default this is a file named .keyring that is stored in the root of the Eclipse configuration folder. Both of these values can be overriden with command line options. To clear the cache, you have to delete the file. Eclipse will create a new empty keyring when you restart</p> </blockquote>
1,106,377
Detect when a browser receives a file download
<p>I have a page that allows the user to download a dynamically-generated file. It takes a long time to generate, so I'd like to show a &quot;waiting&quot; indicator. The problem is, I can't figure out how to detect when the browser has received the file so that I can hide the indicator.</p> <p>I'm requesting a hidden form, which <a href="https://en.wikipedia.org/wiki/POST_%28HTTP%29" rel="noreferrer">POSTs</a> to the server, and targets a hidden iframe for its results. This is, so I don't replace the entire browser window with the result. I listen for a &quot;load&quot; event on the iframe, hoping that it will fire when the download is complete.</p> <p>I return a &quot;<code>Content-Disposition: attachment</code>&quot; header with the file, which causes the browser to show the &quot;Save&quot; dialog. But the browser doesn't fire a &quot;load&quot; event in the iframe.</p> <p>One approach I tried is using a <code>multi-part</code> response. So it would send an empty HTML file, as well as the attached downloadable file.</p> <p>For example:</p> <pre><code>Content-type: multipart/x-mixed-replace;boundary=&quot;abcde&quot; --abcde Content-type: text/html --abcde Content-type: application/vnd.fdf Content-Disposition: attachment; filename=foo.fdf file-content --abcde </code></pre> <p>This works in Firefox; it receives the empty HTML file, fires the <em>&quot;load&quot;</em> event, and then shows the <em>&quot;Save&quot;</em> dialog for the downloadable file. But it fails on <a href="https://en.wikipedia.org/wiki/Internet_Explorer" rel="noreferrer">Internet Explorer</a> and <a href="https://en.wikipedia.org/wiki/Safari_%28web_browser%29" rel="noreferrer">Safari</a>; Internet Explorer fires the &quot;load&quot; event, but it doesn't download the file, and <em>Safari downloads</em> the file (with the wrong name and content-type) and doesn't fire the <em>&quot;load&quot;</em> event.</p> <p>A different approach might be to call to start the file creation, poll the server until it's ready, and then download the already-created file. But I'd rather avoid creating temporary files on the server.</p> <p>What should I do?</p>
4,168,965
24
8
null
2009-07-09 20:51:12.227 UTC
218
2022-04-27 09:40:59.343 UTC
2022-01-11 02:15:11.13 UTC
null
63,550
null
4,321
null
1
557
javascript|http|mime
401,679
<p>One <a href="http://gruffcode.com/2010/10/28/detecting-the-file-download-dialog-in-the-browser/" rel="noreferrer">possible solution</a> uses JavaScript on the client.</p> <p>The client algorithm:</p> <ol> <li>Generate a random unique token.</li> <li>Submit the download request, and include the token in a GET/POST field.</li> <li>Show the "waiting" indicator.</li> <li>Start a timer, and every second or so, look for a cookie named "fileDownloadToken" (or whatever you decide).</li> <li>If the cookie exists, and its value matches the token, hide the "waiting" indicator.</li> </ol> <p>The server algorithm:</p> <ol> <li>Look for the GET/POST field in the request.</li> <li>If it has a non-empty value, drop a cookie (e.g. "fileDownloadToken"), and set its value to the token's value.</li> </ol> <hr> <p>Client source code (JavaScript):</p> <pre><code>function getCookie( name ) { var parts = document.cookie.split(name + "="); if (parts.length == 2) return parts.pop().split(";").shift(); } function expireCookie( cName ) { document.cookie = encodeURIComponent(cName) + "=deleted; expires=" + new Date( 0 ).toUTCString(); } function setCursor( docStyle, buttonStyle ) { document.getElementById( "doc" ).style.cursor = docStyle; document.getElementById( "button-id" ).style.cursor = buttonStyle; } function setFormToken() { var downloadToken = new Date().getTime(); document.getElementById( "downloadToken" ).value = downloadToken; return downloadToken; } var downloadTimer; var attempts = 30; // Prevents double-submits by waiting for a cookie from the server. function blockResubmit() { var downloadToken = setFormToken(); setCursor( "wait", "wait" ); downloadTimer = window.setInterval( function() { var token = getCookie( "downloadToken" ); if( (token == downloadToken) || (attempts == 0) ) { unblockSubmit(); } attempts--; }, 1000 ); } function unblockSubmit() { setCursor( "auto", "pointer" ); window.clearInterval( downloadTimer ); expireCookie( "downloadToken" ); attempts = 30; } </code></pre> <p>Example server code (PHP):</p> <pre><code>$TOKEN = "downloadToken"; // Sets a cookie so that when the download begins the browser can // unblock the submit button (thus helping to prevent multiple clicks). // The false parameter allows the cookie to be exposed to JavaScript. $this-&gt;setCookieToken( $TOKEN, $_GET[ $TOKEN ], false ); $result = $this-&gt;sendFile(); </code></pre> <p>Where:</p> <pre><code>public function setCookieToken( $cookieName, $cookieValue, $httpOnly = true, $secure = false ) { // See: http://stackoverflow.com/a/1459794/59087 // See: http://shiflett.org/blog/2006/mar/server-name-versus-http-host // See: http://stackoverflow.com/a/3290474/59087 setcookie( $cookieName, $cookieValue, 2147483647, // expires January 1, 2038 "/", // your path $_SERVER["HTTP_HOST"], // your domain $secure, // Use true over HTTPS $httpOnly // Set true for $AUTH_COOKIE_NAME ); } </code></pre>
1,017,624
When is a function name too long?
<p>I try to be rather descriptive with my function names, where possible. This occasionally results in function names in the twenty to thirty character range such as <code>GetActionFromTypeName</code> or <code>GetSelectedActionType</code>. At what point do functions get too long to manage (not too long for the compiler)?</p>
1,017,638
27
9
2009-06-19 12:15:54.81 UTC
2009-06-19 12:12:22.04 UTC
6
2021-02-05 09:24:05.45 UTC
2021-02-05 09:24:05.45 UTC
null
2,287,576
null
16,487
null
1
49
language-agnostic|naming-conventions
24,760
<p>If there's a shorter, but yet descriptive way to name the function, then the function name is too long.</p>
905,551
Are there any O(1/n) algorithms?
<p>Are there any O(1/n) algorithms?</p> <p>Or anything else which is less than O(1)? </p>
905,832
31
6
2010-07-09 01:14:17.793 UTC
2009-05-25 06:15:28.03 UTC
136
2021-01-24 22:40:04.077 UTC
2010-07-10 11:57:02.92 UTC
null
334,220
null
14,559
null
1
355
theory|complexity-theory|big-o
70,804
<p>This question isn't as silly as it might seem to some. At least theoretically, something such as <em>O</em>(1/<em>n</em>) is completely sensible when we take the mathematical definition of the <a href="http://en.wikipedia.org/wiki/Big_O_notation" rel="noreferrer">Big O notation</a>:</p> <p><img src="https://i.stack.imgur.com/9ii3q.png" alt="" /></p> <p>Now you can easily substitute <em>g</em>(<em>x</em>) for 1/<em>x</em> … it's obvious that the above definition still holds for some <em>f</em>.</p> <p>For the purpose of estimating asymptotic run-time growth, this is less viable … a meaningful algorithm cannot get faster as the input grows. Sure, you can construct an arbitrary algorithm to fulfill this, e.g. the following one:</p> <pre class="lang-py prettyprint-override"><code>def get_faster(list): how_long = (1 / len(list)) * 100000 sleep(how_long) </code></pre> <p>Clearly, this function spends less time as the input size grows … at least until some limit, enforced by the hardware (precision of the numbers, minimum of time that <code>sleep</code> can wait, time to process arguments etc.): this limit would then be a constant lower bound so in fact the above function <em>still</em> has runtime <em>O</em>(1).</p> <p>But there <em>are</em> in fact real-world algorithms where the runtime can decrease (at least partially) when the input size increases. Note that these algorithms will <em>not</em> exhibit runtime behaviour below <em>O</em>(1), though. Still, they are interesting. For example, take the very simple text search algorithm by <a href="https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm" rel="noreferrer">Horspool</a>. Here, the expected runtime will decrease as the length of the search pattern increases (but increasing length of the haystack will once again increase runtime).</p>
685,060
design a stack such that getMinimum( ) should be O(1)
<p>This is an interview question.</p> <blockquote> <p>You need to design a stack which holds an integer value such that <code>getMinimum()</code> function should return the minimum element in the stack.</p> <p>For example:</p> <blockquote> <p>case #1</p> <p>5 ← TOP<br /> 1<br /> 4<br /> 6<br /> 2</p> <p>When getMinimum() is called it should return 1, which is the minimum element in the stack.</p> <p>case #2</p> <p><code>stack.pop()</code><br /> <code>stack.pop()</code></p> <p>Note: Both 5 and 1 are popped out of the stack. So after this, the stack looks like</p> <p>4 ← TOP<br /> 6<br /> 2</p> <p>When <code>getMinimum()</code> is called it should return 2 which is the minimum in the stack.</p> </blockquote> <p><strong>Constraints:</strong></p> <ol> <li>getMinimum should return the minimum value in O(1)</li> <li>Space constraint also has to be considered while designing it and if you use extra space, it should be of constant space.</li> </ol> </blockquote>
685,074
31
1
null
2009-03-26 09:29:17.827 UTC
93
2021-03-28 15:02:24.807 UTC
2021-03-28 14:31:52.437 UTC
null
3,789,665
Ganesh M
43,502
null
1
124
algorithm|language-agnostic|data-structures|stack
116,312
<p>EDIT: This fails the "constant space" constraint - it basically doubles the space required. I very much doubt that there's a solution which <em>doesn't</em> do that though, without wrecking the runtime complexity somewhere (e.g. making push/pop O(n)). Note that this doesn't change the <em>complexity</em> of the space required, e.g. if you've got a stack with O(n) space requirements, this will still be O(n) just with a different constant factor.</p> <p><strong>Non-constant-space solution</strong></p> <p>Keep a "duplicate" stack of "minimum of all values lower in the stack". When you pop the main stack, pop the min stack too. When you push the main stack, push either the new element or the current min, whichever is lower. <code>getMinimum()</code> is then implemented as just <code>minStack.peek()</code>.</p> <p>So using your example, we'd have:</p> <pre><code>Real stack Min stack 5 --&gt; TOP 1 1 1 4 2 6 2 2 2 </code></pre> <p>After popping twice you get:</p> <pre><code>Real stack Min stack 4 2 6 2 2 2 </code></pre> <p>Please let me know if this isn't enough information. It's simple when you grok it, but it might take a bit of head-scratching at first :)</p> <p>(The downside of course is that it doubles the space requirement. Execution time doesn't suffer significantly though - i.e. it's still the same complexity.)</p> <p>EDIT: There's a variation which is slightly more fiddly, but has better space in general. We still have the min stack, but we only pop from it when the value we pop from the main stack is equal to the one on the min stack. We only <em>push</em> to the min stack when the value being pushed onto the main stack is less than <em>or equal</em> to the current min value. This allows duplicate min values. <code>getMinimum()</code> is still just a peek operation. For example, taking the original version and pushing 1 again, we'd get:</p> <pre><code>Real stack Min stack 1 --&gt; TOP 1 5 1 1 2 4 6 2 </code></pre> <p>Popping from the above pops from both stacks because 1 == 1, leaving:</p> <pre><code>Real stack Min stack 5 --&gt; TOP 1 1 2 4 6 2 </code></pre> <p>Popping again <em>only</em> pops from the main stack, because 5 > 1:</p> <pre><code>Real stack Min stack 1 1 4 2 6 2 </code></pre> <p>Popping again pops both stacks because 1 == 1:</p> <pre><code>Real stack Min stack 4 2 6 2 </code></pre> <p>This ends up with the same worst case space complexity (double the original stack) but much better space usage if we rarely get a "new minimum or equal".</p> <p>EDIT: Here's an implementation of Pete's evil scheme. I haven't tested it thoroughly, but I <em>think</em> it's okay :)</p> <pre><code>using System.Collections.Generic; public class FastMinStack&lt;T&gt; { private readonly Stack&lt;T&gt; stack = new Stack&lt;T&gt;(); // Could pass this in to the constructor private readonly IComparer&lt;T&gt; comparer = Comparer&lt;T&gt;.Default; private T currentMin; public T Minimum { get { return currentMin; } } public void Push(T element) { if (stack.Count == 0 || comparer.Compare(element, currentMin) &lt;= 0) { stack.Push(currentMin); stack.Push(element); currentMin = element; } else { stack.Push(element); } } public T Pop() { T ret = stack.Pop(); if (comparer.Compare(ret, currentMin) == 0) { currentMin = stack.Pop(); } return ret; } } </code></pre>
6,327,631
Displaying an image on Javascript function call !
<p>I am a javascript noob and I need help with this problem !</p> <p>On a specific condition a function is called and when it is called , I want an image to be displayed ! How do I do that ? this is not working!</p> <pre><code>&lt;script type="text/javascript"&gt; function _enabled() { document.write("&lt;img border="0" src="http://4.bp.blogspot.com/-C4vvMEB9MyI/TfW0lduV2NI/AAAAAAAAAZc/N7HL1pUusGw/s1600/some image.png" /&gt;"); } var r =true; &lt;/script&gt; </code></pre> <p>This is not working , I get this error</p> <pre><code>Error: missing ) after argument list Source File: file:///C:/Users/Gowtham/Desktop/new%20%202.html Line: 5, Column: 33 Source Code: document.write("&lt;img border="0" src="http://4.bp.blogspot.com/-C4vvMEB9MyI/TfW0lduV2NI/AAAAAAAAAZc/N7HL1pUusGw/s1600/sjs.png" /&gt;"); </code></pre>
6,327,694
5
0
null
2011-06-13 07:22:24.203 UTC
null
2011-06-13 07:39:07.247 UTC
null
null
null
null
787,563
null
1
1
javascript|function|image
44,341
<p>The syntax error is that you're using double quotes for your <code>document.write</code> string literal, but you've also used a double quotes your HTML attributes:</p> <pre><code>document.write("&lt;img border="0" src="http://4.bp.blogspot.com/-C4vvMEB9MyI/TfW0lduV2NI/AAAAAAAAAZc/N7HL1pUusGw/s1600/some image.png" /&gt;"); // ^--- here and other places </code></pre> <p>That double quote ends the string literal, so you get a syntax error. You'd want to escape that with a backslash, or use JavaScript's handy feature where you can use single quotes around string literals.</p> <p>But that alone isn't going to solve the problem. If you call <code>document.write</code> after the main parsing of the page is finished, you're going to completely erase the page and <em>replace</em> it with new content.</p> <p>To display an image after the main parsing of the page is complete, you create a new <code>img</code> element via the DOM <code>document.createElement</code> function and then append it to the element in which you want it to appear. For instance, this code puts a new image at the end of the document:</p> <pre><code>function addTheImage() { var img = document.createElement('img'); img.src = "http://...."; document.body.appendChild(img); } </code></pre> <p>To add to another element, rather than the end of <code>body</code>, you just need to get a reference to the element. There are various ways to do that, including <code>document.getElementById</code> to look it up by its <code>id</code> value, <code>document.getElementsByTagName</code> to look up all elements with a given tag, etc. Some browsers offer very rich methods like <code>querySelectorAll</code> that let you use CSS selectors, but not all do yet. (Many JavaScript libraries like <a href="http://jquery.com" rel="noreferrer">jQuery</a>, <a href="http://prototypejs.org" rel="noreferrer">Prototype</a>, <a href="http://developer.yahoo.com/yui/" rel="noreferrer">YUI</a>, <a href="http://code.google.com/closure/library" rel="noreferrer">Closure</a>, or <a href="http://en.wikipedia.org/wiki/List_of_JavaScript_libraries" rel="noreferrer">any of several others</a> plug that gap for you, though, and offer other handy utility features, and features smoothing over browser inconsistencies and outright browser bugs.)</p> <p>More about the dom:</p> <ul> <li>The <a href="http://www.w3.org/TR/DOM-Level-2-Core/" rel="noreferrer">DOM2 Core specification</a> (widely supported by major browsers)</li> <li>The <a href="http://www.w3.org/TR/DOM-Level-2-HTML/" rel="noreferrer">DOM2 HTML specification</a> (DOM stuff specific to HTML, also fairly widely supported)</li> <li>The <a href="http://www.w3.org/TR/DOM-Level-3-Core/" rel="noreferrer">DOM3 Core specificiation</a> (less widely supported, but things are improving)</li> </ul>
6,496,866
Best way to do a weighted search over multiple fields in mysql?
<p>Here's what i want to do:</p> <ul> <li>match a search subject against multiple fields of my table</li> <li>order the results by importance of the field and relevance of the matching (in that order)</li> </ul> <p>Ex: let's assume I have a blog. Then someone searches for "php". The results would appear that way:</p> <ul> <li>first, the matches for the field 'title', ordered by relevance</li> <li>then, the matches for the field 'body', ordered by relevance too</li> <li>and so on with the specified fields...</li> </ul> <p>I actually did this with a class in PHP but it uses a lot of UNIONS (a lot!) and grows with the size of the search subject. So I'm worried about performance and DOS issues. Does anybody has a clue on this?</p>
6,496,964
6
0
null
2011-06-27 17:52:57.83 UTC
17
2020-06-25 09:14:55.47 UTC
2014-11-17 17:55:07.537 UTC
null
434,293
null
434,293
null
1
25
php|mysql|search
11,575
<p>Probably this approach of doing a weighted search / results is suitable for you:</p> <pre><code>SELECT *, IF( `name` LIKE "searchterm%", 20, IF(`name` LIKE "%searchterm%", 10, 0) ) + IF(`description` LIKE "%searchterm%", 5, 0) + IF(`url` LIKE "%searchterm%", 1, 0) AS `weight` FROM `myTable` WHERE ( `name` LIKE "%searchterm%" OR `description` LIKE "%searchterm%" OR `url` LIKE "%searchterm%" ) ORDER BY `weight` DESC LIMIT 20 </code></pre> <p>It uses a select subquery to provide the weight for ordering the results. In this case three fields searched over, you can specify a weight per field. It's probably less expensive than unions and probably one of the faster ways in plain MySQL only.</p> <p>If you've got more data and need results faster, you can consider using something like Sphinx or Lucene.</p>
6,452,731
Remove '&nbsp;' - still trying
<p>Still looking for a way to delete <code>'&amp;nbsp;'</code> from my html code, found number of ways on stackoverlow.com, but neither of those seam to work!</p> <p><strong>HTML</strong></p> <pre><code>&lt;p&gt;No Space&lt;/p&gt; &lt;p&gt;&amp;nbsp;1 Space&lt;/p&gt; &lt;p&gt;&amp;nbsp;&amp;nbsp;2 Spaces&lt;/p&gt; &lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;3 Spaces&lt;/p&gt; &lt;p&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;4 Spaces&lt;/p&gt; </code></pre> <p><strong>jQuery</strong></p> <pre><code>$(document).ready(function() { $('p').text().replace(/ /g, ''); //$('p').html($(this).html().replace(/&amp;nbsp;/gi,'')); }); </code></pre> <p><strong>jsfiddle - playground</strong> <a href="http://jsfiddle.net/MrTest/hbvjQ/85/" rel="noreferrer">http://jsfiddle.net/MrTest/hbvjQ/85/</a></p> <p>Any help much appreciated.<br /> Pete</p>
6,452,789
6
4
null
2011-06-23 10:41:25.837 UTC
7
2016-05-27 14:34:28.9 UTC
2016-05-27 14:25:06.843 UTC
null
3,518,452
null
616,643
null
1
26
javascript|jquery|string|whitespace|html-entities
65,292
<p>You have &amp;nbsp in your code instead of <code>&amp;nbsp;</code></p> <pre><code>$('p').each(function(){ $(this).html($(this).html().replace(/&amp;nbsp;/gi,'')); }); </code></pre> <p><a href="http://jsfiddle.net/genesis/hbvjQ/76/" rel="noreferrer">http://jsfiddle.net/genesis/hbvjQ/76/</a></p>
6,594,014
javascript innerHTML adding instead of replacing
<p>quick question, i know we can <strong>change</strong> the content of a</p> <p><code>&lt;div id="whatEverId"&gt;hello one&lt;div&gt;</code> by using:</p> <pre><code>document.getElementById("whatEverId").innerHTML="hello two"; </code></pre> <p>now, is there a way I can <strong>ADD</strong> stuff to the div instead of replacing it??? so i can get </p> <p><code>&lt;div id="whatEverId"&gt;hello one hello two&lt;div&gt;</code></p> <p><em>(using something similar of course)</em></p>
6,594,082
6
0
null
2011-07-06 09:11:47.44 UTC
10
2022-07-12 23:01:49.387 UTC
2018-06-14 18:34:52.667 UTC
user4639281
null
null
827,499
null
1
31
javascript|ajax|dom|innerhtml
67,326
<pre><code>&lt;div id="whatever"&gt;hello one&lt;/div&gt; &lt;script&gt; document.getElementById("whatever").innerHTML += " hello two"; &lt;/script&gt; </code></pre>
6,588,265
jQuery Select first and second td
<p>How can I add a class to the first and second td in each tr?</p> <pre><code>&lt;div class='location'&gt; &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;THIS ONE&lt;/td&gt; &lt;td&gt;THIS ONE&lt;/td&gt; &lt;td&gt;else&lt;/td&gt; &lt;td&gt;here&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;THIS ONE&lt;/td&gt; &lt;td&gt;THIS ONE&lt;/td&gt; &lt;td&gt;else&lt;/td&gt; &lt;td&gt;here&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>For the first td, this does nothing?</p> <pre><code>$(".location table tbody tr td:first-child").addClass("black"); </code></pre> <p>Can I also use second-child?</p>
6,588,327
7
2
null
2011-07-05 20:08:42.58 UTC
10
2018-12-14 21:33:11.727 UTC
null
null
null
null
149,664
null
1
47
jquery
167,027
<pre><code>$(".location table tbody tr td:first-child").addClass("black"); $(".location table tbody tr td:nth-child(2)").addClass("black"); </code></pre> <p><a href="http://jsfiddle.net/68wbx/1/" rel="noreferrer">http://jsfiddle.net/68wbx/1/</a></p>
38,105,507
When should I ever use file.read() or file.readlines()?
<p>I noticed that if I iterate over a file that I opened, it is much faster to iterate over it without "read"-ing it. </p> <p>i.e. </p> <pre><code>l = open('file','r') for line in l: pass (or code) </code></pre> <p>is much faster than </p> <pre><code>l = open('file','r') for line in l.read() / l.readlines(): pass (or code) </code></pre> <p>The 2nd loop will take around 1.5x as much time (I used timeit over the exact same file, and the results were 0.442 vs. 0.660), and would give the same result. </p> <p>So - when should I ever use the .read() or .readlines()? </p> <p>Since I always need to iterate over the file I'm reading, and after learning the hard way how painfully slow the .read() can be on large data - I can't seem to imagine ever using it again. </p>
38,105,733
5
2
null
2016-06-29 16:39:42.813 UTC
24
2021-12-01 17:41:49.613 UTC
2018-06-21 19:24:37.19 UTC
null
6,862,601
null
6,296,435
null
1
41
python|io|timeit
89,705
<p>The short answer to your question is that each of these three methods of reading bits of a file have different use cases. As noted above, <code>f.read()</code> reads the file as an individual string, and so allows relatively easy file-wide manipulations, such as a file-wide regex search or substitution.</p> <p><code>f.readline()</code> reads a single line of the file, allowing the user to parse a single line without necessarily reading the entire file. Using <code>f.readline()</code> also allows easier application of logic in reading the file than a complete line by line iteration, such as when a file changes format partway through.</p> <p>Using the syntax <code>for line in f:</code> allows the user to iterate over the file line by line as noted in the question.</p> <p>(As noted in the other answer, this documentation is a very good read):</p> <p><a href="https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects" rel="noreferrer">https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects</a></p> <p>Note: It was previously claimed that <code>f.readline()</code> could be used to skip a line during a for loop iteration. However, this doesn't work in Python 2.7, and is perhaps a questionable practice, so this claim has been removed.</p>
15,556,813
Why is cmp( ) useful?
<p>According to the <a href="http://docs.python.org/2/library/functions.html#cmp" rel="nofollow noreferrer">doc</a> and this <a href="http://www.tutorialspoint.com/python/number_cmp.htm" rel="nofollow noreferrer">tutorial</a>,</p> <p><code>cmp() returns -1 if x &lt; y</code> </p> <p>and </p> <p><code>cmp() returns 0 if x == y</code> </p> <p>and </p> <p><code>cmp() returns 1 if x &gt; y</code> </p> <p>The tutorial also said that</p> <blockquote> <p>cmp() returns the sign of the difference of two numbers</p> </blockquote> <p>I don't really get what <em>sign of the difference of two numbers</em> means. Doesn't that mean that it returns a value when the sign of numbers aren't equal? Since...</p> <pre><code>cmp(80, 100) : -1 # both have positive sign. cmp(180, 100) : 1 # both also have positive sign. cmp(-80, 100) : -1 cmp(80, -100) : 1 </code></pre> <p>**Note: code from the tutorial.*</p> <p>Despite my confusion in sign differences, I can't really think of why do we need a built-in function to return a value of -1 when x &lt; y. </p> <p>Isn't the function <strong><code>cmp( )</code></strong> easily implemented ? Is there any reason why Python creators keep <code>cmp( )</code> function, or is there any hidden usage of this Python's <strong><code>cmp( )</code></strong> function ?</p>
26,515,234
5
0
null
2013-03-21 19:54:34.86 UTC
4
2020-04-06 05:55:48.92 UTC
2020-04-06 05:55:48.92 UTC
null
6,862,601
null
1,031,955
null
1
23
python
41,916
<blockquote> <h1>Why cmp( ) is useful?</h1> </blockquote> <p>It isn't very useful, which is why it was deprecated (the builtin <code>cmp</code> is gone and builtin sorts no longer accept one in Python 3). <a href="https://docs.python.org/3/reference/datamodel.html#object.__lt__" rel="noreferrer">Rich comparison methods</a> supplanted it:</p> <pre><code>object.__lt__(self, other) object.__le__(self, other) object.__eq__(self, other) object.__ne__(self, other) object.__gt__(self, other) object.__ge__(self, other) </code></pre> <p>This allows the <code>&lt;</code> symbol (and other symbols) to be overloaded comparison operators, enabling, for example, subset and superset comparisons of set objects.</p> <pre><code>&gt;&gt;&gt; set('abc') &lt; set('cba') False &gt;&gt;&gt; set('abc') &lt;= set('cba') True &gt;&gt;&gt; set('abc') == set('cba') True &gt;&gt;&gt; set('abc') &gt;= set('cba') True &gt;&gt;&gt; set('abc') &gt; set('cba') False </code></pre> <p>while it could enable the above, <code>cmp</code> wouldn't allow the following:</p> <pre><code>&gt;&gt;&gt; set('abc') == set('bcd') False &gt;&gt;&gt; set('abc') &gt;= set('bcd') False &gt;&gt;&gt; set('abc') &lt;= set('bcd') False </code></pre> <h2>Toy usage for <code>cmp</code></h2> <p>Here's an interesting usage which uses its result as an index (it returns -1 if the first is less than the second, 0 if equal, and 1 if greater than):</p> <pre><code>def cmp_to_symbol(val, other_val): '''returns the symbol representing the relationship between two values''' return '=&gt;&lt;'[cmp(val, other_val)] &gt;&gt;&gt; cmp_to_symbol(0, 1) '&lt;' &gt;&gt;&gt; cmp_to_symbol(1, 1) '=' &gt;&gt;&gt; cmp_to_symbol(1, 0) '&gt;' </code></pre> <p>According to the docs, you should treat cmp as if it wasn't there:</p> <p><a href="https://docs.python.org/3/whatsnew/3.0.html#ordering-comparisons" rel="noreferrer">https://docs.python.org/3/whatsnew/3.0.html#ordering-comparisons</a></p> <h2><code>cmp</code> removed, equivalent operation</h2> <p>But you can use this as the equivalent:</p> <pre><code>(a &gt; b) - (a &lt; b) </code></pre> <p>in our little toy function, that's this:</p> <pre><code>def cmp_to_symbol(val, other_val): '''returns the symbol representing the relationship between two values''' return '=&gt;&lt;'[(val &gt; other_val) - (val &lt; other_val)] </code></pre>
50,835,303
2 column layout with flexBox on React Native
<p>I'm trying to do a two column layout in React Native from a list of items. It only seems to work if I define the width of the items, I would like to define just a percentage of the parent width (0.5 would make a 2 column layout, but 0.25 would make a 4 column one). Can this be done?</p> <pre class="lang-js prettyprint-override"><code>export default class App extends Component { render() { return ( &lt;View style={[styles.container, {width:width}]}&gt; &lt;View style={styles.item}&gt;&lt;Text&gt;{'item1'}&lt;/Text&gt;&lt;/View&gt; &lt;View style={styles.item}&gt;&lt;Text&gt;{'item2'}&lt;/Text&gt;&lt;/View&gt; &lt;View style={styles.item}&gt;&lt;Text&gt;{'item3'}&lt;/Text&gt;&lt;/View&gt; &lt;View style={styles.item}&gt;&lt;Text&gt;{'item4'}&lt;/Text&gt;&lt;/View&gt; &lt;View style={styles.item}&gt;&lt;Text&gt;{'item4'}&lt;/Text&gt;&lt;/View&gt; &lt;View style={styles.item}&gt;&lt;Text&gt;{'item5'}&lt;/Text&gt;&lt;/View&gt; &lt;/View&gt; ); } } const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'row', flexWrap: 'wrap', }, item :{ flex: 0.5, //why this doesnt work??? // width: 150, //using fixed item width instead of flex: 0.5 works height: 100, padding: 10, backgroundColor: 'red', // flexGrow: 1, // flexShrink: 0, } }); </code></pre> <p>You can play with it here: <a href="https://snack.expo.io/SyBjQuRxm" rel="noreferrer">https://snack.expo.io/SyBjQuRxm</a></p> <p>Css working equivalent: <a href="https://codepen.io/klamping/pen/WvvgBX?editors=110" rel="noreferrer">https://codepen.io/klamping/pen/WvvgBX?editors=110</a></p> <p>Obviously I could do something like creating a container for each column, but that's not the point:</p> <pre class="lang-js prettyprint-override"><code>render() { return ( &lt;View style={[styles.container, {width:width}]}&gt; &lt;View style={styles.column1}&gt; &lt;View style={styles.item}&gt;&lt;Text&gt;{'item1'}&lt;/Text&gt;&lt;/View&gt; &lt;View style={styles.item}&gt;&lt;Text&gt;{'item2'}&lt;/Text&gt;&lt;/View&gt; &lt;View style={styles.item}&gt;&lt;Text&gt;{'item3'}&lt;/Text&gt;&lt;/View&gt; &lt;/View&gt; &lt;View style={styles.column2}&gt; &lt;View style={styles.item}&gt;&lt;Text&gt;{'item4'}&lt;/Text&gt;&lt;/View&gt; &lt;View style={styles.item}&gt;&lt;Text&gt;{'item4'}&lt;/Text&gt;&lt;/View&gt; &lt;View style={styles.item}&gt;&lt;Text&gt;{'item5'}&lt;/Text&gt;&lt;/View&gt; &lt;/View&gt; &lt;/View&gt; ); } </code></pre>
50,835,908
2
1
null
2018-06-13 10:48:20.25 UTC
7
2021-08-12 13:59:47.193 UTC
2018-06-13 12:22:09.453 UTC
null
5,068,574
null
1,488,518
null
1
36
react-native|flexbox
68,525
<p>It is possible if you use percentage values for the widths:</p> <pre class="lang-js prettyprint-override"><code>&lt;View style={styles.container}&gt; &lt;View style={styles.item}&gt; ... &lt;/View&gt; &lt;/View&gt; const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'row', flexWrap: 'wrap', alignItems: 'flex-start' // if you want to fill rows left to right }, item: { width: '50%' // is 50% of container width } }) </code></pre>
10,742,749
Get name of function using reflection
<p>I'm trying to use Go's reflection system to retrieve the name of a function but I get an empty string when calling the Name method on its type. Is this the expected behavior?</p> <p>This is a simple example of how I approach the problem:</p> <pre><code>package main import "fmt" import "reflect" func main() { typ := reflect.TypeOf(main) name := typ.Name() fmt.Println("Name of function" + name) } </code></pre>
10,742,933
4
3
null
2012-05-24 17:51:32.32 UTC
10
2021-10-22 16:24:37.283 UTC
2019-11-25 21:46:04.72 UTC
user6169399
13,860
null
11,758
null
1
24
go|reflection|go-reflect
17,114
<p>The solution is to use <a href="http://golang.org/pkg/runtime/#FuncForPC" rel="noreferrer">FuncForPc</a> which returns a <code>*Func</code>.</p> <p>This returns <code>"main.main"</code> :</p> <pre><code>package main import "fmt" import "reflect" import "runtime" func main() { name := runtime.FuncForPC(reflect.ValueOf(main).Pointer()).Name() fmt.Println("Name of function : " + name) } </code></pre> <p>If you want <code>"main"</code>, just tokenize it.</p>
31,870,206
How to insert new cell into UITableView in Swift
<p>I'm working on a project where I have two <code>UITableView</code>s and two <code>UITextField</code>s, when the user presses the button the data in the first <code>textField</code> should go into the <code>tableView</code> and the second go into the second <code>tableView</code>. My problem is that I don't know how to put data in the <code>tableView</code> each time the user pushes the button, I know how to insert data with <code>tableView:cellForRowAtIndexPath:</code> but that works for one time as far as I know. So what method can I use to update the <code>tableView</code> each time the user hits the button?</p>
31,870,301
5
2
null
2015-08-07 05:19:11.533 UTC
34
2021-09-10 11:52:16.47 UTC
2015-09-04 10:51:12.483 UTC
null
4,601,170
null
5,108,131
null
1
80
ios|iphone|swift|uitableview
150,738
<p>Use <code>beginUpdates</code> and <code>endUpdates</code> to insert a new cell when the button clicked.</p> <blockquote> <p>As @vadian said in comment, <code>begin/endUpdates</code> has no effect for a single insert/delete/move operation</p> </blockquote> <p>First of all, append data in your tableview array</p> <pre><code>Yourarray.append([labeltext]) </code></pre> <p>Then update your table and insert a new row</p> <pre><code>// Update Table Data tblname.beginUpdates() tblname.insertRowsAtIndexPaths([ NSIndexPath(forRow: Yourarray.count-1, inSection: 0)], withRowAnimation: .Automatic) tblname.endUpdates() </code></pre> <p>This inserts cell and doesn't need to reload the whole table but if you get any problem with this, you can also use <code>tableview.reloadData()</code></p> <hr /> <p><strong>Swift 3.0</strong></p> <pre><code>tableView.beginUpdates() tableView.insertRows(at: [IndexPath(row: yourArray.count-1, section: 0)], with: .automatic) tableView.endUpdates() </code></pre> <hr /> <p><strong>Objective-C</strong></p> <pre><code>[self.tblname beginUpdates]; NSArray *arr = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:Yourarray.count-1 inSection:0]]; [self.tblname insertRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationAutomatic]; [self.tblname endUpdates]; </code></pre>
31,784,519
Show number of notifications on icon
<p>I have a notification icon (<a href="/questions/tagged/font-awesome" class="post-tag" title="show questions tagged &#39;font-awesome&#39;" rel="tag">font-awesome</a>) which shows the number of notifications.</p> <p>I am having a problem trying to get the number to display in the correct position, as shown in see below image</p> <p><a href="https://i.stack.imgur.com/3xIJW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3xIJW.png" alt="enter image description here"></a></p> <p>I need the text to be smaller and move right and up a little... here is the code</p> <pre><code>.header .bubble { border-radius: 100%; height: 14px; width: 14px; background-color: rgba(226, 32, 91, 0.77); color: #ffffff; text-align: top; position: relative; top: 0px; float: right; right: -3px; } &lt;a href="javascript:;" id="notification-center" class="icon-set globe-fill" data-toggle="dropdown"&gt;&lt;span class="bubble"&gt;2&lt;/span&gt; </code></pre> <p>Can anyone help, I am new to this.</p>
31,784,825
1
4
null
2015-08-03 10:00:59.28 UTC
5
2017-11-03 05:59:16.02 UTC
2015-08-03 11:57:31.893 UTC
null
3,540,289
null
3,092,953
null
1
18
html|css|css-position|font-awesome
43,536
<h3>example1: using background image</h3> <p>The best way to do this is to use <code>position:absolute</code> to child span of parent anchor.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>a.notif { position: relative; display: block; height: 50px; width: 50px; background: url('http://i.imgur.com/evpC48G.png'); background-size: contain; text-decoration: none; } .num { position: absolute; right: 11px; top: 6px; color: #fff; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;a href="" class="notif"&gt;&lt;span class="num"&gt;2&lt;/span&gt;&lt;/a&gt;</code></pre> </div> </div> </p> <h3>example2: using font awesome icon</h3> <p>If you want to use <a href="/questions/tagged/font-awesome" class="post-tag" title="show questions tagged &#39;font-awesome&#39;" rel="tag">font-awesome</a> icon</p> <p>this is code for it</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>a.fa-globe { position: relative; font-size: 2em; color: grey; cursor: pointer; } span.fa-comment { position: absolute; font-size: 0.6em; top: -4px; color: red; right: -4px; } span.num { position: absolute; font-size: 0.3em; top: 1px; color: #fff; right: 2px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /&gt; &lt;a class="fa fa-globe"&gt; &lt;span class="fa fa-comment"&gt;&lt;/span&gt; &lt;span class="num"&gt;2&lt;/span&gt; &lt;/a&gt;</code></pre> </div> </div> </p>
10,754,665
Change column types in a huge table
<p>I have a table in SQL Server 2008 R2 with close to a billion rows. I want to change the datatype of two columns from int to bigint. Two times <code>ALTER TABLE zzz ALTER COLUMN yyy</code> works, but it's very slow. How can I speed the process up? I was thinking to copy the data to another table, drop, create, copy back and switching to simple recovery mode or somehow doing it with a cursor a 1000 rows a time but I'm not sure if those will actually lead to any improvement.</p>
10,754,753
3
8
null
2012-05-25 12:43:47.42 UTC
9
2022-04-06 07:15:34.883 UTC
null
null
null
null
1,417,408
null
1
24
sql|sql-server|sql-server-2008|sql-server-2008-r2
29,207
<p>Depending on what change you are making, sometimes it can be easier to take a maintenance window. During that window (where nobody should be able to change the data in the table) you can:</p> <ol> <li>drop any indexes/constraints pointing to the old column, and disable triggers</li> <li>add a new <em>nullable</em> column with the new data type (even if it is meant to be NOT NULL)</li> <li>update the new column setting it equal to the old column's value (and you can do this in chunks of individual transactions (say, affecting 10000 rows at a time using <code>UPDATE TOP (10000) ... SET newcol = oldcol WHERE newcol IS NULL</code>) and with CHECKPOINT to avoid overrunning your log)</li> <li>once the updates are all done, drop the old column</li> <li>rename the new column (and add a NOT NULL constraint if appropriate)</li> <li>rebuild indexes and update statistics</li> </ol> <p>The key here is that it allows you to perform the update incrementally in step 3, which you can't do in a single ALTER TABLE command.</p> <p>This assumes the column is not playing a major role in data integrity - if it is involved in a bunch of foreign key relationships, there are more steps.</p> <p><strong>EDIT</strong></p> <p>Also, and just wondering out loud, I haven't done any testing for this (but adding it to the list). I wonder if page + row compression would help here? If you change an INT to a BIGINT, with compression in place SQL Server should still treat all values as if they still fit in an INT. Again, I haven't tested if this would make an alter faster or slower, or how much longer it would take to add compression in the first place. Just throwing it out there.</p>
13,659,517
Non-max suppression
<p>We've learned that you can get the gradient direction with <code>atan(dy/dx)</code> which is the direction orthogonal to the edge. Now we had a homework where we were supposed to discretize this direction into four classes (x- and y-direction and both diagonals) and then check both pixel neighbors in the best matching direction for <strong>non-max suppression</strong>.</p> <p>I didn't fully get the solution though. Obviously we had four cases:</p> <ol> <li><p><code>abs(angle) &lt; pi/8</code>, so the gradient (roughly) points in x-direction, thus we check <code>img(i, j-1)</code> and <code>img(i, j+1)</code> (assuming the image origin is in the top left)</p></li> <li><p><code>angle &gt; pi/8 &amp;&amp; angle &lt;= 3*pi/8</code>, so the gradient points to the top right. Now I thought we need to check <code>img(i-1, j+1)</code> and <code>img(i+1, j-1)</code> but instead we check <code>img(i-1, j-1)</code> and <code>img(i+1, j+1)</code> which seems like the orthogonal diagonal.</p></li> </ol> <p>The other two cases are equivalent. I tried to change this but then the edges really look weird so this seems correct but I don't understand why.</p> <p>Can someone explain this to me?</p>
13,840,446
3
5
null
2012-12-01 12:36:56.51 UTC
5
2017-09-20 11:08:13.213 UTC
2015-01-22 03:17:37.177 UTC
null
1,630
null
1,709,708
null
1
13
computer-vision|non-maximum-suppression
51,670
<p>Non-max suppression is a way to eliminate points that do not lie in important edges. In your first case if the gradient is close to zero degrees at a given point, that means the edge is to the north or to the south, and that point will be considered to be on the edge if the magnitude of this point is greater than both magnitudes of the points to its left and right (as in your example). In your second case you are checking for gradient at 45 degrees, so the edge is at 135 degrees, and so you keep the point if it is greater than the points along the gradient direction, i.e. (-1, -1) and (1, 1). Rotating the coordinate system doesn't affect this.</p> <p><img src="https://i.stack.imgur.com/SLBQ4.png" alt="enter image description here"></p>
13,297,157
Best ways to deal with properties values in XML file in Spring, Maven and Eclipses
<p>I am working on a Spring WebFlow project which has a lot of property values in XML files, as any Spring programmer knows. I have database user names, password, URLs, etc. </p> <p>We are using Eclipse with Spring WebFlow and Maven. We are trying to have an SA do the builds but the SA does not want to go into the XML files to change the values, but on the other hand, we don't know the production values. How do we work with this?</p>
13,297,686
3
1
null
2012-11-08 20:22:02.527 UTC
14
2020-12-23 14:22:58.763 UTC
2014-06-19 13:39:34.897 UTC
null
1,354,590
null
1,652,096
null
1
22
eclipse|spring|svn|maven|spring-mvc
93,262
<p>Most SA are more willing and confident to deal with <code>.properties</code> file rather than <code>.xml</code>.</p> <p>Spring provide <a href="http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html" rel="noreferrer">PropertyPlaceholderConfigurer</a> to let you define everything into one or several <code>.properties</code> file and substitute the placeholder in <code>applicationContext.xml</code>.</p> <p>Create a <code>app.properties</code> under <code>src/main/resources/</code> folder:</p> <pre><code>... ... # Dadabase connection settings: jdbc.driverClassName=org.postgresql.Driver jdbc.url=jdbc:postgresql://localhost:5432/app_db jdbc.username=app_admin jdbc.password=password ... ... </code></pre> <p>And use PropertyPlaceholderConfigurer in <code>applicationContext.xml</code> like so:</p> <pre><code>... ... &lt;bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; &lt;property name="location"&gt; &lt;value&gt;app.properties&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; ... ... &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt; &lt;property name="driverClassName" value="${jdbc.driverClassName}" /&gt; &lt;property name="url" value="${jdbc.url}" /&gt; &lt;property name="username" value="${jdbc.username}" /&gt; &lt;property name="password" value="${jdbc.password}" /&gt; &lt;/bean&gt; </code></pre> <p>Check out <a href="http://www.mkyong.com/spring/spring-propertyplaceholderconfigurer-example/" rel="noreferrer">Spring PropertyPlaceholderConfigurer Example</a> for more details.</p> <p>In addition, from application deployment perspective, we usually package app in some executable format and the .properties files are usually packed inside the executable war or ear file. A simple solution is to configure your PropertyPlaceholderConfigurer bean to resolve properties from multiple location in a pre-defined order, so in the deployment environment, you can use a fixed location or environment variable to specify the properties file, also note that in order to simplify the deploy/configure task for SA, we usually use a single external .properties file define all runtime configuration, like so:</p> <pre><code>&lt;bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt; &lt;property name="locations"&gt; &lt;list&gt; &lt;!-- Default location inside war file --&gt; &lt;value&gt;classpath:app.properties&lt;/value&gt; &lt;!-- Environment specific location, a fixed path on server --&gt; &lt;value&gt;file:///opt/my-app/conf/app.properties&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;property name="ignoreResourceNotFound" value="true"/&gt; &lt;/bean&gt; </code></pre> <p>Hope this helps.</p>
13,779,508
open url in new tab or reuse existing one whenever possible
<p>Now I have a link</p> <pre><code>&lt;a href="blabla" target="_blank"&gt;link&lt;/a&gt; </code></pre> <p>However, this always open up a new tab. I want the following effect</p> <ol> <li>If the user already has a tab with the same URL, reuse that tab, and refresh if possible</li> <li>Otherwise, open a new tab</li> </ol> <p>How can I achieve this using JavaScript?</p> <p>It's OK if there're only some browser-specific methods, so users of browsers without corresponding support will "fallback" to the always-new-tab way.</p>
13,779,966
2
1
null
2012-12-08 16:43:08.547 UTC
8
2022-08-10 15:18:33.78 UTC
null
null
null
null
940,313
null
1
34
javascript|html|tabs
45,394
<p>You can set specific window's name, in order to open reuse the tab. The problem is, as far as the href will be the same, it won't be reloaded. So you can't obtain the <code>refresh</code> part easily.</p> <p>So, for instance, you can have:</p> <pre><code>&lt;a href="blabla" target="blabla"&gt;link&lt;/a&gt; &lt;a href="foo" target="bar"&gt;link&lt;/a&gt; </code></pre> <p>In JS, you can actually obtain the same, using <code>window.open</code>. You could also use the url as <code>target</code>, so that you don't need to specify manually:</p> <pre><code>&lt;a href="blabla" onclick="window.open(this.href, this.href); return false"&gt;link&lt;/a&gt; &lt;a href="foo" onclick="window.open(this.href, this.href); return false"&gt;link&lt;/a&gt; </code></pre> <p>You could also generalize, and add a click listener to the document, in order to open some links in this way. Something like:</p> <pre><code>&lt;div id="container"&gt; &lt;a href="blabla"&gt;link&lt;/a&gt; &lt;a href="foo"&gt;link&lt;/a&gt; &lt;/div&gt; &lt;script&gt; document.getElementById("container").onclick = function(evt){ if (evt.target.tagName === "A") window.open(evt.target.href, evt.target.href); return false; } &lt;/script&gt; </code></pre> <p>If the page are on the same domain, at this point you could probably trying to do an empiric refresh of the page as well.</p>
13,517,222
Facebook SDK for Android duplicate support library on dependencies
<p>I have implemented the new Facebook SDK 3.0 beta. The library project contains the Android support library v4. I also have the support library on my own proyect (a different version though). When I add the Facebook SDK as a library I get the next error on the console:</p> <pre><code>Jar mismatch! Fix your dependencies Found 2 versions of android-support-v4.jar in the dependency list, but not all the versions are identical (check is based on SHA-1 only at this time). All versions of the libraries must be the same at this time. </code></pre> <p>I've tried to exclude the <code>libs</code> folder on the buildpath, but the error remains.</p> <p>I have to put the same .jar in both places. Am I missing something here? The idea is to use the support library of my own project (to keep it updated).</p>
13,517,304
3
0
null
2012-11-22 17:00:37.41 UTC
5
2014-11-30 14:42:56.773 UTC
2014-11-30 14:38:38.077 UTC
null
63,550
null
1,587,785
null
1
34
android|facebook-android-sdk|android-support-library
15,965
<p>It seems like the different projects are using two separate support libraries and therefore the checksum is different.</p> <p>You must <strong><em>repeat this for both</em></strong> the Facebook SDK project and the app you are building.</p> <p>What I do when I get this error is:</p> <ol> <li><p>Right click the project.</p></li> <li><p>Hover over Android Tools.</p></li> <li><p>Click on "Add support library..."</p></li> <li><p>Accept the downloading of the library.</p></li> </ol> <p>This insures two things: a. you get the newest version of the support library from the Google sources, and b. you have the EXACT same library in all your projects.</p> <p>Happy coding!</p>
13,346,824
ViewPager detect when user is trying to swipe out of bounds
<p>I am using the ViewPager consisting of 6 pages to display some data. I want to be able to call a method when the user is at position 0 and tries to swipe to the right (backwards), or at position 5 and tries to swipe to the left (forward), even though no more pages exist for these directions. Is there any way I can listen for these scenarios?</p>
13,347,008
5
1
null
2012-11-12 15:46:41.72 UTC
16
2021-09-05 09:14:35.957 UTC
2014-01-06 19:51:26.577 UTC
null
595,881
null
980,782
null
1
35
android
37,026
<p>Extend ViewPager and override <code>onInterceptTouchEvent()</code> like this:</p> <pre><code>public class CustomViewPager extends ViewPager { float mStartDragX; OnSwipeOutListener mListener; public void setOnSwipeOutListener(OnSwipeOutListener listener) { mListener = listener; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { float x = ev.getX(); switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: mStartDragX = x; break; case MotionEvent.ACTION_MOVE: if (mStartDragX &lt; x &amp;&amp; getCurrentItem() == 0) { mListener.onSwipeOutAtStart(); } else if (mStartDragX &gt; x &amp;&amp; getCurrentItem() == getAdapter().getCount() - 1) { mListener.onSwipeOutAtEnd(); } break; } return super.onInterceptTouchEvent(ev); } public interface OnSwipeOutListener { public void onSwipeOutAtStart(); public void onSwipeOutAtEnd(); } } </code></pre>
13,476,267
Hide div element when screen size is smaller than a specific size
<p>I have a div element that I want to hide when the width of the browser is less than or equal to 1026px. Is this possible to do with the css: <strong><code>@media only screen and (min-width: 1140px) {}</code></strong> If it isn't possible with css, Is there any alternative?</p> <p>Extra info: When the div element is hidden, I don't want a blank white gap. I'd like the page to flow as it would if I deleted the div element entirely from the code.</p> <p>The div I am hiding is <strong><code>&lt;div id="fadeshow1"&gt;&lt;/div&gt;</code></strong>.</p> <p>HTML5 Doctype.</p> <p>I used javascript to place a gallery into that div. <br /><br /><br /> <strong>I want it to look like this when it is bigger than 1026px width:</strong> <a href="https://i.stack.imgur.com/REBPi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/REBPi.png" alt="http://i.stack.imgur.com/REBPi.png"></a> <br /><br /><br /></p> <p><strong>I want it to look like this when it is less than 1026px width:</strong> <a href="https://i.stack.imgur.com/XdiL4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XdiL4.png" alt="http://i.stack.imgur.com/XdiL4.png"></a></p>
13,476,297
9
2
null
2012-11-20 15:17:29.38 UTC
16
2020-02-07 09:00:14.78 UTC
2017-02-22 04:47:23.263 UTC
null
7,083,302
null
1,720,220
null
1
60
javascript|html|css
165,997
<p>You can do this with CSS:</p> <pre><code>@media only screen and (max-width: 1026px) { #fadeshow1 { display: none; } } </code></pre> <p>We're using <code>max-width</code>, because we want to make an exception to the CSS, when a screen is <em>smaller</em> than the 1026px. <code>min-width</code> would make the CSS rule count for all screens of 1026px width and <em>larger</em>.</p> <p>Something to keep in mind is that <code>@media</code> queries are not supported on IE8 and lower.</p>
51,760,640
Why helm upgrade --install failed when previous install is failure?
<p>This is the helm and tiller version:</p> <pre><code>&gt; helm version --tiller-namespace data-devops Client: &amp;version.Version{SemVer:"v2.9.1", GitCommit:"20adb27c7c5868466912eebdf6664e7390ebe710", GitTreeState:"clean"} Server: &amp;version.Version{SemVer:"v2.9.1", GitCommit:"20adb27c7c5868466912eebdf6664e7390ebe710", GitTreeState:"clean"} </code></pre> <p>The previous helm installation failed:</p> <pre><code>helm ls --tiller-namespace data-devops NAME REVISION UPDATED STATUS CHART NAMESPACE java-maven-app 1 Thu Aug 9 13:51:44 2018 FAILED java-maven-app-1.0.0 data-devops </code></pre> <p>When I tried to install it again using this command, it failed:</p> <pre><code>helm --tiller-namespace data-devops upgrade java-maven-app helm-chart --install \ --namespace data-devops \ --values helm-chart/values/stg-stable.yaml Error: UPGRADE FAILED: "java-maven-app" has no deployed releases </code></pre> <p>Is the <code>helm upgrade --install</code> command going to fail, if the previous installation failed? I am expecting it to force install. Any idea?</p>
60,995,790
4
5
null
2018-08-09 06:58:25.823 UTC
6
2021-01-25 09:40:11.513 UTC
2018-08-09 19:47:30.32 UTC
null
434,742
null
476,917
null
1
30
kubernetes|kubernetes-helm
40,618
<p>Try:</p> <pre><code>helm delete --purge &lt;deployment&gt; </code></pre> <p>This will do the trick</p> <p>and for helm3 onwards you need to uninstall eg.</p> <pre><code>helm uninstall &lt;deployment&gt; -n &lt;namespace&gt; </code></pre>
39,615,142
Bash get last line from a variable
<p>If I have a variable with multiple lines (text) in it, how can I get the last line out of it?</p> <p>I already figured out how to get the first line:</p> <pre><code>STRING="This is a multiple line variable test" FIRST_LINE=(${STRING[@]}) echo "$FIRST_LINE" # output: "This is a" </code></pre> <p>Probably there should be an operator for the last line. Or at least I assume that because with <code>@</code> the first line comes out.</p>
39,615,292
3
4
null
2016-09-21 11:21:05.557 UTC
6
2016-09-21 11:36:30.357 UTC
2016-09-21 11:34:52.467 UTC
null
1,815,797
null
2,119,043
null
1
38
bash|variables|line
41,119
<p>Using bash string manipulations:</p> <pre><code>$&gt; str="This is a multiple line variable test" $&gt; echo "${str##*$'\n'}" variable test </code></pre> <p><code>${str##*$'\n'}</code> will remove the longest match till <code>\n</code> from start of the string thus leaving only the last line in input.</p>
24,245,105
How to get the filename from the Javascript FileReader?
<p>I'm using the Javascript FileReader to load an image in the browser:</p> <pre><code>e = e.originalEvent; e.dataTransfer.dropEffect = 'copy'; this.documentFile = e.dataTransfer.files[0]; var reader = new FileReader(); reader.onloadend = function () { if (reader.result) { console.log(reader); $('#theImage').attr('src', reader.result); } }; reader.readAsDataURL(this.documentFile); </code></pre> <p>This works fine. I now want to get the original filename of the image, but I've got no clue how and looking around the internet I can't find anything either? </p> <p>Does anybody know how I can get the filename through the FileReader? All tips are welcome!</p>
27,927,981
5
3
null
2014-06-16 13:38:54.02 UTC
3
2021-06-08 00:11:55.567 UTC
2014-06-16 13:56:23.033 UTC
null
1,650,012
null
1,650,012
null
1
39
javascript|jquery|io|filereader
59,959
<p>This is prob not the best solution, BUT it worked for me.</p> <pre><code>var reader = new FileReader(); reader.fileName = file.name // file came from a input file element. file = el.files[0]; reader.onload = function(readerEvt) { console.log(readerEvt.target.fileName); }; </code></pre> <p>Not the best answer, but a working one.</p>
24,278,220
Amazon RDS: Restore snapshot to existing instance
<p>I have created a snapshot of my instance and made some unwanted changes in DB.</p> <p>Now I want to restore my instance from this snapshot.</p> <p>When I try to do it - it creates me one more instance, additionally to the one I have.</p> <p>I specify "DB Instance Identifier" and after that I get two instances with the same ID.</p> <p>So my question: Is there any way to restore snapshot to existing instance?</p> <p>Because in other case - new instance is created with differrent endpoint (hostname) and I need to change my configs to access database. Or there is a better way to manage such cases?</p>
24,279,273
7
3
null
2014-06-18 06:11:31.537 UTC
11
2021-01-12 21:52:36.613 UTC
2016-08-02 16:00:58.707 UTC
null
881,229
null
3,751,064
null
1
107
mysql|amazon-web-services|amazon-rds
59,288
<p>No you can't restore back your existing DB instance to any of the either manual backup or point-in-time snapshot.</p> <p>The only way you can make use of the manual backup or automated snapshot is to create a new RDS DB instance using that. Once the new DB instance is created, you can change the endpoint of DB in your app / code and delete the old DB instance.</p> <p>Bottomline : You have to change the config settings in your app. No other option.</p>
28,853,952
Total number of palindromic subsequences in a string
<p>The question is like this--</p> <p>For every string given as input, you need to tell the number of subsequences of it that are palindromes (need not necessarily be distinct). Note that the empty string is not a palindrome. For example, the palindromic subsequences of "aab" are:</p> <p>"a", "a", "b", "aa", and the method returns 4.</p> <p>I had the Dynamic Programming solution to finding Longest Palindromic Subsequence in mind and therefore tried to take ideas from it. Couldn't really get the solution. May be dynamic programming is not even required. Suggestions please. </p> <p>And there is one more catch. When the condition "need not necessarily be distinct" is removed, can we still count without actually generating all the palindromic subsequences?</p>
28,858,100
3
5
null
2015-03-04 12:00:39.41 UTC
11
2016-11-04 18:48:09.647 UTC
null
null
null
null
1,598,079
null
1
7
algorithm|data-structures|dynamic-programming
7,762
<p><strong>[EDIT 19/10/2015: An anonymous reviewer pointed out a problem with the formula, which prompted me to notice another, even bigger mistake... Now fixed.]</strong></p> <p>I now see how to drop the solution time down to <strong>O(n^2)</strong>. I'll leave my other answer up in case it's interesting as a stepping-stone to this one. Note: This is (also) only a solution to the first part of the problem; I see no way to efficiently count only <em>distinct</em> palindromic subsequences (PS).</p> <p>Instead of counting the number of PS that begin and end at exactly the positions i and j, let's count how many begin at <em>or after</em> i and end at <em>or before</em> j. Call this g(i, j).</p> <p>We can try to write g(i, j) = g(i, j-1) + g(i+1, j) + (x[i] == x[j])*g(i+1, j-1) for the case when j > i. But this doesn't quite work, because the first two terms will double-count any PS that begin <em>after</em> i and end <em>before</em> j.</p> <p>The key insight is to notice that we can easily calculate the number of PS that begin or end at some <em>exact</em> position by subtracting off other values of g(), and perhaps adding yet more values of g() back on to compensate for double-counting. For example, the number of PS that begin at <em>exactly</em> i and end at <em>exactly</em> j is g(i, j) - g(i+1, j) - g(i, j-1) + g(i+1, j-1): the last term corrects for the fact that both the second and third terms count all g(i+1, j-1) PS that begin <em>after</em> i and end <em>before</em> j.</p> <p>Every PS that begins at or after i and ends at or before j is in exactly 1 of 4 categories:</p> <ol> <li>It begins after i, and ends before j.</li> <li>It begins at i, and ends before j.</li> <li>It begins after i, and ends at j.</li> <li>It begins at i, and ends at j.</li> </ol> <p>g(i+1, j) counts all PS in category 1 or 3, and g(i, j-1) counts all PS in category 1 or 2, so their sum g(i+1, j) + g(i, j-1) counts all PS in category 2 or 3 once each, and all PS in category 1 twice. Since g(i+1, j-1) counts all PS in category 1 only, subtracting this off to get g(i+1, j) + g(i, j-1) - g(i+1, j-1) gives the total number of PS in category 1, 2 and 3. The remaining PS are those in category 4. If x[i] != x[j] then there are no PS in this category; otherwise, there are exactly as many as there are PS that begin at or after i+1 and end at or before j-1, namely g(i+1, j-1), plus one extra for the 2-character sequence x[i]x[j]. <strong>[EDIT: Thanks to commenter Tuxdude for 2 fixes here!]</strong></p> <p>With this in hand, we can express g() in a way that changes the quadratic case from f() to constant time:</p> <pre><code>g(i, i) = 1 (i.e. when j = i) g(i, i+1) = 2 + (x[i] == x[i+1]) (i.e. 3 iff adjacent chars are identical, otherwise 2) g(i, j) = 0 when j &lt; i (this new boundary case is needed) g(i, j) = g(i+1, j) + g(i, j-1) - g(i+1, j-1) + (x[i] == x[j])*(g(i+1, j-1)+1) when j &gt;= i+2 </code></pre> <p>The final answer is now simply g(1, n).</p>
29,509,010
How to play a short beep to Android Phone's loudspeaker programmatically
<p>In order to receive the only short beep sound on loudspeaker I want to send single bit to the loudspeaker directly. Similarly to the LED blink. Is there any possibility to do short beep without any kind of Media Players?</p>
29,509,305
4
3
null
2015-04-08 07:56:43.74 UTC
11
2021-08-13 06:21:34.11 UTC
null
null
null
null
3,175,098
null
1
42
android
45,738
<p>I recommend you use the <a href="https://developer.android.com/reference/android/media/ToneGenerator" rel="noreferrer"><code>ToneGenerator</code></a> class. It requires no audio files, no media player, and you can customize the beep's volume, duration (in milliseconds) and Tone type. I like this one:</p> <pre><code>ToneGenerator toneGen1 = new ToneGenerator(AudioManager.STREAM_MUSIC, 100); toneGen1.startTone(ToneGenerator.TONE_CDMA_PIP,150); </code></pre> <p>You can see into the ToneGenerator object (CMD + click over ToneGenerator. , in Mac), and choose another beep type besides <code>TONE_CDMA_PIP</code>, <code>150</code> is the duration in milliseconds, and <code>100</code> the volume.</p>
29,620,783
Apply multiple functions to multiple columns in data.table
<p>I am trying to apply multiple functions to multiple columns of a <code>data.table</code>. Example:</p> <pre><code>DT &lt;- data.table("a"=1:5, "b"=2:6, "c"=3:7) </code></pre> <p>Let's say I want to get the mean and the median of columns <code>a</code> and <code>b</code>. This works:</p> <pre><code>stats &lt;- DT[,.(mean_a=mean(a), median_a=median(a), mean_b=mean(b), median_b=median(b))] </code></pre> <p>But it is way too repetitive. Is there a nice way to achieve a similar result using <code>.SDcols</code> and <code>lapply</code>?</p>
29,621,821
5
4
null
2015-04-14 06:42:47.337 UTC
22
2019-08-07 07:02:04.867 UTC
2018-11-28 10:29:38.437 UTC
null
1,851,712
null
2,795,440
null
1
39
r|data.table
13,345
<p>I'd normally do this:</p> <pre><code>my.summary = function(x) list(mean = mean(x), median = median(x)) DT[, unlist(lapply(.SD, my.summary)), .SDcols = c('a', 'b')] #a.mean a.median b.mean b.median # 3 3 4 4 </code></pre>
16,128,604
Scrollable canvas inside div
<p>I have a html5 canvas. I need to show the fixed portion of it in the div(<code>Div1</code>). When I swipe inside <code>Div1</code>, I need to scroll the canvas. So as I scroll, I'll see corresponding part of the canvas. </p> <p><img src="https://i.stack.imgur.com/3wAW6.png" alt="enter image description here"></p> <p>I tried something like this:</p> <pre><code>&lt;div id="Div1" style=" float: left; width: 50px; overflow:hidden; "&gt; &lt;canvas id="myCanvas1" width="200px" style="border: 1px solid #ff0000; position: absolute;"&gt; &lt;/canvas&gt; &lt;/div&gt; </code></pre> <p><a href="http://jsfiddle.net/9g3GG/" rel="noreferrer">jsFiddled here</a></p>
36,511,409
5
5
null
2013-04-21 06:35:54.027 UTC
7
2018-10-09 21:47:52.59 UTC
2013-04-21 06:57:26.337 UTC
null
845,310
null
1,506,282
null
1
28
javascript|jquery|css|html
37,224
<p>Here is a demo of using an oversize canvas, and scrolling with mouse movements by adjusting the CSS margin: <a href="https://jsfiddle.net/ax7n8944/" rel="noreferrer">https://jsfiddle.net/ax7n8944/</a></p> <p>HTML:</p> <pre><code>&lt;div id="canvasdiv" style="width: 500px; height: 250px; overflow: hidden"&gt; &lt;canvas id="canvas" width="10000px" height="250px"&gt;&lt;/canvas&gt; &lt;/div&gt; </code></pre> <p>JS:</p> <pre><code>var canvas = document.getElementById("canvas"); var context = canvas.getContext('2d'); var dragging = false; var lastX; var marginLeft = 0; for (var i = 0; i &lt; 1000; i++) { context.beginPath(); context.arc(Math.random() * 10000, Math.random() * 250, 20.0, 0, 2 * Math.PI, false); context.stroke(); } canvas.addEventListener('mousedown', function(e) { var evt = e || event; dragging = true; lastX = evt.clientX; e.preventDefault(); }, false); window.addEventListener('mousemove', function(e) { var evt = e || event; if (dragging) { var delta = evt.clientX - lastX; lastX = evt.clientX; marginLeft += delta; canvas.style.marginLeft = marginLeft + "px"; } e.preventDefault(); }, false); window.addEventListener('mouseup', function() { dragging = false; }, false); </code></pre>
16,346,206
Targeting $(this) within nested for each loops in jQuery
<p>I'm trying to figure out, when iterating through some list items, how to target each "$(this)" equivalent within nested foreach loops. Here is an example of my problem:</p> <pre><code>$('li').each(function(){ // I believe $(this) would target each li item... $(this).children("li").each(function(){ // ... but how can I target each of these li items? Doesn't $(this) target the original loop? }); }); </code></pre>
16,346,239
5
2
null
2013-05-02 19:29:18.32 UTC
16
2013-05-02 19:36:46.257 UTC
null
null
null
null
984,323
null
1
50
javascript|jquery|html
59,506
<pre><code>$('li').each(function(){ var $this = $(this); $this.children("li").each(function(){ $this; // parent li this; // child li }); }); </code></pre>
24,914,513
Display google maps in iframe dynamically
<p>I would like to dynamically create a "google maps" link in javascript and than set it as src for my iframe, but I don't know if it is not possible with google maps, because this doesn't work:</p> <pre><code> document.getElementById('map_canvas').src='http://maps.google.com/maps/ms?ie=UTF8&amp;amp;msa=0&amp;amp;msid=209246852521822593612.0004feda304ac527ea40a&amp;amp;output=embed'; </code></pre> <p>although, for example this works:</p> <pre><code> document.getElementById('map_canvas').src='http://www.cnn.com'; </code></pre> <p>This is my iframe:</p> <pre><code>&lt;iframe id="map_canvas" name="map_canvas" width="100%" height="600px" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src=""&gt; &lt;/iframe&gt; </code></pre> <p>Could you explain me, how is it possible to dynamically generate and display a google maps link in iframe ?</p> <p>Thank you for help!</p>
24,934,734
4
6
null
2014-07-23 15:20:58.83 UTC
1
2014-07-24 13:13:13.837 UTC
null
null
null
null
2,205,582
null
1
1
javascript|html|google-maps|iframe
38,188
<p>I solved it this way: I have added iframe per jQuery and set the desired src attr.</p> <pre><code>function displayMapAt(lat, lon, zoom) { $("#map") .html( "&lt;iframe id=\"map_frame\" " + "width=\"100%\" height=\"600px\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" " + "src=\"https://www.google.sk/maps?f=q&amp;amp;output=embed&amp;amp;source=s_q&amp;amp;hl=sk&amp;amp;geocode=&amp;amp;q=https:%2F%2Fwww.google.sk%2Fmaps%2Fms%3Fauthuser%3D0%26vps%3D5%26hl%3Dsk%26ie%3DUTF8%26oe%3DUTF8%26msa%3D0%26output%3Dkml%26msid%3D205427380680792264646.0004fe643d107ef29299a&amp;amp;aq=&amp;amp;sll=48.669026,19.699024&amp;amp;sspn=4.418559,10.821533&amp;amp;ie=UTF8&amp;amp;ll=" + lat + "," + lon + "&amp;amp;spn=0.199154,0.399727&amp;amp;t=m&amp;amp;z=" + zoom + "\"" + "&gt;&lt;/iframe&gt;"); } </code></pre>
27,382,777
Set Parent Width equal to Children Total Width using only CSS?
<p>I don't know how many <code>.child</code> elements <code>.parent</code> will contain but I know their individual width.</p> <p>I want to set the width of <code>.parent</code> to be equal to (width of each <code>.child</code>) <strong>*</strong> (total number of <code>.child</code>)</p> <p>I don't want to use <code>floats</code> and <code>width: auto</code>.</p> <p>Can I do something with <code>calc()</code> without using Javascript?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code> .parent { height: 100%; width: calc({number of children} * {width of each child = 100px}); } .child { height: 100px; width: 100px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;div class="parent"&gt; &lt;div class="child"&gt;a&lt;/div&gt; &lt;div class="child"&gt;b&lt;/div&gt; &lt;div class="child"&gt;c&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
41,476,558
7
4
null
2014-12-09 15:33:22.063 UTC
6
2022-04-06 08:11:19.043 UTC
2022-04-06 08:11:19.043 UTC
null
11,829,408
null
2,272,048
null
1
47
html|css
102,649
<p>I know this is a bit late, but Hope this will help somebody who is looking for similar solution:</p> <pre><code>&lt;div class="parent" style="display: inline-flex"&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;/div&gt; </code></pre> <p>the trick is to use <code>inline-flex</code> for the <code>parent</code> and <code>inline-table</code> for the <code>child</code>. Everything is dynamic. I make the table scrollable horizontally by adding another <code>grandparent</code> with <code>overflow-x:scroll;</code>:</p> <pre><code>&lt;div class="grandparent" style="width: 300px; overflow-x: scroll; background: gray"&gt; &lt;div class="parent" style="display: inline-flex"&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;div class="child" style="display: inline-table"&gt;some button&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
21,671,456
WampServer orange icon
<p>I am having problems with Wamp Server, the icon will never turn green. It is constantly stuck at orange.</p> <p>I have tried many ways, editing HOSTS file, .config files, disabling IIS, changing SKYPE's port, quitting SKYPE, disabling World Wide Web publishing services etc... And under wamp server icon > Apache > Test port 80, it states that Apache is using that port.</p> <p>I am running Windows 8 64 bit and Wamp Server 2.4. Any help would be appreciated.</p>
21,678,795
13
6
null
2014-02-10 07:38:21.517 UTC
17
2022-02-20 06:46:26.747 UTC
2014-06-24 08:07:08.513 UTC
null
2,310,830
null
3,240,916
null
1
44
php|apache|wamp|wampserver
181,630
<p>Before you can fix anything you need to know which service has not started, Apache or MySQL.</p> <p>As the TEST PORT 80 utility is saying Apache is running its probably the MySQL service that has not started. Unless you have another Apache running!</p> <p>So which service has not started???</p> <p>If the wampmanager icon is not GREEN then one of the services ( Apache/MySQL ) has not started properly.</p> <p><strong>How to tell which service is not running if the wampmanager icon is orange.</strong></p> <p>Left click the wampmanager icon to reveal the menu-&gt; Apache -&gt; Service If the <strong>Start/Resume service</strong> menu is Green then Apache <em><strong>IS NOT</strong></em> running.</p> <p>Left click the wampmanager icon to reveal the menu-&gt; MySQL -&gt; Service If the <strong>Start/Resume service</strong> menu is Green then MySQL <em><strong>IS NOT</strong></em> running.</p> <p>If Apache is the service that is not running it is normally, but not always, because something else has captured port 80.</p> <p>Now do, Left click the wampmanager icon to reveal the menu-&gt; Apache -&gt; Service -&gt; Test port 80 This will launch a command window and display some information about what, if anything is using port 80.</p> <p>Whatever it is should be re-configured to not use port 80 or uninstalled if you are not using it.</p> <p>If port 80 is not the problem look for errors in the appropriate error log ( use the wamp manager menus to view the error logs )</p> <p>If these do not exists or show no errors then also check the Windows Event Viewer Start -&gt; Administrative Tools -&gt; Event Viewer And look in the 'Windows Logs' -&gt; Application' section accessed from the menu on the left of the dialog for error messages from Apache and or MySQL.</p> <h3>If its MYSQL that has not started.</h3> <p>Check the mysql error log by using the menus</p> <pre><code>wampmanager-&gt;MySQL-&gt;error log </code></pre> <p>Check the Windows Event log for messages from MYSQL</p> <p>Check you dont have another MYSQL Server instance running.</p> <p><strong>How to Configure SKYPE so it does not require port 80 or 443</strong></p> <p>Run SKYPE then using the menus do this: Tools -&gt; Options -&gt; Advanced -&gt; Connection Un-Check the checkbox next to 'Use port 80 and 443 as alternatives for incomming connections' Now restart SKYPE for these changes to take effect.</p> <p>If you are running Windows 8 SKYPE comes as an app and this cannot ( as yet ) be configured in this way. However if you uninstall the SKYPE app and install SKYPE in the old way, you can reconfigure it, and it works just as well.</p>
45,027,400
reading csv file to pandas dataframe as float
<p>I have a <code>.csv</code> file with strings in the top row and first column, with the rest of the data as floating point numbers. I want to read it into a dataframe with the first row and column as column names and index respectively, and all the floating values as <code>float64</code>.</p> <p>If I use <code>df = pd.read_csv(filename,index_col=0)</code> all the numeric values are left as strings.</p> <p>If I use <code>df = pd.read_csv(filename, index_col=0, dtype=np.float64)</code> I get an exception: <code>ValueError: could not convert string to float</code> as it attempts to parse the first column as <code>float</code>.</p> <p>There are a large number of columns, and i do not have the column names, so I don't want to identify each column for parsing as <code>float</code>; I want to parse every column <em>except</em> the first one.</p>
45,049,446
2
4
null
2017-07-11 06:54:06.617 UTC
2
2017-07-12 05:54:20.287 UTC
null
null
null
null
6,567,949
null
1
6
python|csv|pandas|parsing
39,531
<p>The original code was correct</p> <pre><code>df = pd.read_csv(filename,index_col=0) </code></pre> <p>but the <code>.csv</code> file had been constructed incorrectly.</p> <p>As @juanpa.arrivillaga pointed out, pandas will infer the <code>dtypes</code> without any arguments, provided all the data in a column is of the same <code>dtype</code>. The columns were being interpreted as strings because although <em>most</em> of the data was numeric, one row contained non-numeric data (actually dates). Removing this row from the <code>.csv</code> solved the problem.</p>
17,322,990
How can I refresh my git repository?
<p>I have a git repo offline copy, and after some time somebody else might have made changes to it. How can I bring my repository up to speed with the new changes? How can I check that my repo is at its latest update?</p>
17,323,073
1
2
null
2013-06-26 14:31:10.213 UTC
null
2013-06-26 14:34:30.953 UTC
null
null
null
null
1,489,886
null
1
-1
git
46,131
<p><code>git pull</code> will pull the latest changes.</p> <p><code>git fetch</code> will update the list of changes.<br> <code>git status</code> will check the status of the repo. Without the fetch first, you will not see remote changes.</p> <p>Also, <strong><em>please</em></strong> read the <a href="http://git-scm.com/book/en/Git-Basics-Working-with-Remotes#Fetching-and-Pulling-from-Your-Remotes" rel="noreferrer">documentation</a>.</p>
5,519,674
Using JQuery to set CKEditor Value
<p>I have a CKEditor textarea:</p> <pre><code> &lt;textarea cols="80" id="taBody" name="taBody" class="ckeditor" rows="10" runat="server"&gt;&lt;/textarea&gt; </code></pre> <p>I have jQuery trying to set the value from the database:</p> <pre><code>$('#ContentPlaceHolder_taBody').val(substr[5]); </code></pre> <p>Don't worry about the substring I already tested that it is returning a string. For testing purposes I replaced the substring with 'test' and was receiving the same issue.</p> <p>I know that the jquery surrounding this line doesn't affect it because the other textfields I'm trying to populate work. Just when it comes to the ckeditor.</p> <p>Here is the script in whole:</p> <pre><code>function (obj) { $.ajax({ type: "POST", url: "ContentSections.aspx/GetContentDetails", data: '{"nodeID": "' + obj.attr('id') + '"}', contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { var str = msg.d; var substr = str.split('|||'); $('#ContentPlaceHolder_hfContentSectionID').val(substr[0]); $('.txtAlias').val(substr[1]); $('.txtBrowserTitle').val(substr[2]); $('.txtMetaDescription').val(substr[3]); $('.txtMetaKeywords').val(substr[4]); $('#ContentPlaceHolder_taBody').val(substr[5]); } }); } </code></pre> <p>The issue was that nothing was being populated and no javascript errors were being shown.</p> <p>I tried to read around but couldn't find anything that helped me. Does anyone have any ideas?</p>
5,519,706
3
0
null
2011-04-01 22:47:45.79 UTC
4
2021-03-11 12:55:56.343 UTC
null
null
null
null
316,429
null
1
12
jquery|ajax|ckeditor
46,473
<p>You need to use CKEditor's API instead.</p> <p>Specifically, <a href="http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.editor.html#setData" rel="noreferrer"><strong>http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.editor.html#setData</strong></a></p>
9,394,909
Add values from two textboxes and display the sum in third textbox
<p>I have tried this code to add from textbox1.text and textbox2.text into textbox3.text</p> <pre><code>private void textBox1_TextChanged(object sender, EventArgs e) { if(!string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text)) { textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text).ToString()); } } private void textBox2_TextChanged(object sender, EventArgs e) { if(!string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text)) { textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text).ToString()); } } </code></pre> <p>please Help ... and is there anything like to change 'format 'property of textbox to general number?</p>
9,395,091
4
3
null
2012-02-22 12:38:56.18 UTC
3
2017-03-21 08:47:15.597 UTC
2012-02-22 12:52:28.203 UTC
null
1,216,024
null
1,216,024
null
1
3
c#|winforms|textbox
144,589
<p>You made a mistake <code>||</code> should be replace with <code>&amp;&amp;</code> so it will check both the text boxes are filled with value.</p> <p>You have used <code>.ToString()</code> method wrongly which applies only to <code>textbox2</code>, check the brackets properly.</p> <pre><code>textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text).ToString()); </code></pre> <p>should be</p> <pre><code>textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString()); </code></pre> <p>Try This Tested Code.</p> <pre><code> private void textBox1_TextChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(textBox1.Text) &amp;&amp; !string.IsNullOrEmpty(textBox2.Text)) textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString(); } private void textBox2_TextChanged(object sender, EventArgs e) { if (!string.IsNullOrEmpty(textBox1.Text) &amp;&amp; !string.IsNullOrEmpty(textBox2.Text)) textBox3.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString(); } </code></pre>
20,186,081
Understanding Node.JS async.parallel
<p>I need to request data from two web servers. The tasks are independent; therefore, I am using <a href="https://github.com/caolan/async" rel="noreferrer">aync.parallel</a>. Now I am only writing 'abc', 'xyz', and 'Done' to the body of my web page.</p> <p>Since tasks are performed at the same time, can I run into a strange output? E.g.,</p> <pre><code>xab cyz </code></pre> <p><strong>The code.</strong></p> <pre><code>var async = require('async'); function onRequest(req, res) { res.writeHead(200, { "Content-Type" : "text/plain" }); async.parallel([ function(callback) { res.write('a'); res.write('b'); res.write('c\n'); callback(); }, function(callback) { res.write('x'); res.write('y'); res.write('z\n'); callback(); } ], function done(err, results) { if (err) { throw err; } res.end("\nDone!"); }); } var server = require('http').createServer(onRequest); server.listen(9000); </code></pre>
20,189,732
1
2
null
2013-11-25 06:28:44.333 UTC
13
2018-04-15 08:20:57.463 UTC
2013-11-25 06:37:25.897 UTC
null
559,028
null
1,065,835
null
1
25
javascript|node.js|parallel-processing
74,590
<p>If you want to be absolutely certain in the order in which the results are printed, you should pass your data (<code>abc\n</code> and <code>xyz\n</code>) through the <a href="https://github.com/caolan/async#parallel" rel="noreferrer">callbacks</a> (first parameter is the error) and handle/write them in the final <code>async.parallel</code> callback's <code>results</code> argument.</p> <pre><code>async.parallel({ one: function(callback) { callback(null, 'abc\n'); }, two: function(callback) { callback(null, 'xyz\n'); } }, function(err, results) { // results now equals to: results.one: 'abc\n', results.two: 'xyz\n' }); </code></pre>
19,931,929
Reading a column from CSV file using JAVA
<p>Hi I am trying to read a CSV File called <code>test.csv</code> in JAVA . Below is my code : </p> <pre><code>import java.io.BufferedReader; import java.io.FileReader; public class InsertValuesIntoTestDb { @SuppressWarnings("rawtypes") public static void main(String[] args) throws Exception { String splitBy = ","; BufferedReader br = new BufferedReader(new FileReader("test.csv")); String line = br.readLine(); while(line!=null){ String[] b = line.split(splitBy); System.out.println(b[0]); } br.close(); } } </code></pre> <p>This is my CSV File (test.csv):</p> <pre><code>a,f,w,b,numinst,af,ub 1RW,800,64,22,1,48:2,true 1RW,800,16,39,1,48:2,true 1RW,800,640,330,1,48:2,true 1RW,800,40,124,1,48:2,true 1RW,800,32,104,1,48:2,true 1RW,800,8,104,1,48:2,true 1R1W,800,65536,39,1,96:96,true 1R1W,800,2048,39,1,96:96,true 1R1W,800,8192,39,1,48:48,true </code></pre> <p>I am trying to print the first column in the csv ,but the output I get is only <code>a</code> in an infinite loop . Can anyone please help me fix this code to print the entire first column. Thanks.</p>
19,931,945
4
3
null
2013-11-12 14:31:51.043 UTC
5
2018-02-23 16:00:48.677 UTC
null
null
null
null
2,559,838
null
1
24
java|csv
119,629
<p>Read the input continuously within the loop so that the variable <code>line</code> is assigned a value other than the initial value</p> <pre><code>while ((line = br.readLine()) !=null) { ... } </code></pre> <p>Aside: This problem has already been solved using CSV libraries such as <a href="http://opencsv.sourceforge.net/">OpenCSV</a>. Here are examples for <a href="http://opencsv.sourceforge.net/#how-to-read">reading and writing</a> CSV files</p>
20,176,959
uWSGI: No request plugin is loaded, you will not be able to manage requests
<p>I've loaded uWSGI v 1.9.20, built from source. I'm getting this error, but how do I tell which plugin is needed?</p> <pre><code>!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!! no request plugin is loaded, you will not be able to manage requests. you may need to install the package for your language of choice, or simply load it with --plugin. !!!!!!!!!!! END OF WARNING !!!!!!!!!! </code></pre> <p>Which plugin should be loaded?</p>
24,719,979
7
3
null
2013-11-24 16:33:01.323 UTC
3
2021-01-14 12:35:49.21 UTC
null
null
null
null
451,007
null
1
43
python|uwsgi
30,368
<p>I had this problem and was stuck for hours.</p> <h3>Python2</h3> <p>My issue is different than the answer listed, make sure you have <code>plugins = python</code> in your uwsgi <code>.ini</code> file and you install the <code>uwsgi python</code> plugin:</p> <pre class="lang-sh prettyprint-override"><code>sudo apt-get install uwsgi-plugin-python </code></pre> <h3>Python3</h3> <p>If you're using Python3, use the same approach and do:</p> <pre class="lang-sh prettyprint-override"><code>sudo apt-get install uwsgi-plugin-python3 </code></pre> <p>then add <code>plugins = python3</code> inside your uwsgi <code>.ini</code> file.</p> <hr /> <p>After I did the above my application worked. Obviously this is for <code>python</code> projects, but a similar approach is required for other projects.</p>
15,006,849
What's the difference between $locationChangeSuccess and $locationChangeStart?
<p>What's the difference between <code>$locationChangeSuccess</code> and <code>$locationChangeStart</code>?</p> <p>They are both undocumented events related to <code>window.location</code>.</p>
15,007,296
1
0
null
2013-02-21 16:05:39.727 UTC
9
2013-08-19 20:16:01.567 UTC
2013-08-19 20:16:01.567 UTC
null
40,342
null
146,636
null
1
25
angularjs|window.location
26,408
<p>The <code>$locationChangeStart</code> is fired when AngularJS starts to update browser's location based on mutations done via <code>$location</code> service (<code>$location.path()</code>, <code>$location.search()</code>). </p> <p>It might happen that an application will listen to the <code>$locationChangeStart</code> event and will call <code>preventDefault()</code> on it. In this case the second event (<code>$locationChangeSuccess</code>) won't be broadcasting.</p> <p>In short: <code>$locationChangeStart</code> fires when the location gets updated. It is followed by <code>$locationChangeSuccess</code> if the first action wasn't prevented.</p> <p>Relevant bits of the source code are here: <a href="https://github.com/angular/angular.js/blob/2508b47c1a34dfc834f8fde858574f81af4d287e/src/ng/location.js#L598" rel="noreferrer">https://github.com/angular/angular.js/blob/2508b47c1a34dfc834f8fde858574f81af4d287e/src/ng/location.js#L598</a></p>
15,292,175
How to send a key to another application
<p>I want to send a specific key (e.g. k) to another program named notepad, and below is the code that I used:</p> <pre><code>private void SendKey() { [DllImport (&quot;User32.dll&quot;)] static extern int SetForegroundWindow(IntPtr point); var p = Process.GetProcessesByName(&quot;notepad&quot;)[0]; var pointer = p.Handle; SetForegroundWindow(pointer); SendKeys.Send(&quot;k&quot;); } </code></pre> <p>But the code doesn't work, what's wrong with the code?</p> <p>Is it possible that I send the &quot;K&quot; to the notepad without notepad to be the active window? (e.g. active window = &quot;Google chrome&quot;, notepad is in the background, which means sending a key to a background application)?</p>
15,292,428
3
9
null
2013-03-08 10:45:39.593 UTC
17
2021-11-04 00:56:48.09 UTC
2021-08-09 10:11:28.45 UTC
null
466,862
null
1,212,812
null
1
36
c#|sendkeys
152,289
<p>If notepad is already started, you should write:</p> <pre><code>// import the function in your class [DllImport ("User32.dll")] static extern int SetForegroundWindow(IntPtr point); //... Process p = Process.GetProcessesByName("notepad").FirstOrDefault(); if (p != null) { IntPtr h = p.MainWindowHandle; SetForegroundWindow(h); SendKeys.SendWait("k"); } </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/z3w4xdc9.aspx" rel="noreferrer"><code>GetProcessesByName</code></a> returns an array of processes, so you should get the first one (or find the one you want).</p> <p>If you want to start <code>notepad</code> and send the key, you should write:</p> <pre><code>Process p = Process.Start("notepad.exe"); p.WaitForInputIdle(); IntPtr h = p.MainWindowHandle; SetForegroundWindow(h); SendKeys.SendWait("k"); </code></pre> <p>The only situation in which the code may not work is when <code>notepad</code> is started as Administrator and your application is not.</p>
14,984,555
NSLocalizedString with format
<p>How would I use <code>NSLocalizedString</code> for this string:</p> <pre><code>[NSString stringWithFormat:@"Is “%@“ still correct for “%@“ tap “OK“ otherwise tap “Change“ to choose new contact details", individual.contactInfo, individual.name]; </code></pre> <p>When using stringWithFormat before I've used it in the following manner: </p> <pre><code>[NSString stringWithFormat:@"%d %@", itemCount, NSLocalizedString(@"number of items", nil)]; </code></pre>
14,984,616
4
4
null
2013-02-20 16:10:42.287 UTC
4
2019-02-20 13:55:12.533 UTC
null
null
null
null
294,661
null
1
42
objective-c|nslocalizedstring
25,077
<pre><code>[NSString stringWithFormat:NSLocalizedString(@"Is “%@“ still correct for “%@“ tap “OK“ otherwise tap “Change“ to choose new contact details", @"Query if parm 1 is still correct for parm 2"), individual.contactInfo, individual.name]; </code></pre>
15,108,229
How to count number of words from String using shell
<p>I want to count number of words from a String using Shell.</p> <p>Suppose the String is:</p> <pre><code>input="Count from this String" </code></pre> <p>Here the delimiter is space <code>' '</code> and expected output is 4. There can also be trailing space characters in the input string like <code>"Count from this String "</code>.</p> <p>If there are trailing space in the String, it should produce the same output, that is 4. How can I do this?</p>
15,108,286
8
0
null
2013-02-27 09:17:16.14 UTC
3
2022-02-22 11:26:39.553 UTC
2016-12-21 10:45:47.473 UTC
null
55,075
null
1,679,435
null
1
64
bash
121,738
<pre><code>echo "$input" | wc -w </code></pre> <p>Use wc -w to count the number of words.</p> <p>Or as per dogbane's suggestion, the echo can be got rid of as well:</p> <pre><code>wc -w &lt;&lt;&lt; "$input" </code></pre> <p>If &lt;&lt;&lt; is not supported by your shell you can try this variant:</p> <pre><code>wc -w &lt;&lt; END_OF_INPUT $input END_OF_INPUT </code></pre>
9,491,001
Closing a Userform with Unload Me doesn't work
<p>I need to close an Excel userform using VBA when a user has clicked a submit button and operations have been carried out.</p> <p>How can I close a Userform from itself?</p> <p>I have tried this but it returns a 361 error.</p> <pre><code>Unload Me </code></pre>
25,938,039
4
9
null
2012-02-28 22:45:27.283 UTC
1
2019-11-20 19:36:08.437 UTC
2016-05-11 15:43:23.513 UTC
null
2,756,409
null
873,565
null
1
24
vba|excel|excel-2010
220,407
<p>As specified by the top answer, I used the following in the code behind the button control.</p> <pre><code>Private Sub btnClose_Click() Unload Me End Sub </code></pre> <p>In doing so, it will not attempt to unload a control, but rather will unload the user form where the button control resides. The "Me" keyword refers to the user form object even when called from a control on the user form. If you are getting errors with this technique, there are a couple of possible reasons.</p> <ol> <li><p>You could be entering the code in the wrong place (such as a separate module)</p></li> <li><p>You might be using an older version of Office. I'm using Office 2013. I've noticed that VBA changes over time.</p></li> </ol> <p>From my experience, the use of the the DoCmd.... method is more specific to the macro features in MS Access, but not commonly used in Excel VBA.</p> <p>Under normal (out of the box) conditions, the code above should work just fine.</p>
8,460,037
List of Delphi language features and version in which they were introduced/deprecated
<p>Before I begin, I would like to point out that I have honestly and genuinely searched repeatedly and exhaustively via Google for such a thing, and been unable to find one.</p> <p>I require (for a project I'm developing) a list of all Delphi (2007 to the very latest released version, I no longer support any version older than 2007) "Language Features", and the versions in which they were introduced and (where applicable) deprecated, improved or removed.</p> <p>I have noted similar questions to this on Stack Overflow before, though most of those were phrased in the form of "which feature is best", and closed as deemed unsuitable.</p> <p>If anyone knows of such a list (or has enough spare time to compile one), I would be very grateful.</p> <p>The accepted answer will either contain a link to such a list, or the list itself.</p>
8,460,108
3
3
null
2011-12-10 21:31:31.86 UTC
98
2022-08-01 23:03:04.927 UTC
2022-08-01 22:56:20.193 UTC
null
62,576
null
590,975
null
1
120
delphi
32,437
<p><strong>Note that this answer only lists new <em>language</em> features</strong><br /> <em><strong>not</strong> new VCL/FMX features.</em></p> <p>Here are the links to the RAD Studio docwiki:</p> <ul> <li><a href="https://docwiki.embarcadero.com/RADStudio/Alexandria/en/What%27s_New" rel="nofollow noreferrer">What's new in RAD Studio 11 Alexandria</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/Sydney/en/What%27s_New" rel="nofollow noreferrer">What's new in Rad Studio 10.4 Sydney</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/Rio/en/What%27s_New" rel="nofollow noreferrer">What's new in Rad Studio 10.3 Rio</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/Tokyo/en/What%27s_New" rel="nofollow noreferrer">What's new in Delphi and C++Builder 10.2 Tokyo</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/Berlin/en/What%27s_New" rel="nofollow noreferrer">What's new in Delphi and C++Builder 10.1 Berlin</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/Seattle/en/What%27s_New" rel="nofollow noreferrer">What's new in Delphi and C++Builder 10 Seattle</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/XE8/en/What%27s_New_in_Delphi_and_C++Builder_XE8" rel="nofollow noreferrer">What's new in Delphi and C++Builder XE8</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/XE7/en/What%27s_New_in_Delphi_and_C++Builder_XE7" rel="nofollow noreferrer">What's New in Delphi and C++Builder XE7</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/XE6/en/What%27s_New_in_Delphi_and_C++Builder_XE6" rel="nofollow noreferrer">What's New in Delphi and C++Builder XE6</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/XE5/en/What%27s_New_in_Delphi_and_C++Builder_XE5" rel="nofollow noreferrer">What's New in Delphi and C++Builder XE5</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/XE4/en/What%27s_New_in_Delphi_and_C%2B%2BBuilder_XE4" rel="nofollow noreferrer">What's New in Delphi and C++Builder XE4</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/en/What%27s_New_in_Delphi_and_C%2B%2BBuilder_XE3" rel="nofollow noreferrer">What's New in Delphi and C++Builder XE3</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/en/What%27s_New_in_Delphi_and_C++Builder_XE2" rel="nofollow noreferrer">What's New in Delphi and C++Builder XE2</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/en/What%27s_New_in_Delphi_and_C++Builder_XE" rel="nofollow noreferrer">What's New in Delphi and C++Builder XE</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/XE3/en/What%27s_New_in_Delphi_and_C++Builder_2010" rel="nofollow noreferrer">What's New in Delphi and C++Builder 2010</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/XE4/en/What%27s_New_in_Delphi_and_C%2B%2BBuilder_2009" rel="nofollow noreferrer">What's New in Delphi and C++Builder 2009</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/en/What%27s_New_in_RAD_Studio_%28Delphi_for_Win32_2007%29" rel="nofollow noreferrer">What's New in RAD Studio (Delphi for Win32 2007)</a></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/en/What%27s_New_in_RAD_Studio_%28C++Builder_2007%29" rel="nofollow noreferrer">What's New in RAD Studio (C++Builder 2007)</a></li> <li><a href="http://edn.embarcadero.com/article/33411" rel="nofollow noreferrer">What’s New in Delphi 2006</a></li> <li><a href="http://edn.embarcadero.com/article/32778" rel="nofollow noreferrer">What’s New in Delphi 2005</a></li> <li><a href="http://edn.embarcadero.com/article/images/28980/D7_whats_new.pdf" rel="nofollow noreferrer">What’s New in Delphi 7</a></li> <li><a href="http://www.drbob42.com/examines/examin19.htm" rel="nofollow noreferrer">What’s New in Delphi 6</a></li> <li><a href="http://web.archive.org/web/20010210005242/http://www.borland.com/delphi/whatsnew.html" rel="nofollow noreferrer">What’s New in Delphi 5</a></li> <li><a href="http://web.archive.org/web/20010419235658/http://www.borland.com/delphi/del4/del4newfeat.html" rel="nofollow noreferrer">What's New in Delphi 4</a></li> <li><a href="http://www.tempest-sw.com/secrets/delphi3.htm" rel="nofollow noreferrer">What's New in Delphi 3</a></li> <li><a href="http://web.archive.org/web/20010428075910/http://www.borland.com/delphi/del2/" rel="nofollow noreferrer">What's New in Delphi 2</a></li> <li><a href="http://web.archive.org/web/20010511115847/http://www.borland.com/delphi/del1/" rel="nofollow noreferrer">Delphi 1 Features</a></li> </ul> <p>The full list from Embarcadero: <a href="http://docwiki.embarcadero.com/RADStudio/en/What%27s_New" rel="nofollow noreferrer">What's New</a><br /> See also: <a href="http://www.slideshare.net/embarcaderotechnet/delphi-innovations-from-delphi-1-through-delphi-xe5" rel="nofollow noreferrer">David I's list</a><br /> See also: <a href="https://github.com/ideasawakened/DelphiKB/wiki/Delphi-Master-Release-List" rel="nofollow noreferrer">Delphi Master Release List wiki</a></p> <hr /> <p>To summarize:</p> <p><strong><a href="https://docwiki.embarcadero.com/RADStudio/Alexandria/en/What%27s_New" rel="nofollow noreferrer">Delphi 11</a></strong></p> <ul> <li>Binary Literals and Digit Separators</li> <li>Inline assembler support for AVX instructions (AVX-512)</li> <li>New record helpers: <a href="https://docwiki.embarcadero.com/Libraries/Alexandria/en/System.DateUtils.TDateTimeHelper" rel="nofollow noreferrer">TDateTimeHelper</a> and <a href="https://docwiki.embarcadero.com/Libraries/Alexandria/en/System.SysUtils.TCurrencyHelper" rel="nofollow noreferrer">TCurrencyHelper</a></li> <li>macOS ARM 64-bit target platform</li> </ul> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/Sydney/en/What%27s_New" rel="nofollow noreferrer">Delphi 10.4</a></strong></p> <ul> <li>Unified memory management on all platforms - full ARC compiler has been removed and all compilers now use manual (classic) memory management for objects</li> <li><a href="http://docwiki.embarcadero.com/RADStudio/Sydney/en/Custom_Managed_Records" rel="nofollow noreferrer">Custom managed records</a></li> <li>Support for macOS 64-bit</li> <li>Support for Android 64-bit</li> </ul> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/Rio/en/What%27s_New" rel="nofollow noreferrer">Delphi 10.3</a></strong></p> <ul> <li><a href="https://community.embarcadero.com/blogs/entry/directions-for-arc-memory-management-in-delphi" rel="nofollow noreferrer">The 64-bit Linux compiler no longer uses ARC</a>, it instead uses the default manual managed, which is the same as in the Windows compiler. This makes porting code from Windows or OSX to Linux much easier.</li> <li><a href="https://community.embarcadero.com/blogs/entry/introducing-inline-variables-in-the-delphi-language" rel="nofollow noreferrer">Inline variables</a> with automatic type inference</li> <li>8 bit AnsiChar/AnsiString support in enabled on Linux.</li> <li>C++Builder and Delphi now use the same ABI for all calls.</li> </ul> <p><strong><a href="http://community.embarcadero.com/article/news/16211-embarcadero-rad-studio-2016-product-approach-and-roadmap-2" rel="nofollow noreferrer">Delphi 10.2 Tokyo</a></strong></p> <ul> <li>Support for Linux server apps (Intel 64-bit using LLVM and ARC).</li> <li><a href="https://community.embarcadero.com/pt/blogs/entry/new-warnings-illegal-casts-and-other-delphi-compiler-changes-in-10-2-tokyo" rel="nofollow noreferrer">Assigning a dynamic arrays to a pointer using the <code>@</code> operator is only allowed when hard-casting the array.</a></li> <li><a href="https://community.embarcadero.com/pt/blogs/entry/new-warnings-illegal-casts-and-other-delphi-compiler-changes-in-10-2-tokyo" rel="nofollow noreferrer">More flexible namespace resolution of unit names</a></li> </ul> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/Berlin/en/What%27s_New" rel="nofollow noreferrer">Delphi 10.1 Berlin</a></strong></p> <ul> <li>Native support for <a href="http://docwiki.embarcadero.com/Libraries/Berlin/en/System.UTF8String" rel="nofollow noreferrer">Utf8String</a> and <a href="http://docwiki.embarcadero.com/Libraries/Berlin/en/System.RawByteString" rel="nofollow noreferrer">RawByteString</a> type on all platforms</li> <li>The <a href="http://docwiki.embarcadero.com/RADStudio/Berlin/en/Compiler_Attributes#Unsafe" rel="nofollow noreferrer"><code>[weak]</code>, <code>[unsafe]</code> and <code>[volatile]</code> attributes</a> are supported on all compilers.</li> <li><a href="http://docwiki.embarcadero.com/Libraries/Berlin/en/System.Extended" rel="nofollow noreferrer">The size of extended on OSX is now 16 bytes.</a></li> <li><a href="http://blog.marcocantu.com/blog/2016-june-closing-class-helpers-loophole.html" rel="nofollow noreferrer">class and record helpers cannot access private members of the classes or records they extend</a>.</li> <li>Support for Android up to 6.01.</li> </ul> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/Seattle/en/What%27s_New" rel="nofollow noreferrer">Delphi 10 Seattle</a></strong></p> <ul> <li>Support for Android 5.1.1 and iOS 8.4</li> <li>Improved OSX exception handling</li> </ul> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/XE8/en/What%27s_New_in_Delphi_and_C++Builder_XE8" rel="nofollow noreferrer">Delphi XE8</a></strong></p> <ul> <li>Support for 64-bit iOS;</li> <li>New integer types: <a href="http://docwiki.embarcadero.com/Libraries/XE8/en/System.FixedInt" rel="nofollow noreferrer">FixedInt</a>, <a href="http://docwiki.embarcadero.com/Libraries/XE8/en/System.FixedUInt" rel="nofollow noreferrer">FixedUInt</a> 32-bit integer types on all platforms;</li> <li>New platform dependent integer types: <a href="http://docwiki.embarcadero.com/Libraries/XE8/en/System.Longint" rel="nofollow noreferrer">LongInt</a>, <a href="http://docwiki.embarcadero.com/Libraries/XE8/en/System.LongWord" rel="nofollow noreferrer">LongWord</a> (64-bits on iOS-64, 32-bits on all other platforms);</li> </ul> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/XE7/en/What%27s_New_in_Delphi_and_C++Builder_XE7" rel="nofollow noreferrer">Delphi XE7</a></strong></p> <ul> <li><p><a href="http://blog.marcocantu.com/blog/2014_september_dynamic_arrays_delphixe7.html" rel="nofollow noreferrer">String-Like Operations Supported on Dynamic Arrays</a></p> </li> <li><p><a href="http://community.embarcadero.com/index.php/blogs/entry/parallel-programming-using-the-new-rad-studio-xe7-runtime-library" rel="nofollow noreferrer">Parallel Library added to the RTL</a></p> </li> <li><p><a href="http://delphisorcery.blogspot.com/2014/10/new-language-feature-in-xe7.html" rel="nofollow noreferrer">New compiler intrinsic routines (undocumented):</a></p> <p><code>function IsManagedType(T: TypeIdentifier): Boolean; function HasWeakRef(T: TypeIdentifier): Boolean; function GetTypeKind(T: TypeIdentifier): TTypeKind; function IsConstValue(Value): boolean;</code></p> </li> </ul> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/XE6/en/What%27s_New_in_Delphi_and_C++Builder_XE6" rel="nofollow noreferrer">Delphi XE6</a></strong></p> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/XE5/en/What%27s_New_in_Delphi_and_C++Builder_XE5" rel="nofollow noreferrer">Delphi XE5</a></strong></p> <ul> <li>Android Support;<br /> needs device with ArmV6 + Neon or ArmV7 for deployment<br /> introduces <a href="http://docwiki.embarcadero.com/RADStudio/XE5/en/Conditional_compilation_%28Delphi%29" rel="nofollow noreferrer">conditional define ANDROID</a></li> <li><a href="http://blog.marcocantu.com/blog/class_operators_delphi.html" rel="nofollow noreferrer">Operator overloading for classes (but only for the NextGen compiler {Android/iOS})</a></li> </ul> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/XE4/en/What%27s_New_in_Delphi_and_C%2B%2BBuilder_XE4" rel="nofollow noreferrer">Delphi XE4</a></strong></p> <ul> <li><p>The following new conditionals are introduced/enabled in XE4:<br /> AUTOREFCOUNT<br /> CPUARM<br /> EXTERNAL_LINKER<br /> IOS<br /> NEXTGEN<br /> UNDERSCOREIMPORTNAME<br /> WEAKREF<br /> WEAKINSTREF<br /> WEAKINTREF</p> </li> <li><p>Reintroduced support for iOS.</p> </li> <li><p>New <a href="http://docwiki.embarcadero.com/RADStudio/XE8/en/Procedures_and_Functions#Specifying_Dependencies_of_the_Library" rel="nofollow noreferrer"><code>dependency</code> directive</a> for specifying the dependencies of an external library (undocumented until XE8).</p> </li> <li><p><a href="http://blog.marcocantu.com/blog/automatic_reference_counting_for_delphi.html" rel="nofollow noreferrer">ARC support</a> in NextGen compilers (including <a href="http://docwiki.embarcadero.com/Libraries/XE4/en/System.TObject.DisposeOf" rel="nofollow noreferrer">TObject.DisposeOf</a>).<br /> <sub><a href="http://blog.synopse.info/post/2012/10/06/Delphi-XE3-is-preparing-reference-counting-for-class-instances" rel="nofollow noreferrer">Note that much of the groundwork for ARC was already in XE3, but much of it was disabled</a></sub></p> </li> <li><p><a href="http://docwiki.embarcadero.com/RADStudio/Seattle/en/IFEND_directive_%28Delphi%29" rel="nofollow noreferrer">Before the XE4 release, <code>$IF</code> statements could only be terminated with <code>$IFEND</code></a>, and the <code>$IFDEF</code>, <code>$IFNDEF</code>, <code>$IFOPT</code> directives could only be terminated with <code>$ENDIF</code>.</p> </li> </ul> <p>At XE4, this changed so that $ENDIF became an accepted terminator for $IF, $IFDEF, $IFNDEF, and $IFOPT.</p> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/en/What%27s_New_in_Delphi_and_C%2B%2BBuilder_XE3" rel="nofollow noreferrer">Delphi XE3</a></strong></p> <ul> <li><a href="http://delphi.about.com/od/objectpascalide/a/delphi-record-helpers-for-sets-and-other-simple-types.htm" rel="nofollow noreferrer">Record helpers for built-in types</a></li> <li>Removed support for iOS.</li> <li>Atomic intrinsic functions:<br /> <a href="http://docwiki.embarcadero.com/Libraries/XE4/en/System.AtomicExchange" rel="nofollow noreferrer"><code>AtomicExchange()</code></a>, <a href="http://docwiki.embarcadero.com/Libraries/XE4/en/System.AtomicIncrement" rel="nofollow noreferrer"><code>AtomicIncrement()</code></a>, <a href="http://docwiki.embarcadero.com/Libraries/XE4/en/System.AtomicCmpExchange" rel="nofollow noreferrer"><code>AtomicCmpExchange()</code></a>, <a href="http://docwiki.embarcadero.com/Libraries/XE4/en/System.AtomicDecrement" rel="nofollow noreferrer"><code>AtomicDecrement()</code></a></li> <li>Introduction of the <a href="http://docwiki.embarcadero.com/RADStudio/Berlin/en/Parameters_(Delphi)#Constant_Parameters" rel="nofollow noreferrer">[ref] attribute</a>.</li> </ul> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/en/What%27s_New_in_Delphi_and_C++Builder_XE2" rel="nofollow noreferrer">Delphi XE2</a></strong></p> <ul> <li><p>Cross platform support for Mac OSX (32-bit) and iOS;</p> </li> <li><p>Support for Win64;</p> </li> <li><p>Modified RTL to support cross platform;</p> </li> <li><p><a href="https://stackoverflow.com/questions/8460862/what-does-packed-now-forces-byte-alignment-of-records-mean"><code>Packed</code> Now Forces Byte Alignment of Records</a> (Pre XE2 it did not necessarily do this)</p> </li> <li><p>Eight new DEFINEs have been added:</p> <p>ALIGN_STACK<br /> CPUX86<br /> CPUX64<br /> MACOS (Mac operating system)<br /> MACOS32<br /> PC_MAPPED_EXCEPTIONS<br /> PIC<br /> WIN64</p> </li> <li><p><a href="http://docwiki.embarcadero.com/RADStudio/XE7/en/Unit_Scope_Names" rel="nofollow noreferrer">Full unit scope names are now required in your <code>uses</code> clause.</a></p> </li> <li><p><a href="http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Floating_point_precision_control_%28Delphi_for_x64%29" rel="nofollow noreferrer"><code>{$ExcessPrecision on/off}</code> compiler directive</a> (x64 only)</p> </li> <li><p>The build-in types differ depending on the target platform (32/64-bit)</p> <ul> <li>Extended Data Type Is 10 bytes on Win32, but 8 (!) bytes on Win64</li> </ul> </li> </ul> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/en/What%27s_New_in_Delphi_and_C++Builder_XE" rel="nofollow noreferrer">Delphi XE</a></strong></p> <ul> <li>The <code>{$STRINGCHECKS}</code> compiler directive is ignored in XE;</li> <li>New 16-byte value for the <code>{$ALIGN}</code> directive: The acceptable values for the <code>{$ALIGN}</code> directive now include 1, 2, 4, 8, and 16.</li> <li>new <code>{$CODEALIGN}</code> directive, this sets the starting address for a procedure or function.</li> <li>The <code>{$STRONGLINKTYPES ON}</code> directive</li> <li>Support for regular expressions.</li> </ul> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/XE3/en/What%27s_New_in_Delphi_and_C++Builder_2010" rel="nofollow noreferrer">Delphi 2010</a></strong></p> <ul> <li>Enhanced Delphi RTTI (Run Time Type Information).</li> <li><a href="http://delphi.about.com/od/oopindelphi/a/delphi-attributes-understanding-using-attributes-in-delphi.htm" rel="nofollow noreferrer">Attributes</a></li> <li>The <code>as</code> operator can be used to cast an interface reference back to the object from which it was extracted.</li> <li>The <code>is</code> operator can be used to verify whether an interface reference was extracted from a certain class.</li> <li>Normal unsafe casting can be performed on an interface: <code>TObject(SomeInterface)</code>.</li> <li>new <code>delayed</code> directive indicates that an external library such as a DLL is not to be loaded at declaration time but is to wait until the first call to the method</li> <li><a href="http://docwiki.embarcadero.com/RADStudio/Seattle/en/Methods#Class_Constructors" rel="nofollow noreferrer">Class Constructor/Destructor</a></li> </ul> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/XE4/en/What%27s_New_in_Delphi_and_C%2B%2BBuilder_2009" rel="nofollow noreferrer">Delphi 2009</a></strong></p> <ul> <li>Intrinsic type <code>string</code> now maps to <code>UnicodeString</code>;</li> <li><a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devcommon/compdirshighcharunicode_xml.html" rel="nofollow noreferrer"><code>{$HighCharUnicode on|off}</code> compiler directive</a></li> <li><a href="http://delphi.about.com/od/objectpascalide/a/understanding-generic-types-in-delphi.htm" rel="nofollow noreferrer">Generics</a>;</li> <li><a href="https://stackoverflow.com/a/30417597/650492"><code>function Default(T): T</code> intrinsic function (Undocumented)</a></li> <li><a href="http://blog.barrkel.com/2008/09/smart-pointers-in-delphi.html" rel="nofollow noreferrer">Smart pointers</a>;</li> <li><a href="http://delphi.about.com/od/objectpascalide/a/understanding-anonymous-methods-in-delphi.htm" rel="nofollow noreferrer">Anonymous methods</a>;</li> <li><a href="http://eurekalog.blogspot.com.au/2010/05/new-exception-class-in-delphi-2009-and_05.html" rel="nofollow noreferrer">Support for nested exceptions and exception tracing</a>;</li> <li>support for pointermath and a new compiler directive: <code>{$PointerMath on|off}</code>;</li> <li>Four new compiler warnings: <ul> <li><code>W1057 Implicit string cast from '%s' to '%s'</code>,</li> <li><code>W1058 Implicit string cast with potential data loss from '%s' to '%s'</code>,</li> <li><code>W1059 Explicit string cast from '%s' to '%s'</code>,</li> <li><code>W1060 Explicit string cast with potential data loss from '%s' to '%s'</code>;</li> </ul> </li> <li>The <code>Exit</code> function can take a parameter specifying a result;</li> <li><code>resourcestrings</code> as Widestrings;</li> <li><code>TObject</code> has a <a href="http://blogs.teamb.com/craigstuntz/2009/03/25/38138/" rel="nofollow noreferrer">extra hidden pointer to <code>TMonitor</code></a> in addition to its VMT pointer;</li> <li>the <code>deprecated</code> keyword can now have additional text</li> </ul> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/en/What%27s_New_in_RAD_Studio_%28Delphi_for_Win32_2007%29" rel="nofollow noreferrer">Delphi 2007</a></strong></p> <ul> <li>No language changes that I know of;<br /> <em>Note that Delphi 2007 is a non-breaking release, DCU's from D2006 will work unchanged in D2007</em>;</li> <li><em>(The .NET 'personality' of 2007 <a href="http://hallvards.blogspot.nl/2007/08/highlander2-beta-generics-in-delphi-for.html" rel="nofollow noreferrer">introduced generics</a>)</em></li> </ul> <p><strong><a href="http://docwiki.embarcadero.com/RADStudio/en/What%27s_New_in_RAD_Studio_%28C++Builder_2007%29" rel="nofollow noreferrer">Delphi 2006</a></strong></p> <ul> <li><a href="https://stackoverflow.com/questions/843387/when-should-i-use-enhanced-record-types-in-delphi-instead-of-classes">Enhanced records</a>;</li> <li><a href="https://stackoverflow.com/questions/1587777/what-kinds-of-operator-overloads-does-delphi-support">operator overloading</a>;</li> <li><code>static</code> methods and properties;</li> <li>FastMM is the default memory manager;</li> <li><a href="https://stackoverflow.com/questions/1516493/difference-between-strict-private-and-protected-access-modifiers-in-delphi"><code>strict</code> private/protected visibility keyword</a>;</li> <li><code>final</code> keyword for virtual methods;</li> <li><code>{$METHODINFO}</code> directive;</li> </ul> <p><strong><a href="http://edn.embarcadero.com/article/33411" rel="nofollow noreferrer">Delphi 2005</a></strong></p> <ul> <li><code>for ... in</code> loops,</li> <li><code>inline</code> keyword</li> <li>Wildcard in uses statement allowed</li> <li>nested types</li> <li>nested constants</li> <li><code>{$REGION}</code>/<code>{$ENDREGION}</code> directives</li> <li><a href="https://stackoverflow.com/questions/253399/what-are-good-uses-for-class-helpers">class helpers</a> (added in Delphi 8 for .net);</li> </ul> <p><strong><a href="http://edn.embarcadero.com/article/32778" rel="nofollow noreferrer">Delphi 7</a></strong></p> <ul> <li>three additional compiler warnings:</li> <li>Unsafe_Type,</li> <li>Unsafe_Code, and</li> <li>Unsafe_Cast. <em>These warnings are disabled by default, but can be enabled</em></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/Seattle/en/Warning_messages_%28Delphi%29" rel="nofollow noreferrer">new compiler directive <code>{$WARN UNSAFE_CODE ON}</code></a></li> <li>Overloads of routines that format and parse numbers, date-time values, and currency using a <code>TFormatSettings</code> structure.</li> </ul> <p><strong><a href="http://edn.embarcadero.com/article/images/28980/D7_whats_new.pdf" rel="nofollow noreferrer">Delphi 6</a></strong></p> <ul> <li><code>[TCustomVariantType][68]</code> provides <a href="http://docwiki.embarcadero.com/RADStudio/Berlin/en/Implementing_Binary_Operations" rel="nofollow noreferrer">operator overloading for custom variant types</a></li> <li>New compiler directives: <ul> <li><code>{$IFDEF MSWINDOWS}</code></li> <li><code>{$IFDEF LINUX}</code></li> <li><a href="https://books.google.co.za/books?id=YbS3dPcobl8C&amp;pg=PA495&amp;lpg=PA495&amp;dq=$LIBPREFIX%20delphi&amp;source=bl&amp;ots=woTSgancta&amp;sig=8Bl__UwwlrbsdS3CpPl5fDzmhGE&amp;hl=en&amp;sa=X&amp;ei=DUElVe3YI6up7Abfz4HQDw&amp;ved=0CCwQ6AEwAg#v=onepage&amp;q=%24LIBPREFIX%20delphi&amp;f=false" rel="nofollow noreferrer"><code>{$LIBPREFIX}</code></a></li> <li><a href="https://books.google.co.za/books?id=YbS3dPcobl8C&amp;pg=PA495&amp;lpg=PA495&amp;dq=$LIBPREFIX%20delphi&amp;source=bl&amp;ots=woTSgancta&amp;sig=8Bl__UwwlrbsdS3CpPl5fDzmhGE&amp;hl=en&amp;sa=X&amp;ei=DUElVe3YI6up7Abfz4HQDw&amp;ved=0CCwQ6AEwAg#v=onepage&amp;q=%24LIBPREFIX%20delphi&amp;f=false" rel="nofollow noreferrer"><code>{$LIBSUFFIX}</code></a></li> <li><a href="https://books.google.co.za/books?id=YbS3dPcobl8C&amp;pg=PA495&amp;lpg=PA495&amp;dq=$LIBPREFIX%20delphi&amp;source=bl&amp;ots=woTSgancta&amp;sig=8Bl__UwwlrbsdS3CpPl5fDzmhGE&amp;hl=en&amp;sa=X&amp;ei=DUElVe3YI6up7Abfz4HQDw&amp;ved=0CCwQ6AEwAg#v=onepage&amp;q=%24LIBPREFIX%20delphi&amp;f=false" rel="nofollow noreferrer"><code>{$LIBVERSION}</code></a></li> <li><a href="https://stackoverflow.com/questions/6162457/can-i-generate-a-custom-compiler-error-if-so-how/6162482#6162482"><code>{$MESSAGE 'message'}</code></a></li> <li><code>{$SetPEFlags}</code></li> </ul> </li> <li>Support for <code>{$IF}{$ELSE}</code> compiler directives</li> <li><a href="http://docwiki.embarcadero.com/RADStudio/XE4/en/Declarations_and_Statements#Hinting_Directives" rel="nofollow noreferrer">Compiler hinting directives: <code>experimental</code>, <code>deprecated</code>, <code>library</code>, <code>platform</code></a> (but without additional text for deprecated)</li> <li>Variant is no longer based on COM but changed to be CLX compatible, COM based variant renamed to <code>OLEVariant</code></li> <li><a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devcommon/compdirswriteabletypedconstants_xml.html" rel="nofollow noreferrer">Typed constants cannot be assigned to <em>(Override with <code>{$J+}</code>)</em></a></li> <li>Enumerated types can be assigned an explicit value (cf C++);</li> <li>Interface properties</li> <li>Support for calling <code>varargs</code> external functions (but only for the <code>cdecl</code> calling convention)</li> <li>custom variants</li> </ul> <p><strong><a href="http://www.drbob42.com/examines/examin19.htm" rel="nofollow noreferrer">Delphi 5</a></strong></p> <p>No new language features, but:</p> <ul> <li><a href="http://docwiki.embarcadero.com/RADStudio/Seattle/en/Working_with_Frames" rel="nofollow noreferrer">Support added for Frames</a></li> </ul> <p><strong><a href="http://web.archive.org/web/20010419235658/http://www.borland.com/delphi/del4/del4newfeat.html" rel="nofollow noreferrer">Delphi 4</a></strong></p> <ul> <li><a href="http://www.drbob42.com/delphi4/dynarray.htm" rel="nofollow noreferrer">Dynamic arrays</a></li> <li><code>LongWord</code> and <code>Int64</code>; <code>Cardinal</code> is an UINT32 <em>(before it was unsigned 31-bit value)</em></li> <li><code>Real</code> takes 8 bytes and is the same as <code>double</code> (previously it was 6 bytes); <ul> <li>Override with the new <code>{$REALCOMPATIBILITY ON}</code> compiler directive;</li> <li><code>REAL48</code> replaces the old 6-byte <code>real</code>;</li> </ul> </li> <li>Support for <code>resourcestrings</code></li> <li><a href="http://www.drbob42.com/delphi4/overload.htm" rel="nofollow noreferrer">Method overloading</a></li> <li><a href="http://www.drbob42.com/delphi4/defparam.htm" rel="nofollow noreferrer">Default parameters</a></li> <li><code>{$EXTERNALSYM}</code> and <code>{$NODEFINE}</code> directives</li> <li><a href="http://docwiki.embarcadero.com/RADStudio/Seattle/en/Using_Implements_for_Delegation" rel="nofollow noreferrer"><code>implements</code> keyword</a> for properties</li> </ul> <p><strong><a href="http://www.tempest-sw.com/secrets/delphi3.htm" rel="nofollow noreferrer">Delphi 3</a></strong></p> <ul> <li>Wordbool, longbool and bytebool store <code>true</code> as <code>-1</code> instead of 1 (Boolean is unchanged)</li> <li>Components must be installed using <code>packages</code>.</li> <li>Assertions.</li> <li><code>out</code> parameters.</li> <li><code>Widestring</code></li> <li><code>interface</code> and <code>dispinterface</code> keyword and COM (<code>dispid</code>) support.</li> </ul> <p><strong><a href="http://web.archive.org/web/20010428075910/http://www.borland.com/delphi/del2/" rel="nofollow noreferrer">Delphi 2</a></strong></p> <ul> <li>Support for 32-bit;</li> <li><code>Ansistring</code> replaces <code>shortstring</code> as the default string type</li> <li><code>Currency</code></li> <li><a href="http://docwiki.embarcadero.com/RADStudio/XE6/en/Variant_Types" rel="nofollow noreferrer"><code>Variant</code></a> (for interop with OLE automation).</li> <li>Threading support and <a href="http://www.delphibasics.co.uk/RTL.asp?Name=ThreadVar" rel="nofollow noreferrer"><code>ThreadVar</code></a> keyword.</li> <li>4 byte data is 4 byte aligned new <code>packed</code> keyword overrides this behavior;</li> <li>TDateTime starts at <code>1899/12/30</code> <em>under D1 it started at <code>0000/00/00</code></em></li> <li>new <code>finalization</code> keyword</li> <li><code>register</code> and <code>stdcall</code> calling conventions added.</li> <li><code>packed</code> keyword.</li> </ul>
8,882,753
Clang on Windows
<p>First of all, I've followed <a href="http://clang.llvm.org/get_started.html" rel="noreferrer">"Getting Started: Building and Running Clang"</a>. In particular, I've built it according to "Using Visual Studio" section. In other words, I've built it using Visual Studio 2010.</p> <p>Secondly, I've manually set include and library paths to MinGW distribution:</p> <p><img src="https://i.stack.imgur.com/qzw8D.png" alt="enter image description here"></p> <p>The simple program I'm trying to compile:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { cout &lt;&lt; "Hello, World!" &lt;&lt; endl; return 0; } </code></pre> <p>I get the following feedback from the compiler:</p> <pre><code>In file included from C:\MinGW\lib\gcc\mingw32\4.5.2\include\c++\iostream:39: In file included from C:\MinGW\lib\gcc\mingw32\4.5.2\include\c++\ostream:39: In file included from C:\MinGW\lib\gcc\mingw32\4.5.2\include\c++\ios:38: In file included from C:\MinGW\lib\gcc\mingw32\4.5.2\include\c++\iosfwd:41: In file included from C:\MinGW\lib\gcc\mingw32\4.5.2\include\c++\bits/postypes.h:41: C:\MinGW\lib\gcc\mingw32\4.5.2\include\c++\cwchar:144:11: error: no member named 'fgetws' in the global namespace using ::fgetws; ~~^ C:\MinGW\lib\gcc\mingw32\4.5.2\include\c++\cwchar:146:11: error: no member named 'fputws' in the global namespace using ::fputws; ~~^ C:\MinGW\lib\gcc\mingw32\4.5.2\include\c++\cwchar:150:11: error: no member named 'getwc' in the global namespace using ::getwc; ~~^ C:\MinGW\lib\gcc\mingw32\4.5.2\include\c++\cwchar:151:11: error: no member named 'getwchar' in the global namespace using ::getwchar; ~~^ C:\MinGW\lib\gcc\mingw32\4.5.2\include\c++\cwchar:156:11: error: no member named 'putwc' in the global namespace using ::putwc; ~~^ C:\MinGW\lib\gcc\mingw32\4.5.2\include\c++\cwchar:157:11: error: no member named 'putwchar' in the global namespace using ::putwchar; ~~^ 6 errors generated. Build error occurred, build is stopped Time consumed: 646 ms. </code></pre> <p>The obvious question is - why do I get this?</p> <p>Additionally, I would like to know more details, and since, Clang website provides extremely brief information - I thought that somebody could clarify the following questions to me:</p> <ol> <li>As far as I understand Clang does not have its own standard library (stdc++ I guess, isn't it?). That's why I have to use MinGW's headers and libraries - am I right?</li> <li>What is the difference between building Clang with Visual Studio and MinGW?</li> <li>Do I have to hard-code include paths in <code>clang/lib/Frontend/InitHeaderSearch.cpp</code> or I can skip it and rather specify those paths later through "-I" option as I do in the screenshot above?</li> </ol>
8,883,505
2
4
null
2012-01-16 16:08:03.25 UTC
12
2020-11-04 08:51:28.077 UTC
null
null
null
null
1,743,860
null
1
23
c++|windows|mingw|llvm|clang
37,222
<p>If you build Clang with MSVS, it will automatically search the default VS include paths, and pull in those headers. This is the reason the libstdc++ headers are producing errors: they are importing C functions not present in the VS headers. Using Clang for C++ with VS is for now a no-go: you will get link failures due to missing ABI (name mangling and others) functionality in Clang. If you still want to use the MSVS Clang, don't point it to MinGW headers. It will parse the VS headers (including C++), it just will fail to link.</p> <hr> <p><strong>EDIT</strong>: I have built a dw2 version of GCC (32-bit only) accompanied by Clang. Exceptions work in this build, and so you can build real C++ stuff with Clang now on Windows. <a href="http://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win32/Personal%20Builds/rubenvb/clang-3.2-release/">Get version 3.2 here</a>.</p>
8,400,101
Android: Accessing images from assets/drawable folders
<p>The app I am currently working on has hundreds of images. At the moment I store them in the 'Drawable' folder. I was thinking about moving all of them to Assets folder. </p> <p>My question is: Is there any difference in performance when using both approaches? </p>
8,400,282
4
4
null
2011-12-06 12:47:48.04 UTC
5
2015-04-04 13:01:14.877 UTC
null
null
null
null
400,493
null
1
28
android|image|drawable|assets
9,791
<p><strong>I don't think so there is bit difference in performance of using these two folders</strong>, I think using drawable folder you can get easily images (All will be indexed in the R file, which makes it much faster (and much easier!) to load them.), and If you want to use it from asset then you have to use <code>AssetManager</code> then using <code>AssetFileDescriptor</code> you have to get those images. </p> <ul> <li><p><code>Assets</code> can also be organized into a folder hierarchy, which is not supported by resources. It's a different way of managing data. Although resources cover most of the cases, assets have their occasional use.</p></li> <li><p>In the <code>res/drawable</code> directory each file is given a pre-compiled ID which can be accessed easily through R.id.[res id]. This is useful to quickly and easily access images, sounds, icons...</p></li> </ul>
5,321,344
Android Animation: Wait until finished?
<p>I would like to wait until an animation is finished* in an Android ImageView before continuing program execution, what is the proper way to do this?</p> <ul> <li>(in this context "finished" means that it runs through all of its frames exactly one time and stops on the last one. I am unclear whether this animation will be an android:oneshot="true" animation because I will be using it multiple times, but it will not be run continuously but intermittently)</li> </ul> <p>Research/Guesses:</p> <p>A. At heart my question seems to be a Java thread question because the Android <a href="http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html" rel="noreferrer">AnimationDrawable</a> implements <a href="http://developer.android.com/reference/java/lang/Runnable.html" rel="noreferrer">Java.lang.Runnable</a>. So maybe threads are the solution. Perhaps the answer will include <a href="http://download.oracle.com/javase/tutorial/essential/concurrency/join.html" rel="noreferrer">join</a>?</p> <p>B. The approach of others seems to have been to use <a href="https://stackoverflow.com/questions/4750939/android-animation-is-not-finished-in-onanimationend">AnimationListener</a>, this seems difficult and needlessly complex for my simple needs. Plus I'm not exactly sure how to do it.</p> <p>C. The <a href="http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html#isRunning%28%29" rel="noreferrer">AnimationDrawable</a> class has a (boolean) isRunning method which could probably be used in a while loop (i.e. while(anim.isRunning()){wait(100ms)}). But I have a gut feeling that this is the wrong approach. Although something similar seems to be mentioned in the <a href="http://download.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html" rel="noreferrer">concurrency tutorial</a></p> <p>Code Snippet</p> <pre><code> this.q_pic_view.setImageResource(0); this.q_pic_view.setBackgroundResource(R.drawable.animation_test); AnimationDrawable correct_animation = (AnimationDrawable) this.q_pic_view.getBackground(); correct_animation.start(); //here I tried to implement option C but it didn't work while(correct_animation.isRunning()){ try { Thread.sleep(20); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } </code></pre> <p>Animation</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;animation-list android:id="@+id/AnimTest" android:oneshot="true" xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:drawable="@drawable/animtest001" android:duration="33"/&gt; &lt;item android:drawable="@drawable/animtest002" android:duration="100"/&gt; &lt;item android:drawable="@drawable/animtest003" android:duration="66"/&gt; &lt;item android:drawable="@drawable/animtest004" android:duration="66"/&gt; &lt;item android:drawable="@drawable/animtest005" android:duration="33"/&gt; &lt;item android:drawable="@drawable/animtest006" android:duration="66"/&gt; &lt;item android:drawable="@drawable/animtest007" android:duration="33"/&gt; &lt;item android:drawable="@drawable/animtest008" android:duration="66"/&gt; &lt;item android:drawable="@drawable/animtest009" android:duration="100"/&gt; &lt;item android:drawable="@drawable/animtest010" android:duration="100"/&gt; &lt;/animation-list&gt; </code></pre> <p>One Possible way to achieve the desired effect, though not an answer to my question, is to delay the execution of further code by doing something like this:</p> <pre><code>int duration = 0; //Add all of the frames together for (int i=0; i&lt;my_animation.getNumberOfFrames(); i++){ duration = duration + correct_animation.getDuration(i); } //delay the execution Handler handler = new Handler(); handler.postDelayed(new Runnable(){ public void run() { DoYourNextStuff(); } }, duration); //delay is here </code></pre> <p>Edit: There are many ways to solve this problem, the answer given probably does solve the problem <em>I didn't test it</em>, but I ended up just waiting the correct amount of time (at first), then I changed to using an async task (which has a handler method for completion) and ran my animation in the updateProgress call of the async task directly. In the last iteration I am using a threaded surface view to run the animation. This last way is by far the fastest and best (for reasons other then those asked about in this post). I hope it helps someone.</p>
5,321,508
4
3
null
2011-03-16 05:16:15.323 UTC
14
2015-02-06 09:31:32.203 UTC
2017-05-23 12:03:02.517 UTC
null
-1
null
530,634
null
1
33
java|android|concurrency|android-animation
63,262
<p>Suggest you </p> <ul> <li>Create an object to encapsulate the "animation" lifetime</li> <li>In the object, you'll have a thread OR a Timer</li> <li>Provide methods to <code>start()</code> the animation and <code>awaitCompletion()</code></li> <li>Use a <code>private final Object completionMonitor</code> field to track completion, <code>synchronize</code> on it, and use <code>wait()</code> and <code>notifyAll()</code> to coordinate the <code>awaitCompletion()</code></li> </ul> <p>Code snippet:</p> <pre><code>final class Animation { final Thread animator; public Animation() { animator = new Thread(new Runnable() { // logic to make animation happen }); } public void startAnimation() { animator.start(); } public void awaitCompletion() throws InterruptedException { animator.join(); } } </code></pre> <p>You could also use a <code>ThreadPoolExecutor</code> with a single thread or <code>ScheduledThreadPoolExecutor</code>, and capture each frame of the animation as a <code>Callable</code>. Submitting the sequence of <code>Callable</code>s and using <code>invokeAll()</code> or a <code>CompletionService</code> to block your interested thread until the animation is complete.</p>
4,928,557
How do I create and use a class arrow operator?
<p>So, after researching everywhere for it, I cannot seem to find how to create a class arrow operator, i.e.,</p> <pre><code>class Someclass { operator-&gt; () /* ? */ { } }; </code></pre> <p>I just need to know how to work with it and use it appropriately. - what are its inputs? - what does it return? - how do I properly declare/prototype it?</p>
4,928,626
4
1
null
2011-02-08 01:02:14.473 UTC
17
2018-06-07 05:49:24.087 UTC
null
null
null
null
586,652
null
1
44
c++|class|operator-keyword
53,270
<p>The operator -> is used to overload member access. A small example:</p> <pre><code>#include &lt;iostream&gt; struct A { void foo() {std::cout &lt;&lt; "Hi" &lt;&lt; std::endl;} }; struct B { A a; A* operator-&gt;() { return &amp;a; } }; int main() { B b; b-&gt;foo(); } </code></pre> <p>This outputs:</p> <pre><code>Hi </code></pre>
5,165,753
How to get full stack of StackOverflowError
<p><strong>When observing a StackOverflowError how to retrieve the full call stack?</strong></p> <p>Consider this simple example:</p> <pre><code>public class Overflow { public Overflow() { new Overflow(); } public static void a() { new Overflow(); } public static void main(String[] argv) { a(); } } </code></pre> <p>Now the error reported is:</p> <pre><code>Exception in thread "main" java.lang.StackOverflowError at Overflow.&lt;init&gt;(Overflow.java:11) [last line repeated many times] </code></pre> <p>But I can't see the <code>main</code> and <code>a</code> method in the stack trace. My guess is this is because of overflow, the newest entry on the stack replaces the oldest one (?).</p> <p>Now, how to get the <code>a</code> and <code>main</code> stack entries in the output? </p> <p>The background is I get the a StackOverflowError (but that's not an infinite recursion, because it doesn't happen when increasing stack size) and it's hard to spot the problem in the code. I only get the multiple lines from <code>java.util.regex.Pattern</code> but not the information what code called that. The application is too complicated to set a breakpoint on each call to <code>Pattern</code>s.</p>
19,331,083
5
8
null
2011-03-02 09:50:09.717 UTC
8
2019-07-25 13:07:47.01 UTC
2011-03-02 10:01:18.927 UTC
null
21,234
null
118,587
null
1
38
java|stack-overflow
11,562
<p>The JVM has an artificial limit of 1024 entries that you can have in the stack trace of an Exception or Error, probably to save memory when it occurs (since the VM has to allocate memory to store the stack trace).</p> <p>Fortunately, there is a flag that allows to increase this limit. Just run your program with the following argument:</p> <pre><code>-XX:MaxJavaStackTraceDepth=1000000 </code></pre> <p>This will print up to 1 million entries of your stack trace, which should be more than enough. It is also possible to set this value at <code>0</code> to set the number of entries as unlimited.</p> <p><a href="http://stas-blogspot.blogspot.fr/2011/07/most-complete-list-of-xx-options-for.html#MaxJavaStackTraceDepth" rel="noreferrer">This list of non-standard JVM options</a> gives more details:</p> <blockquote> <p>Max. no. of lines in the stack trace for Java exceptions (0 means all). With Java > 1.6, value 0 really means 0. value -1 or any negative number must be specified to print all the stack (tested with 1.6.0_22, 1.7.0 on Windows). With Java &lt;= 1.5, value 0 means everything, JVM chokes on negative number (tested with 1.5.0_22 on Windows).</p> </blockquote> <p>Running the sample of the question with this flag gives the following result:</p> <pre><code>Exception in thread "main" java.lang.StackOverflowError at Overflow.&lt;init&gt;(Overflow.java:3) at Overflow.&lt;init&gt;(Overflow.java:4) at Overflow.&lt;init&gt;(Overflow.java:4) at Overflow.&lt;init&gt;(Overflow.java:4) (more than ten thousand lines later:) at Overflow.&lt;init&gt;(Overflow.java:4) at Overflow.&lt;init&gt;(Overflow.java:4) at Overflow.a(Overflow.java:7) at Overflow.main(Overflow.java:10) </code></pre> <p>This way, you can find the original callers of the code that threw the Error, even if the actual stack trace is more than 1024 lines long.</p> <p>If you can not use that option, there is still another way, if you are in a recursive function like this, and if you can modify it. If you add the following try-catch:</p> <pre><code>public Overflow() { try { new Overflow(); } catch(StackOverflowError e) { StackTraceElement[] stackTrace = e.getStackTrace(); // if the stack trace length is at the limit , throw a new StackOverflowError, which will have one entry less in it. if (stackTrace.length == 1024) { throw new StackOverflowError(); } throw e; // if it is small enough, just rethrow it. } } </code></pre> <p>Essentially, this will create and throw a new <code>StackOverflowError</code>, discarding the last entry because each one will be sent one level up compared to the previous one (this can take a few seconds, because all these Errors have to be created). When the stack trace will be reduced to 1023 elements, it is simply rethrown. </p> <p>Ultimately this will print the 1023 lines at the bottom of the stack trace, which is not the complete stack trace, but is probably the most useful part of it.</p>
5,589,491
jQuery click event, after appending content
<p>Wondering why the example below doesn't work? </p> <pre><code>&lt;a id="load_list" href="#"&gt;Load the list&lt;/a&gt; &lt;ul&gt;&lt;/ul&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $('#load_list').click(function() { $('ul').append('&lt;li&gt;&lt;a href="#"&gt;Click here&lt;/a&gt;&lt;/li&gt;'); return false; }); $('ul li a').click(function() { alert('Thank you for clicking'); return false; }); }); &lt;/script&gt; </code></pre>
5,589,510
6
2
null
2011-04-08 01:31:42.91 UTC
5
2017-04-25 16:27:19.97 UTC
2013-04-18 13:34:18.11 UTC
null
1,862,225
null
661,803
null
1
25
jquery
68,526
<p>Because the elements that you are appending do not exist when you define the the <code>click</code> handler, they are created dynamically. To fix this you can use the <a href="http://api.jquery.com/delegate/" rel="noreferrer">delegate()</a> method from jQuery.</p> <pre><code>$('ul').delegate('a','click',function() { // your code here ... }); </code></pre> <p><strong>Online example:</strong> <a href="http://jsfiddle.net/J5QJ9/" rel="noreferrer">http://jsfiddle.net/J5QJ9/</a></p>
5,323,777
How to Change Font Size of Cell in uitableview
<p>I tried this, but it is not working.</p> <pre><code>cell.textLabel.adjustsFontSizeToFitWidth=NO; cell.textLabel.minimumFontSize=6; </code></pre> <p>I need a code snippet.</p>
5,323,929
8
0
null
2011-03-16 10:13:45.037 UTC
5
2019-05-15 04:26:27.86 UTC
2019-05-15 04:26:27.86 UTC
null
4,348,556
null
642,943
null
1
40
iphone|cocoa-touch|uitableview|iphone-sdk-3.0
47,079
<pre><code>UIFont *myFont = [ UIFont fontWithName: @"Arial" size: 18.0 ]; cell.textLabel.font = myFont; </code></pre> <p><a href="http://developer.apple.com/library/ios/#documentation/uikit/reference/UIFont_Class/Reference/Reference.html" rel="noreferrer">UIFont reference</a> </p>
4,862,385
SQL Server add auto increment primary key to existing table
<p>As the title, I have an existing table which is already populated with 150000 records. I have added an Id column (which is currently null).</p> <p>I'm assuming I can run a query to fill this column with incremental numbers, and then set as primary key and turn on auto increment. Is this the correct way to proceed? And if so, how do I fill the initial numbers?</p>
4,862,427
16
0
null
2011-02-01 12:11:45.067 UTC
80
2021-08-29 09:55:29.903 UTC
2017-07-14 09:51:28.86 UTC
null
13,302
null
207,752
null
1
303
sql-server|sql-server-2008|primary-key|alter-table
667,982
<p>No - you have to do it the other way around: add it right from the get go as <code>INT IDENTITY</code> - it will be filled with identity values when you do this:</p> <pre><code>ALTER TABLE dbo.YourTable ADD ID INT IDENTITY </code></pre> <p>and then you can make it the primary key:</p> <pre><code>ALTER TABLE dbo.YourTable ADD CONSTRAINT PK_YourTable PRIMARY KEY(ID) </code></pre> <p>or if you prefer to do all in one step:</p> <pre><code>ALTER TABLE dbo.YourTable ADD ID INT IDENTITY CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED </code></pre>
16,748,074
How to convert video to gif in android programmatically
<p>Is it possible to convert recorded <strong>video</strong> into <strong>GIF</strong> in Android programmatically? Can you help me with some sniped code or tell me how to do it? </p>
16,749,193
2
0
null
2013-05-25 09:12:50.28 UTC
11
2013-12-01 18:27:46.953 UTC
null
null
null
null
1,812,147
null
1
7
android
11,690
<ol> <li><p>Import <code>ffmpeg</code> in your project, grab the portion or entire video and convert it to gif.</p> <p>or </p></li> <li><p>Use <code>MediaRetriever</code> to extract range of frames with simple looping through the range and then converting to Drawable or Bitmap so you can save it.</p> <p>or</p></li> <li><p>Grab the frames while the video is playing from the <code>SurfaceViewHolder</code> or <code>SurfaceView</code> Canvas.</p></li> </ol>
16,749,522
symbol table and relocation table in object file
<p>From what I understand, instructions and data in an object file all have addresses. First data item start at address 0 and first instruction also start at address 0. </p> <p>The relocation table contains information about instructions that need to be updated if the addresses in the file change, for example if the file is linked together with another. Line A, in the example below, would be in the relocation table. I don't think B would be in the relocation table, since the address of label "equal" is relative to B. Are these correct assumptions?</p> <p>I know the symbol table show the labels the file have and also labels that haven't been resolved. But what other information does the symbol table contain?</p> <p>Also, when the assembler translates the instructions to binary, what is placed in those instructions that have unresolved references?. B in this example. </p> <pre><code>.data TEXT: .asciiz "Foo" .text .global main main: li t0, 1 beq t0, 1, equal #B equal: la a0, TEXT jal printf #A </code></pre>
16,750,324
1
0
null
2013-05-25 12:21:44.84 UTC
9
2013-05-25 14:02:49.11 UTC
null
null
null
null
1,047,423
null
1
11
assembly|compilation|object-files|symbol-table
21,168
<p>Yes, your assumptions are correct. There are various types of relocations, what the assembler emits into the instruction depends on the type. Generally it's an offset to be added. You can use <code>objdump -dr</code> to see relocations. For better illustration I have changed your code a little:</p> <pre><code>.data .int 0 TEXT: .asciiz "Foo" .text .global main main: li $t0, 1 beq $t0, 1, equal #B bne $t0, 42, foo #C equal: la $a0, TEXT jal printf #A </code></pre> <p>Output of objdump:</p> <pre><code>00000000 &lt;main&gt;: 0: 24080001 li t0,1 4: 24010001 li at,1 8: 11010004 beq t0,at,1c &lt;equal&gt; c: 00000000 nop 10: 2401002a li at,42 14: 1501ffff bne t0,at,14 &lt;main+0x14&gt; 14: R_MIPS_PC16 foo 18: 00000000 nop 0000001c &lt;equal&gt;: 1c: 3c040000 lui a0,0x0 1c: R_MIPS_HI16 .data 20: 0c000000 jal 0 &lt;main&gt; 20: R_MIPS_26 printf 24: 24840004 addiu a0,a0,4 24: R_MIPS_LO16 .data </code></pre> <p>As you said, there is no relocation for the <code>beq</code> since that's a relative address within this object file.</p> <p>The <code>bne</code> I added (line marked with <code>C</code>) references an external symbol, so even though the address is relative a relocation entry is needed. It will be of type <code>R_MIPS_PC16</code> to produce a 16 bit signed word offset to symbol <code>foo</code>. As the instruction encoding requires offset from the next word and not the current <code>PC</code> that the relocation uses, <code>1</code> has to be subtracted, and that's encoded as 2's complement <code>ffff</code> into the instruction itself.</p> <p>The <code>la</code> pseudoinstruction has been translated by the assembler into a <code>lui</code>/<code>addiu</code> pair (the latter in the delay slot of the <code>jal</code>). For the <code>lui</code> a <code>R_MIPS_HI16</code> relocation is created against the <code>.data</code> section which will fill in the top 16 bits. Since the symbol <code>TEXT</code> is at address <code>4</code> in the <code>.data</code> section, the top 16 bits of the offset are <code>0</code>. This means the instruction contains <code>0</code> offset. Similarly, for the low 16 bits, except there the instruction contains an offset of <code>4</code>.</p> <p>Finally, the <code>jal printf</code> is using yet another kind of relocation that is tailored for the encoding required by the instruction. The offset is zero because the jump is directly to the referenced symbol. Note that objdump is trying to be helpful by decoding that, but it doesn't process the relocation so the <code>&lt;main&gt;</code> it outputs is of course nonsense.</p>
29,538,527
MongoDB + Elasticsearch or only Elasticsearch?
<p>We have a new project there for index a large amount of data and for provide real time. I have also complexe search with facets, full text, geospatial...</p> <p>The first prototype is to index in MongoDB and next, into Elasticsearch, because I had read that Elasticsearch does not apply a checksum on stored files and the index can't be fully trusted. But since last versions (in the version 1.5), there is now a checksum and I'm guessing if we can use Elasticsearch as primary data store ? And what is the benefit to use MongoDB in addition to Elasticsearch ?</p> <p>I can't find up to date answer about thoses features in Elasticsearch</p> <p>Thanks a lot</p>
29,561,593
4
8
null
2015-04-09 12:29:35.203 UTC
15
2019-08-23 12:51:36.397 UTC
2017-09-22 18:01:22.247 UTC
null
-1
null
1,853,777
null
1
36
mongodb|elasticsearch|nosql
32,292
<p>Talking about arguments <em>to use</em> Mongo instead of/together with ES:</p> <ol> <li><p>User/role management.</p> <ul> <li>Built-in in MongoDB. May not fit all your needs, may be clumsy somewhere, but it exists and it was implemented pretty long time ago.</li> <li>The only thing for security in ES is <a href="https://www.elastic.co/products/shield"><code>shield</code></a>. But it ships only for Gold/Platinum subscription for production use.</li> </ul></li> <li><p>Schema</p> <ul> <li>ES is schemaless, but its built on top of <code>Lucene</code> and written in <code>Java</code>. The core idea of this tool - index and search documents, and working this way requires index consistency. At back end, all documents should be fitted in flat <code>lucene</code> index, which requires some understanding about how ES should deal with your nested documents and values, and how you should organize your indexes to maintain balance between speed and data completeness/consistency. Working with ES requires you to keep some things about schema in mind constantly. I.e: as you can index almost anything to ES without putting corresponding mapping in advance, ES can "guess" mapping on the fly but sometimes do it wrong and sometimes implicit mapping is evil, because once it put, it can't be changed w/o reindexing whole index. So, its better to not treat ES as schemaless store, because you can step on a rake some time (and this will be <em>pain</em> :) ), but rather treat it as schema-intensive, at least when you work with documents, that can be sliced to concrete fields.</li> <li>Mongo, on the other hand, can "chew and leave no crumbs" out of almost anything you put in it. And most your queries will work fine, `til you remember how Mongo will deal with your data from JavaScript perspective. And as JS is weakly typed, you can work with really schemaless workflow (for sure, if you need such)</li> </ul></li> <li><p>Handling non-table-like data.</p> <ul> <li>ES is limited to handle data without putting it to search index. And this solution is good enough, when you need to store and retrieve some extra data (comparing to data you want to search against).</li> <li>MongoDB supports <a href="http://docs.mongodb.org/manual/core/gridfs/"><code>gridFS</code></a>. This gives you ability to handle large chunks of data behind the same interface. I.e., you can store binary data in Mongo and retrieve it within the same interface, from your code perspective.</li> </ul></li> </ol>
12,539,772
Adding an index on a boolean field
<p>I have a Rails model with a boolean field that I search on (I use a scope that finds all instances where the field is set to true). I'm using Postgres.</p> <p>My instinct is to add an index on the boolean field. Is that good practice, or is there something in Postgres that makes an index on a boolean field unnecessary?</p>
12,539,801
2
0
null
2012-09-22 00:47:03.74 UTC
4
2016-05-10 22:20:42.527 UTC
null
null
null
null
1,279,844
null
1
29
ruby-on-rails|postgresql
7,882
<p>No, you can index a boolean field if you'll be filtering by it. That's a perfectly reasonable thing to do, although as with all indexes, PostgreSQL may choose to ignore it if it won't exclude enough of the table -- an index scan plus a ton of row fetches may be more expensive than a sequential scan -- which may or may not affect you depending on the values in that column.</p> <p>You should also be aware that PostgreSQL lets you put conditions on indexes, which I often find useful with boolean fields. (See <a href="http://www.postgresql.org/docs/9.2/static/indexes-partial.html">Partial Indexes</a> for details.) If you'll be commonly filtering or sorting within that scope, you might be best served by something like <code>CREATE INDEX ... ON table (some_field) WHERE boolean_field</code>.</p>
12,129,077
Content Security Policy: cannot load Google API in Chrome extension
<p>This is relative an Chrome extension. I am trying a simple one which uses the Google Chart API</p> <p>I have this code in my html document "popup.html", which is loaded on the click on the Icon.</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="js/libs/jquery-1.8.0.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/popup.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://www.google.com/jsapi?key=xxxxxxxxxxx"&gt;&lt;/script&gt; [...] &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I get the following message:</p> <blockquote> <p>Refused to load the script 'http://www.google.com/jsapi?key=xxxxxxxxxxx' because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".</p> </blockquote> <p>I understood it is something relative to permissions, I tried to modify my Manifest file but without success:</p> <pre><code>{ [...] "manifest_version": 2, "permissions": ["http://*.google.com/"], "content_security_policy": "script-src 'self' http://www.google.com; object-src 'self'", } </code></pre> <p>Any idea?</p>
12,129,214
3
1
null
2012-08-26 09:40:23.3 UTC
9
2019-07-12 05:10:22.377 UTC
2012-11-09 10:11:04.757 UTC
null
99,220
null
1,128,999
null
1
31
javascript|google-chrome-extension|google-api|content-security-policy
43,088
<p>Just make it use the <code>https</code> protocol instead. The error you're getting is regarding the <a href="https://developer.chrome.com/extensions/contentSecurityPolicy" rel="nofollow noreferrer">Content Security Policy</a>.</p> <p>See the <code>Relaxing the default policy</code> section of the page. It mentions that you can only whitelist <code>HTTPS</code>, <code>chrome-extension</code>, and <code>chrome-extension-resource</code>.</p>
12,311,346
How to set fixed aspect ratio for a layout in Android
<p>I am trying to set the width of the layout to "fill_parent" while having the height of the view just the same length, to make the layout a square.</p> <p>Any suggestions will be appreciate, thanks in advance! :D </p>
45,964,536
8
5
null
2012-09-07 03:31:41.23 UTC
8
2020-09-16 08:36:55.307 UTC
2012-09-07 03:36:25.3 UTC
null
1,628,832
null
505,530
null
1
46
android
74,321
<p>With introduction of <a href="https://developer.android.com/training/constraint-layout/index.html" rel="noreferrer">ConstraintLayout</a> you don't have to write either a single line of code or use third-parties or rely on <code>PercentFrameLayout</code> which were deprecated in 26.0.0.</p> <p>Here's the example of how to keep 1:1 aspect ratio for your layout using <code>ConstraintLayout</code>:</p> <pre><code>&lt;android.support.constraint.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;FrameLayout android:layout_width="0dp" android:layout_height="0dp" android:layout_marginEnd="0dp" android:layout_marginStart="0dp" android:layout_marginTop="0dp" android:background="@android:color/black" app:layout_constraintDimensionRatio="H,1:1" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"&gt; &lt;/FrameLayout&gt; &lt;/android.support.constraint.ConstraintLayout&gt; </code></pre> <p>Or instead of editing your XML file, you can edit your layout directly in Layout Editor:</p> <p><a href="https://i.stack.imgur.com/LN29x.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LN29x.png" alt="Layout Editor"></a></p>
3,440,082
java vector to arraylist
<p>Is there any way to copy or convert a vector to arraylist in Java?</p>
3,440,087
3
0
null
2010-08-09 12:44:24.377 UTC
2
2012-10-23 00:20:38.283 UTC
null
null
null
null
236,112
null
1
28
java|vector|arraylist
30,691
<p>Yup - just use the constructor which takes a collection as its parameter:</p> <pre><code>Vector&lt;String&gt; vector = new Vector&lt;String&gt;(); // (... Populate vector here...) ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;(vector); </code></pre> <p>Note that it only does a shallow copy.</p>
22,539,779
How to tell if JRE or JDK is installed
<p>I have one computer that I intentionally installed JDK on. I have another computer with JRE, for, among other things, testing. However, when I got a java application working on this computer, and then tried it on another, it complained that JDK was required. How can I check if JDK was somehow installed on my system? Note: the computer in question is a Mac.</p>
23,267,681
6
4
null
2014-03-20 16:47:58.657 UTC
32
2019-11-06 21:44:20.883 UTC
null
null
null
null
3,000,704
null
1
152
java|macos|java-8
302,152
<p>You can open up terminal and simply type </p> <pre><code>java -version // this will check your jre version javac -version // this will check your java compiler version if you installed </code></pre> <p>this should show you the version of java installed on the system (assuming that you have set the path of the java in system environment). </p> <p>And if you haven't, add it via </p> <pre><code>export JAVA_HOME=/path/to/java/jdk1.x </code></pre> <p>and if you unsure if you have java at all on your system just use <code>find</code> in terminal</p> <p>i.e. <code>find / -name "java"</code></p>
18,795,028
javascript remove li without removing ul?
<p>Is there any way to remove the li elements of a ul without also removing the ul? I can only seem to find this.</p> <pre><code>var element = document.getElementById('myList'); element.parentNode.removeChild(element); </code></pre> <p>But, this removes the ul. I'm hoping to be able to remove and append li elements on the fly without also having to createElement the ul every time I remove li elements. Just looking for a simpler way. Thanks for any help.</p> <pre><code>&lt;div id="listView"&gt; &lt;ul id="myList" class="myList-class"&gt; &lt;li&gt;item 1&lt;/li&gt; &lt;li&gt;item 2&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre>
18,795,074
7
10
null
2013-09-13 20:50:30.63 UTC
3
2021-12-18 14:43:57.51 UTC
2013-09-13 20:56:30.653 UTC
null
756,487
null
756,487
null
1
30
javascript|html-lists|removechild
87,734
<p>You can do something like this.</p> <pre><code>var myList = document.getElementById('myList'); myList.innerHTML = ''; </code></pre> <p>If you are using jQuery</p> <pre><code>$('#myList').empty(); </code></pre> <p>Both of these will remove EVERYTHING inside the list.</p>
8,709,001
Git asks me to commit or stash changes on checkout master, even though all changes were committed?
<p>I have two branches locally, <code>master</code> and <code>Berislav</code>. The latter is currently active, and I have committed all the changes. When I try to checkout to <code>master</code>, I get the following message:</p> <blockquote> <p>error: Your local changes to the following files would be overwritten by checkout: [list of files changed in the active branch] Please, commit your changes or stash them before you can switch branches. Aborting</p> </blockquote> <p>However, everything else I tried -- <code>commit</code>, <code>status</code>, <code>merge</code> -- tells me that there's nothing to commit (working directory clean). What do I need to do to get to my <code>master</code> branch?</p> <p>EDIT: When I try <code>git stash</code>, I'm getting:</p> <blockquote> <p>error: feeding unmodified [file path] to diffcore</p> </blockquote> <p>for all the files listed in the error above.</p>
11,860,766
8
6
null
2012-01-03 07:07:55.527 UTC
7
2019-07-12 08:13:45.023 UTC
2017-04-16 03:32:04.19 UTC
null
1,033,581
null
122,033
null
1
40
git
65,825
<p>I encountered a similar problem today. <code>git status</code> wasn't listing the files which checkout was complaining about. I did a:</p> <pre><code>git checkout -- path/to/file </code></pre> <p>And that undoes any changes to the file.</p> <p>An even easier way to undo all unstaged changes on current working directory <strong>[1]</strong>:</p> <pre><code>git checkout -- . </code></pre> <p><strong>[1]</strong> - Be warned - you will lose any other unstaged changes you were working on (if any). If you don't know what you are doing, then keep a backup of the files you were working on :)</p>
26,050,899
How to mount host volumes into docker containers in Dockerfile during build
<p><em>Since 2014 when this question has been asked, many situations had happened and many things has changed. I'm revisiting the topic again today, and I'm editing this question for the 12th time to reflect the latest changes</em>. The question may seem long but it is arranged in the reverse chronological order, so the latest changes are at the top and feel free stop reading at any point.</p> <p>The question I wanted to solve was -- how to mount host volumes into docker containers in Dockerfile during build, i.e., having the <code>docker run -v /export:/export</code> capability during <code>docker build</code>.</p> <p>One reason behind it, for me, is when building things in Docker, I don't want those (<code>apt-get install</code>) caches locked in a single docker, but to share/reuse them.</p> <p>That was the main reason I was asking this question. And one more reason I'm facing today is trying to make use of a huge private repo from host which I have to otherwise do <code>git clone</code> from a private repo within docker using my private ssh key, which I don't know how and haven't looked into yet.</p> <p><strong>Latest Update:</strong></p> <p>The Buildkit in @BMitch's answer</p> <blockquote> <p>With that <code>RUN --mount</code> syntax, you can also bind mount read-only directories from the build-context...</p> </blockquote> <p>it has now been built-in in docker (which I thought being a third-party tool), as long as yours' over 18.09. Mine is 20.10.7 now -- <a href="https://docs.docker.com/develop/develop-images/build_enhancements/" rel="noreferrer">https://docs.docker.com/develop/develop-images/build_enhancements/</a></p> <blockquote> <p>To enable BuildKit builds</p> <p>Easiest way from a fresh install of docker is to set the DOCKER_BUILDKIT=1 environment variable when invoking the docker build command, such as:</p> <p><code>$ DOCKER_BUILDKIT=1 docker build .</code></p> </blockquote> <p>Else, you'll get:</p> <p><code>the --mount option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled</code></p> <p>So it'll be the perfect solution to my second use-case as explained above.</p> <p><strong>Update as of May 7, 2019:</strong></p> <p>Before docker v18.09, the correct answer should be the one that starts with:</p> <blockquote> <p>There is a way to mount a volume during a build, but it doesn't involve Dockerfiles.</p> </blockquote> <p>However, that was a poorly stated, organized and supported answer. When I was reinstalling my docker contains, I happened to stumble upon the following article:</p> <p><strong>Dockerize an apt-cacher-ng service</strong><br /> <a href="https://web.archive.org/web/20140613164606/http://docker.readthedocs.org/en/v0.7.3/use/working_with_volumes/" rel="noreferrer">https://docs.docker.com/engine/examples/apt-cacher-ng/</a></p> <p>That's the docker's solution to this/my question, not directly but indirectly. It's the orthodox way docker suggests us to do. And I admit it is better than the one I was trying to ask here.</p> <p>Another way is, the <em><strong>newly accepted answer</strong></em>, e.g., the Buildkit in v18.09.</p> <p>Pick whichever suits you.</p> <hr /> <p><strong>Was:</strong> There had been a solution -- rocker, which was not from Docker, but now that rocker is discontinued, I revert the answer back to <em>&quot;Not possible&quot;</em> again.</p> <hr /> <p><strong>Old Update:</strong> So the answer is &quot;Not possible&quot;. I can accept it as an answer as I know the issue has been extensively discussed at <a href="https://github.com/docker/docker/issues/3156" rel="noreferrer">https://github.com/docker/docker/issues/3156</a>. I can understand that portability is a paramount issue for docker developer; but as a docker user, I have to say I'm very disappointed about this missing feature. Let me close my argument with a quote from aforementioned discussion: &quot;<em>I would like to use Gentoo as a base image but definitely don't want &gt; 1GB of Portage tree data to be in any of the layers once the image has been built. You could have some nice a compact containers if it wasn't for the gigantic portage tree having to appear in the image during the install.</em>&quot; Yes, I can use wget or curl to download whatever I need, but the fact that merely a portability consideration is now forcing me to download &gt; 1GB of Portage tree each time I build a Gentoo base image is neither efficient nor user friendly. Further more, the package repository WILL ALWAYS be under /usr/portage, thus ALWAYS PORTABLE under Gentoo. Again, I respect the decision, but please allow me expressing my disappointment as well in the mean time. Thanks.</p> <hr /> <p><strong>Original question</strong> in details:</p> <p>From</p> <p><strong>Share Directories via Volumes</strong><br /> <a href="http://docker.readthedocs.org/en/v0.7.3/use/working_with_volumes/" rel="noreferrer">http://docker.readthedocs.org/en/v0.7.3/use/working_with_volumes/</a></p> <p>it says that Data volumes feature &quot;have been available since version 1 of the Docker Remote API&quot;. My docker is of version 1.2.0, but I found the example given in above article not working:</p> <pre><code># BUILD-USING:        docker build -t data . # RUN-USING:          docker run -name DATA data FROM          busybox VOLUME        [&quot;/var/volume1&quot;, &quot;/var/volume2&quot;] CMD           [&quot;/usr/bin/true&quot;] </code></pre> <p>What's the proper way in Dockerfile to mount host-mounted volumes into docker containers, via the VOLUME command?</p> <pre><code>$ apt-cache policy lxc-docker lxc-docker: Installed: 1.2.0 Candidate: 1.2.0 Version table: *** 1.2.0 0 500 https://get.docker.io/ubuntu/ docker/main amd64 Packages 100 /var/lib/dpkg/status $ cat Dockerfile FROM debian:sid VOLUME [&quot;/export&quot;] RUN ls -l /export CMD ls -l /export $ docker build -t data . Sending build context to Docker daemon 2.56 kB Sending build context to Docker daemon Step 0 : FROM debian:sid ---&gt; 77e97a48ce6a Step 1 : VOLUME [&quot;/export&quot;] ---&gt; Using cache ---&gt; 59b69b65a074 Step 2 : RUN ls -l /export ---&gt; Running in df43c78d74be total 0 ---&gt; 9d29a6eb263f Removing intermediate container df43c78d74be Step 3 : CMD ls -l /export ---&gt; Running in 8e4916d3e390 ---&gt; d6e7e1c52551 Removing intermediate container 8e4916d3e390 Successfully built d6e7e1c52551 $ docker run data total 0 $ ls -l /export | wc 20 162 1131 $ docker -v Docker version 1.2.0, build fa7b24f </code></pre>
52,762,779
11
4
null
2014-09-26 02:00:44.447 UTC
71
2022-09-06 20:10:15.323 UTC
2022-02-18 20:24:23.987 UTC
null
2,125,837
null
2,125,837
null
1
313
share|docker|host|mount
282,805
<p>First, to answer "why doesn't <code>VOLUME</code> work?" When you define a <code>VOLUME</code> in the Dockerfile, you can only define the target, not the source of the volume. During the build, you will only get an anonymous volume from this. That anonymous volume will be mounted at every <code>RUN</code> command, prepopulated with the contents of the image, and then discarded at the end of the <code>RUN</code> command. Only changes to the container are saved, not changes to the volume.</p> <hr> <p>Since this question has been asked, a few features have been released that may help. First is multistage builds allowing you to build a disk space inefficient first stage, and copy just the needed output to the final stage that you ship. And the second feature is Buildkit which is dramatically changing how images are built and new capabilities are being added to the build.</p> <p>For a multi-stage build, you would have multiple <code>FROM</code> lines, each one starting the creation of a separate image. Only the last image is tagged by default, but you can copy files from previous stages. The standard use is to have a compiler environment to build a binary or other application artifact, and a runtime environment as the second stage that copies over that artifact. You could have:</p> <pre><code>FROM debian:sid as builder COPY export /export RUN compile command here &gt;/result.bin FROM debian:sid COPY --from=builder /result.bin /result.bin CMD ["/result.bin"] </code></pre> <p>That would result in a build that only contains the resulting binary, and not the full /export directory.</p> <hr> <p>Buildkit is coming out of experimental in 18.09. It's a complete redesign of the build process, including the ability to change the frontend parser. One of those parser changes has has implemented the <code>RUN --mount</code> option which lets you mount a cache directory for your run commands. E.g. here's one that mounts some of the debian directories (with a reconfigure of the debian image, this could speed up reinstalls of packages):</p> <pre><code># syntax = docker/dockerfile:experimental FROM debian:latest RUN --mount=target=/var/lib/apt/lists,type=cache \ --mount=target=/var/cache/apt,type=cache \ apt-get update \ &amp;&amp; DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ git </code></pre> <p>You would adjust the cache directory for whatever application cache you have, e.g. $HOME/.m2 for maven, or /root/.cache for golang.</p> <hr> <p><strong>TL;DR: Answer is here:</strong> With that <code>RUN --mount</code> syntax, you can also bind mount read-only directories from the build-context. The folder must exist in the build context, and it is not mapped back to the host or the build client:</p> <pre><code># syntax = docker/dockerfile:experimental FROM debian:latest RUN --mount=target=/export,type=bind,source=export \ process export directory here... </code></pre> <p>Note that because the directory is mounted from the context, it's also mounted read-only, and you cannot push changes back to the host or client. When you build, you'll want an 18.09 or newer install and enable buildkit with <code>export DOCKER_BUILDKIT=1</code>.</p> <p>If you get an error that the mount flag isn't supported, that indicates that you either didn't enable buildkit with the above variable, or that you didn't enable the experimental syntax with the syntax line at the top of the Dockerfile before any other lines, including comments. Note that the variable to toggle buildkit will only work if your docker install has buildkit support built in, which requires version 18.09 or newer from Docker, both on the client and server.</p>
22,075,140
Am I doing this split, reverse, join correctly?
<p>Having a little trouble understanding what this does. If I have a string, </p> <p>Using <code>"Mcdonalds"</code> as an example, I do:</p> <pre><code>"McDonalds".split("").reverse().join(); </code></pre> <p>What exactly am I doing?</p> <p>Am I splitting each character <code>(M c D o n a l d s)</code>, then reversing it <code>(s d l a n o D c M)</code> then joining to get <code>(sdlanoDcM)</code>? (Trying to see if I understand this right)</p>
22,075,215
2
4
null
2014-02-27 16:56:04.283 UTC
3
2016-06-24 14:36:13.52 UTC
2016-06-24 14:36:13.52 UTC
null
1,715,579
user2344665
null
null
1
8
javascript|join|split|reverse
42,398
<p>Make sure you specify an empty string to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join"><code>.join</code></a>, otherwise you'll get commas between each character:</p> <pre><code>"McDonalds".split("").reverse().join(""); // "sdlanoDcM" </code></pre>
10,934,420
FFmpeg - How to scale a video then apply a watermark?
<p>Im trying to scale a video so that it is always 512 wide where the height changes in proportion to the original video. Once scaled, I then want to apply a watermark/overlay to the video, therefore the video will scale but the watermark wont.</p> <p>I am able to achieve each of these separately using the following filters:</p> <p><strong>Scale</strong></p> <pre><code>-vf &quot;scale=512:-1&quot; </code></pre> <p><strong>Watermark</strong></p> <pre><code>-vf &quot;movie=watermark.png [watermark]; [in][watermark] overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2 [out]&quot; </code></pre> <p>They work successfully on their own.</p> <p>However when trying to combine the two, Im having a bit of trouble.</p> <p>Having both as parameters of course does not work as one will override the other.</p> <p>Ive tried:</p> <pre><code>-vf &quot;scale=512:-1,movie=watermark.png [watermark]; [in][watermark] overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2 [out]&quot; </code></pre> <p>my thinking was that the scale would be applied first then the watermark but all I get is an error</p> <blockquote> <p>Too many inputs specified for the &quot;movie&quot; filter.</p> <p>Error opening filters!</p> </blockquote> <p>Then changing the , to a ; resulted in:</p> <blockquote> <p>Simple filtergraph 'scale=512:-1; movie=watermark.png [watermark]; [in][watermark] overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2 [out]' does not have exactly one input and output.</p> <p>Error opening filters!</p> </blockquote> <p>I presume I need to do something more with filterchains but Im struggling to figure it out.</p> <p>Any ideas anyone?</p> <p>Many thanks in advance.</p>
11,566,178
3
2
null
2012-06-07 15:00:49.873 UTC
11
2016-08-28 20:41:46.077 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
717,373
null
1
13
filter|ffmpeg|overlay|scale|watermark
32,494
<p>Thank you to both @DiJuMx and @LordNeckbeard, you both got me closer to my solution. Ive not tried the filter_complex option yet but it certainly looks simpler.</p> <p>The solution I found to work is:</p> <pre><code>-vf "movie=watermark.png [watermark]; [in]scale=512:trunc(ow/a/2)*2 [scale]; [scale][watermark] overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2 [out]" </code></pre> <p>Note that Ive replaced the -1 in the scale as that had the potential to cause an uneven number of pixels in the height of the video when scaling which would then cause encoding errors.</p>
10,897,996
Gethomepath not working on iOS 5 / OSxLion
<p>Whenever I use the Gethomepath function of Delphi I keep getting Shell Script Invocation Error.</p> <p>Was this function replaced by a newer one? </p>
13,246,212
1
5
null
2012-06-05 13:14:04.587 UTC
2
2012-11-06 07:18:19.517 UTC
2012-11-02 13:25:57.36 UTC
null
912,495
null
1,437,074
null
1
29
delphi|osx-lion|firemonkey
592
<p>I finally found a workaround for this: blogs.embarcadero.com/ao/2011/10/04/39144#comment-7998 </p> <p>So "S := ExtractFilePath(paramstr(0)); S := Copy(S, 1, length(S) - 14);" gets the job done.</p> <p>Note that the length of S depends on your application title.</p>
11,107,608
What's "wrong" with C++ wchar_t and wstrings? What are some alternatives to wide characters?
<p>I have seen a lot of people in the C++ community(particularly ##c++ on freenode) resent the use of <code>wstrings</code> and <code>wchar_t</code>, and their use in the windows api. What is exactly "wrong" with <code>wchar_t</code> and <code>wstring</code>, and if I want to support internationalization, what are some alternatives to wide characters?</p>
11,107,667
2
9
null
2012-06-19 19:00:50.673 UTC
39
2014-05-11 06:56:37.883 UTC
2013-08-23 09:03:44.65 UTC
null
1,237,747
null
596,065
null
1
87
c++|winapi|unicode|internationalization|wstring
32,869
<h3>What is wchar_t?</h3> <p>wchar_t is defined such that any locale's char encoding can be converted to a wchar_t representation where every wchar_t represents exactly one codepoint:</p> <blockquote> <p>Type wchar_t is a distinct type whose values can represent distinct codes for all members of the largest extended character set specified among the supported locales (22.3.1).</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<em>— C++ [basic.fundamental] 3.9.1/5</em></p> </blockquote> <p>This <em>does not</em> require that wchar_t be large enough to represent any character from all locales simultaneously. That is, the encoding used for wchar_t may differ between locales. Which means that you cannot necessarily convert a string to wchar_t using one locale and then convert back to char using another locale.<sup>1</sup></p> <p>Since using wchar_t as a common representation between all locales seems to be the primary use for wchar_t in practice you might wonder what it's good for if not that.</p> <p>The original intent and purpose of wchar_t was to make text processing simple by defining it such that it requires a one-to-one mapping from a string's code-units to the text's characters, thus allowing the use of the same simple algorithms as are used with ascii strings to work with other languages.</p> <p>Unfortunately the wording of wchar_t's specification assume a one-to-one mapping between characters and codepoints to achieve this. Unicode breaks that assumption<sup>2</sup>, so you can't safely use wchar_t for simple text algorithms either.</p> <p>This means that portable software cannot use wchar_t either as a common representation for text between locales, or to enable the use of simple text algorithms.</p> <h3>What use is wchar_t today?</h3> <p>Not much, for portable code anyway. If <code>__STDC_ISO_10646__</code> is defined then values of wchar_t directly represent Unicode codepoints with the same values in all locales. That makes it safe to do the inter-locale conversions mentioned earlier. However you can't rely only on it to decide that you can use wchar_t this way because, while most unix platforms define it, Windows does not even though Windows uses the same wchar_t locale in all locales.</p> <p>The reason Windows doesn't define <code>__STDC_ISO_10646__</code> is because Windows use UTF-16 as its wchar_t encoding, and because UTF-16 uses surrogate pairs to represent codepoints greater than U+FFFF, which means that UTF-16 doesn't satisfy the requirements for <code>__STDC_ISO_10646__</code>.</p> <p>For platform specific code wchar_t may be more useful. It's essentially required on Windows (e.g., some files simply cannot be opened without using wchar_t filenames), though Windows is the only platform where this is true as far as I know (so maybe we can think of wchar_t as 'Windows_char_t').</p> <p>In hindsight wchar_t is clearly not useful for simplifying text handling, or as storage for locale independent text. Portable code should not attempt to use it for these purposes. Non-portable code may find it useful simply because some API requires it.</p> <h3>Alternatives</h3> <p>The alternative I like is to use UTF-8 encoded C strings, even on platforms not particularly friendly toward UTF-8.</p> <p>This way one can write portable code using a common text representation across platforms, use standard datatypes for their intended purpose, get the language's support for those types (e.g. string literals, though some tricks are necessary to make it work for some compilers), some standard library support, debugger support (more tricks may be necessary), etc. With wide characters it's generally harder or impossible to get all of this, and you may get different pieces on different platforms.</p> <p>One thing UTF-8 does not provide is the ability to use simple text algorithms such as are possible with ASCII. In this UTF-8 is no worse than any other Unicode encoding. In fact it may be considered to be better because multi-code unit representations in UTF-8 are more common and so bugs in code handling such variable width representations of characters are more likely to be noticed and fixed than if you try to stick to UTF-32 with NFC or NFKC.</p> <p>Many platforms use UTF-8 as their native char encoding and many programs do not require any significant text processing, and so writing an internationalized program on those platforms is little different from writing code without considering internationalization. Writing more widely portable code, or writing on other platforms requires inserting conversions at the boundaries of APIs that use other encodings.</p> <p>Another alternative used by some software is to choose a cross-platform representation, such as unsigned short arrays holding UTF-16 data, and then to supply all the library support and simply live with the costs in language support, etc.</p> <p>C++11 adds new kinds of wide characters as alternatives to wchar_t, char16_t and char32_t with attendant language/library features. These aren't actually guaranteed to be UTF-16 and UTF-32, but I don't imagine any major implementation will use anything else. C++11 also improves UTF-8 support, for example with UTF-8 string literals so it won't be necessary to trick VC++ into producing UTF-8 encoded strings (although I may continue to do so rather than use the <code>u8</code> prefix).</p> <h3>Alternatives to avoid</h3> <p>TCHAR: TCHAR is for migrating ancient Windows programs that assume legacy encodings from char to wchar_t, and is best forgotten unless your program was written in some previous millennium. It's not portable and is inherently unspecific about its encoding and even its data type, making it unusable with any non-TCHAR based API. Since its purpose is migration to wchar_t, which we've seen above isn't a good idea, there is no value whatsoever in using TCHAR.</p> <hr> <p><em> <sub>1. Characters which are representable in wchar_t strings but which are not supported in any locale are not required to be represented with a single wchar_t value. This means that wchar_t could use a variable width encoding for certain characters, another clear violation of the intent of wchar_t. Although it's arguable that a character being representable by wchar_t is enough to say that the locale 'supports' that character, in which case variable-width encodings aren't legal and Window's use of UTF-16 is non-conformant.</sub></p> <p><sub>2. Unicode allows many characters to be represented with multiple code points, which creates the same problems for simple text algorithms as variable width encodings. Even if one strictly maintains a composed normalization, some characters still require multiple code points. See: <a href="http://www.unicode.org/standard/where/" rel="noreferrer">http://www.unicode.org/standard/where/</a></sub> </em></p>
11,403,932
Python AttributeError: 'module' object has no attribute 'Serial'
<p>I'm trying to access a serial port with Python 2.6 on my Raspberry Pi running Debian. My script named <code>serial.py</code> tries to import pySerial:</p> <pre><code>import serial ser = serial.Serial('/dev/ttyAMA0', 9600) ser.write(&quot;hello world!&quot;) </code></pre> <p>For some reason it refuses to establish the serial connection with this error:</p> <pre><code>AttributeError: 'module' object has no attribute 'Serial' </code></pre> <p>When I try to type the same code in the interactive Python interpreter it still doesn't work.</p> <p>Strangely, it used to work about a couple hours ago.</p> <p>What could be the problem? I've tried to fix this for a while, installing pySerial again, rewriting my code, double-checking the serial port, etc.</p>
11,404,052
7
10
null
2012-07-09 22:09:25.193 UTC
28
2022-01-04 13:43:44.837 UTC
2022-01-04 13:43:44.837 UTC
null
8,839,059
null
547,398
null
1
163
python|serial-port|raspberry-pi
516,098
<p>You're importing the module, not the class. So, you must write:</p> <pre><code>from serial import Serial </code></pre> <p>You need to install <code>serial</code> module correctly: <code>pip install pyserial</code>.</p>
13,102,963
Word wrap in Chrome Dev Tools?
<p>I cannot figure out how to get the HTML elements to wrap lines in Chrome dev tools. I'm working with some long and complicated SVG paths and I hate scrolling horizontally to check the other element attributes. Word wrap is checked under the settings area in chrome dev tools. Suggestions?</p> <p><a href="https://i.stack.imgur.com/DAGQY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DAGQY.png" alt="enter image description here"></a></p>
16,240,802
3
1
null
2012-10-27 18:30:54.413 UTC
5
2021-09-14 22:33:07.907 UTC
2018-03-04 09:36:58.527 UTC
null
863,110
null
1,204,209
null
1
38
google-chrome|console|google-chrome-devtools|word-wrap
25,568
<p>Looks like there is no Word Wrap available for now :( and seems like people have been asking forever, I just posted my vote for word wrap too</p> <p><a href="https://code.google.com/p/chromium/issues/detail?can=2&amp;start=0&amp;num=100&amp;q=&amp;colspec=ID%20Pri%20M%20Iteration%20ReleaseBlock%20Cr%20Status%20Owner%20Summary%20OS%20Modified&amp;groupby=&amp;sort=&amp;id=73193" rel="noreferrer">https://code.google.com/p/chromium/issues/detail?can=2&amp;start=0&amp;num=100&amp;q=&amp;colspec=ID%20Pri%20M%20Iteration%20ReleaseBlock%20Cr%20Status%20Owner%20Summary%20OS%20Modified&amp;groupby=&amp;sort=&amp;id=73193</a></p> <p><strong>Edit: looks like it is a feature by default now (click on the three dots on the top right, then click on Settings):</strong></p> <p><img src="https://i.stack.imgur.com/l8xo3.png" alt="enter image description here"></p>
30,351,529
Find and replace with a newline in Visual Studio Code
<p>I am trying out the new Microsoft Visual Studio Code editor in Linux Fedora environment. I would like to know how to replace new line (\n) in place of some other text. </p> <p>For example, I have html text like this</p> <pre><code>&lt;tag&gt;&lt;tag&gt; </code></pre> <p>which I would like to replace as </p> <pre><code>&lt;tag&gt; &lt;tag&gt; </code></pre> <p>In sublime I would use regex pattern and find <em>">&lt;"</em> and replace with <em>">\n&lt;"</em> How do I accomplish this in Visual Studio Code?</p>
30,775,857
11
6
null
2015-05-20 13:43:37.393 UTC
85
2022-08-09 09:40:00.513 UTC
2016-04-14 22:24:20.8 UTC
null
100,596
null
1,179,958
null
1
663
visual-studio-code
520,541
<p>In the local searchbox (<kbd>ctrl</kbd> + <kbd>f</kbd>) you can insert newlines by pressing <kbd>ctrl</kbd> + <kbd>enter</kbd>.</p> <p><a href="https://code.visualstudio.com/assets/updates/1_38/multiple-line-support.gif" rel="noreferrer"><img src="https://code.visualstudio.com/assets/updates/1_38/multiple-line-support.gif" alt="Image of multiline search in local search"></a></p> <p>If you use the global search (<kbd>ctrl</kbd> + <kbd>shift</kbd> + <kbd>f</kbd>) you can insert newlines by pressing <kbd>shift</kbd> + <kbd>enter</kbd>.</p> <p><a href="https://i.stack.imgur.com/aEmuy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aEmuy.png" alt="Image of multiline search in global search"></a></p> <p>If you want to search for multilines by the character literal, remember to check the <strong>rightmost regex icon</strong>.</p> <p><a href="https://i.stack.imgur.com/uR2Zc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uR2Zc.png" alt="Image of regex mode in search replace"></a></p> <hr> <p>In previous versions of Visual Studio code this was difficult or impossible. Older versions require you to use the regex mode, older versions yet did not support newline search whatsoever.</p>
17,101,903
What does LayoutInflater class do? (in Android)
<p>I am unable to understand the use of LayoutInflater in Android.</p> <p>What exactly is the role of LayoutInflater, and how to use it for a simple Android app?</p>
17,102,180
5
3
null
2013-06-14 05:49:44.9 UTC
13
2016-12-23 14:34:15.53 UTC
2016-12-08 13:41:32.99 UTC
null
4,666,542
null
2,484,803
null
1
31
android|android-layout
38,672
<p><strong>What is Layoutinflater ?</strong></p> <p><code>LayoutInflater</code> is a class (wrapper of some implementation or service), you can get one:</p> <pre><code>LayoutInflater li = LayoutInflater.from(context); </code></pre> <hr> <p><strong>How to use Layoutinflater ?</strong></p> <p>You feed it an XML layout file. You need not give full file address, just its resource id, generated for you automatically in <code>R</code> class. For example, a layout file which look like:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;TextView android:id="@+id/text_view" android:layout_width="fill_parent" android:layout_height="fill_parent"/&gt; &lt;/LinearLayout&gt; </code></pre> <p>saved as <code>/res/layout/my_layout.xml</code>. </p> <p>You give it to <code>LayoutInflater</code> like:</p> <pre><code> View v = li.inflate(R.layout.my_layout,null,false); </code></pre> <hr> <p><strong>What did Layout Inflater do ?</strong></p> <p>That <code>v</code> is now a <code>LinearLayout</code> object <sup>(<code>LinearLayout</code> extends <code>View</code>)</sup> , and contains a <code>TextView</code> object, arranged in exact order and with all properties set, as we <em>described</em> in the XML above.</p> <hr> <p><strong>TL;DR:</strong> A <code>LayoutInflater</code> reads an XML in which we describe how we want a UI layout to be. It then creates actual <code>View</code>objects for UI from that XML.</p>