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
30,040,308
mkvirtualenv: Too many levels of symbolic links
<p>I am running <a href="https://github.com/brainsik/virtualenv-burrito">virtualenv burrito</a> and getting an error that there are too many levels of symbolic links. I have no idea what that means.</p> <pre><code>mkvirtualenv --python /usr/local/bin/Python3 mantis </code></pre> <p>Error:</p> <pre><code>Running virtualenv with interpreter /usr/local/bin/Python3 Using base prefix '/Library/Frameworks/Python.framework/Versions/3.4' New python executable in mantis/bin/Python3 Also creating executable in mantis/bin/python Traceback (most recent call last): File "/Users/croberts/.venvburrito/lib/python2.7/site-packages/virtualenv.py", line 2352, in &lt;module&gt; main() File "/Users/croberts/.venvburrito/lib/python2.7/site-packages/virtualenv.py", line 825, in main symlink=options.symlink) File "/Users/croberts/.venvburrito/lib/python2.7/site-packages/virtualenv.py", line 985, in create_environment site_packages=site_packages, clear=clear, symlink=symlink)) File "/Users/croberts/.venvburrito/lib/python2.7/site-packages/virtualenv.py", line 1439, in install_python raise e File "/Users/croberts/.venvburrito/lib/python2.7/site-packages/virtualenv.py", line 1431, in install_python stdout=subprocess.PIPE) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 859, in __init__ restore_signals, start_new_session) File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/subprocess.py", line 1457, in _execute_child raise child_exception_type(errno_num, err_msg) OSError: [Errno 62] Too many levels of symbolic links </code></pre> <p>I was getting this error before and solved it by doing Python3.4 instead of Python3. Now it won't work no matter which python I try to use. Even if I try to use the default (2.7)</p>
30,920,838
8
0
null
2015-05-04 21:28:51.063 UTC
3
2020-01-15 19:42:37.24 UTC
2015-05-04 21:33:55.723 UTC
null
1,481,072
null
1,481,072
null
1
32
virtualenv|virtualenvwrapper
41,443
<p>The reason this wasn't working was because I was capitalizing Python. As soon as I did it using <code>python3</code> instead of <code>Python3</code> I stopped getting trouble.</p>
27,606,595
ngRepeat Filter by deep property
<p>If I have a complex object with objects as property values, how can I filter by one of the nested properties?</p> <p>Can this be done with the OOB ng-repeat filter?</p> <p><strong>Data</strong></p> <pre><code>{ Name: 'John Smith', Manager: { id: 123, Name: 'Bill Lumburg' } } </code></pre> <p><strong>ngRepeat</strong></p> <pre><code>&lt;li ng-repeat="e in emps | filter:Manager.Name"&gt;{{ e.Name }}&lt;/li&gt; </code></pre>
32,994,920
4
0
null
2014-12-22 16:30:55.217 UTC
15
2018-06-27 11:36:57.673 UTC
2014-12-22 16:40:55.25 UTC
null
798,539
null
798,539
null
1
52
javascript|json|angularjs|filter|angularjs-ng-repeat
56,775
<p>You need to pass in the argument to filter by:</p> <pre><code>&lt;input ng-model="filter.key"&gt; &lt;ul&gt; &lt;li ng-repeat="e in list | filter: {Manager: {Name: filter.key}}"&gt; {{e.Name}} (Manager: {{e.Manager.Name}}) &lt;/li&gt; &lt;/ul&gt; </code></pre> <p><a href="http://plnkr.co/edit/7KlAX1XmwdUyUMnk6XlJ?p=preview" rel="noreferrer">Example on Plunker</a></p>
42,796,143
How do I install crystal-lang on rapsberry pi?
<p>When I try to add it to sources as per <a href="https://crystal-lang.org/docs/installation/on_debian_and_ubuntu.html" rel="noreferrer">debian install instructions</a> I get this error. I'm guessing this means that there are no arm packages for it.</p> <blockquote> <p>Failed to fetch <a href="https://dist.crystal-lang.org/apt/dists/crystal/InRelease" rel="noreferrer">https://dist.crystal-lang.org/apt/dists/crystal/InRelease</a> Unable to find expected entry 'main/binary-armhf/Packages' in Release file (Wrong sources.list entry or malformed file)</p> </blockquote> <p>I'm guessing I probably need to install it from source. How would I go about doing that with an arm cpu? When I check it out and run <code>make</code> I get the error:</p> <blockquote> <p>You need to have a crystal executable in your path! Makefile:113: recipe for target '.build/crystal' failed make: *** [.build/crystal] Error 1</p> </blockquote> <p>Any suggestions would be greatly appreciated.</p>
42,796,648
1
0
null
2017-03-14 20:40:27.587 UTC
10
2019-04-28 04:07:34.913 UTC
2017-03-14 21:11:24.733 UTC
null
1,757,348
null
1,757,348
null
1
18
arm|raspberry-pi3|crystal-lang
3,775
<p>EDIT: There's now a semi-official repository for crystal on raspbian, check it out here: <a href="http://public.portalier.com/raspbian" rel="noreferrer">http://public.portalier.com/raspbian</a></p> <hr> <p>Crystal doesn't build Debian packages for ARM, and you're correct in that you'll need to build from source.</p> <p>However, the Crystal compiler is written in Crystal. This presents the obvious problem of how to get a compiler to build the compiler. The answer is cross-compilation: building an arm binary on a x86 desktop computer and copying it across.</p> <p>Here's a quick step-by-step based on my memory of last time I cross-compiled:</p> <ol> <li>Install Crystal on a x86 desktop PC, and check it works.</li> <li>Install <a href="https://github.com/crystal-lang/crystal/wiki/All-required-libraries" rel="noreferrer">all required libraries</a> on the desktop and Raspberry Pi. You'll need the same LLVM version on the Raspberry Pi and desktop. This is probably the hardest and longest step. You can install llvm 3.9 from <a href="https://packages.debian.org/stretch/llvm-3.9-dev" rel="noreferrer">debian testing</a> for ARM, see <a href="https://serverfault.com/a/22418/203839">this stackoverflow post</a> for how to install only LLVM from debian testing. </li> <li>Check out the sources from git on both computers, and run <code>make deps</code>.</li> <li>Cross-compile the compiler by running this command in the root of the git repository: <pre><code>./bin/crystal build src/compiler/crystal.cr --cross-compile --target arm-unknown-linux-gnueabihf --release -s -D without_openssl -D without_zlib</pre></code> This command will create a <code>crystal.o</code> file in your current directory, and also output a linker command (<code>cc crystal.o -o crystal ...</code>).</li> <li>Copy <code>crystal.o</code> to the raspberry pi, and run the linker command. Be sure to edit the absolute path to <code>llvm_ext.o</code> so that it points to the Crystal checkout on your Raspberry Pi, not the checkout on your desktop. Also make sure that all references to <code>llvm-config</code> in the command are for the correct LLVM version. For example, changing <code>/usr/local/bin/llvm-config</code> to <code>llvm-config-3.9</code> on Raspbian.</li> <li>Run the crystal executable in your current directory (<code>./crystal -v</code>) and make sure it works.</li> <li>Ensure to set <code>CRYSTAL_PATH</code> environment variable is set to <code>lib:/path/to/crystal/source/checkout/src</code> so that the compiler can find the standard library when compiling applications. </li> </ol>
21,177,107
How to check if path or file exist in Scala
<p>How do I check if a path / file exists in Scala similar to Python ? An example below: </p> <pre><code>os.path.exists("/home") Out[4]: True </code></pre>
21,177,158
4
0
null
2014-01-17 03:07:49.67 UTC
5
2019-08-08 15:40:26.983 UTC
null
null
null
null
501,800
null
1
73
scala
67,258
<p>Well, sorry I found the answer to my own question: </p> <pre><code>scala&gt; new java.io.File("/tmp").exists res0: Boolean = true </code></pre>
24,551,235
How to add a folder to a nuspec file
<p>So I'm actually trying to package up a web site project (not web application so no csproj file) into a NuGet package ready for Octopus to consume but am running into one brick wall after another..</p> <p>I looked into using OctoPack but it doesn't support web site projects only web application projects.</p> <p>I am now trying to find a way of adding a folder (in my case a web site) into a Nuget package but Nuget doesn't allow this via the command line does it? It also requires a .csproj file!</p> <p>I've also tried trying to create the NuGet spec files and pass it in a folder but not possible?</p> <p>For the moment I may have to use the NuGet package explorer but I want to script this.</p> <p>I've looked at this question but doesn't seem to handle my scenario <a href="https://stackoverflow.com/questions/22977258/can-i-create-a-nuget-package-without-a-project-file">Can I create a nuget package without a project file</a></p> <p>So does anyone know how to best add a folder to a NuGet package via the command line!?</p>
24,551,639
1
0
null
2014-07-03 10:28:54.34 UTC
3
2015-05-08 17:17:00.713 UTC
2017-05-23 10:31:39.507 UTC
null
-1
null
156,446
null
1
28
nuget|octopus-deploy|nuget-spec
31,098
<p>I don't know OctoPack, but with nuget.exe, packaging is done in two steps:</p> <ol> <li>Either create a .nuspec manually, or generate one from a .csproj or existing assembly (see <code>nuget spec</code> in <a href="http://docs.nuget.org/docs/creating-packages/creating-and-publishing-a-package" rel="noreferrer">the docs</a>).</li> <li>Call <code>nuget pack</code> with the .nuspec created in the previous step as a parameter.</li> </ol> <p>Since you don't have a .csproj lying around, you're stuck creating the .nuspec manually (or with a GUI tool like <a href="https://npe.codeplex.com/" rel="noreferrer">NuGet Package Explorer</a>).</p> <p>You can read all about how to create a .nuspec file in the <a href="http://docs.nuget.org/docs/reference/nuspec-reference" rel="noreferrer">Nuspec Reference</a>, specifically the section about <a href="http://docs.nuget.org/docs/reference/nuspec-reference#Specifying_Files_to_Include_in_the_Package" rel="noreferrer">Specifying Files to Include in the Package</a>.</p> <p>If you want to include a folder (recursively?) in the package, you need to add something like this to the XML:</p> <pre><code>&lt;files&gt; &lt;file src="bin\Release\**\*.*" target="content" /&gt; &lt;/files&gt; </code></pre> <p>This will take all the files and (recursive) sub-folders of the <code>bin\Release</code> folder and put them in the <code>content</code> folder of the NuGet package.</p> <p>I have no idea what format OctopusDeploy expects in the packages, but that's how you include a folder in the package.</p> <p><strong>EDIT</strong>: There seems to be some documentation on this in the <a href="https://github.com/OctopusDeploy/OctoPack#what-is-packaged" rel="noreferrer">OctoPack README</a>.</p>
50,350,001
Run some Javascript in Flutter Webview
<p>How can I run Javascript in flutter_webview_plugin? I tried with this:</p> <pre><code>onPressed: () { flutterWebviewPlugin.evalJavascript('&lt;script language=&quot;JavaScript&quot; type=&quot;text/javascript&quot;&gt;alert(&quot;Hello World&quot;)&lt;/script&gt;'); }, </code></pre> <p>But nothing happens.</p> <p>I thought with <code>flutterWebviewPlugin.evalJavascript</code> it's possible to run Javascript in a Webview. Did I do something wrong?</p>
50,350,069
6
0
null
2018-05-15 12:17:07.19 UTC
8
2022-08-04 21:04:33.95 UTC
2021-11-05 07:57:55.977 UTC
null
13,534,779
null
9,690,646
null
1
15
javascript|webview|dart|flutter
38,309
<pre><code>flutterWebviewPlugin.evalJavascript('&lt;script language="JavaScript" type="text/javascript"&gt;alert("Hello World")&lt;/script&gt;') </code></pre> <p>expects JavaScript, not HTML</p> <pre><code>&lt;script language="JavaScript" type="text/javascript"&gt;alert("Hello World")&lt;/script&gt; </code></pre> <p>is HTML.</p> <p>Try </p> <pre><code>flutterWebviewPlugin.evalJavascript('alert("Hello World")') </code></pre>
50,531,864
Customizing item-text in v-select
<p>Please tell me if we can customize <code>item-text</code> for <code>v-select</code> ? </p> <p>I want customize each item in <code>v-select</code>, something like this :</p> <pre><code>:item-text="item.name - item.description" </code></pre>
50,533,063
5
0
null
2018-05-25 14:48:20.183 UTC
17
2021-11-03 09:14:03.163 UTC
2020-10-20 01:38:55.753 UTC
null
2,541,658
null
393,186
null
1
72
javascript|vue.js|vuetify.js
105,149
<p>Yes you can, using <code>scoped slot</code> as described in the doc and provide a <code>template</code>.</p> <p>For <code>v-select</code> you have two <code>scoped slot</code> : </p> <ul> <li><code>selection</code> : to describe how <code>v-select</code> should render items when selected</li> <li><code>item</code> : to describe how <code>v-select</code> should render items when opened</li> </ul> <p>It looks like this :</p> <pre><code>&lt;v-select&gt; // Don't forget your props &lt;template slot="selection" slot-scope="data"&gt; &lt;!-- HTML that describe how select should render selected items --&gt; {{ data.item.name }} - {{ data.item.description }} &lt;/template&gt; &lt;template slot="item" slot-scope="data"&gt; &lt;!-- HTML that describe how select should render items when the select is open --&gt; {{ data.item.name }} - {{ data.item.description }} &lt;/template&gt; &lt;/v-select&gt; </code></pre> <p><a href="https://codepen.io/anon/pen/YBBJGr?&amp;editors=101" rel="noreferrer">CodePen with a complex example</a></p> <p><a href="https://vuetifyjs.com/en/components/selects#example-scoped-slots" rel="noreferrer">Vuetify Doc about Scoped Slot in V-Select</a></p> <hr> <p><strong>Edit for Vuetify 1.1.0+</strong> : Those slots are also available with new components <code>v-autocomplete</code> and <code>v-combobox</code> as they inherit from <code>v-select</code>.</p> <hr> <p><strong>Edit for Vue 2.6+</strong>, replace :</p> <ul> <li><code>slot="selection" slot-scope="data"</code> by <code>v-slot:selection="data"</code></li> <li><code>slot="item" slot-scope="data"</code> by <code>v-slot:item="data"</code></li> </ul>
46,308,048
How to target a specific column or row in CSS Grid Layout?
<p>Is it possible to select a specific grid column or row with CSS?</p> <p>For example, say I have a 3 row by 2 column CSS Grid Layout: <code>grid-template-rows: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr;</code>. How would I select all elements from the 2nd column? For example: <code>grid:nth-child(column:2)</code> (just my idea, not valid code).</p> <p>I have tried <code>nth-child</code> selectors on the <code>div</code> elements, but this does not allow me to specify row or column when the items are automatically placed by the Grid Layout engine.</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>body { display: grid; grid-template-rows: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr; grid-gap: 10px; } .item { background: #999; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="item"&gt; &lt;p&gt;Customer Name&lt;/p&gt; &lt;p&gt;Element 1 | Element 2&lt;/p&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;p&gt;Right Justify&lt;/p&gt; &lt;p&gt;Element 1 | Element 2&lt;/p&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;p&gt;Customer Name&lt;/p&gt; &lt;p&gt;Element 1 | Element 2&lt;/p&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;p&gt;Customer Name&lt;/p&gt; &lt;p&gt;Element 1 | Element 2&lt;/p&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;p&gt;Customer Name&lt;/p&gt; &lt;p&gt;Element 1 | Element 2&lt;/p&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;p&gt;Customer Name&lt;/p&gt; &lt;p&gt;Element 1 | Element 2&lt;/p&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;p&gt;Customer Name&lt;/p&gt; &lt;p&gt;Element 1 | Element 2&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
46,308,148
6
0
null
2017-09-19 19:05:53.593 UTC
15
2022-09-16 19:04:28.947 UTC
2017-09-27 15:50:42.203 UTC
null
3,597,276
null
1,232,167
null
1
95
html|css|css-selectors|css-grid
79,506
<p>Not possible with CSS.</p> <p>CSS targets HTML elements, attributes and attribute values.</p> <p>Grid columns and rows have none of these "hooks".</p> <p>You'll have to target the grid items directly.</p> <p><em>You wrote:</em></p> <blockquote> <p>For example, say I have a 3 row by 2 column CSS Grid Layout: <code>grid-template-rows: 1fr 1fr 1fr; grid-template-columns: 1fr 1fr;</code>. How would I select all elements from the 2nd column?</p> </blockquote> <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>grid-container { display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr 1fr; grid-gap: 10px; padding: 10px; height: 50vh; background-color: gray; } grid-item { background-color: lightgreen; } grid-item:nth-child(2n) { border: 2px dashed red; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;grid-container&gt; &lt;grid-item&gt;&lt;/grid-item&gt; &lt;grid-item&gt;&lt;/grid-item&gt; &lt;grid-item&gt;&lt;/grid-item&gt; &lt;grid-item&gt;&lt;/grid-item&gt; &lt;grid-item&gt;&lt;/grid-item&gt; &lt;grid-item&gt;&lt;/grid-item&gt; &lt;/grid-container&gt;</code></pre> </div> </div> </p>
52,508,038
How to increase AWS EBS NVME size
<p>I have upgraded an EC2 instance from m4 to m5, and now I want to increase the volume.</p> <p>I did perform this command and got the error:</p> <pre><code>growpart /dev/nvme0n1 p1 FAILED: partition-number must be a number </code></pre> <p>Can't find instruction from AWS docs and forums.</p> <p>Any idea how to increase NVME disk ?</p>
52,563,443
4
0
null
2018-09-25 23:48:37.6 UTC
12
2021-09-17 06:27:19.71 UTC
null
null
null
null
7,882,462
null
1
28
nvme
28,576
<p><a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/recognize-expanded-volume-linux.html" rel="noreferrer">https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/recognize-expanded-volume-linux.html</a></p> <p><code>growpart [OPTIONS] DISK PARTITION-NUMBER</code></p> <pre><code>$ lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT nvme0n1 259:0 0 16G 0 disk ├─nvme0n1p1 259:1 0 8G 0 part / └─nvme0n1p128 259:2 0 1M 0 part </code></pre> <p>So to grow the partition, we use the diskname <code>nvme0n1</code> (see <code>disk</code> under <code>TYPE</code>) and desired partition is <code>1</code></p> <pre><code>sudo growpart /dev/nvme0n1 1 </code></pre> <p>And then to extend the fs - <code>resize2fs device [ size ]</code></p> <p>(device refers to the location of the target filesystem)</p> <pre><code>$ df -h Filesystem Size Used Avail Use% Mounted on devtmpfs 470M 52K 470M 1% /dev tmpfs 480M 0 480M 0% /dev/shm /dev/nvme0n1p1 7.8G 7.7G 3.1M 100% / </code></pre> <p>So to extend the fs, we use the device name <code>/dev/nvme01np1</code>:</p> <pre><code>sudo resize2fs /dev/nvme0n1p1 </code></pre> <p>Voila!</p> <pre><code>$ df -h Filesystem Size Used Avail Use% Mounted on devtmpfs 470M 52K 470M 1% /dev tmpfs 480M 0 480M 0% /dev/shm /dev/nvme0n1p1 16G 7.7G 7.9G 50% / </code></pre>
6,053,592
Vertically centering a UL inside a DIV
<p>I have the following:</p> <pre><code>&lt;div style="background: Red; height: 100px;"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="/"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>I would like to vertically center the ul in the div but I'm not sure how. <a href="http://jsfiddle.net/JzuFT/" rel="noreferrer">Fiddle demo</a> Can anyone advise me on this. </p> <p>Marilou</p>
6,053,669
4
1
null
2011-05-19 03:58:55.157 UTC
2
2014-03-14 15:55:57.45 UTC
null
null
null
null
760,320
null
1
8
html|css
43,893
<p>CSS does not support vertical centering of arbitrary block elements. However, there are many "hacks" that will let you "make it work".</p> <p>You can set the parent div to display:inline. However, you will then have issues with your height and background color.</p> <p>W3C Link: <a href="http://www.w3.org/wiki/CSS/Properties/vertical-align" rel="nofollow">http://www.w3.org/wiki/CSS/Properties/vertical-align</a></p> <p>One hack that will do it: (has a great explanation too) <a href="http://phrogz.net/css/vertical-align/index.html" rel="nofollow">http://phrogz.net/css/vertical-align/index.html</a></p>
34,533,349
How to get Dapper to ignore/remove underscores in field names when mapping?
<p>There are many ways to map database field names to class names, but what is the simplest way to just remove the underscores?</p> <pre><code> public IEnumerable&lt;PersonResult&gt; GetPerson(int personId) { using (var dbConnection = _dbConnectionFactory.Create(ConnectionStrings.ProjectXYZ)) { IEnumerable&lt;PersonResult&gt; result = dbConnection.Query&lt;PersonResult&gt;("fn_get_person", new { personId }, commandType: CommandType.StoredProcedure).ToList(); return result; } } </code></pre> <p>Table and database fields:</p> <pre><code>person -------- person_id full_name </code></pre> <p>Class that works: (dapper already ignores capitalization)</p> <pre><code>public class PersonResult { public int Person_Id { get; set; } public string Full_Name { get; set; } } </code></pre> <p>What I would like to change the class to:</p> <pre><code>public class PersonResult { public int PersonId { get; set; } public string FullName { get; set; } } </code></pre>
34,536,829
2
2
null
2015-12-30 16:33:14.827 UTC
9
2015-12-30 20:33:31.567 UTC
null
null
null
null
1,315,626
null
1
31
postgresql|mapping|dapper
11,963
<pre><code>Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true; </code></pre> <p>job done ;p</p>
2,077,733
What columns stores the slug in wordpress
<p>In wordpress, what column stores the slug (either auto generated, or user entered)?</p> <p>I can not find this in either <code>wp_posts</code> or <code>wp_postmeta</code>. The <code>wp_posts</code> <code>GUID</code> stores a direct link, but not the slug.</p>
2,077,748
2
0
null
2010-01-16 15:02:38.163 UTC
0
2019-07-10 03:50:41.643 UTC
null
null
null
null
121,793
null
1
31
wordpress
16,046
<p>The slug for Posts and Pages are stored in the <code>wp_posts</code> posts table in the column <code>post_name</code>. Just be aware that all the automatic saves as well as attachments are stored in the same table, so there will not be a solid column full of slugs, but only one for each "parent" (parent to the revisions) Post or Page.</p>
53,367,195
Invariant Violation: The navigation prop is missing for this navigator
<p>I am receiving this message when I tried starting my react native app. Usually this kind of format works on other multi screen navigation yet somehow does not work in this case.</p> <p>Here is the error:</p> <pre><code>Invariant Violation: The navigation prop is missing for this navigator. In react-navigation 3 you must set up your app container directly. More info: https://reactnavigation.org/docs/en/app-containers.html </code></pre> <p>Here is my app format:</p> <pre><code>import React, {Component} from 'react'; import { StyleSheet, Text, View } from 'react-native'; import { createStackNavigator } from 'react-navigation'; import Login from './view/login.js' import SignUp from './view/signup.js' const RootStack = createStackNavigator( { Home: { screen: Login }, Signup: { screen: SignUp } }, { initialRouteName: 'Home' } ); export default class App extends React.Component { render() { return &lt;RootStack /&gt;; } } </code></pre>
53,367,656
10
2
null
2018-11-19 01:28:30.67 UTC
20
2020-07-26 11:35:41.793 UTC
null
null
null
null
4,967,349
null
1
128
reactjs|react-native
81,395
<p>React Navigation 3.0 has a number of <a href="https://reactnavigation.org/blog/#breaking-changes" rel="noreferrer">breaking changes</a> including an explicit app container required for the root navigator. </p> <blockquote> <p>In the past, any navigator could act as the navigation container at the top-level of your app because they were all wrapped in “navigation containers”. The navigation container, now known as an app container, is a higher-order-component that maintains the navigation state of your app and handles interacting with the outside world to turn linking events into navigation actions and so on.</p> <p>In v2 and earlier, the containers in React Navigation are automatically provided by the create*Navigator functions. As of v3, you are required to use the container directly. In v3 we also renamed createNavigationContainer to createAppContainer.</p> </blockquote> <p>Also please note that if you are now using v4, navigators have been moved to a separate repo. You'll now need to install and import from <code>'react-navigation-stack'</code>. For example <code>import { createStackNavigator } from 'react-navigation-stack'</code> The solution below is for v3.</p> <pre><code>import { createStackNavigator, createAppContainer } from 'react-navigation'; const MainNavigator = createStackNavigator({...}); const App = createAppContainer(MainNavigator); </code></pre> <p>A more comprehensive code example:</p> <pre><code>import { createStackNavigator, createAppContainer } from 'react-navigation'; import Login from './view/login.js' import SignUp from './view/signup.js' const RootStack = createStackNavigator({ Home: { screen: Login }, Signup: { screen: SignUp } }); const App = createAppContainer(RootStack); export default App; </code></pre>
5,600,659
Rebasing a branch including all its children
<p>I have the following Git repository topology:</p> <pre><code>A-B-F (master) \ D (feature-a) \ / C (feature) \ E (feature-b) </code></pre> <p>By rebasing <code>feature</code> branch I expected to rebase the whole subtree (including child branches):</p> <pre><code>$ git rebase feature master A-B-F (master) \ D (feature-a) \ / C (feature) \ E (feature-b) </code></pre> <p>However, this is the actual result:</p> <pre><code> C' (feature) / A-B-F (master) \ D (feature-a) \ / C \ E (feature-b) </code></pre> <p>I know I can easily fix it manually by executing:</p> <pre><code>$ git rebase --onto feature C feature-a $ git rebase --onto feature C feature-b </code></pre> <p>But is there a way to automatically rebase branch including all its children/descendants?</p>
5,632,027
5
4
null
2011-04-08 20:52:33.617 UTC
53
2021-09-30 17:39:52.017 UTC
2012-12-06 18:48:41.917 UTC
null
1,864,976
null
605,744
null
1
96
git|version-control|branch|rebase|git-rebase
13,590
<pre><code>git branch --format='%(refname:short)' --contains C | \ xargs -n 1 \ git rebase --committer-date-is-author-date --onto F C^ </code></pre>
5,620,269
Migrate from sql server 2000 to 2008 r2 - how to
<p>I have a database working on SQL Server 2000. We are now migrating to a new server with SQL Server 2008 r2. Can anyone please point me to some resource or howto? I'm not really finding my way around SQL 2000.</p> <p>Thank you!</p>
5,620,551
7
1
null
2011-04-11 10:54:09.347 UTC
2
2013-10-01 17:21:03.727 UTC
null
null
null
null
625,242
null
1
10
sql-server-2008|migration|sql-server-2000
49,493
<p>Basically, what you need to do is:</p> <ul> <li>backup your database in SQL Server 2000 to a .bak file</li> <li>move that *.bak file to your new server</li> <li>restore that database onto your new server </li> </ul> <p>You're done! There's really nothing more to it..... just backup (on your old system) and restore (on your new system).</p> <p>So where exactly is your problem ??</p> <p><strong>Update:</strong> as @Péter correctly mentions: this leaves your database in the SQL Server 2000 compatibility mode. This means: even though you've "migrated" to SQL Server 2008 R2, you can still only use the 2000 features.</p> <p>In order to see what compatibility mode your database is in, check the <code>sys.databases</code> catalog view:</p> <pre><code>SELECT * FROM sys.databases WHERE name = 'YourDatabaseName' </code></pre> <p>One column is called <code>compatibility_level</code> and contains an <code>INT</code>; 80 = SQL Server 2000, 90 = SQL Server 2005, 100 = SQL Server 2008 / 2008 R2 and 110 = SQL Server 2012</p> <p>In order to change your database to a different compatibility level, use this command:</p> <pre><code>ALTER DATABASE YourDatabaseNameHere SET COMPATIBILITY_LEVEL = 100; </code></pre> <p>This will put your database into the "native" SQL Server 2008 (and 2008 R2) mode and now your migration is complete, you can use all the new SQL Server 2008 R2 features.</p>
5,884,784
How to pull remote branch from somebody else's repo
<p>I've got a project hosted on GitHub which somebody has forked. On their fork, they've created a new branch "foo" and made some changes. How do I pull their "foo" into a new branch also named "foo" in my repo?</p> <p>I understand they could submit a pull request to me, but I'd like to initiate this process myself.</p> <p>Assume the following:</p> <ol> <li>Because they forked my project, both our repos share the same 'history'</li> <li>Although GitHub shows their project was forked from mine, my local repository doesn't have any references to this person's project. Do I need to add theirs as a remote?</li> <li>I don't have a branch called "foo" yet - I don't know if I need to manually create this first.</li> <li>I definitely want this pulled into a separate branch and not my master.</li> </ol>
5,884,825
7
0
null
2011-05-04 14:14:56.057 UTC
166
2022-08-22 10:06:51.627 UTC
2019-02-05 09:10:33.2 UTC
null
472,495
null
158,766
null
1
349
git|github|git-branch|git-pull|git-remote
206,383
<pre><code>git remote add coworker git://path/to/coworkers/repo.git git fetch coworker git checkout --track coworker/foo </code></pre> <p>This will setup a local branch <code>foo</code>, tracking the remote branch <code>coworker/foo</code>. So when your co-worker has made some changes, you can easily pull them:</p> <pre><code>git checkout foo git pull </code></pre> <hr> <p>Response to comments:</p> <blockquote> <p>Cool :) And if I'd like to make my own changes to that branch, should I create a second local branch "bar" from "foo" and work there instead of directly on my "foo"?</p> </blockquote> <p>You don't need to create a new branch, even though I recommend it. You might as well commit directly to <code>foo</code> and have your co-worker pull your branch. But that branch already exists and your branch <code>foo</code> need to be setup as an upstream branch to it:</p> <pre><code>git branch --set-upstream foo colin/foo </code></pre> <p>assuming <code>colin</code> is your repository (a remote to your co-workers repository) defined in similar way:</p> <pre><code>git remote add colin git://path/to/colins/repo.git </code></pre>
5,952,467
How to specify a editor to open crontab file? "export EDITOR=vi" does not work
<p>I'm using Red Hat Enterprise Linux 5, and I want to set the vim editor to edit the crontab file. </p> <p>If I run <code>echo $EDITOR</code>, I get vim. But when I run <code>crontab -e</code>, I get different editor.</p>
5,952,569
8
0
null
2011-05-10 15:25:22.077 UTC
21
2017-11-02 07:23:18.733 UTC
2014-10-02 07:20:02.243 UTC
null
647,670
null
647,670
null
1
105
linux|vim
134,500
<p>Very probable that your <code>VISUAL</code> environment variable is set to something else. Try:</p> <pre><code>export VISUAL=vi </code></pre>
6,249,707
Check if PHP session has already started
<p>I have a PHP file that is sometimes called from a page that has started a session and sometimes from a page that doesn't have session started. Therefore when I have <code>session_start()</code> on this script I sometimes get the error message for "session already started". For that I've put these lines:</p> <pre><code>if(!isset($_COOKIE["PHPSESSID"])) { session_start(); } </code></pre> <p>but this time I got this warning message:</p> <blockquote> <p>Notice: Undefined variable: _SESSION </p> </blockquote> <p>Is there a better way to check if session has already started?</p> <p>If I use <code>@session_start</code> will it make things work properly and just shut up the warnings?</p>
18,542,272
26
2
null
2011-06-06 09:00:51.393 UTC
118
2022-04-21 20:55:10.72 UTC
2012-07-18 21:25:05.64 UTC
null
9,314
null
751,969
null
1
506
php|session|session-variables
524,926
<p>Recommended way for versions of <strong>PHP &gt;= 5.4.0 , PHP 7, PHP 8</strong></p> <pre><code>if (session_status() === PHP_SESSION_NONE) { session_start(); } </code></pre> <p>Reference: <a href="http://www.php.net/manual/en/function.session-status.php" rel="noreferrer">http://www.php.net/manual/en/function.session-status.php</a></p> <p>For versions of <strong>PHP &lt; 5.4.0</strong></p> <pre><code>if(session_id() == '') { session_start(); } </code></pre>
18,145,697
bootstrap nav push-left / push-right
<p>I need to have one part of my horizontal menu/navigation floating left, and other floating right.</p> <p>Like this:<br> <strong>Option1_Option2____Option3_Option4_<em>_</em>__<em>_</em>__<em>_</em>__<em>_</em>__Option5_Option6</strong></p> <p>I am using this technique:</p> <pre><code>&lt;ul class="nav navbar-nav pull-left"&gt; &lt;li&gt;&lt;a href="#"&gt;Option1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Option2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Option3&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Option4&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul class="nav navbar-nav pull-right"&gt; &lt;li&gt;&lt;a href="#"&gt;Option5&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Option6&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>but since the floats are (has to be)<code>!important</code>I am having problems when the menu collapses on smaller (tablet/mobile) screen sizes.<br>It ends up being like this:</p> <p><strong>Option1<br>Option2<br>Option3<br>Option4<br>&nbsp;&nbsp;Option5<br>&nbsp;&nbsp;Option6</strong></p> <p>As you can see the two last needs to be floated to the left, so I have tried changing the <code>.pull-right {float: right !important;}</code> to <code>.pull-right {float: left !important;}</code> in the <code>@media</code> queries but no luck... I am stuck. Is there any way to over-ride<code>!important</code> in the @media queries, or any other way to address this issue?</p>
18,148,258
1
4
null
2013-08-09 11:28:29.337 UTC
1
2013-08-09 14:38:36.26 UTC
2013-08-09 12:13:04.587 UTC
null
1,409,882
null
1,409,882
null
1
3
css|twitter-bootstrap|css-float|alignment
50,917
<p>Are you wrapping your <code>ul</code>s in a <code>&lt;div class="nav-collapse collapse"&gt;</code> ? your code seems to work just fine for me. See here -> <a href="http://jsfiddle.net/SchmalzyB/VNjYz/" rel="nofollow">jsFiddle</a></p> <p>If you watch the computed styles of the <code>.pull-right</code> <code>ul</code> when collapsing the nav-bar you can see bootstrap changes the <code>float</code> from <code>right</code> to <code>none</code>.</p> <p>This it directly from bootstrap.css....</p> <pre><code>@media (max-width: 979px) .navbar .nav-collapse .nav.pull-right { float: none; margin-left: 0; } </code></pre> <p>I am betting you have some conflicting CSS that is messing it up. Remove any custom <code>.pull-right</code> CSS you have, or any custom CSS for the entire navbar...</p>
21,545,424
TFS 2012 : The working folder is already in use after Hard Disk Format
<p>I have referred to a lot of forums and also this <a href="https://stackoverflow.com/questions/226288/team-build-error-the-path-is-already-mapped-to-workspace">so question</a> but my problem is that I have formatted my machine. So I'm not able to overcome this issue. I have tried deleting workspaces from visual studio command prompt and also clearing cache, but I feel this mapping is more on the server-side than local cache, because my machine was formatted. I don't know which file has this old working path saved.</p> <p>Also I have tried downloading the project into a new working path. I was able to download, but then I don't get the TFS icon against each file. i.e.it's like working offline (disjoint from TFS database). On right click we generally have an option to return online or go online. In this case on right click I get TEAM -> Apply Patch &amp; TEAM -> Share Project</p> <p>Please help me with this.I had the same problem in my asp.net projects, when I simply downloaded them onto a new working path it worked fine. But this java project in eclipse just doesn't seem to connect to tfs when downloaded into a new path nor does it allow to download in the old path.</p> <p>Please not I have formatted the machine.So my case is different, so this may not be a possible duplicate of other SO questions.</p> <p>I did not disconnect or delete workspace before a format(due to lack of knowledge) at that point. May be doing that would never cause this. All I did is check in all files and re-formatted my windows.</p>
21,556,369
8
1
null
2014-02-04 06:26:43.443 UTC
9
2021-07-30 20:26:26.797 UTC
2017-05-23 10:31:27.11 UTC
null
-1
null
425,094
null
1
25
team-explorer|tf-cli|source-control-explorer
31,019
<p>I'd suggest using the (free) tool TFS Sidekicks: <a href="http://www.attrice.info/cm/tfs/" rel="noreferrer">http://www.attrice.info/cm/tfs/</a></p> <p>This will give you a GUI to view all workspaces (across all users and machines), and delete the obsolete ones.</p> <p><img src="https://i.stack.imgur.com/zEcyj.gif" alt="enter image description here"></p>
33,009,825
docker-compose yml running a script after up
<p>I want to run a script, right after running </p> <pre><code>`docker-compose up -d` </code></pre> <p>Here is my snippet of <code>docker-compose.yml</code> . The other settings are mysql server, redis...etc....but they are not causing any problems</p> <pre><code>web: image: nginx container_name: web-project volumes: - ./code:/srv working_dir: /srv/myweb extra_hosts: - "myweb.local:127.0.0.1" ports: - 8081:80 # tty: true command: sh /srv/scripts/post-run-web.sh </code></pre> <p>So whenever i run <code>docker-compose up -d</code> or <code>docker-compose up</code> It all stops. (the containers do not keep running). Although my shell script is simple (running echos...or phpunit). Here is my script.</p> <pre><code>#!/bin/bash echo running post install scripts for web..; cd /srv/myweb npm install composer self-update composer update </code></pre> <p>And this is the error I get. It is like the server (nginx) is not running yet. Also if I connect to the server using exec bash, and i check out the processes. I do not see nginx running (yet).</p> <pre><code>web_1 | You are already using composer version 7a9eb02190d334513e99a479510f87eed18cf958. web_1 | Loading composer repositories with package information web_1 | Updating dependencies (including require-dev) web_1 | Generating autoload files web-project exited with code 0 Gracefully stopping... (press Ctrl+C again to force) Stopping mysql-project... done Stopping rabbitmq-project... done Stopping redis-project... done </code></pre> <p>So why is it exiting, although the script is syntax-wise correct? How can i make it run correctly? (what am I doing, setting up wrong!)</p>
33,010,014
1
1
null
2015-10-08 07:54:40.6 UTC
7
2018-03-26 08:40:09.447 UTC
2018-03-26 08:40:09.447 UTC
null
2,877,029
null
1,099,972
null
1
41
bash|nginx|docker|docker-compose
70,474
<p><a href="https://docs.docker.com/compose/compose-file/#command" rel="noreferrer">command</a> overrides the default command.</p> <p>That's the reason your container stops: nginx never starts.</p> <p>At the end of your script you have to run <code>nginx</code></p> <pre><code>#!/bin/bash echo running post install scripts for web..; cd /srv/myweb npm install composer self-update composer update nginx </code></pre> <p>By the way, I suggest you to change your script and run <code>npm install</code> and <code>composer *update</code> only if required (thus only if some file in /src/myweb does not exists), because it makes your container startup time increase in vain.</p> <p>Note that by doing so, NginX will never catch the SIGTERM signal sent by docker stop. That can cause it to be abruptly killed.</p> <p>Instead, if you want to be sure that SIGTERM is received by nginx, you have to replace the last line with <code>exec nginx</code>. This replaces the bash process with nginx itself.</p>
32,623,834
How does this Java code snippet work? (String pool and reflection)
<p>Java string pool coupled with reflection can produce some unimaginable result in Java:</p> <pre><code>import java.lang.reflect.Field; class MessingWithString { public static void main (String[] args) { String str = "Mario"; toLuigi(str); System.out.println(str + " " + "Mario"); } public static void toLuigi(String original) { try { Field stringValue = String.class.getDeclaredField("value"); stringValue.setAccessible(true); stringValue.set(original, "Luigi".toCharArray()); } catch (Exception ex) { // Ignore exceptions } } } </code></pre> <p>Above code will print:</p> <pre><code>"Luigi Luigi" </code></pre> <p>What happened to Mario?</p>
32,623,895
7
2
null
2015-09-17 06:29:43.257 UTC
19
2015-09-22 08:52:02.757 UTC
2015-09-17 11:35:56.363 UTC
null
2,736,496
null
3,033,318
null
1
86
java|string|reflection|string-pool
4,236
<blockquote> <p>What happened to Mario ??</p> </blockquote> <p>You changed it, basically. Yes, with reflection you can violate the immutability of strings... and due to string interning, that means any use of "Mario" (other than in a larger string constant expression, which would have been resolved at compile-time) will end up as "Luigi" in the rest of the program.</p> <p>This kinds of thing is why reflection requires security permissions...</p> <p>Note that the expression <code>str + " " + "Mario"</code> does <em>not</em> perform any compile-time concatenation, due to the left-associativity of <code>+</code>. It's effectively <code>(str + " ") + "Mario"</code>, which is why you still see <code>Luigi Luigi</code>. If you change the code to:</p> <pre><code>System.out.println(str + (" " + "Mario")); </code></pre> <p>... then you'll see <code>Luigi Mario</code> as the compiler will have interned <code>" Mario"</code> to a different string to <code>"Mario"</code>.</p>
9,290,269
How to navigate through windows with MVVM Light for WPF?
<p>I've just started a new project in which the presentation layer will be done by WPF and <a href="http://www.mvvmlight.net/">MVVM Light</a> by GalaSoft.</p> <p>I need a lot of views and it's not clear to me how to manage navigation through windows.</p> <p>First of all, the templates offered in MVVM Light for creating a new "WPF MVVM View" create a new <code>Window</code> that is not possible to use for navigation by frame (I mean, by putting a frame in <code>mainView</code> and changing the source path to navigate).</p> <p>Do I simply have to change <code>Window</code> to <code>Page</code> for all the views I create using templates?</p> <p>Or is there a different way to perform navigation in WPF with the MVVM Light toolkit?</p>
9,361,548
3
0
null
2012-02-15 08:48:45.833 UTC
17
2019-09-24 18:39:43.463 UTC
2014-06-05 20:22:55.817 UTC
null
6,651
null
365,561
null
1
19
wpf|design-patterns|mvvm|mvvm-light
31,144
<p>Eventually I did it this way.</p> <p>Following the idea of o_q, I created NavigationWindow as MainWindow and changed all the the views to page.</p> <p>Then, I created an inteface and a class which using Navigation:</p> <pre class="lang-cs prettyprint-override"><code> public interface INavigationService { event NavigatingCancelEventHandler Navigating; void NavigateTo(Uri pageUri); void GoBack(); } public class NavigationService : INavigationService { private NavigationWindow _mainFrame; #region Implementation of INavigationService public event NavigatingCancelEventHandler Navigating; public void NavigateTo(Uri pageUri) { if (EnsureMainFrame()) { _mainFrame.Navigate(pageUri); } } public void GoBack() { if (EnsureMainFrame() &amp;&amp; _mainFrame.CanGoBack) { _mainFrame.GoBack(); } } #endregion private bool EnsureMainFrame() { if (_mainFrame != null) { return true; } _mainFrame = System.Windows.Application.Current.MainWindow as NavigationWindow; if (_mainFrame != null) { // Could be null if the app runs inside a design tool _mainFrame.Navigating += (s, e) =&gt; { if (Navigating != null) { Navigating(s, e); } }; return true; } return false; } } </code></pre> <p>Then, in viewModelLocator I created all the const string nedded to store the paths to my views:</p> <pre class="lang-cs prettyprint-override"><code> public class ViewModelLocator { #region Views Paths public const string FrontendViewPath = "../Views/FrontendView.xaml"; public const string BackendViewPath = "../Views/BackendView.xaml"; public const string StartUpViewPath = "../Views/StartUpView.xaml"; public const string LoginViewPath = "../Views/LoginView.xaml"; public const string OutOfOrderViewPath = "../Views/OutOfOrderView.xaml"; public const string OperativeViewPath = "../Views/SubViews/OperativeView.xaml"; public const string ConfigurationViewPath = "../Views/SubViews/ConfigurationView.xaml"; #endregion } </code></pre> <p>In App.cs, in the Application_Startup event handler, with the help of Unity IoC I registered a singleton of NavigationService:</p> <pre class="lang-cs prettyprint-override"><code> public partial class App : System.Windows.Application { private static IUnityContainer _ambientContainer; public static IServiceLocator AmbientLocator { get; private set; } ... private void Application_Startup(object sender, System.Windows.StartupEventArgs e) { _ambientContainer = new UnityContainer(); _ambientContainer.RegisterType&lt;INavigationService, NavigationService&gt;(new ContainerControlledLifetimeManager()); AmbientLocator = new UnityServiceLocator(_ambientContainer); ServiceLocator.SetLocatorProvider(() =&gt; AmbientLocator); </code></pre> <p>Now, in my ViewModelLocator, I can register a "Galasoft" message to catch all the events and navigate to a page; in the constructor I have:</p> <pre class="lang-cs prettyprint-override"><code> public ViewModelLocator() { CreateMain(); CreateFrontend(); CreateBackend(); CreateStartUp(); CreateOperative(); CreateLogin(); CreateConfiguration(); CreateOutOfOrder(); // Set Startup Page... ServiceLocator.Current.GetInstance&lt;INavigationService&gt;().NavigateTo(new Uri(StartUpViewPath, UriKind.Relative)); Messenger.Default.Register&lt;MoveToViewMessage&gt;(this, message =&gt; { switch (message.StateInfo.StateType) { case StateType.StartUpState: ServiceLocator.Current.GetInstance&lt;INavigationService&gt;().NavigateTo(new Uri(StartUpViewPath,UriKind.Relative)); break; case StateType.LoginState: ServiceLocator.Current.GetInstance&lt;INavigationService&gt;().NavigateTo(new Uri(LoginViewPath, UriKind.Relative)); break; case StateType.OperativeState: ServiceLocator.Current.GetInstance&lt;INavigationService&gt;().NavigateTo(new Uri(OperativeViewPath, UriKind.Relative)); break; case StateType.ConfigurationState: ServiceLocator.Current.GetInstance&lt;INavigationService&gt;().NavigateTo(new Uri(ConfigurationViewPath, UriKind.Relative)); break; case StateType.ClosedState: case StateType.OutOfOrderState: ServiceLocator.Current.GetInstance&lt;INavigationService&gt;().NavigateTo(new Uri(OutOfOrderViewPath, UriKind.Relative)); break; default: ServiceLocator.Current.GetInstance&lt;INavigationService&gt;().NavigateTo(new Uri(StartUpViewPath, UriKind.Relative)); break; } }); } </code></pre> <p>In this way I keep all the viewModels "ignorant"... they don't know anything about navigation, plus I don't have code behind.</p> <p>If I need to navigate by using a button from a view I can resolve NavigationService from the connected viewModel and navigate to the Page I need.</p> <p>And, most important thing, it works!</p>
10,269,274
I get 'Command Not Found' when I try to run Android Emulator on Mac OS X
<p>When I use the <a href="https://en.wikipedia.org/wiki/Terminal_%28OS_X%29" rel="noreferrer">Mac OS X Terminal</a> to navigate to the folder with my Android Emulator and type <code>emulator</code>, I get:</p> <blockquote> <p>command not found</p> </blockquote> <p>Here's what happens:</p> <pre><code>$ emulator -bash: emulator: command not found </code></pre> <p>How do I get it to work?</p>
10,269,303
6
1
null
2012-04-22 15:32:25.413 UTC
3
2022-03-15 07:37:40.843 UTC
2018-01-25 13:04:59.963 UTC
null
874,188
null
773,649
null
1
61
android|macos|shell|emulation
69,271
<p>The <a href="https://superuser.com/questions/156582/why-is-not-in-the-path-by-default">current directory is not normally included in your <code>$PATH</code> on a *nix operating system</a> like OS X; to execute a program in the current directory, precede it with the path to the current directory (<code>.</code>):</p> <pre><code>$ ./emulator </code></pre>
22,725,281
How do you update an existing Bootstrap modal data-target?
<p>I tried to update an existing <code>data-target</code> with a <code>data-target="#testModal1"</code> to point to the <code>#testModal2</code> modal using jquery <code>.data</code>, but even after the data attribute change it still is linked to <code>#testModal1</code></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>//Jquery: $('#testButton').data('target', '#testModal2')</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!-- HTML: --&gt; &lt;button id='testButton' data-toggle="modal" data-target="#testModal1"&gt; Test &lt;/button&gt; &lt;div class="modal fade" id="testModal1" tabindex="-1" role="dialog" aria-hidden="true" style='display:none'&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; Testing Testing 1 &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="modal fade" id="testModal2" tabindex="-1" role="dialog" aria-hidden="true" style='display:none;'&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; Testing Testing 2 &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
22,756,614
2
1
null
2014-03-29 00:06:13.497 UTC
1
2021-01-29 17:46:52.847 UTC
2018-04-02 13:35:22.313 UTC
null
3,641,900
null
1,678,772
null
1
14
jquery|twitter-bootstrap-3
44,205
<p>Let's look in the jQuery documetation what <code>.data()</code> is:</p> <blockquote> <h1><a href="http://api.jquery.com/data/" rel="noreferrer"><code>.data()</code></a></h1> <p>Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.</p> <h2><code>.data( key, value )</code></h2> <p><strong>Description</strong>: Store arbitrary data associated with the matched elements.</p> <ul> <li><p>key</p> <p>Type: <code>String</code></p> <p>A string naming the piece of data to set.</p></li> <li><p>value</p> <p>Type: Object</p> <p>The new data value; it can be <strong>any Javascript type</strong> including Array or Object.</p></li> </ul> </blockquote> <hr> <p>Using <code>$('#testButton').data('target','#testModal2')</code> you will <strong>not</strong> modify the <code>data-target</code> attribute but you will store the string <code>"#testModal2"</code> in <code>"target"</code> field. Then <code>$('#testButton').data('target')</code> will return <code>"#testModal2"</code>.</p> <p>It's true that <code>.data('key')</code> can be used to return the <code>data-key</code> attribute value. But you cannot set it using <code>.data('key', 'newValue'</code>).</p> <p>To set an attribute value the most common and easy way is to use <a href="http://api.jquery.com/attr/#attr2" rel="noreferrer"><code>.attr()</code></a> method.</p> <p>So, the answer is easy: change <code>data</code> in <code>attr</code> and use <code>data-target</code> instead of <code>target</code>:</p> <pre><code>$('#testButton').attr('data-target','#testModal2'); </code></pre> <p><a href="http://jsfiddle.net/m5TMF/150/" rel="noreferrer"><strong>JSFIDDLE</strong></a></p>
7,254,047
python : working with german umlaut
<pre><code>months = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"] print months[2].decode("utf-8") </code></pre> <p>Printing month[2] fails with </p> <pre><code>UnicodeDecodeError: 'utf8' codec can't decode bytes in position 1-2: invalid data </code></pre> <p>help to get rid of this!</p>
7,254,078
2
1
null
2011-08-31 07:52:04.03 UTC
3
2015-10-03 08:53:18.277 UTC
2015-10-03 08:53:18.277 UTC
null
426,305
null
426,305
null
1
18
python|unicode|diacritics
54,001
<p>Did you add an encoding in the begining of your source file ?</p> <pre><code># -*- coding: utf-8 -*- </code></pre>
31,940,220
DB2 SQL error sqlcode=-104 sqlstate=42601
<p>I am relatively new to DB2 but not to SQL. I am experiencing the below error when trying a <code>SELECT</code> statement while subtracting a few minutes from a <code>timestamp</code>:</p> <pre><code>SELECT * TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP </code></pre> <p>The error that I am experiencing is:</p> <blockquote> <p>DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=TCCAWZTXD;SELECT*;, DRIVER=3.66.46</p> </blockquote> <p>How can I fix this error?</p>
31,940,283
1
1
null
2015-08-11 11:11:59.06 UTC
null
2021-06-28 13:50:03.757 UTC
2020-03-21 12:19:26.523 UTC
null
10,312,071
null
3,884,487
null
1
12
sql|db2
147,110
<p>You miss the <code>from</code> clause</p> <pre><code>SELECT * from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP </code></pre>
31,456,660
FileOutputStream: Does the "close" method calls also "flush"?
<p>I'm really confused about flush and close method.In my code I always close my <code>FileOutputStream</code> object. But I want to know that if I have to use flush method here, and where can I use it?</p> <p>I will write a project that download 4 or 5 files repeatedly. I will write a method(for download files) and my method will be in a loop and download files repeatedly.My method will have a code like this.</p> <p>Does the <code>close</code> method calls <code>flush</code>, or do I have to use flush before closing?</p> <pre><code>try { InputStream inputStream = con.getInputStream(); FileOutputStream outputStream = new FileOutputStream("C:\\programs\\TRYFILE.csv"); int bytesRead = -1; byte[] buffer = new byte[4096]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } } catch(Exception e) { // } finally { outputStream.close(); inputStream.close(); } </code></pre> <p>Note that the code works well: it download the file successfully. But I'm not sure about using <code>flush</code>.</p>
31,456,919
2
3
null
2015-07-16 14:10:33.62 UTC
8
2015-07-16 14:47:40.587 UTC
2015-07-16 14:28:22.19 UTC
null
3,924,118
null
5,123,910
null
1
27
java|io|fileoutputstream
19,088
<p>The method <code>flush</code> is used to "flush" bytes retained in a buffer. <code>FileOutputStream</code> doesn't use any buffer, so flush method is empty. Calling it or not doesn't change the result of your code.</p> <p>With buffered writers the method <code>close</code> call explicitly <code>flush</code>.</p> <p>So you need to call flush when you like to write the data <strong>before closing the stream</strong> and before the buffer is full (when the buffer is full the writer starts writing without waiting a flush call).</p> <p>The source code of class <code>FileOutputStream</code> hasn't a custom version of method <code>flush</code>. So the <code>flush</code> method used is the version of its super class <code>OutputStream</code>. The code of flush in <code>OutputStream</code> is the following</p> <pre><code>public void flush() throws IOException { } </code></pre> <p>As you see this is an empty method doing nothing, so calling it or not is the same.</p>
19,129,133
Qt signals and slots: permissions
<p>There are discrepancies between respected answers here on SO and the actual Qt docs.</p> <p>I've read <a href="https://stackoverflow.com/questions/2143183/private-public-qt-signals">this question</a> and I want some further clarification. Can anyone confirm:</p> <ul> <li>A signal is always <code>protected</code>, therefore it can be emitted only by the class or any of its subclasses. I'm not sure this is true; the question above shows answers supporting this statement. But the <a href="http://qt-project.org/doc/qt-5.0/qtcore/signalsandslots.html" rel="noreferrer">Qt docs</a> say: <code>Signals are public access functions and can be emitted from anywhere, but we recommend to only emit them from the class that defines the signal and its subclasses.</code> So which is it?</li> <li>Slots are just functions, and thus may be public, private or protected. Obviously an outside class <em>will</em> have the ability to control if your class connects one of its own signals to one of its own slots if the slot is public. However, again the SO information differs from the docs, which say: <code>a signal emitted from an instance of an arbitrary class can cause a private slot to be invoked in an instance of an unrelated class.</code> This means that <code>private</code> is not honored by the signal/slot mechanism?</li> <li>The words public, private, protected have no use with working with the <code>signal</code> keyword</li> <li>The emitted signal is <em>always</em> available to all other classes, that is, any other class may always connect to that signal (regardless of its permission to emit the signal).</li> <li>Despite that all signals are viewable to by all classes, you could still have two classes with signals of the same name since the <code>connect</code> function takes the class name as a signal prefix (i.e. <code>SomeClass::itsSignal</code>)</li> </ul>
19,130,831
3
1
null
2013-10-02 02:33:49.61 UTC
9
2015-12-10 16:54:46.49 UTC
2017-05-23 11:54:34.133 UTC
null
-1
null
3,758,484
null
1
28
c++|qt|inheritance|signals-slots|qt-signals
18,973
<ul> <li>Signals are protected in Qt4 but are public in Qt5, thus the contradictory information.</li> <li>Slots are functions and public/protected/private is honored when calling them as such, when connecting to a signal, the metaobject system ignores it though.</li> <li>As <code>signals</code> is defined as <code>public:</code>, prepending them with e.g. private leads </li> </ul> <p>to:</p> <pre><code>private: public: //signals: void theSignal(); </code></pre> <p>Thus it's without effect.</p> <ul> <li>All classes can be connected to any signal, correct. Signals are part of the public API in that regard.</li> <li>Having identical signal signatures is not a problem. The context is defined by the object specified as sender.</li> </ul> <p>Using old-style connect:</p> <pre><code>Apple *apple ... Orange* orange connect(apple, SIGNAL(changed()), this, SLOT(appleChanged())); connect(orange, SIGNAL(changed()), this, SLOT(orangeChanged())); </code></pre> <p>The signal is specified as string here (without the class name in it), but as <code>apple</code> and <code>orange</code> have only one signal <code>changed()</code> each and the lookup is done in the metaobject of the QObject instance, which exists one per class (not instance), they cannot collide.</p> <p>Qt 5 version with compile-time checking:</p> <pre><code>connect(apple, &amp;Apple::changed, this, &amp;MyReceiver::appleChanged); </code></pre> <p>Here one must specify a function, so depending on the scope, one must specify a class name (and maybe namespaces). As an ambiguous function name wouldn't be valid C++ and thus not compile, so one is safe here.</p>
58,403,651
React component has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
<p>I am calling the Web API from the my react component using fetch when I used to run it as one application, there was no problem, but when I am running the application react separate from API, I am getting the CORS error, my fetch call is as below, </p> <pre><code> componentDidMount() { console.log(clientConfiguration) fetch(clientConfiguration['communitiesApi.local']) .then((response) =&gt; { return response.json(); }) .then(data =&gt; { console.log(data); let communitiesFromApi = data.map(community =&gt; { return { value: community, display: community } }); this.setState({ communities: [{ value: '', display: 'Select a Community...' }].concat(communitiesFromApi) }); }).catch(error =&gt; { console.log(error); }); }; </code></pre> <p>and my POST call using Axios as below also. </p> <pre><code> handleDownload = (e) =&gt; { e.preventDefault(); var formData = new FormData(); formData.append('communityname', this.state.selectedCommunity); formData.append('files', JSON.stringify(this.state['checkedFiles'])); let url = clientConfiguration['filesApi.local']; let tempFiles = clientConfiguration['tempFiles.local']; axios({ method: 'post', responseType: 'application/zip', contentType: 'application/zip', url: url, data: formData }) .then(res =&gt; { var fileName = `${this.state['selectedCommunity']}.zip`; saveAs(`https://localhost:44352/TempFiles/${res.data}`, fileName); }); }; </code></pre> <p>Here is my server side api code:</p> <pre><code> [HttpGet("{communityName}")] public string Get(string communityName) { string rootPath = Configuration.GetValue&lt;string&gt;("ROOT_PATH"); string communityPath = rootPath + "\\" + communityName; string[] files = Directory.GetFiles(communityPath); List&lt;string&gt; strippedFiles = new List&lt;string&gt;(); foreach (string file in files) { strippedFiles.Add(file.Replace(communityPath + "\\", "")); } return JsonConvert.SerializeObject(strippedFiles); } [HttpPost] public string Post([FromForm] string communityName, [FromForm] string files) //FileContentResult { var removedInvalidCharsFromFileName = removeInvalidCharsFromFileName(files); var tFiles = removedInvalidCharsFromFileName.Split(','); string rootPath = Configuration.GetValue&lt;string&gt;("ROOT_PATH"); string communityPath = rootPath + "\\" + communityName; byte[] theZipFile = null; using (MemoryStream zipStream = new MemoryStream()) { using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true)) { foreach (string attachment in tFiles) { var zipEntry = zip.CreateEntry(attachment); using (FileStream fileStream = new FileStream(communityPath + "\\" + attachment, FileMode.Open)) using (Stream entryStream = zipEntry.Open()) { fileStream.CopyTo(entryStream); } } } theZipFile = zipStream.ToArray(); } ////return File(theZipFile, "application/zip", communityName + ".zip"); string tempFilesPath = Configuration.GetValue&lt;string&gt;("Temp_Files_Path"); if (!System.IO.Directory.Exists(tempFilesPath)) System.IO.Directory.CreateDirectory(tempFilesPath); System.IO.File.WriteAllBytes($"{tempFilesPath}\\{communityName}.zip", theZipFile); //return System.IO.File.ReadAllBytes($"{tempFilesPath}\\Test.zip"); //return $"{tempFilesPath}\\{communityName}.zip"; return $"{communityName}.zip"; } </code></pre> <p>And I am getting the error for Get as below: "Access to fetch at '<a href="https://localhost:44368/api/communities" rel="noreferrer">https://localhost:44368/api/communities</a>' from origin '<a href="http://localhost:3000" rel="noreferrer">http://localhost:3000</a>' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."</p>
58,403,702
6
1
null
2019-10-15 23:06:16.173 UTC
null
2022-02-04 23:05:30.41 UTC
2019-10-16 02:53:50.613 UTC
null
7,249,598
null
12,127,473
null
1
10
javascript|reactjs|asp.net-web-api
41,069
<p>You'll need to modify your sever. You'll need to</p> <ol> <li>Enable CORS on the server side and</li> <li>Add the domain where you'll be hosting your front-end to your list of Allowed Origins.</li> </ol>
40,909,205
Java Gson Exclude fields during serialization
<p>I have a <code>ConfigInstance</code> class which contains a <code>password</code> and a <code>password_hash</code>. Now I want to serialize the object using gson but exclude the <code>password</code> field.</p> <pre><code>public class ConfigInstance { public String database_address; public int database_port; public String database_user; @Expose(serialize = false) private String database_pass; public String database_pass_hash; public String GetPass() { return database_pass; } public void Encrypt() { /* Creates the hash before serializing*/ } public void Decrypt() { /* Creates the password after deserializing */} } </code></pre> <p>As you can see, I have tried using <code>@Expose(serialize = false)</code> but it doesn't seem to do anything. Also I already set the field to private since I figured that this would "override" the <code>@Expose</code></p> <p>but running following code:</p> <pre><code>private void toFile(File file, ConfigInstance map) { map.Encrypt(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String jsonConfig = gson.toJson(map); FileWriter writer; try { writer = new FileWriter(file); writer.write(jsonConfig); writer.flush(); writer.close(); } catch (IOException e) { System.out.println("Error exporting config: " + e.toString()); } } </code></pre> <p>still results in the following file content without Errors:</p> <pre><code>{ "database_address": "127.0.0.1", "database_port": 1521, "database_user": "test", "database_pass": "test1234", "database_pass_hash": "B9FE2C011B59F0D0D383D70073E48A19" } </code></pre> <p>So what am I doing wrong? I am pretty clueless right now and would appreciate any help since <a href="http://www.javacreed.com/gson-annotations-example/" rel="noreferrer">THIS</a> doesn't seem to work.</p> <p>Thanks in advance.</p>
40,913,991
7
1
null
2016-12-01 11:13:27.103 UTC
2
2018-11-05 08:38:38.447 UTC
null
null
null
null
3,026,072
null
1
24
java|serialization|gson
41,127
<p>In order to get this result, you need to annotate all the fields with the <code>@Expose</code>:</p> <pre><code>public class ConfigInstance { @Expose public String database_address; @Expose public int database_port; @Expose public String database_user; @Expose(serialize = false) private String database_pass; @Expose public String database_pass_hash; </code></pre> <p>And configure Gson to only expose fields that are annotated and ignore the rest as shown in the following:</p> <pre><code>Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting().create(); </code></pre> <p>Then, you'll get:</p> <pre><code>{ "database_address": "127.0.0.1", "database_port": 1521, "database_user": "test", "database_pass_hash": "B9FE2C011B59F0D0D383D70073E48A19" } </code></pre> <p>Also, when deserialising the string you'll still have the password attribute as well.</p> <hr> <p>Still, you have the possibility to configure a <a href="http://www.javacreed.com/gson-serialiser-example/" rel="noreferrer">Gson Serializer</a> to accomplish this.</p>
18,562,752
Understanding IoC Containers and Dependency Injection
<p><strong>My understanding:</strong></p> <ul> <li>A dependency is when an instance of ClassA requires an instance of ClassB to instantiate a new instance of ClassA.</li> <li>A dependency injection is when ClassA is passed an instance of ClassB, either through a parameter in ClassA's constructor or through a set~DependencyNameHere~(~DependencyNameHere~ $param) function. <em>(This is one of the areas I'm not completely certain on)</em>. </li> <li>An IoC container is a singleton Class(can only have 1 instance instantiated at any given time) where the specific way of instantiating objects of those class for this project can be registered. <a href="https://gist.github.com/echochamber/021bb0d59f272ac0f421#file-registering-a-mysqli-object" rel="noreferrer">Here's a link to an example of what I'm trying to describe along with the class definition for the IoC container I've been using</a></li> </ul> <p>So at this point is where I start trying use the IoC container for more complicated scenarios. As of now it seems in order to use the IoC container, I am limited to a has-a relationship for pretty much any class I want to create that has dependencies it wants to define in the IoC container. What if I want to create a class that inherits a class, but only if the parent class has been created in a specific way it was registered in the IoC container. </p> <p>So for example: I want to create a child class of mysqli, but I want to register this class in the IoC container to only instantiate with the parent class constructed in a way I've previously registered in the IoC container. I cannot think of a way to do this without duplicating code (and since this is a learning project I'm trying to keep it as 'pure' as possible). <a href="https://gist.github.com/echochamber/021bb0d59f272ac0f421#file-inheritance-ioc" rel="noreferrer">Here are some more examples of what I am trying to describe.</a></p> <p><strong>So here are some of my questions:</strong></p> <ul> <li>Is what I'm trying to do above possible without breaking some principle of OOP? I know in c++ I could use dynamic memory and a copy constructor to accomplish it, but I haven't been able to find that sort of functionality in php. (I will admit that I have very little experience using any of the other magic methods besides __construct, but from reading and __clone if I understood correctly, I couldn't use in the constructor it to make the child class being instantiated a clone of an instance of the parent class).</li> <li>Where should all my dependency class definitions go in relation to the IoC? (Should my IoC.php just have a bunch of require_once('dependencyClassDefinition.php') at the top? My gut reaction is that there is a better way, but I haven't come up with one yet)</li> <li>What file should I be registering my objects in? Currently doing all the calls to IoC::register() in the IoC.php file after the class definition.</li> <li>Do I need to register a dependency in the IoC before I register a class that needs that dependency? Since I'm not invoking the anonymous function until I actually instantiate an object registered in the IoC, I'm guessing not, but its still a concern.</li> <li>Is there anything else I'm overlooking that I should be doing or using? I'm trying to take it one step at a time, but I also don't want to know that my code will be reusable and, most importantly, that somebody who knows nothing about my project can read it and understand it.</li> </ul>
18,564,335
1
0
null
2013-09-01 20:45:10.25 UTC
61
2019-09-24 19:02:38.823 UTC
2019-09-24 19:02:38.823 UTC
null
1,426,539
null
2,171,102
null
1
64
php|oop|inheritance|dependency-injection|inversion-of-control
26,331
<p>Put simply (because it's not a problem limited to OOP world only), a <strong>dependency</strong> is a situation where component A needs (depends on) component B to do the stuff it's supposed to do. The word is also used to describe the depended-on component in this scenario. To put this in OOP/PHP terms, consider the following example with the obligatory car analogy:</p> <pre><code>class Car { public function start() { $engine = new Engine(); $engine-&gt;vroom(); } } </code></pre> <p><code>Car</code> <em>depends</em> on <code>Engine</code>. <code>Engine</code> is <code>Car</code>'s <em>dependency</em>. This piece of code is pretty bad though, because:</p> <ul> <li>the dependency is implicit; you don't know it's there until you inspect the <code>Car</code>'s code</li> <li>the classes are tightly coupled; you can't substitute the <code>Engine</code> with <code>MockEngine</code> for testing purposes or <code>TurboEngine</code> that extends the original one without modifying the <code>Car</code>.</li> <li>It looks kind of silly for a car to be able to build an engine for itself, doesn't it?</li> </ul> <p><strong>Dependency injection</strong> is a way of solving all these problems by making the fact that <code>Car</code> needs <code>Engine</code> explicit and explicitly providing it with one:</p> <pre><code>class Car { protected $engine; public function __construct(Engine $engine) { $this-&gt;engine = $engine; } public function start() { $this-&gt;engine-&gt;vroom(); } } $engine = new SuperDuperTurboEnginePlus(); // a subclass of Engine $car = new Car($engine); </code></pre> <p>The above is an example of <strong>constructor injection</strong>, in which the dependency (the depended-on object) is provided to the dependent (consumer) through the class constructor. Another way would be exposing a <code>setEngine</code> method in the <code>Car</code> class and using it to inject an instance of <code>Engine</code>. This is known as <strong>setter injection</strong> and is useful mostly for dependencies that are supposed to be swapped at run-time.</p> <p>Any non-trivial project consists of a bunch of interdependent components and it gets easy to lose track on what gets injected where pretty quickly. A <strong>dependency injection container</strong> is an object that knows how to instantiate and configure other objects, knows what their relationship with other objects in the project are and does the dependency injection for you. This lets you centralize the management of all your project's (inter)dependencies and, more importantly, makes it possible to change/mock one or more of them without having to edit a bunch of places in your code.</p> <p>Let's ditch the car analogy and look at what OP's trying to achieve as an example. Let's say we have a <code>Database</code> object depending on <code>mysqli</code> object. Let's say we want to use a really primitive dependency indection container class <code>DIC</code> that exposes two methods: <code>register($name, $callback)</code> to register a way of creating an object under the given name and <code>resolve($name)</code> to get the object from that name. Our container setup would look something like this:</p> <pre><code>$dic = new DIC(); $dic-&gt;register('mysqli', function() { return new mysqli('somehost','username','password'); }); $dic-&gt;register('database', function() use($dic) { return new Database($dic-&gt;resolve('mysqli')); }); </code></pre> <p>Notice we're telling our container to grab an instance of <code>mysqli</code> <em>from itself</em> to assemble an instance of <code>Database</code>. Then to get a <code>Database</code> instance with its dependency automatically injected, we would simply:</p> <pre><code>$database = $dic-&gt;resolve('database'); </code></pre> <p>That's the gist of it. A somewhat more sophisticated but still relatively simple and easy to grasp PHP DI/IoC container is <a href="http://pimple.sensiolabs.org/" rel="noreferrer">Pimple</a>. Check its documentation for more examples.</p> <hr> <p><strong>Regarding OP's code and questions:</strong></p> <ul> <li>Don't use static class or a singleton for your container (or for anything else for that matter); <a href="http://www.youtube.com/watch?v=-FRm3VPhseI" rel="noreferrer">they're both evil</a>. Check out Pimple instead.</li> <li>Decide whether you want your <code>mysqliWrapper</code> class <em>extend</em> <code>mysql</code> or <em>depend</em> on it.</li> <li>By calling <code>IoC</code> from within <code>mysqliWrapper</code> you're swapping one dependency for another. Your objects shouldn't be aware of or use the container; otherwise it's not DIC anymore it's Service Locator (anti)pattern.</li> <li>You don't need to <code>require</code> a class file before registering it in the container since you don't know if you're going to use an object of that class at all. Do all your container setup in one place. If you don't use an autoloader, you can <code>require</code> inside the anonymous function you register with the container.</li> </ul> <hr> <p><strong>Additional resources:</strong></p> <ul> <li><a href="http://www.martinfowler.com/articles/injection.html" rel="noreferrer">Inversion of Control Containers and the Dependency Injection pattern</a> by Martin Fowler </li> <li><a href="http://www.youtube.com/watch?v=RlfLCWKxHJ0" rel="noreferrer">Don't look for things</a> -- a Clean Code Talk about IoC/DI</li> </ul>
28,355,079
How do Node.js Streams work?
<p>I have a question about Node.js streams - specifically how they work conceptually. </p> <p>There is no lack of documentation on how to use streams. But I've had difficulty finding how streams work at the data level. </p> <p>My limited understanding of web communication, HTTP, is that full "packages" of data are sent back and forth. Similar to an individual ordering a company's catalogue, a client sends a GET (catalogue) request to the server, and the server responds with the catalogue. The browser doesn't receive a page of the catalogue, but the whole book. </p> <p>Are node streams perhaps multipart messages? </p> <p>I like the REST model - especially that it is stateless. Every single interaction between the browser and server is completely self contained and sufficient. Are node streams therefore not RESTful? One developer mentioned the similarity with socket pipes, which keep the connection open. Back to my catalogue ordering example, would this be like an infomercial with the line "But wait! There's more!" instead of the fully contained catalogue?</p> <p>A large part of streams is the ability for the receiver 'down-stream' to send messages like 'pause' &amp; 'continue' upstream. What do these messages consist of? Are they POST?</p> <p>Finally, my limited visual understanding of how Node works includes this event loop. Functions can be placed on separate threads from the thread pool, and the event loop carries on. But shouldn't sending a stream of data keep the event loop occupied (i.e. stopped) until the stream is complete? How is it ALSO keeping watch for the 'pause' request from downstream?n Does the event loop place the stream on another thread from the pool and when it encounters a 'pause' request, retrieve the relevant thread and pause it?</p> <p>I've read the node.js docs, completed the nodeschool tutorials, built a heroku app, purchased TWO books (real, self contained, books, kinda like the catalogues spoken before and likely not like node streams), asked several "node" instructors at code bootcamps - all speak about how to use streams but none speak about what's actually happening below.</p> <p>Perhaps you have come across a good resource explaining how these work? Perhaps a good anthropomorphic analogy for a non CS mind?</p>
28,356,033
4
1
null
2015-02-05 22:13:42.623 UTC
15
2020-05-20 13:36:57.5 UTC
2015-02-05 23:31:00.973 UTC
null
782,822
null
2,942,295
null
1
24
node.js|http|stream
4,839
<p>The first thing to note is: node.js streams are not limited to HTTP requests. HTTP requests / Network resources are just one example of a stream in node.js.</p> <p>Streams are useful for everything that can be processed in small chunks. They allow you to process potentially huge resources in smaller chunks that fit into your RAM more easily.</p> <p>Say you have a file (several gigabytes in size) and want to convert all lowercase into uppercase characters and write the result to another file. The naive approach would read the whole file using <a href="http://nodejs.org/api/fs.html#fs_fs_readfile_filename_options_callback" rel="noreferrer"><code>fs.readFile</code></a> (error handling omitted for brevity):</p> <pre><code>fs.readFile('my_huge_file', function (err, data) { var convertedData = data.toString().toUpperCase(); fs.writeFile('my_converted_file', convertedData); }); </code></pre> <p>Unfortunately this approch will easily overwhelm your RAM as the whole file has to be stored before processing it. You would also waste precious time waiting for the file to be read. Wouldn't it make sense to process the file in smaller chunks? You could start processing as soon as you get the first bytes while waiting for the hard disk to provide the remaining data:</p> <pre><code>var readStream = fs.createReadStream('my_huge_file'); var writeStream = fs.createWriteStream('my_converted_file'); readStream.on('data', function (chunk) { var convertedChunk = chunk.toString().toUpperCase(); writeStream.write(convertedChunk); }); readStream.on('end', function () { writeStream.end(); }); </code></pre> <p>This approach is much better:</p> <ol> <li>You will only deal with small parts of data that will easily fit into your RAM.</li> <li>You start processing once the first byte arrived and don't waste time doing nothing, but waiting.</li> </ol> <p>Once you open the stream node.js will open the file and start reading from it. Once the operating system passes some bytes to the thread that's reading the file it will be passed along to your application. </p> <hr> <p>Coming back to the HTTP streams:</p> <ol> <li>The first issue is valid here as well. It is possible that an attacker sends you large amounts of data to overwhelm your RAM and take down (DoS) your service.</li> <li>However the second issue is even more important in this case: The network may be very slow (think smartphones) and it may take a long time until everything is sent by the client. By using a stream you can start processing the request and cut response times.</li> </ol> <hr> <p>On pausing the HTTP stream: This is not done at the HTTP level, but way lower. If you pause the stream node.js will simply stop reading from the underlying TCP socket. What is happening then is up to the kernel. It may still buffer the incoming data, so it's ready for you once you finished your current work. <a href="http://datacenteroverlords.com/2013/02/02/ethernet-congestion-drop-it-or-pause-it/" rel="noreferrer">It may also inform the sender at the TCP level that it should pause sending data</a>. Applications don't need to deal with that. That is none of their business. In fact the sender application probably does not even realize that you are no longer actively reading!</p> <p>So it's basically about being provided data as soon as it is available, but without overwhelming your resources. The underlying hard work is done either by the operating system (e.g. <code>net</code>, <code>fs</code>, <code>http</code>) or by the author of the stream you are using (e.g. <code>zlib</code> which is a <code>Transform</code> stream and usually bolted onto <code>fs</code> or <code>net</code>).</p>
1,503,582
Implementing Log file using Enterprise Library in asp.net
<p>I m using Microsoft Enterprise Library 3.1 for Exception Handling in asp.net, the erors are stored in <strong>Event Viewer</strong> of the system . </p> <p>Instead of Event Viewer I need to store these errors in a log File using Enterprise Library. </p>
1,518,972
3
0
null
2009-10-01 12:10:38.247 UTC
4
2016-03-08 14:04:42.73 UTC
2016-03-08 14:04:42.73 UTC
null
206,730
null
140,586
null
1
3
asp.net|enterprise-library
42,855
<p>Dear 2:30, You paste the following code inside configuration section at app.config or web.config file</p> <pre><code> &lt;configSections&gt; &lt;section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null" /&gt; &lt;section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null" /&gt; &lt;/configSections&gt; &lt;loggingConfiguration name="Logging Application Block" tracingEnabled="true" defaultCategory="Tracing" logWarningsWhenNoCategoriesMatch="true"&gt; &lt;listeners&gt; &lt;add fileName="AppLog.log" rollSizeKB="1024" timeStampPattern="yyyy-MM-dd" rollFileExistsBehavior="Increment" rollInterval="None" formatter="Text Formatter" header="" footer="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null" traceOutputOptions="LogicalOperationStack" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null" name="AppLog" /&gt; &lt;add fileName="Exception.log" rollSizeKB="1024" timeStampPattern="MM-dd-yyyy" rollFileExistsBehavior="Increment" rollInterval="None" formatter="Text Formatter" header="" footer="" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null" traceOutputOptions="Callstack" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null" name="Exception" /&gt; &lt;add fileName="trace.log" rollSizeKB="1024" timeStampPattern="yyyy-MM-dd" rollFileExistsBehavior="Increment" rollInterval="Month" formatter="Text Formatter" header="----------------------------------------" footer="----------------------------------------" listenerDataType="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.RollingFlatFileTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null" traceOutputOptions="None" type="Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.RollingFlatFileTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null" name="Trace" /&gt; &lt;/listeners&gt; &lt;formatters&gt; &lt;add template="{timestamp} : {message}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null" name="Text Formatter" /&gt; &lt;/formatters&gt; &lt;categorySources&gt; &lt;add switchValue="All" name="AppLog"&gt; &lt;listeners&gt; &lt;add name="AppLog" /&gt; &lt;/listeners&gt; &lt;/add&gt; &lt;add switchValue="Verbose" name="ExceptionHandling"&gt; &lt;listeners&gt; &lt;add name="Exception" /&gt; &lt;/listeners&gt; &lt;/add&gt; &lt;add switchValue="Information" name="Tracing"&gt; &lt;listeners&gt; &lt;add name="Trace" /&gt; &lt;/listeners&gt; &lt;/add&gt; &lt;/categorySources&gt; &lt;specialSources&gt; &lt;allEvents switchValue="All" name="All Events" /&gt; &lt;notProcessed switchValue="All" name="Unprocessed Category" /&gt; &lt;errors switchValue="Off" name="Logging Errors &amp;amp; Warnings" /&gt; &lt;/specialSources&gt; &lt;/loggingConfiguration&gt; </code></pre> <p>Application log can be logged into applog.log file using following statement</p> <pre><code>Logger.Write("Application Started", "AppLog"); </code></pre> <p>Application exception can be logged into Exception.log file using following statement</p> <pre><code>Logger.Write("Error: Invalid information you passed", "ExceptionHandling"); </code></pre> <p>Note: You can find the Logger class in Microsoft.Practices.EnterpriseLibrary.Logging;</p> <p>AppLog.log and Exception.log file will be created in bin folder automatically.</p>
1,537,273
window.href for all browser
<p>How can i replace <code>window.href = "someurlhtml"</code> for firefox and IE support ?</p>
1,537,279
3
0
null
2009-10-08 11:36:41.543 UTC
5
2011-12-06 06:07:01.347 UTC
2011-12-06 06:06:37.927 UTC
null
738,746
null
40,521
null
1
21
javascript|cross-browser
40,853
<pre><code>window.location.href = "someurl"; </code></pre>
8,917,977
Installing lapack for numpy
<p>Running Ubuntu 11.10 + python2.7...built numpy from source and installed it, but when I go to install it, I get </p> <pre><code>ImportError: /usr/lib/liblapack.so.3gf: undefined symbol: ATL_chemv </code></pre> <p>when it tries to import lapack_lite from numpy.linalg. I tried to rebuild lapack from scratch, but it seems to just make </p> <pre><code>/usr/local/lib/libblas.a /usr/local/lib/liblapack.a /usr/local/lib/libtmglib.a </code></pre> <p>and the .so file. Where does the .so.3gf come from, and how do I fix it?</p>
9,713,071
4
1
null
2012-01-18 21:50:16.297 UTC
7
2016-01-22 21:49:23.893 UTC
2013-05-12 21:21:34.647 UTC
null
832,621
null
907,773
null
1
30
python|numpy|installation|lapack
28,872
<p>I was having the same problem and removing the package libopenblas-base did the trick:</p> <pre><code>sudo apt-get remove libopenblas-base </code></pre> <p>As already explained by others, several packages provide incompatible versions of liblapack.so.3gf.</p>
8,503,327
Difference between java.exe, javaw.exe and jvm.dll
<p>What is the difference in running an application (for example, Eclipse) with java.exe, javaw.exe and jvm.dll? Also, does it make any difference in terms of performance?</p>
8,503,524
2
1
null
2011-12-14 10:57:03.327 UTC
8
2015-05-23 18:48:34.43 UTC
2015-05-23 18:48:34.43 UTC
null
814,702
null
913,369
null
1
32
java|jvm
15,492
<ul> <li><p><code>jvm.dll</code> is the actual Windows implementation of the JVM (or better, the main entry point). C or C++ applications can use this DLL to run an embedded Java runtime, and that would allow the application to interface directly with the JVM, e.g. if they want to use Java for its GUI.</p></li> <li><p><code>java.exe</code> is a wrapper around the DLL so that people can actually run Java classes without the need for a custom launcher application. It is a Win32 Console application, so Windows will open a fresh Command Prompt window if the exe is not run from a batch file.</p></li> <li><p><code>javaw.exe</code> is a wrapper like <code>java.exe</code>, but it is a Win32 GUI application. Windows doesn't have to open a Command Prompt window, which is exactly what you want to run a GUI application which opens its own windows.</p></li> </ul> <p>EDIT: These shouldn't make any difference in performance except for the overhead of process creation and initialization.</p> <p>The most important thing: it should't matter; if you are worrying about this you might actually want to keep Java running instead of launching it hundreds of times.</p>
8,732,307
Does XAML have a conditional compiler directive for debug mode?
<p>I need something like this for styles in XAML :</p> <pre><code>&lt;Application.Resources&gt; #if DEBUG &lt;Style TargetType="{x:Type ToolTip}"&gt; &lt;Setter Property="FontFamily" Value="Arial"/&gt; &lt;Setter Property="FlowDirection" Value="LeftToRight"/&gt; &lt;/Style&gt; #else &lt;Style TargetType="{x:Type ToolTip}"&gt; &lt;Setter Property="FontFamily" Value="Tahoma"/&gt; &lt;Setter Property="FlowDirection" Value="RightToLeft"/&gt; &lt;/Style&gt; #endif &lt;/Application.Resources&gt; </code></pre>
19,940,157
5
1
null
2012-01-04 18:54:45.257 UTC
38
2021-10-14 22:00:03.453 UTC
2018-04-04 12:51:50.377 UTC
null
4,390,133
null
404,339
null
1
86
c#|wpf|xaml
29,178
<p>I recently had to do this and was suprised at how simple it was when I couldn't easily find any clear examples. What I did was add the following to AssemblyInfo.cs:</p> <pre><code>#if DEBUG [assembly: XmlnsDefinition( "debug-mode", "Namespace" )] #endif </code></pre> <p>Then, use the markup-compatability namespace's AlternateContent tag to choose your content based on the presense of that namespace definition:</p> <pre><code>&lt;Window x:Class="Namespace.Class" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="debug-mode" Width="400" Height="400"&gt; ... &lt;mc:AlternateContent&gt; &lt;mc:Choice Requires="d"&gt; &lt;Style TargetType="{x:Type ToolTip}"&gt; &lt;Setter Property="FontFamily" Value="Arial"/&gt; &lt;Setter Property="FlowDirection" Value="LeftToRight"/&gt; &lt;/Style&gt; &lt;/mc:Choice&gt; &lt;mc:Fallback&gt; &lt;Style TargetType="{x:Type ToolTip}"&gt; &lt;Setter Property="FontFamily" Value="Tahoma"/&gt; &lt;Setter Property="FlowDirection" Value="RightToLeft"/&gt; &lt;/Style&gt; &lt;/mc:Fallback&gt; &lt;/mc:AlternateContent&gt; ... &lt;/Window&gt; </code></pre> <p>Now, when DEBUG is defined, "debug-mode" will also be defined, and the "d" namespace will be present. This makes the AlternateContent tag choose the first block of code. If DEBUG is not defined, the Fallback block of code will be used.</p> <p>This sample code was not tested, but it's basically the same thing that I'm using in my current project to conditionally show some debug buttons.</p> <p>I did see a blog post with some example code that relied on the "Ignorable" tag, but that seemed a lot less clear and easy to use as this method.</p>
27,138,483
How can I re-use/import script code in PowerShell scripts?
<p>I have to create a PowerShell script which does exactly same thing as my <a href="https://stackoverflow.com/questions/26706941/convert-xml-to-specific-json-structure-with-powershell/26707226#26707226">previous script</a>, but this time I have to read a CSV file instead of an XML file. My plan is to create a PowerShell script which has common functions required for both scripts and re-use this common script file in both main files.</p> <p>Suppose I create 2 main files in 2 directories in <code>C:\</code> drive and keep my common file and other 3<sup>rd</sup> party libraries in a folder of <code>D:\</code> drive, e.g. <code>C:\script_1_folder\Script1.ps1</code>, <code>C:\script_2_folder\Script2.ps1</code> and common file and 3<sup>rd</sup> party libraries will be in <code>D:\script_common</code>.</p> <ol> <li><p>How do I call\re-use common file in my main files (how to get the path, do I have to create an instance of common file and how do I use it)</p> <p>What is the difference between </p> <pre><code>$script_path = $myinvocation.invocationname; $script_folder = split-path $script_path -parent; write-host $script_folder $script_name = split-path $script_path -leaf; $current_folder = [system.io.directory]::getcurrentdirectory() [system.io.directory]::setcurrentdirectory($script_folder) Set-Location $script_folder add-type -path ".\AlexFTPS-1.1.0\AlexPilotti.FTPS.Client.dll" </code></pre> <p>and </p> <pre><code>$path = (split-path $MyInvocation.MyCommand.Path) $loggerPath = $path + "\Logger\release\Logger.ps1"; .$loggerPath; $logger = Logger; $logger.load($path + "\Logger\config\log4ps.xml","log.log"); </code></pre> <p>and what is the best way to do it with regard to my problem?</p></li> <li><p>How do I create a temp folder in windows temp folder?</p></li> </ol>
27,138,623
3
2
null
2014-11-25 23:07:18.15 UTC
18
2018-01-24 12:37:00.793 UTC
2017-05-23 12:34:50.397 UTC
null
-1
null
936,329
null
1
84
powershell
104,885
<h1>Common Code In Powershell</h1> <p>You can just put the code you want to include in a different PS1 file, and then "dot source" that file to include it in the current scope:</p> <pre class="lang-powershell prettyprint-override"><code>. D:\script_common\MyCode.ps1 </code></pre> <p>That's all there is to that.</p> <h2>Using a Module</h2> <p>You might consider using a module instead, which can be included using the <code>Import-Module</code> cmdlet. You might have used this to work with things like Active Directory, where you could do something like this:</p> <pre class="lang-powershell prettyprint-override"><code>Import-Module ActiveDirectory </code></pre> <p>In that case, you only need the name of the module because it's in a special directory.</p> <p>To write your own modules in Powershell, you name the module with a <code>.psm1</code> extension. Typically, you don't do free floating code in one of these; you write functions which are then available to the code which imports the module.</p> <p>To import a script module from anywhere, use the full path:</p> <pre class="lang-powershell prettyprint-override"><code>Import-Module D:\script_common\MyModule.psm1 </code></pre> <h2>Module Paths</h2> <p>When you create your own modules, you can keep them any old place and then refer to them by their full path (as above). There are also several <a href="http://msdn.microsoft.com/en-us/library/dd878350(v=vs.85).aspx" rel="noreferrer">locations that Powershell looks for modules</a>:</p> <ul> <li><code>$PSHome\Modules</code> (%Windir%\System32\WindowsPowerShell\v1.0\Modules) -- <strong>Reserved for modules that ship with Windows. Do not put things here.</strong></li> <li><code>$Home\Documents\WindowsPowerShell\Modules</code> (%UserProfile%\Documents\WindowsPowerShell\Modules) </li> <li>%ProgramFiles%\WindowsPowerShell\Modules -- this isn't mentioned in the link, and seems to be used more for Desired State Configuration modules (probably because it applies to the entire system).</li> </ul> <p>These are defaults, but Powershell uses its own environment variable called <code>PSModulePath</code> to determine where to look, and much like <code>PATH</code> you can add your own folder(s) to that variable.</p> <p>That lets you keep your modules in your own location. Do see the link for more info on how to structure your folders and how to do naming.</p> <p>So as far as keeping your modules and "3rd party" modules in the same place, that depends on the 3rd party stuff. It may install its own modules in its own place and modify the path, or it may just let you put them wherever you want.</p> <h1>Creating a Temp Folder</h1> <p>You can use the <code>TEMP</code> or <code>TMP</code> environment variables to get the path of the temp folder. To retrieve them in Powershell, use <code>$env:TEMP</code> or <code>$env:TMP</code>.</p> <p>You'll have to come up with a unique name of a folder to create in there. One way to do that might be to use a GUID:</p> <pre class="lang-powershell prettyprint-override"><code>$dirName = [System.Guid]::NewGuid().ToString() New-Item -Path "$($env:TEMP)\$dirName" </code></pre>
19,444,414
How to set the dynamic controller for directives?
<p>Talk is cheap, show my codes first:</p> <p>HTML:</p> <pre><code>&lt;div add-icons="IconsCtrl"&gt; &lt;/div&gt; </code></pre> <p>directive:</p> <pre><code>angular.module('attrDirective',[]).directive('addIcons', function($compile){ return { restrict : 'A', controller : "IconsCtrl" }, link : function (scope, elem , attrs, ctrl) { var parentElem = $(elem); var icons = $compile("&lt;i class='icon-plus' ng-click='add()'&gt;&lt;/i&gt;)(scope); parentElem.find(".accordion-heading").append(icons); }, } </code></pre> <p>});</p> <p>controller:</p> <pre><code>function IconsCtrl($scope){ $scope.add = function(){ console.log("add"); }; } </code></pre> <p>now it works, when i click the plus icon, browser console output "add".</p> <p>but i want to set the controller into the directive dynamically,like this:</p> <p>HTML:</p> <pre><code>&lt;div add-icons="IconsOneCtrl"&gt; &lt;/div&gt; &lt;div add-icons="IconsTwoCtrl"&gt; &lt;/div&gt; </code></pre> <p>Controller:</p> <pre><code>function IconsOneCtrl($scope){ $scope.add = function(){ console.log("IconsOne add"); }; } function IconsTwoCtrl($scope){ $scope.add = function(){ console.log("IconsTwo add"); } } </code></pre> <p>directive likes :</p> <pre><code>angular.module('attrDirective',[]).directive('addIcons', function($compile){ return { restrict : 'A', controller : dynamic set,depends on attrs.addIcons }, link : function (scope, elem , attrs, ctrl) { var parentElem = $(elem); var icons = $compile("&lt;i class='icon-plus' ng-click='add()'&gt;&lt;/i&gt;)(scope); parentElem.find(".accordion-heading").append(icons); }, } }); </code></pre> <p>how to achieve my goal? thanks for your answer!</p>
23,647,720
3
1
null
2013-10-18 07:54:33.883 UTC
8
2016-10-26 06:16:50.897 UTC
2014-05-14 07:17:23.39 UTC
null
1,900,149
null
2,587,703
null
1
31
angularjs|angularjs-directive
24,617
<p>Now it is possible with AngularJS. In directive you just add two new property called <code>controller</code> , <code>name</code> property and also <code>isolate scope</code> is exactly needed here.</p> <p>Important to note in directive</p> <pre><code>scope:{}, //isolate scope controller : "@", // @ symbol name:"controllerName", // controller names property points to controller. </code></pre> <p><a href="http://jsfiddle.net/p6Hb4/" rel="noreferrer">Working Demo for Setting Dynamic controller for Directives</a></p> <p>HTML Markup :</p> <pre><code>&lt;communicator controller-name="PhoneCtrl" &gt;&lt;/communicator&gt; &lt;communicator controller-name="LandlineCtrl" &gt;&lt;/communicator&gt; </code></pre> <p>Angular Controller and Directive :</p> <pre><code>var app = angular.module('myApp',[]). directive('communicator', function(){ return { restrict : 'E', scope:{}, controller : "@", name:"controllerName", template:"&lt;input type='text' ng-model='message'/&gt;&lt;input type='button' value='Send Message' ng-click='sendMsg()'&gt;&lt;br/&gt;" } }). controller("PhoneCtrl",function($scope){ $scope.sendMsg = function(){ alert( $scope.message + " : sending message via Phone Ctrl"); } }). controller("LandlineCtrl",function($scope){ $scope.sendMsg = function(){ alert( $scope.message + " : sending message via Land Line Ctrl "); } }) </code></pre> <p>Your case you can try this below code snippets.</p> <p><a href="http://jsfiddle.net/LqXrC/1/" rel="noreferrer">Working Demo</a></p> <p>HTML Markup :</p> <pre><code>&lt;div add-icons controller-name="IconsOneCtrl"&gt; &lt;/div&gt; &lt;div add-icons controller-name="IconsTwoCtrl"&gt; &lt;/div&gt; </code></pre> <p>Angular Code :</p> <pre><code>angular.module('myApp',[]). directive('addIcons', function(){ return { restrict : 'A', scope:{}, controller : "@", name:"controllerName", template:'&lt;input type="button" value="(+) plus" ng-click="add()"&gt;' } }). controller("IconsOneCtrl",function($scope){ $scope.add = function(){ alert("IconsOne add "); } }). controller("IconsTwoCtrl",function($scope){ $scope.add = function(){ alert("IconsTwo add "); } }); </code></pre>
19,612,459
MIPS - How does MIPS allocate memory for arrays in the stack?
<p>I'm quite new to the MIPS assembly language and am currently taking a class on computer architecture which has a large section on MIPS coding. I've studied several other high-level programming languages (C, C#, Python) in the past so have some bases in programming. </p> <p>My question here specifically asks: How does MIPS allocate memory for arrays in the stack? I'm hoping that answering this question will hopefully give me a better total understanding of MIPS as I'm still a bit lot on conceptualizing the idea of the MIPS language and it's architecture. I don't quite understand how pointers work in this whole regard either...</p> <p>Would be brilliant if someone could take the time to help out this confused student! :)</p>
19,612,647
3
1
null
2013-10-26 22:11:14.58 UTC
8
2021-03-28 08:43:07.283 UTC
null
null
null
null
2,923,915
null
1
15
assembly|malloc|mips|computer-architecture
40,149
<p>Well.. you should be aware that MIPS, like C, essentially has three different ways of allocating memory.</p> <p>Consider the following C code:</p> <pre><code>int arr[2]; //global variable, allocated in the data segment int main() { int arr2[2]; //local variable, allocated on the stack int *arr3 = malloc(sizeof(int) * 2); //local variable, allocated on the heap } </code></pre> <p>MIPS assembly supports all these types of data. </p> <p>To allocate an int array in the data segment you could use:</p> <pre><code>.data arr: .word 0, 0 #enough space for two words, initialized to 0, arr label points to the first element </code></pre> <p>To allocate an int array on the stack you could use:</p> <pre><code>#save $ra addi $sp $sp -4 #give 4 bytes to the stack to store the frame pointer sw $fp 0($sp) #store the old frame pointer move $fp $sp #exchange the frame and stack pointers addi $sp $sp -12 #allocate 12 more bytes of storage, 4 for $ra and 8 for our array sw $ra -4($fp) # at this point we have allocated space for our array at the address -8($fp) </code></pre> <p>To allocate space on the heap, a system call is required. In the spim simulator this is <a href="http://www.doc.ic.ac.uk/lab/secondyear/spim/node8.html">system call 9</a>:</p> <pre><code>li $a0 8 #enough space for two integers li $v0 9 #syscall 9 (sbrk) syscall # address of the allocated space is now in $v0 </code></pre>
984,878
What is the possible use for "#define for if (false) {} else for"?
<p>In another question, I just spotted this little pearl of <strong>C</strong> wisdom:</p> <pre><code>#define for if (false) {} else for </code></pre> <p>which caused MSVC to spit out "constant expression" warnings for a quite valid statement:</p> <pre><code>for (int i = 0; i &lt;= 10; i++) {...} </code></pre> <p>I understand <em>why</em> MSVC is complaining because it expands to:</p> <pre><code>if (false) {} else for (int i = 0; i &lt;= 10; i++) {...} </code></pre> <p>I just don't understand why the developers would use that little snippet. Anyone have an idea?</p>
985,036
4
0
null
2009-06-12 03:52:51.453 UTC
7
2015-11-27 11:22:44.763 UTC
2015-11-27 11:22:44.763 UTC
null
4,370,109
null
14,860
null
1
45
c|c-preprocessor
8,338
<p>It's to fix a bug in old versions of Visual C++ (v6.0 and earlier). In the past, Visual C++ had broken scope rules about variables declared inside <code>for</code> statements:</p> <pre><code>// This compiles in old versions of Visual C++, but it is in fact INVALID C++ for(int i = 0; ...) { ... } for(i = 0; ...) { } </code></pre> <p>In other words, Visual C++ gives <code>i</code> a scope as if it were declared outside the loop, and it lets you continue using it after the loop is done. This lead to code such as the above snippet. In more standards-compliant compilers, <code>i</code> is no longer in scope at the definition of the second <code>for</code> loop, so the compiler issues an error about <code>i</code> being undefined.</p> <p>To fix this, some people used this macro (or very similar, equivalent macros):</p> <pre><code>#define for if(0) {} else for </code></pre> <p>This changes the <code>for</code> loop into this:</p> <pre><code>if(0) { } else for(int i = 0; ...) { ... } </code></pre> <p>This puts the <code>for</code> loop into an extra level of scope, so that any variables declared in the <code>for</code> loop will be out of scope afterwards, regardless of Visual C++'s bug. This makes sure that the same code compiles correctly consistently in both Visual C++ and standards-compliant compilers, and that incorrect code does not compile correctly consistently.</p> <p>Also note that if the macro were instead defined as so:</p> <pre><code>// DO NOT USE #define for if(1) for </code></pre> <p>Then although that would have the same effect for some simple code, it would suddenly cause the following code to be compiled incorrectly:</p> <pre><code>if(foo) for(...) { ... } else doSomething(); </code></pre> <p>Because if you expand the macro, you get this:</p> <pre><code>if(foo) if(1) for(...) { ... } else doSomething(); </code></pre> <p>And the <code>else</code> now matches up with the wrong <code>if</code>! So, the clever use of using <code>if(0) {} else</code> instead of <code>if(1)</code> avoids this problem.</p> <p>As a final note, <code>#define for if(0) {} else for</code> does not cause infinite recursion, because the preprocessor will not recursively replace the macro which you are currently defining. It will only do one replacement in this case. </p>
23,808,216
T-SQL INSERT INTO with LEFT JOIN
<p>Sorry this is a syntax question, but in T-SQL how do I specify in INSERT statement in which DB I want to INSERT and in LEFT JOIN from which DB I want to join?</p> <pre><code>if not exists (select * from [DB_A].[dbo.a_test]) create table [DB_A].[dbo.a_test] ( a int(10) , b int(10) , c varchar(200) , d varchar(200) , e varchar(200) , PRIMARY KEY (a) ) INSERT INTO [DB_A].[dbo.a_test] (a,b,c, d) VALUES dbo.products.product_info, dbo.products.product_date, dbo.products.smth, *dbo.program.program_name*, dbo.program.program_smth FROM [DB_B].dbo.products LEFT JOIN [DB_B].dbo.program ON dbo.program.program_name = dbo.products.product_info </code></pre> <p>Sorry for such a noob question, but I could not find a suitable example.</p>
23,808,344
2
1
null
2014-05-22 13:25:46.067 UTC
5
2019-09-21 08:01:18.17 UTC
null
null
null
null
1,054,844
null
1
30
sql|sql-server|tsql
80,054
<p>You want <code>insert into . . . select</code>:</p> <pre><code>INSERT INTO [DB_A].[dbo.a_test](a,b,c,d,e) --ADDED A COLUMN select p.product_info, p.product_date, p.smth, pr.program_name, pr.program_smth FROM [DB_B].dbo.products p LEFT JOIN [DB_B].dbo.program pr ON p.program_name = pr.product_info; </code></pre> <p>I also fixed the query to use table aliases, so it is much easier to read.</p>
34,104,638
How can I chain HTTP calls in Angular 2?
<p>I'm new to Angular 2 and HTTP Observables. I have a component which calls an HTTP service and returns an Observable. Then I subscribe to that Observable and it works fine.</p> <p>Now, I want, in that component, after calling the first HTTP service, if the call was successful, to call another HTTP service and return that Observable. So, if the first call is not successful the component returns that Observable, opposite it returns Observable of the second call.</p> <p>What is the best way to chain HTTP calls? Is there an elegant way, for example like <a href="https://en.wikipedia.org/wiki/Monad_(functional_programming)" rel="noreferrer">monads</a>?</p>
34,107,312
2
0
null
2015-12-05 11:58:21.13 UTC
25
2021-09-09 19:29:07.303 UTC
2021-09-09 19:23:55.33 UTC
null
63,550
null
1,529,202
null
1
74
http|angular
56,747
<p>You can do this using the <code>mergeMap</code> operator.</p> <p><strong>Angular 4.3+ (using <code>HttpClientModule</code>) and RxJS 6+</strong></p> <pre class="lang-js prettyprint-override"><code>import { mergeMap } from 'rxjs/operators'; this.http.get('./customer.json').pipe( mergeMap(customer =&gt; this.http.get(customer.contractUrl)) ).subscribe(res =&gt; this.contract = res); </code></pre> <p><strong>Angular &lt; 4.3 (using <code>HttpModule</code>) and RxJS &lt; 5.5</strong></p> <p>Import the operators <code>map</code> and <code>mergeMap</code>, then you can chain two calls as follows:</p> <pre class="lang-js prettyprint-override"><code>import 'rxjs/add/operator/map'; import 'rxjs/add/operator/mergeMap'; this.http.get('./customer.json') .map((res: Response) =&gt; res.json()) .mergeMap(customer =&gt; this.http.get(customer.contractUrl)) .map((res: Response) =&gt; res.json()) .subscribe(res =&gt; this.contract = res); </code></pre> <p>Some more details here: <a href="http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http" rel="noreferrer">http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http</a></p> <p>More information about the mergeMap operator can be found <a href="https://www.learnrxjs.io/operators/transformation/mergemap.html" rel="noreferrer">here</a></p>
29,768,562
Obtain .NET PublicKeyToken from snk file?
<p>How to obtain the PublicKeyToken from an snk file? Using command line tools. I thought about using sn.exe, however, couldn't find a suiting parameter.</p>
29,768,613
4
0
null
2015-04-21 09:45:35.85 UTC
11
2021-09-03 19:00:46.257 UTC
null
null
null
null
1,400,869
null
1
26
.net
12,469
<p>If you want to use the <code>sn.exe</code> tool:</p> <pre><code>sn -p yourkey.snk publickey.snk </code></pre> <p>now there is the publickey.snk with only the public key</p> <pre><code>sn -tp publickey.snk </code></pre> <p>now you have both the public key and the public key token.</p> <hr> <p>Given a <code>byte[]</code> cotnaining the snk file, like</p> <pre><code>byte[] snk = File.ReadAllBytes("YourSnkFile.snk"); </code></pre> <p>use</p> <pre><code>byte[] publicKey = GetPublicKey(snk); byte[] publicKeyToken = GetPublicKeyToken(publicKey); </code></pre> <p>with these utility methods</p> <pre><code>public static byte[] GetPublicKey(byte[] snk) { var snkp = new StrongNameKeyPair(snk); byte[] publicKey = snkp.PublicKey; return publicKey; } public static byte[] GetPublicKeyToken(byte[] publicKey) { using (var csp = new SHA1CryptoServiceProvider()) { byte[] hash = csp.ComputeHash(publicKey); byte[] token = new byte[8]; for (int i = 0; i &lt; 8; i++) { token[i] = hash[hash.Length - i - 1]; } return token; } } </code></pre>
25,491,997
How to read multiple integer values from one line in Java using BufferedReader object?
<p>I am using BufferedReader class to read inputs in my Java program. I want to read inputs from a user who can enter multiple integer data in single line with space. I want to read all these data in an integer array.</p> <p>Input format- the user first enters how many numbers he/she want to enter</p> <p>And then multiple integer values in the next single line-</p> <p>INPUT:</p> <p>5</p> <p>2 456 43 21 12</p> <p>Now, I read input using an object (br) of BufferedReader</p> <pre><code>int numberOfInputs = Integer.parseInt(br.readLine()); </code></pre> <p>Next, I want to read next line inputs in an array</p> <pre><code>int a[] = new int[n]; </code></pre> <p>But we cannot read using this technique</p> <pre><code>for(int i=0;i&lt;n;i++) { a[i]=Integer.parseInt(br.readLine()); //won't work } </code></pre> <p>So, is there any solution to my problem or we can't just read multiple integers from one line using BufferedReader objects</p> <p>Because using Scanner object we can read this type of input</p> <pre><code>for(int i=0;i&lt;n;i++) { a[i]=in.nextInt(); //will work..... 'in' is object of Scanner class } </code></pre>
25,492,055
9
1
null
2014-08-25 18:16:36.947 UTC
7
2021-08-13 07:05:14.74 UTC
2018-11-09 07:07:45.537 UTC
null
4,826,457
null
3,976,183
null
1
6
java|arrays|integer|buffer|bufferedreader
66,509
<p>Try the next:</p> <pre><code>int a[] = new int[n]; String line = br.readLine(); // to read multiple integers line String[] strs = line.trim().split("\\s+"); for (int i = 0; i &lt; n; i++) { a[i] = Integer.parseInt(strs[i]); } </code></pre>
20,412,379
ViewPager update fragment on swipe
<p>i have a problem that i have been struggling with for the past 2 days. </p> <p>I am building an app that uses ActionBar, ViewPager &amp; FragmentPagerAdapter. The code for the Activity, Fragments &amp; FragmentPagerAdapter are exactly as the ones stated in the android example on <a href="http://developer.android.com/reference/android/support/v4/view/ViewPager.html">http://developer.android.com/reference/android/support/v4/view/ViewPager.html</a></p> <p>The problem i am facing is -- assuming i have only 2 fragments in the viewPager. when switching/swiping between the two, the fragments are not getting updated. onResume does not get called because the viewPager caches a minimum of 1 fragment to either side of the displayed fragment.</p> <p>I tried using the onTabSelected to detect when a fragment is selected and then start a method from that fragment with the help of an interface (code below).</p> <pre><code>public void onTabSelected(Tab tab, FragmentTransaction ft) { TabInfo tag = (TabInfo)tab.getTag(); for (int i=0; i&lt;mTabs.size(); i++) { if (mTabs.get(i) == tag) { mViewPager.setCurrentItem(i); } } ((IStartStop)getItem(tab.getPosition())).Start(); } </code></pre> <p>However, when the Start method is used a NullPointerException is fired when trying to update a textview. The start method's code is:</p> <pre><code>public void Start() { TextView tv = _view.findViewById(R.id.text); tv.setText("test"); } </code></pre> <p>The exception is thrown at line:</p> <pre><code>TextView tv = _view.findViewById(R.id.text); </code></pre> <p>The IStartStop interface is quite simple:</p> <pre><code>public interface IStartStop { public void Start(); public void Stop(); } </code></pre> <p>I don't want to use notifyDataSetChanged(); with POSITION_NONE because every time I swipe to a new fragment, it takes a few seconds to load the fragments</p> <p>At this time, the fragments only include a textview, in the future they will have an animation and so it is important to:</p> <p>1- Only run an animation when the fragment is selected and not when the fragment next to it is selected (the way ViewPager caches and resumes fragments).</p> <p>2- Stop the animation when the fragment is no longer selected to avoid wasting device resources.</p> <p>Yes, i already checked everything available on the internet but nothing seems to work with me.</p> <p>Thank you very much for your help!</p>
20,412,875
4
1
null
2013-12-05 22:46:41.69 UTC
18
2016-10-21 14:26:18.323 UTC
2013-12-05 22:52:00.833 UTC
null
3,072,237
null
3,072,237
null
1
29
android|exception|android-viewpager|refresh|fragment
38,523
<p>Surprisingly the <code>ViewPager</code> doesn't do this "natively" (among other things). But not all is lost.</p> <p>First you have to modify your fragments so they only run the animation when you tell them that it's ok and not when they are instantiated. This way you can play with the viewpager offset (default = 3) and have 2-3 fragments preloaded but not animated.</p> <p>Second step is to create an interface or similar that defines when the "fragment has become visible".</p> <p>Third step would be to attach a new OnPageScrollListener to your viewpager.</p> <p>Code follows (in semi-untested-code):</p> <p>1) Attach the Listener:</p> <pre><code>mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(final int i, final float v, final int i2) { } @Override public void onPageSelected(final int i) { YourFragmentInterface fragment = (YourFragmentInterface) mPagerAdapter.instantiateItem(mViewPager, i); if (fragment != null) { fragment.fragmentBecameVisible(); } } @Override public void onPageScrollStateChanged(final int i) { } }); </code></pre> <p>2) This is your Interface:</p> <pre><code>public interface YourFragmentInterface { void fragmentBecameVisible(); } </code></pre> <p>3) Change your fragments so they implement this:</p> <pre><code>public class YourLovelyFragment extends Fragment implements YourFragmentInterface { </code></pre> <p>4) Implement the interface in the fragment</p> <pre><code>@Override public void fragmentBecameVisible() { // You can do your animation here because we are visible! (make sure onViewCreated has been called too and the Layout has been laid. Source for another question but you get the idea. } </code></pre> <p><strong>Where to go from here?</strong></p> <p>You might want to implement a method/listener to notify the "other" fragments that they are no longer visible (i.e. when one is visible, the others are not). But that may not be needed.</p>
51,732,435
is there a yarn alternative for npm audit?
<p>need pinned resolution feature of yarn, but also want to audit with <code>npm audit</code>? Is there a yarn alternative to <code>npm audit</code>? Or, alternately, will pinning resolutions of dependencies of dependencies work in <code>npm</code>?</p>
52,697,488
10
3
null
2018-08-07 17:33:33.93 UTC
29
2022-07-10 19:08:55.033 UTC
2018-08-09 08:21:58.553 UTC
null
6,250,402
null
1,549,306
null
1
97
security|npm|dependencies|yarnpkg|audit
56,837
<p><code>yarn audit</code> / <code>yarn install --audit</code> has been available since [email protected]</p> <p><a href="https://github.com/yarnpkg/yarn/releases/tag/v1.12.0" rel="noreferrer">https://github.com/yarnpkg/yarn/releases/tag/v1.12.0</a></p> <p>Unfortunately no <code>--fix</code> option yet, but as workaround you can use <a href="https://www.npmjs.com/package/yarn-audit-fix" rel="noreferrer">https://www.npmjs.com/package/yarn-audit-fix</a></p>
29,759,978
Laravel Model->save() returns false but no error
<p>Normally when I call <code>Model-&gt;save()</code>, it creates the new record in the database successfully. I'm trying to debug a situation when nothing happens and <code>Model-&gt;save()</code> returns false. How do I find out what's happening?</p> <pre><code>$user = new User; $user-&gt;fields = 'example'; $user-&gt;save(); // returns false </code></pre> <p>Running this does not show any insert queries.</p> <pre><code>dd(DB::getQueryLog()); </code></pre> <p>But if I <code>var_dump($user)</code>, I correctly get all the fields properly saved in the object.</p> <p>Thanks!</p>
29,761,882
2
2
null
2015-04-20 23:06:01.95 UTC
7
2022-07-11 02:21:19.583 UTC
null
null
null
null
243,055
null
1
38
php|laravel|laravel-4
68,430
<p>To get the insert queries when <code>$user-&gt;save();</code> error, you can try to catch the exception like this:</p> <pre><code> try{ $user = new User; $user-&gt;fields = 'example'; $user-&gt;save(); // returns false } catch(\Exception $e){ // do task when error echo $e-&gt;getMessage(); // insert query } </code></pre> <p>Hope this helps :)</p>
32,363,998
Function to calculate geospatial distance between two points (lat,long) using R
<p>I have geocoded points in long, lat format, and I want to calculate the distance between them using R. This seems pretty straight forward, yet I can't find a function that will do it easily. I've been attempting to do it with the gdistance package, but it seems very convoluted and oriented to graphing, I just need a number. Something like <code>distanceBetween(pointA,pointB)</code> that returns a number. </p>
32,364,246
2
3
null
2015-09-02 22:11:35.147 UTC
25
2020-02-11 05:58:08.41 UTC
2020-02-11 05:58:08.41 UTC
null
2,204,410
null
852,561
null
1
74
r|package|geospatial|distance|latitude-longitude
127,107
<p>Loading the geosphere package you can use a number of different functions</p> <pre><code>library(geosphere) distm(c(lon1, lat1), c(lon2, lat2), fun = distHaversine) </code></pre> <p>Also:</p> <pre><code>distHaversine() distMeeus() distRhumb() distVincentyEllipsoid() distVincentySphere() </code></pre> <p>...</p>
4,614,608
Execute commands with notepad++
<p>How can I specify the actual file to process using the Run command in Notepad++. I want for example run pdflatex using the actualfile as input, or the cs compiler, etc. Using the entire path isn't practical, it must works with any actual file.</p>
4,614,903
1
1
null
2011-01-06 11:52:19.847 UTC
13
2022-03-17 08:01:39.183 UTC
2014-05-01 10:26:09.32 UTC
null
1,122,645
null
1,169,720
null
1
38
command|notepad++
52,603
<p>You can automatically add the current file using a variable in the execution string:</p> <pre><code>C:\temp\test.exe &quot;$(FULL_CURRENT_PATH)&quot; </code></pre> <p>The list of available variables is documented <a href="https://npp-user-manual.org/docs/config-files/#userdefinedcommands" rel="nofollow noreferrer">here</a>. Examples:</p> <ul> <li>FULL_CURRENT_PATH = <code>E:\My Web\main\welcome.html</code></li> <li>CURRENT_DIRECTORY = <code>E:\My Web\main</code></li> <li>FILE_NAME = <code>welcome.html</code></li> <li>NAME_PART = <code>welcome</code></li> <li>EXT_PART = <code>.html</code></li> <li>SYS.<code>&lt;var&gt;</code> e.g.: SYS.PATH = <code>%PATH%</code></li> <li>CURRENT_WORD = <code>&lt;selection or word under cursor&gt;</code></li> <li>CURRENT_LINE = <code>&lt;line number&gt;</code></li> <li>CURRENT_COLUMN = <code>&lt;column number&gt;</code></li> <li>NPP_DIRECTORY = <code>c:\Program Files\notepad++</code></li> <li>NPP_FULL_FILE_PATH = <code>c:\Program Files\notepad++\notepad++.exe</code></li> </ul> <p>You can also see the source code at RunDlg.cpp <a href="https://github.com/notepad-plus-plus/notepad-plus-plus/blob/06db9ee338ac9659b01b960325486a1791b249b0/PowerEditor/src/WinControls/StaticDialog/RunDlg/RunDlg.cpp#L77" rel="nofollow noreferrer">line 77</a> and <a href="https://github.com/notepad-plus-plus/notepad-plus-plus/blob/93a9962fdea155552fc9f08d09b729ecf7d9073a/PowerEditor/src/WinControls/StaticDialog/RunDlg/RunDlg.h#L26" rel="nofollow noreferrer">line 26</a></p>
34,587,254
Accessing multiple controllers with same request mapping
<p>Please find my HomeController and DemoController</p> <pre><code>class HomeController{ @RequestMapping(value="index") public void home(){ } } class DemoController{ @RequestMapping(value="index") public void demo(){ } } </code></pre> <p>when I try to send a request to index, which one will get executed? I wanted to know how can we have same request mapping value for multiple controllers</p>
34,590,355
3
4
null
2016-01-04 08:34:10.407 UTC
4
2017-07-14 15:56:25.733 UTC
null
null
null
null
5,557,745
null
1
19
spring|spring-mvc
42,651
<p>In <a href="http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html" rel="noreferrer">Spring Web MVC</a> this is not possible. Each mapping must be unique in your context. If not, you will receive a <code>RuntimeException</code> during context initialization.</p> <p>You cannot even use parameters to differentiate your endpoints because they are not evaluated while searching for a suitable handler (applicable for Servlet environments). From <a href="https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html" rel="noreferrer"><code>@RequestMapping</code></a> javadoc:</p> <blockquote> <p>In a Servlet environment, parameter mappings are considered as restrictions that are enforced at the type level. The primary path mapping (i.e. the specified URI value) still has to uniquely identify the target handler, with parameter mappings simply expressing preconditions for invoking the handler.</p> </blockquote> <p>Note that you can do the opposite, so multiple URLs can point to the same handler. Have a look at <a href="https://stackoverflow.com/questions/3898442/spring-mvc-mapping-multiple-urls-to-same-controller">Spring MVC: Mapping Multiple URLs to Same Controller</a></p>
25,153,342
Open a workbook using FileDialog and manipulate it in Excel VBA
<p>I am learning how to use Excel macros and I found this code:</p> <pre><code>Dim fd As Office.FileDialog Set fd = Application.FileDialog(msoFileDialogFilePicker) With fd .AllowMultiSelect = False .Title = "Please select the file to kill his non colored cells" .Filters.Add "Excel", "*.xls" .Filters.Add "All", "*.*" If .Show = True Then txtFileName = .SelectedItems(1) End If End With </code></pre> <p>This code opens the FileDialog. How can I open the selected Excel file without over-writing the previously opened?</p>
25,176,411
2
2
null
2014-08-06 06:11:00.107 UTC
4
2017-02-27 21:59:05.703 UTC
2016-04-08 14:39:19.13 UTC
null
594,137
null
3,576,866
null
1
13
vba|excel|openfiledialog
129,452
<p>Thankyou Frank.i got the idea. Here is the working code.</p> <pre><code>Option Explicit Private Sub CommandButton1_Click() Dim directory As String, fileName As String, sheet As Worksheet, total As Integer Dim fd As Office.FileDialog Set fd = Application.FileDialog(msoFileDialogFilePicker) With fd .AllowMultiSelect = False .Title = "Please select the file." .Filters.Clear .Filters.Add "Excel 2003", "*.xls?" If .Show = True Then fileName = Dir(.SelectedItems(1)) End If End With Application.ScreenUpdating = False Application.DisplayAlerts = False Workbooks.Open (fileName) For Each sheet In Workbooks(fileName).Worksheets total = Workbooks("import-sheets.xlsm").Worksheets.Count Workbooks(fileName).Worksheets(sheet.Name).Copy _ after:=Workbooks("import-sheets.xlsm").Worksheets(total) Next sheet Workbooks(fileName).Close Application.ScreenUpdating = True Application.DisplayAlerts = True End Sub </code></pre>
39,732,481
How to split a string from the first space occurrence only Java
<p>I tried to split a string using string.Index and string.length but I get an error that string is out of range. How can I fix that?</p> <pre><code>while (in.hasNextLine()) { String temp = in.nextLine().replaceAll("[&lt;&gt;]", ""); temp.trim(); String nickname = temp.substring(temp.indexOf(' ')); String content = temp.substring(' ' + temp.length()-1); System.out.println(content); </code></pre>
39,732,527
4
2
null
2016-09-27 19:05:38.83 UTC
2
2020-01-29 13:48:04.417 UTC
2019-01-30 03:50:21.603 UTC
null
1,033,581
null
5,656,041
null
1
24
java|string
49,297
<p>Must be some around this: </p> <pre><code>String nickname = temp.substring(0, temp.indexOf(' ')); String content = temp.substring(temp.indexOf(' ') + 1); </code></pre>
31,551,888
Casting int to bool in C/C++
<p>I know that in C and C++, when casting bools to ints, <code>(int)true == 1</code> and <code>(int)false == 0</code>. I'm wondering about casting in the reverse direction...</p> <p>In the code below, all of the following assertions held true for me in .c files compiled with Visual Studio 2013 and Keil µVision 5. Notice <code>(bool)2 == true</code>.</p> <p>What do the C and C++ standards say about casting non-zero, non-one integers to bools? Is this behavior specified? Please include citations.</p> <pre><code>#include &lt;stdbool.h&gt; #include &lt;assert.h&gt; void TestBoolCast(void) { int i0 = 0, i1 = 1, i2 = 2; assert((bool)i0 == false); assert((bool)i1 == true); assert((bool)i2 == true); assert(!!i0 == false); assert(!!i1 == true); assert(!!i2 == true); } </code></pre> <p><strong>Not</strong> a duplicate of <a href="https://stackoverflow.com/questions/2725044">Can I assume (bool)true == (int)1 for any C++ compiler?</a>:</p> <ol> <li>Casting in the reverse direction (int --> bool).</li> <li>No discussion there of non-zero, non-one values.</li> </ol>
31,551,979
3
11
null
2015-07-22 00:27:29.19 UTC
7
2020-07-22 06:53:39.397 UTC
2017-05-23 12:10:01.113 UTC
null
-1
null
1,995,714
null
1
43
c++|c|casting|boolean
143,392
<p>0 values of basic types <sup>(1)(2)</sup>map to <code>false</code>.</p> <p>Other values map to <code>true</code>.</p> <p>This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.</p> <hr> <p>It's a common error to assume that as function return values, <code>false</code> indicates failure. But in particular from <code>main</code> it's <code>false</code> that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang <em>easy</em> to get wrong), hence this heads-up beware beware.</p> <hr> <p>There's no need to cast to <code>bool</code> for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. <code>return !!x</code>, works nicely. One can read <code>!!</code> as a &ldquo;convert to <code>bool</code>&rdquo; operator, much as <code>--&gt;</code> can be read as &ldquo;goes to&rdquo;. For those who are deeply into readability of operator notation. ;-)</p> <hr> <p><sup> <sup>1)</sup> C++14 §4.12/1 &ldquo;A zero value, null pointer value, or null member pointer value is converted to <code>false</code>; any other value is converted to <code>true</code>. For direct-initialization (8.5), a prvalue of type <code>std::nullptr_t</code> can be converted to a prvalue of type <code>bool</code>; the resulting value is <code>false</code>.&rdquo;<br> <sup>2)</sup> C99 and C11 §6.3.1.2/1 &ldquo;When any scalar value is converted to <code>_Bool</code>, the result is 0 if the value compares equal to 0; otherwise, the result is 1.&rdquo; </sup></p>
31,527,969
How to I update my C++ project in Visual Studio 2015 to use the new Universal CRT?
<p>After VS2015 updated my project to the new Platform toolset v140, it fails to build due to a linker error : LNK1104 cannot open file 'libucrt.lib'. </p> <p>It appears this library has been moved around due to the new Universal CRT as mentioned in this article : <a href="http://blogs.msdn.com/b/vcblog/archive/2015/03/03/introducing-the-universal-crt.aspx?PageIndex=2">http://blogs.msdn.com/b/vcblog/archive/2015/03/03/introducing-the-universal-crt.aspx?PageIndex=2</a>.</p> <p>While the article does tell me what I should link towards now, it does not provide instructions how. </p> <p>My Solution generates a .exe and a .dll it uses. I do not know what to do with the matrix the article describes below.</p> <p>Release DLLs (/MD ): msvcrt.lib vcruntime.lib ucrt.lib</p> <p>Release Static (/MT ): libcmt.lib libvcruntime.lib libucrt.lib</p>
31,529,033
4
13
null
2015-07-20 23:26:43.34 UTC
8
2016-10-12 12:39:15.733 UTC
2015-07-21 01:37:21.717 UTC
null
1,707,286
null
1,707,286
null
1
15
c++|visual-studio-2015|crt
18,677
<p>When you convert your project, you need to make sure you update both the includes AND the linker settings to point to the new CRT.</p> <p>For includes, add the following:</p> <pre><code>$(UniversalCRT_IncludePath) </code></pre> <p>For link, add one of the following depending on your target processor:</p> <pre><code>$(UniversalCRT_LibraryPath_x86) $(UniversalCRT_LibraryPath_x64) $(UniversalCRT_LibraryPath_arm) </code></pre>
19,841,626
Move Assignment incompatible with Standard Copy and Swap
<p>Testing out the new Move Semantics.</p> <p>I just asked about an issues I was having with the Move Constructor. But as it turns out in the comments the problem is really that the "Move Assignment" operator and "Standard Assignment" operator clash when you use the standard "Copy and Swap" idiom.</p> <p>This is the class I am using:</p> <pre><code>#include &lt;string.h&gt; #include &lt;utility&gt; class String { int len; char* data; public: // Default constructor // In Terms of C-String constructor String() : String("") {} // Normal constructor that takes a C-String String(char const* cString) : len(strlen(cString)) , data(new char[len+1]()) // Allocate and zero memory { memcpy(data, cString, len); } // Standard Rule of three String(String const&amp; cpy) : len(cpy.len) , data(new char[len+1]()) { memcpy(data, cpy.data, len); } String&amp; operator=(String rhs) { rhs.swap(*this); return *this; } ~String() { delete [] data; } // Standard Swap to facilitate rule of three void swap(String&amp; other) throw () { std::swap(len, other.len); std::swap(data, other.data); } // New Stuff // Move Operators String(String&amp;&amp; rhs) throw() : len(0) , data(null) { rhs.swap(*this); } String&amp; operator=(String&amp;&amp; rhs) throw() { rhs.swap(*this); return *this; } }; </code></pre> <p>Pretty bog standard I think.</p> <p>Then I tested my code like this:</p> <pre><code>int main() { String a("Hi"); a = String("Test Move Assignment"); } </code></pre> <p>Here the assignment to <code>a</code> should use the "Move Assignment" operator. But there is a clash with the "Standard Assignment" operator (which is written as your standard copy and swap).</p> <pre><code>&gt; g++ --version Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/c++/4.2.1 Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn) Target: x86_64-apple-darwin13.0.0 Thread model: posix &gt; g++ -std=c++11 String.cpp String.cpp:64:9: error: use of overloaded operator '=' is ambiguous (with operand types 'String' and 'String') a = String("Test Move Assignment"); ~ ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ String.cpp:32:17: note: candidate function String&amp; operator=(String rhs) ^ String.cpp:54:17: note: candidate function String&amp; operator=(String&amp;&amp; rhs) ^ </code></pre> <p>Now I can fix this by modifying the "Standard Assignment" operator to:</p> <pre><code> String&amp; operator=(String const&amp; rhs) { String copy(rhs); copy.swap(*this); return *this; } </code></pre> <p>But this is not good as it messes with the compiler's ability to optimize the copy and swap. See What is the copy-and-swap idiom? <a href="https://stackoverflow.com/a/3279550/14065">here</a> and <a href="https://stackoverflow.com/a/3279616/14065">here</a></p> <p>Am I missing something not so obvious?</p>
19,841,737
3
1
null
2013-11-07 16:41:38.847 UTC
6
2018-01-02 02:14:58.55 UTC
2018-01-02 02:14:58.55 UTC
null
1,033,581
null
14,065
null
1
33
c++|c++11|move-semantics|copy-and-swap
5,735
<p>If you define the assignment operator to take a value, you should not (need not and cannot) define the assignment operator taking an rvalue-reference. There is no point to it.</p> <p>In general, you only need to provide an overload taking an rvalue-reference when you need to differentiate an lvalue from an rvalue, but in this case your choice of implementation means that you don't need to make that distinction. Whether you have an lvalue or an rvalue you are going to create the argument and swap the contents.</p> <pre><code>String f(); String a; a = f(); // with String&amp; operator=(String) </code></pre> <p>In this case, the compiler will resolve the call to be <code>a.operator=(f());</code> it will realize that the only reason for the return value is being the argument to <code>operator=</code> and will elide any copy --this is the point of making the function take a value in the first place!</p>
6,845,839
Marking an email message as read using Exchange Web Services 2007
<p>I am subscribed to an email account using Exchange Web Services 2007 and processing attachments as new emails come in. I would like to mark those emails as "read" on the server after I'm done processing them, but I'm finding it's not as simple as setting the "IsRead" property to true. I've even tried the following:</p> <pre><code>Dim msg As EmailMessage msg.Load(New PropertySet({EmailMessageSchema.IsRead})) msg.IsRead = True </code></pre> <p>I tried this after finding out that I had to load specific schema properties if I wanted to interact with certain parts of the message (like attachments). I've also tried directly binding the message to a new object and loading additional properties:</p> <pre><code>Dim iID as ItemId = msg.Id Dim tmpMsg as EmailMessage = EmailMessage.Bind(service, iID, New PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.IsRead)) tmpMsg.IsRead = True </code></pre> <p>I'm getting no luck. I've googled around and found <a href="http://blogs.msdn.com/b/vikas/archive/2007/11/30/howto-ews-update-isread-flag-for-items-using-exchange-web-services.aspx?PageIndex=2" rel="noreferrer">one MSDN blog example</a> that seems like it should work, but he's got some classes that I can't seem to find (like the <code>Microsoft.Exchange.WebServices.SetItemFieldType</code> class; all I've got in the <code>WebServices</code> namespace are the <code>Data</code> and <code>AutoDiscover</code> namespaces, no classes or anything). And since I can't find those classes or anything similar I'm kinda stuck. He also listed a DAV example but, again, his code uses classes I can't find in my version of the EWS dll (which is 14.0.0.0). I tried downloading the latest API from Microsoft but that seemed to be the same version as what I already have.</p> <p>So my question is, is there a way of marking an item as read using Exchange 2007 Web Services?</p>
6,848,333
2
0
null
2011-07-27 14:09:32.463 UTC
2
2021-10-27 12:40:05.933 UTC
null
null
null
null
749,434
null
1
28
.net|exchangewebservices
15,497
<p>You need to call the tmpMsg.Update method to persist changes back to the server.</p>
7,144,976
jQuery - multiple :not selector
<p>I'm trying to target page-wide links that do not start with a '#' and do not include in-line javascript but I'm having problems figuring out how to structure the selector properly.</p> <p>Based on what I've googled about multiple selectors this should work, both selectors work independently, just not together!</p> <pre><code>$('a:not([href*=javascript]), a:not([href^=#])') .each(function(){... </code></pre>
7,145,009
3
3
null
2011-08-22 08:45:29.877 UTC
10
2015-03-12 10:34:03.537 UTC
2014-05-19 17:02:51.993 UTC
null
775,283
null
638,419
null
1
90
jquery|jquery-selectors
75,263
<p>Try using</p> <pre><code>$('a:not([href*=javascript]):not([href^=#])') ... </code></pre>
8,342,140
CouchApp user registration
<p>I'm building a standalone couchdb application. These are called couchapps. The idea is that the database itself is served on port 80 and returns HTML and works as the actual website. This is a very powerful idea and I'm entirely amazed by this new concept of having your code live inside your database.</p> <p>But I'm having some issues with user registration. The one built into couchdb allows for cookies to be set and makes it really easy to plug it into your website. But there's several quite important things missing that my app requires in order to say that it has a "proper" user registration system.</p> <ol> <li><p>There's no signup verification. No email is sent, no captcha is displayed. This means that anyone could spam your <code>_users</code> database and create as many new users as they please.</p></li> <li><p>If a user forgets their password there's no facility to help them recover it. </p></li> </ol> <p>Any idea how I could overcome these issues without doing any hardcore Erlang development at a lower level (not an Erlang guy)? It would also be great if anybody knew if I could be using OAuth to authenticate against Twitter or GitHub accounts and have that integrate seemlessly with how couchdb data is handled (inside <code>validate_doc_update</code> functions).</p> <p>Thank you</p>
8,345,600
1
0
null
2011-12-01 13:27:34.96 UTC
13
2012-05-20 12:16:28.93 UTC
2011-12-01 16:56:24.1 UTC
null
50,394
null
50,394
null
1
13
oauth|couchdb|couchapp
3,249
<p>While the built in user database can work, I would not recommend it for the workflow you describe. Here are some other options:</p> <h1>Browser ID</h1> <p>I would really recommend using BrowserID. IrisCouch has provided a plugin to couchdb here:</p> <p><a href="https://github.com/iriscouch/browserid_couchdb" rel="noreferrer">https://github.com/iriscouch/browserid_couchdb</a></p> <p>This will take care of the normal registration workflow.</p> <p>If you want to take it a step further and have your users &quot;Fairly Anonymous&quot;, you can follow the example of this couchapp called &quot;Mingle&quot;</p> <p><a href="https://github.com/thedod/Mingle" rel="noreferrer">https://github.com/thedod/Mingle</a></p> <h1>Twitter Integration</h1> <p>Max Ogden's &quot;DataCouch&quot; project has a log in via twitter, although it is using some Node external processors to make it work. See here:</p> <p><a href="https://github.com/maxogden/datacouch/blob/master/processors/auth/twitterauth.js" rel="noreferrer">https://github.com/maxogden/datacouch/blob/master/processors/auth/twitterauth.js</a></p> <h1>Facebook integration</h1> <p><a href="https://github.com/ocastalabs/CouchDB-Facebook-Authentication" rel="noreferrer">https://github.com/ocastalabs/CouchDB-Facebook-Authentication</a></p> <h1>OpenID</h1> <p><a href="https://github.com/mcaprari/couchdb-openid" rel="noreferrer">https://github.com/mcaprari/couchdb-openid</a></p> <hr /> <p>I dont think you can use the oauth purely with Couch, as this post suggests:</p> <p><a href="http://bennolan.com/2011/01/11/couchdb-oath.html" rel="noreferrer">http://bennolan.com/2011/01/11/couchdb-oath.html</a></p> <p>so the closest you will get there is following what Datacouch has done.</p> <p>Hope these suggestions help.</p>
1,974,338
Where can I find a complete list of predefined Oracle pl/SQL Exceptions?
<p>Where can I find a full list of all predefined Oracle pl/SQL Exceptions?</p> <p>In this <a href="http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96624/07_errs.htm" rel="noreferrer">link</a> i found this list, are there anymore?</p> <pre><code>ACCESS_INTO_NULL ORA-06530 CASE_NOT_FOUND ORA-06592 COLLECTION_IS_NULL ORA-06531 CURSOR_ALREADY_OPEN ORA-06511 DUP_VAL_ON_INDEX ORA-00001 INVALID_CURSOR ORA-01001 INVALID_NUMBER ORA-01722 LOGIN_DENIED ORA-01017 NO_DATA_FOUND ORA-01403 NOT_LOGGED_ON ORA-01012 PROGRAM_ERROR ORA-06501 ROWTYPE_MISMATCH ORA-06504 SELF_IS_NULL ORA-30625 STORAGE_ERROR ORA-06500 SUBSCRIPT_BEYOND_COUNT ORA-06533 SUBSCRIPT_OUTSIDE_LIMIT ORA-06532 SYS_INVALID_ROWID ORA-01410 TIMEOUT_ON_RESOURCE ORA-00051 TOO_MANY_ROWS ORA-01422 VALUE_ERROR ORA-06502 ZERO_DIVIDE ORA-01476 </code></pre>
1,974,413
4
0
null
2009-12-29 12:12:50.57 UTC
11
2013-12-30 21:14:38.3 UTC
2013-12-30 21:11:46.553 UTC
null
700
null
91,299
null
1
23
sql|oracle|ora-00001
49,103
<p>These are for 11gr2, a quick scan says they are still the same: <a href="http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/errors.htm#i9355" rel="noreferrer">http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/errors.htm#BABHDGGG</a></p> <p>This is from $ORACLE_HOME/rdbms/admin/stdspec.sql (good point from egorius standard package is the place to look for the answer)</p> <pre><code> /********** Predefined exceptions **********/ CURSOR_ALREADY_OPEN exception; pragma EXCEPTION_INIT(CURSOR_ALREADY_OPEN, '-6511'); DUP_VAL_ON_INDEX exception; pragma EXCEPTION_INIT(DUP_VAL_ON_INDEX, '-0001'); TIMEOUT_ON_RESOURCE exception; pragma EXCEPTION_INIT(TIMEOUT_ON_RESOURCE, '-0051'); INVALID_CURSOR exception; pragma EXCEPTION_INIT(INVALID_CURSOR, '-1001'); NOT_LOGGED_ON exception; pragma EXCEPTION_INIT(NOT_LOGGED_ON, '-1012'); LOGIN_DENIED exception; pragma EXCEPTION_INIT(LOGIN_DENIED, '-1017'); NO_DATA_FOUND exception; pragma EXCEPTION_INIT(NO_DATA_FOUND, 100); ZERO_DIVIDE exception; pragma EXCEPTION_INIT(ZERO_DIVIDE, '-1476'); INVALID_NUMBER exception; pragma EXCEPTION_INIT(INVALID_NUMBER, '-1722'); TOO_MANY_ROWS exception; pragma EXCEPTION_INIT(TOO_MANY_ROWS, '-1422'); STORAGE_ERROR exception; pragma EXCEPTION_INIT(STORAGE_ERROR, '-6500'); PROGRAM_ERROR exception; pragma EXCEPTION_INIT(PROGRAM_ERROR, '-6501'); VALUE_ERROR exception; pragma EXCEPTION_INIT(VALUE_ERROR, '-6502'); ACCESS_INTO_NULL exception; pragma EXCEPTION_INIT(ACCESS_INTO_NULL, '-6530'); COLLECTION_IS_NULL exception; pragma EXCEPTION_INIT(COLLECTION_IS_NULL , '-6531'); SUBSCRIPT_OUTSIDE_LIMIT exception; pragma EXCEPTION_INIT(SUBSCRIPT_OUTSIDE_LIMIT,'-6532'); SUBSCRIPT_BEYOND_COUNT exception; pragma EXCEPTION_INIT(SUBSCRIPT_BEYOND_COUNT ,'-6533'); -- exception for ref cursors ROWTYPE_MISMATCH exception; pragma EXCEPTION_INIT(ROWTYPE_MISMATCH, '-6504'); SYS_INVALID_ROWID EXCEPTION; PRAGMA EXCEPTION_INIT(SYS_INVALID_ROWID, '-1410'); -- The object instance i.e. SELF is null SELF_IS_NULL exception; pragma EXCEPTION_INIT(SELF_IS_NULL, '-30625'); CASE_NOT_FOUND exception; pragma EXCEPTION_INIT(CASE_NOT_FOUND, '-6592'); -- Added for USERENV enhancement, bug 1622213. USERENV_COMMITSCN_ERROR exception; pragma EXCEPTION_INIT(USERENV_COMMITSCN_ERROR, '-1725'); -- Parallel and pipelined support NO_DATA_NEEDED exception; pragma EXCEPTION_INIT(NO_DATA_NEEDED, '-6548'); -- End of 8.2 parallel and pipelined support /********** Add new exceptions here **********/ </code></pre>
1,392,396
Advantages of UserDict class?
<p>What are advantages of using <strong><code>UserDict</code></strong> class?</p> <p>I mean, what I really get if instead of</p> <pre><code>class MyClass(object): def __init__(self): self.a = 0 self.b = 0 ... m = MyClass() m.a = 5 m.b = 7 </code></pre> <p>I will write the following:</p> <pre><code>class MyClass(UserDict): def __init__(self): UserDict.__init__(self) self[&quot;a&quot;] = 0 self[&quot;b&quot;] = 0 ... m = MyClass() m[&quot;a&quot;] = 5 m[&quot;b&quot;] = 7 </code></pre> <p><strong>Edit</strong>: If I understand right I can add new fields to an object in a runtime in both cases?</p> <pre><code>m.c = &quot;Cool&quot; </code></pre> <p>and</p> <pre><code>m[&quot;c&quot;] = &quot;Cool&quot; </code></pre>
1,394,572
4
0
null
2009-09-08 07:00:17.533 UTC
10
2022-02-26 18:43:35.463 UTC
2022-02-26 18:43:35.463 UTC
null
355,230
null
52,042
null
1
26
python|oop
26,969
<p><a href="http://docs.python.org/library/userdict.html?#UserDict.UserDict" rel="noreferrer"><code>UserDict.UserDict</code></a> has no substantial added value since Python 2.2, since, as @gs mention, you can now subclass <code>dict</code> directly -- it exists only for backwards compatibility with Python 2.1 and earlier, when builtin types could not be subclasses. Still, it was kept in Python 3 (now in its proper place in the <code>collections</code> module) since, as <a href="http://docs.python.org/3.1/library/collections.html?#collections.UserDict" rel="noreferrer">the docs</a> now mention,</p> <blockquote> <p>The need for this class has been partially supplanted by the ability to subclass directly from dict; however, this class can be easier to work with because the underlying dictionary is accessible as an attribute.</p> </blockquote> <p><code>UserDict.DictMixin</code>, in Python 2, is quite handy -- as the docs say,</p> <blockquote> <p>The module defines a mixin, DictMixin, defining all dictionary methods for classes that already have a minimum mapping interface. This greatly simplifies writing classes that need to be substitutable for dictionaries (such as the shelve module).</p> </blockquote> <p>You subclass it, define some fundamental methods (at least <code>__getitem__</code>, which is sufficient for a read-only mapping without the ability to get keys or iterate; also <code>keys</code> if you need those abilities; possibly <code>__setitem__</code>, and you have a R/W mapping without the ability of removing items; add <code>__delitem__</code> for full capability, and possibly override other methods for reasons of performance), and get a full-fledged implementation of <code>dict</code>'s rich API (<code>update</code>, <code>get</code>, and so on). A great example of the <a href="http://en.wikipedia.org/wiki/Template_method_pattern" rel="noreferrer">Template Method</a> design pattern.</p> <p>In Python 3, <code>DictMixin</code> is gone; you can get <em>almost</em> the same functionality by relying on <code>collections.MutableMapping</code> instead (or just <code>collections.Mapping</code> for R/O mappings). It's a bit more elegant, though not QUITE as handy (see <a href="http://bugs.python.org/issue5402" rel="noreferrer">this issue</a>, which was closed with "won't fix"; the short discussion is worth reading).</p>
2,265,036
How to serve static files via Rack?
<p>I am currently developing a Rack-based application and want to redirect all file requests (e.g. <code>filename.filetype</code>) to a specified folder.</p> <p><code>Rack::Static</code> only supports file requests for a special folder(e.g. &quot;/media&quot;).</p> <p>Do I have to write my own Rack middleware or does an out-of-the-box solution exist?</p>
2,271,193
4
0
null
2010-02-15 09:49:27.557 UTC
21
2021-07-21 10:00:16.77 UTC
2021-07-21 10:00:16.77 UTC
null
2,452,869
null
175,927
null
1
41
ruby|file|static|rack
19,278
<p>To redirect every request to a particular path, use <a href="http://rack.rubyforge.org/doc/classes/Rack/File.html" rel="noreferrer"><code>Rack::File</code></a> (for some reason this class is absent in recent documentation, but it is <a href="http://github.com/rack/rack/blob/master/lib/rack/file.rb" rel="noreferrer">still part of</a> the latest Rack):</p> <pre><code>run Rack::File.new("/my/path") </code></pre> <p>To redirect every request, and add an HTML index of all files in the target dir, use <a href="http://rack.rubyforge.org/doc/Rack/Directory.html" rel="noreferrer"><code>Rack::Directory</code></a>:</p> <pre><code>run Rack::Directory.new("/my/path") </code></pre> <p>To combine several directories or serve only a some requests from the target dir:</p> <pre><code>map "/url/prefix" do run Rack::File.new("/my/path") end # More calls to map if necessary... # All other requests. run MyApp.new </code></pre>
1,446,256
Pass a return value back through an EventHandler
<p>Im trying to write to an API and I need to call an eventhandler when I get data from a table. Something like this:</p> <pre><code> public override bool Run(Company.API api) { SomeInfo _someInfo = new SomeInfo(); if (_someInfo.Results == 1) return true; else return false; using (MyTable table = new MyTable(api)) { table.WhenData += new EventHandler&lt;DataEventArgs&lt;Record&gt;&gt;(table_WhenData); table.WhenDead += new EventHandler&lt;EventArgs&gt;(table_WhenDead); table.Start(); } public void table_WhenData(object sender, DataEventArgs&lt;Record&gt; e) { return true; } </code></pre> <p>The problem that Im having is I dont know how to pass a return value back from table_WhenData to the Run method.</p> <p>Ive tried many ways (like trying to pass _someInfo to the method) but I just cant seem to get the syntax right.</p> <p>Any suggestion is greatly appreciated.</p>
1,446,269
4
2
null
2009-09-18 18:43:10.123 UTC
13
2019-10-02 14:34:51.643 UTC
null
null
null
null
151,954
null
1
45
c#|return-value|event-handling
80,052
<p>The common pattern here is not to return any data from the event handler, but to add properties to your event argument object so that the consumer of the event can set the properties which the caller can then access. This is very common in UI handling code; you see the Cancel event concept all over the place.</p> <p>The following is pseudo code, and not compile ready. Its intent is to show the pattern.</p> <pre><code>public class MyEventArgs : EventArgs { public bool Cancel{get;set;} } public bool fireEvent() { MyEventArgs e=new MyEventArgs(); //Don't forget a null check, assume this is an event FireEventHandler(this,e); return e.Cancel; } public HandleFireEvent(object sender, MyEventArgs e) { e.Cancel=true; } </code></pre> <p><strong>Edit</strong></p> <p>I like how Jon Skeet worded this: make the <code>EventArgs</code> mutuable. That is, the consumer of the event can modify the state of the <code>EventArgs</code> object allowing for the raiser of the event to get to that data.</p>
1,800,859
How can I change the remote/target repository URL on Windows?
<p>I created a local GIT repository on Windows. Let's call it AAA. I staged, committed, and pushed the contents to GitHub. <code>[email protected]:username/AAA.git</code> </p> <p>I realized I made a mistake with the name.</p> <p>On GitHub, I renamed it to <code>[email protected]:username/BBB.git</code> </p> <p>Now, on my Windows machine, I need to change <code>[email protected]:username/AAA.git</code> to <code>[email protected]:username/BBB.git</code> because the settings are still trying to "push" to <code>[email protected]:username/AAA.git</code> but I need to push to <code>[email protected]:username/BBB.git</code> now.</p> <p>How could I do that?</p>
1,800,998
4
0
null
2009-11-26 00:14:39.31 UTC
54
2018-03-15 07:31:12.96 UTC
2012-07-30 20:11:10.717 UTC
null
1,288
null
169,320
null
1
141
windows|git|github
174,582
<p>The easiest way to tweak this in my opinion (imho) is to edit the .git/config file in your repository. Look for the entry you messed up and just tweak the URL.</p> <p>On my machine in a repo I regularly use it looks like this:</p> <pre><code>KidA% cat .git/config [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true ignorecase = true autocflg = true [remote "origin"] url = ssh://localhost:8888/opt/local/var/git/project.git #url = ssh://xxx.xxx.xxx.xxx:80/opt/local/var/git/project.git fetch = +refs/heads/*:refs/remotes/origin/* </code></pre> <p>The line you see commented out is an alternative address for the repository that I sometimes switch to simply by changing which line is commented out.</p> <p>This is the file that is getting manipulated under-the-hood when you run something like <code>git remote rm</code> or <code>git remote add</code> but in this case since its only a typo you made it might make sense to correct it this way.</p>
49,609,889
flutter doctor doesn't work on neither Command Prompt or PowerShell window?
<p><code>flutter doctor</code> doesn't work on either Command Prompt or PowerShell window? I have been trying to install flutter on windows. I have cloned the Flutter SDK as mentioned in the tutorial. I have added git and the flutter to my path. But still when I try to run the <code>flutter doctor</code> the command prompt reply with this:</p> <pre><code>'where' is not recognized as an internal or external command operable program or batch file. Error: Unable to find git in your path </code></pre> <hr /> <p><a href="https://i.stack.imgur.com/db9eb.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/db9eb.jpg" alt="enter image description here" /></a></p> <p>check the cmd image you will see exactly the problem</p>
53,465,355
20
6
null
2018-04-02 10:52:25.17 UTC
6
2021-08-30 08:50:30.493 UTC
2021-01-16 04:57:58.45 UTC
user10563627
null
null
9,442,683
null
1
60
powershell|flutter|command|flutter-doctor
141,812
<p>to run flutter from the command prompt on your windows system it requires three things</p> <ol> <li>path to the bin folder of <a href="https://storage.googleapis.com/flutter_infra/releases/beta/windows/flutter_windows_v0.11.9-beta.zip" rel="noreferrer">downloaded flutter sdk</a> I have downloaded and saved the sdk in my documents so for me path will be</li> </ol> <p><code>C:\Users\mahesh_2\Documents\flutter_windows_v0.11.9-beta\flutter\bin</code></p> <ol start="2"> <li><strong>where.exe</strong> located at <code>C:\Windows\System32</code> </li> </ol> <p><em>Note:you need to download <strong>git</strong> from <a href="https://git-scm.com/downloads" rel="noreferrer">here</a> if you dont find path in step 3</em></p> <ol start="3"> <li><strong>git-cmd.exe</strong> located in <code>C:\Program Files\Git\git-cmd.exe</code> </li> </ol> <p>so to simply add these three paths to your environment variables go to system environment variables with <strong>variable name</strong> as <strong><code>Path</code></strong></p> <p>and <strong>value as</strong> </p> <p><code>C:\Windows\System32;C:\Program Files\Git\git-cmd.exe;C:\Users\mahesh_2\Documents\flutter_windows_v0.11.9-beta\flutter\bin</code></p> <p><a href="https://i.stack.imgur.com/38pn2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/38pn2.png" alt="enter image description here"></a></p> <p>restart the command prompt and try running flutter and <strong>Voila!</strong> you should get something like this</p> <p><a href="https://i.stack.imgur.com/bX2oh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bX2oh.png" alt="enter image description here"></a></p>
28,605,833
Overriding an Autowired Bean in Unit Tests
<p>Is there a simple way I can easily override an autowired bean in specific unit tests? There is only a single bean of every type in the compile classes so it's not a problem for autowiring in this case. The test classes would contain additional mocks. When running a unit test I'd simply like to specify an additional Configuration that says basically, while running this unit test use this mock instead of the standard bean.</p> <p>Profiles seem a bit overkill for what I require and I'm not sure this would be achievable with the Primary annotation as different unit test could have different mocks.</p>
35,866,949
6
3
null
2015-02-19 12:00:35.377 UTC
16
2021-07-31 10:29:28.607 UTC
2019-07-13 11:13:43.597 UTC
null
447,522
null
447,522
null
1
77
spring|spring-boot|spring-annotations
89,810
<p>If you just simply want to provide a different bean in your tests, i think you don't need to use spring profiles or mockito.</p> <p>Just do the following:</p> <pre><code>@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = { TestConfig.class }) public class MyTest { @Configuration @Import(Application.class) // the actual configuration public static class TestConfig { @Bean public IMyService myService() { return new MockedMyService(); } } @Test public void test() { .... } } </code></pre> <p>NOTE: tested with spring boot 1.3.2 / spring 4.2.4</p>
71,318,804
Google OAuth 2.0 failing with Error 400: invalid_request for some client_id, but works well for others in the same project
<p>We have some apps (or maybe we should call them a handful of scripts) that use Google APIs to facilitate some administrative tasks. Recently, after making another client_id in the same project, I started getting an error message similar to the one described in <a href="https://stackoverflow.com/q/70008449/1213346">localhost redirect_uri does not work for Google Oauth2 (results in 400: invalid_request error)</a>. I.e.,</p> <blockquote> <p>Error 400: invalid_request</p> <p>You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy for keeping apps secure.</p> <p>You can let the app developer know that this app doesn't comply with one or more Google validation rules.</p> <p>Request details:</p> <p>The content in this section has been provided by the app developer. This content has not been reviewed or verified by Google.</p> <p>If you’re the app developer, make sure that these request details comply with Google policies.</p> <p>redirect_uri: urn:ietf:wg:oauth:2.0:oob</p> </blockquote> <p>How do I get through this error? It is important to note that:</p> <ul> <li>The OAuth consent screen for this project is marked as &quot;Internal&quot;. Therefore any mentions of Google review of the project, or publishing status are irrelevant</li> <li>I do have &quot;Trust internal, domain-owned apps&quot; enabled for the domain</li> <li>Another client id in the same project works and there are no obvious differences between the client IDs - they are both &quot;Desktop&quot; type which only gives me a Client ID and Client secret that are different</li> <li>This is a command line script, so I use the &quot;copy/paste&quot; verification method as <a href="https://developers.google.com/identity/protocols/oauth2/native-app?hl=en#step-2:-send-a-request-to-googles-oauth-2.0-server" rel="noreferrer">documented here</a> hence the <code>urn:ietf:wg:oauth:2.0:oob</code> redirect URI (copy/paste is the only friendly way to run this on a headless machine which has no browser).</li> <li>I was able to reproduce the same problem in a dev domain. I have three client ids. The oldest one is from January 2021, another one from December 2021, and one I created today - March 2022. Of those, only the December 2021 works and lets me choose which account to authenticate with before it either accepts it or rejects it with &quot;Error 403: org_internal&quot; (this is expected). The other two give me an &quot;Error 400: invalid_request&quot; and do not even let me choose the &quot;internal&quot; account. Here are the URLs generated by my app (I use the ruby google client APIs) and the only difference between them is the client_id - <a href="https://accounts.google.com/o/oauth2/auth?access_type=offline&amp;approval_prompt=force&amp;client_id=566372898811-b89vfj17vaqpcd7bat5tdvbdcpbb41li.apps.googleusercontent.com&amp;include_granted_scopes=true&amp;redirect_uri=urn:ietf:wg:oauth:2.0:oob&amp;response_type=code&amp;scope=https://www.googleapis.com/auth/admin.directory.user.readonly%20https://www.googleapis.com/auth/admin.directory.group.readonly%20https://www.googleapis.com/auth/admin.directory.domain.readonly%20https://www.googleapis.com/auth/drive.readonly%20profile%20https://www.googleapis.com/auth/admin.reports.audit.readonly%20https://www.googleapis.com/auth/drive.file" rel="noreferrer">January 2021</a>, <a href="https://accounts.google.com/o/oauth2/auth?access_type=offline&amp;approval_prompt=force&amp;client_id=566372898811-htvr8md883tk25e1t8q7kabacpmh94dc.apps.googleusercontent.com&amp;include_granted_scopes=true&amp;redirect_uri=urn:ietf:wg:oauth:2.0:oob&amp;response_type=code&amp;scope=https://www.googleapis.com/auth/admin.directory.user.readonly%20https://www.googleapis.com/auth/admin.directory.group.readonly%20https://www.googleapis.com/auth/admin.directory.domain.readonly%20https://www.googleapis.com/auth/drive.readonly%20profile%20https://www.googleapis.com/auth/admin.reports.audit.readonly%20https://www.googleapis.com/auth/drive.file" rel="noreferrer">December 2021</a>, <a href="https://accounts.google.com/o/oauth2/auth?access_type=offline&amp;approval_prompt=force&amp;client_id=566372898811-214ho9i7ngt1faa5llusv3j4sigabl14.apps.googleusercontent.com&amp;include_granted_scopes=true&amp;redirect_uri=urn:ietf:wg:oauth:2.0:oob&amp;response_type=code&amp;scope=https://www.googleapis.com/auth/admin.directory.user.readonly%20https://www.googleapis.com/auth/admin.directory.group.readonly%20https://www.googleapis.com/auth/admin.directory.domain.readonly%20https://www.googleapis.com/auth/drive.readonly%20profile%20https://www.googleapis.com/auth/admin.reports.audit.readonly%20https://www.googleapis.com/auth/drive.file" rel="noreferrer">March 2022</a>.</li> </ul> <p>Here is the part of the code around the authorization flow, and the URLs for the different client IDs are what was produced on the <code>$stderr.puts url</code> line. It is pretty much the same thing as <a href="https://github.com/googleapis/google-auth-library-ruby#example-command-line" rel="noreferrer">documented in the official example here</a> (<a href="https://github.com/googleapis/google-auth-library-ruby/blob/b1b6b18355863cf553e52fbffe23cd42f7b18bf5/README.md#example-command-line" rel="noreferrer">version as of this writing</a>).</p> <pre class="lang-rb prettyprint-override"><code> OOB_URI = 'urn:ietf:wg:oauth:2.0:oob' def user_credentials_for(scope, user_id = 'default') token_store = Google::Auth::Stores::FileTokenStore.new(:file =&gt; token_store_path) authorizer = Google::Auth::UserAuthorizer.new(client_id, scope, token_store) credentials = authorizer.get_credentials(user_id) if credentials.nil? url = authorizer.get_authorization_url(base_url: OOB_URI) $stderr.puts &quot;&quot; $stderr.puts &quot;-----------------------------------------------&quot; $stderr.puts &quot;Requesting authorization for '#{user_id}'&quot; $stderr.puts &quot;Open the following URL in your browser and authorize the application.&quot; $stderr.puts url code = $stdin.readline.chomp $stderr.puts &quot;-----------------------------------------------&quot; credentials = authorizer.get_and_store_credentials_from_code( user_id: user_id, code: code, base_url: OOB_URI) end credentials end </code></pre>
71,327,990
9
6
null
2022-03-02 07:20:31.39 UTC
7
2022-08-23 19:30:45.12 UTC
2022-03-16 03:11:18.267 UTC
null
1,213,346
null
1,213,346
null
1
31
oauth-2.0|google-api|google-oauth|google-api-client
30,466
<p>I sent off an email to someone on the Google OAuth team. This is the gist of their response.</p> <p>As I feared your issue is related to <a href="https://developers.googleblog.com/2022/02/making-oauth-flows-safer.html#dates-oob" rel="noreferrer">Making Google OAuth interactions safer by using more secure OAuth flows</a></p> <p>The current recommendation from google is to move to use localhost/loopback redirects as recommended here: <a href="https://developers.googleblog.com/2022/02/making-oauth-flows-safer.html#instructions-oob" rel="noreferrer">instructions-oob</a> or use the OAuth for devices flow if you are using non-sensitive scopes and need a headless solution.</p>
7,269,271
Which control caused the postback?
<p>I have two buttons:</p> <pre><code>&lt;asp:Button ID="Button1" runat="server" Text="Button" /&gt; &lt;asp:Button ID="Button2" runat="server" Text="Button" /&gt; </code></pre> <p>How can I determine on pageLoad which one of this two caused the postback? Is there a short solution as I know there are only two controls that can cause this postback?</p>
7,271,155
5
1
null
2011-09-01 10:51:33.873 UTC
6
2019-07-26 13:42:17.443 UTC
2014-04-27 10:40:32.297 UTC
null
559,933
null
559,933
null
1
41
asp.net|postback
63,160
<p>You can use this method to get the control that caused the postback:</p> <pre><code>/// &lt;summary&gt; /// Retrieves the control that caused the postback. /// &lt;/summary&gt; /// &lt;param name="page"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; private Control GetControlThatCausedPostBack(Page page) { //initialize a control and set it to null Control ctrl = null; //get the event target name and find the control string ctrlName = page.Request.Params.Get("__EVENTTARGET"); if (!String.IsNullOrEmpty(ctrlName)) ctrl = page.FindControl(ctrlName); //return the control to the calling method return ctrl; } </code></pre>
7,110,360
Easy_install and Pip doesn't work
<p>Easy_install and Pip doesn't work anymore on python 2.7, when I try to do:</p> <pre><code>sudo easy_install pip </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "/usr/bin/easy_install", line 5, in &lt;module&gt; from pkg_resources import load_entry_point File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 2713, in &lt;module&gt; parse_requirements(__requires__), Environment() File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 584, in resolve raise DistributionNotFound(req) pkg_resources.DistributionNotFound: distribute==0.6.15 </code></pre> <p>And when I try:</p> <pre><code>sudo pip install [package] </code></pre> <p>I get:</p> <pre><code>Traceback (most recent call last): File "/usr/bin/pip", line 5, in &lt;module&gt; from pkg_resources import load_entry_point File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 2713, in &lt;module&gt; parse_requirements(__requires__), Environment() File "/usr/bin/lib/python2.7/site-packages/distribute-0.6.19-py2.7.egg/pkg_resources.py", line 584, in resolve raise DistributionNotFound(req) pkg_resources.DistributionNotFound: pip==0.8.2 </code></pre> <p>I've already install both of them (and yes, first deleted them), but no result...</p> <p>Thanks!</p> <p><a href="https://stackoverflow.com/questions/5585473/upgraded-python-on-snowleopard-using-homebrew-now-pip-and-easy-install-dont-work">(I tried already this post)</a></p>
7,110,428
6
1
null
2011-08-18 15:53:22.127 UTC
5
2018-05-25 14:32:57.003 UTC
2017-09-21 19:57:54.87 UTC
null
2,246,488
null
898,731
null
1
16
python|python-2.7
52,850
<p>Try</p> <pre><code> sudo easy_install Distribute </code></pre> <p>and if that exists, but is too old</p> <pre><code> sudo easy_install -U Distribute </code></pre> <p>Looks like either Distribute/setuptools (it's old name) is messed up or Python package settings. If either of these do not help, try removing the full Python 2.7 installation and reinstall everything from the scratch.</p> <p>Possible reasons for the mess is that you have used both sudo easy_install / sudo pip and Linux distribution packages to mix and match system-wide installation packages. You should use virtualenv instead if you use pip/easy_install (no sudo needed)</p> <p><a href="http://pypi.python.org/pypi/virtualenv" rel="noreferrer">http://pypi.python.org/pypi/virtualenv</a></p>
7,086,393
Create HTML Table with SQL FOR XML
<p>I'm creating a HL7 Continuity of Care Document (CCD) using FOR XML statements in SQL Server 2008 R2.</p> <p>I've done A LOT with this method, but this is the first time I have to represent part of the data in a HTML table, which is giving me trouble.</p> <p>So, I have the following information in a table:</p> <pre><code> Problem | Onset | Status --------------------------------- Ulcer | 01/01/2008 | Active Edema | 02/02/2005 | Active </code></pre> <p>and I'm trying to render the following</p> <pre><code>&lt;tr&gt; &lt;th&gt;Problem&lt;/th&gt; &lt;th&gt;Onset&lt;/th&gt; &lt;th&gt;Status&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Ulcer&lt;/td&gt; &lt;td&gt;01/01/2008&lt;/td&gt; &lt;td&gt;Active&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Edema&lt;/td&gt; &lt;td&gt;02/02/2005&lt;/td&gt; &lt;td&gt;Active&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>I'm using this query:</p> <pre><code>SELECT p.ProblemType AS "td" , p.Onset AS "td" , p.DiagnosisStatus AS "td" FROM tblProblemList p WHERE p.PatientUnitNumber = @PatientUnitNumber FOR XML PATH('tr') </code></pre> <p>And I keep getting the following:</p> <pre><code>&lt;tr&gt; &lt;td&gt;Ulcer2008-01-01Active&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Edema2005-02-02Active&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>Anyone got any advice?</p>
7,087,899
8
1
null
2011-08-16 23:37:21.463 UTC
22
2019-07-18 17:20:49.023 UTC
2019-07-18 17:20:49.023 UTC
null
5,089,204
null
81,770
null
1
33
html|sql-server|xml|tsql|html-table
91,366
<pre><code>select (select p.ProblemType as 'td' for xml path(''), type), (select p.Onset as 'td' for xml path(''), type), (select p.DiagnosisStatus as 'td' for xml path(''), type) from tblProblemList p where p.PatientUnitNumber = @PatientUnitNumber for xml path('tr') </code></pre> <p>To add the header as well you can use <code>union all</code>.</p> <pre><code>select (select 'Problem' as th for xml path(''), type), (select 'Onset' as th for xml path(''), type), (select 'Status' as th for xml path(''), type) union all select (select p.ProblemType as 'td' for xml path(''), type), (select p.Onset as 'td' for xml path(''), type), (select p.DiagnosisStatus as 'td' for xml path(''), type) from tblProblemList p where p.PatientUnitNumber = @PatientUnitNumber for xml path('tr') </code></pre>
14,355,651
Getting the first (and only value) from a collection
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1671378/java-get-first-item-from-a-collection">Java: Get first item from a collection</a> </p> </blockquote> <p>In Java, I often encounter a collection with one single element, which I need to retrieve. Because collections do not guarantee consistent ordering, there is no <code>first()</code> or <code>get(int index)</code> methods, so I need to use rather ugly things, such as:</p> <pre><code>public Integer sillyExample(Collection&lt;Integer&gt; collection){ if(collection.size()==1){ return collection.iterator().next(); } return someCodeToDecideBetweenElements(collection); } </code></pre> <p>So, how do <em>you</em> get the only element out? I can't believe there isn't a better way...</p> <p>Please note, I understand there's no concept of "first", I'm just trying to avoid building an iterator when I know there is only one element in it.</p> <p>EDIT: Peter Wooster found a very similar question <a href="https://stackoverflow.com/questions/1671378/java-get-first-item-from-a-collection">here</a>. I'm leaving this open because I'm not trying to get the "first" element, which would imply a consistent ordering, but the "one and only" element after checking that it indeed is the only element.</p>
14,355,866
3
13
null
2013-01-16 09:59:09.093 UTC
2
2014-01-29 20:40:30.317 UTC
2017-05-23 12:17:58.683 UTC
null
-1
null
373,962
null
1
26
java|collections
45,744
<p>The easiest answer is what you've done!</p> <pre><code>first = collection.iterator().next(); </code></pre> <p>note that iterator() is a method, was that a typo?</p>
13,865,534
Visual Studio "Add As Link" not working while debugging
<p>I use Visual Studio 2010 to maintain around 40 different web applications that are all housed on the same website upon deployment. These projects are in the same solution but housed in different projects as they each do very different things. </p> <p>I'm trying to share css/js files among the various projects via the "Add As Link" option that way I can update the css or js files once and automatically have the updates reflected in the various projects without having to build and redeploy each project. </p> <p>The issue that I am having is when I am trying to run a project locally on my PC for debugging purposes those linked files aren't working. I'm getting a file not found.</p> <blockquote> <p><em><strong>My Thought:</em></strong> I assume that this because the folder structure is different when running the applications locally. I'm curious if there is a way to copy the files to the project only when building in debug mode and adjust the relative URLs accordingly so that I will be able to properly test the application before publishing to our web server.</p> </blockquote> <p>Thanks, </p>
13,868,281
4
5
null
2012-12-13 17:50:02 UTC
11
2019-04-05 23:30:59.663 UTC
null
null
null
null
565,964
null
1
29
asp.net|asp.net-mvc-3|visual-studio-2010|web|webforms
10,207
<p>The solution to this problem is copying content files (like js, css or others) which are added as link during each build. There are several ways to do this. I can advice to use MSBuild target which can be reused by different web application projects.</p> <p>So you can create the following file (for example by naming it WebApplication.Extension.targets) with the following content:</p> <pre><code>&lt;Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"&gt; &lt;!-- Override the default target dependencies to --&gt; &lt;!-- include the new CopyLinkedContentFiles target. --&gt; &lt;PropertyGroup&gt; &lt;BuildDependsOn&gt; CopyLinkedContentFiles; $(BuildDependsOn); &lt;/BuildDependsOn&gt; &lt;/PropertyGroup&gt; &lt;!-- ============================================================ CopyLinkedContentFiles A new target to copy any linked content files into the web application output folder. NOTE: This is necessary even when '$(OutDir)' has not been redirected. ============================================================ --&gt; &lt;Target Name="CopyLinkedContentFiles"&gt; &lt;!-- Remove any old copies of the files --&gt; &lt;Delete Condition=" '%(Content.Link)' != '' AND Exists('$(WebProjectOutputDir)\%(Content.Link)') " Files="$(WebProjectOutputDir)\%(Content.Link)" /&gt; &lt;!-- Copy linked content files recursively to the project folder --&gt; &lt;Copy Condition=" '%(Content.Link)' != '' " SourceFiles="%(Content.Identity)" DestinationFiles="$(WebProjectOutputDir)\%(Content.Link)" /&gt; &lt;/Target&gt; &lt;/Project&gt; </code></pre> <p>And then add this target to you web application project by placing the following line in .csproj file:</p> <pre><code>&lt;Import Project="$(MSBuildProjectDirectory)[RelativePathToFile]\WebApplication.Extension.targets" /&gt; </code></pre> <p>Basically you can add this line in .csproj file after the following one:</p> <pre><code>&lt;Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /&gt; </code></pre> <p>After this problem with content files added as link should be resolved.</p> <p><strong>Edit:</strong> To execute the following logic only when debug configuration is built in MSBUILD you have ability to specify Condition element.</p> <p>For example to import specified target only for debug configuration you can update import statement to the following:</p> <pre><code>&lt;Import Project="$(MSBuildProjectDirectory)[RelativePathToFile]\WebApplication.Extension.targets" Condition=" '$(Configuration)' == 'Debug' "/&gt; </code></pre> <p><strong>Edit2:</strong></p> <p>To overcome this problem some time ago I created a '<a href="https://www.nuget.org/packages/MSBuild.WebApplication.CopyContentLinkedFiles/" rel="noreferrer">MSBuild.WebApplication.CopyContentLinkedFiles</a>' nuget package. This package adds MsBuild target which copies all content files added as link to project folder during build. </p>
43,312,223
Asynchronous call in componentWillMount finishes after render method
<p>I am trying to perform an asynchronous call to an API in the componentWillMount method. Indeed I would like the <code>render</code> method to executed after the componentWillMount method as I need to pass <code>props</code> to the component in my <code>render</code> method.</p> <p>Here is my code : </p> <pre><code>class TennisSearchResultsContainer extends React.Component { componentWillMount () { // TODO: Build markers for the map // TODO: Check courtsResults object and database for tennis court this.courtsMarkers = this.props.courtsResults.map((court) =&gt; { return new google.maps.Marker({ position: new google.maps.LatLng(JSON.parse(court.LOC).coordinates[1], JSON.parse(court.LOC).coordinates[0]), title: court.NAME, animation: google.maps.Animation.DROP }); }); } render () { return &lt;TennisSearchResults criterias={this.props.criterias} courtsMarkers={this.courtsMarkers} /&gt;; } } </code></pre> <p>I don't understand then why my render method seems to do not wait for the asynchronous call to finish and pass undefined props to my child component...</p> <p>Am I right? And what should I do to fix that? What is the way to handle this?</p>
43,312,301
2
2
null
2017-04-09 21:40:02.217 UTC
22
2019-10-09 03:53:24.213 UTC
2017-09-12 05:47:37.897 UTC
null
4,015,856
null
7,477,752
null
1
47
javascript|reactjs|asynchronous
45,089
<p>You might need to understand javascript async behavior better. Async means "don't wait". That the task will happen in the background and other code will continue to execute. A good way to manage this is to set state on your component. For example, when you enter <code>componentDidMount</code> set a <code>loading</code> state to <code>true</code>. Then when your async function completes, set that state to <code>false</code>. In your <code>render</code> function you can then either display a "loading..." message or the data.</p> <p>Here is some code that shows a simplified example of fetching data async and how you could handle that in React. Open the developer tools in your browser and look at the console output to understand the React lifecycle better.</p> <p>EDIT: Code has been updated to use the new React Lifecycle recommendations as of April 2018. In summary, I replaced <code>componentWillMount</code> with the safer <code>componentDidMount</code>.</p> <p>It might seem inefficient to update the state <em>after</em> the component has already mounted, as 'component<strong>DID</strong>mount' correctly implies. However, per the <a href="https://reactjs.org/docs/react-component.html#componentdidmount" rel="noreferrer">official React documentation on componentDidMount</a>:</p> <p>"If you need to load data from a remote endpoint, this is a good place to instantiate the network request."</p> <p>"Calling <code>setState()</code> in this method will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the <code>render()</code> will be called twice in this case, the user won’t see the intermediate state."</p> <p>Here's the complete example code:</p> <pre><code>class MyComponent extends React.Component { constructor(props) { super(); console.log('This happens 1st.'); this.state = { loading: 'initial', data: '' }; } loadData() { var promise = new Promise((resolve, reject) =&gt; { setTimeout(() =&gt; { console.log('This happens 6th (after 3 seconds).'); resolve('This is my data.'); }, 3000); }); console.log('This happens 4th.'); return promise; } componentDidMount() { console.log('This happens 3rd.'); this.setState({ loading: 'true' }); this.loadData() .then((data) =&gt; { console.log('This happens 7th.'); this.setState({ data: data, loading: 'false' }); }); } render() { if (this.state.loading === 'initial') { console.log('This happens 2nd - after the class is constructed. You will not see this element because React is still computing changes to the DOM.'); return &lt;h2&gt;Intializing...&lt;/h2&gt;; } if (this.state.loading === 'true') { console.log('This happens 5th - when waiting for data.'); return &lt;h2&gt;Loading...&lt;/h2&gt;; } console.log('This happens 8th - after I get data.'); return ( &lt;div&gt; &lt;p&gt;Got some data!&lt;/p&gt; &lt;p&gt;{this.state.data}&lt;/p&gt; &lt;/div&gt; ); } } ReactDOM.render( &lt;MyComponent /&gt;, document.getElementsByClassName('root')[0] ); </code></pre> <p>And here is the <a href="http://codepen.io/tchaffee/pen/jBgMQy" rel="noreferrer">working example on CodePen</a>.</p> <p>Finally, I think this image of the modern React lifecycle <a href="https://twitter.com/dan_abramov/status/981712092611989509" rel="noreferrer">created by React maintainer Dan Abramov</a> is helpful in visualizing what happens and when.</p> <p><a href="https://i.stack.imgur.com/HZhwN.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/HZhwN.jpg" alt="enter image description here"></a></p> <p>NOTE that as of of React 16.4, this lifecycle diagram has a small inaccuracy: <code>getDerivedStateFromProps</code> is now also called after <code>setState</code> as well as <code>forceUpdate</code>. See this article from the official React blog about the <a href="https://reactjs.org/blog/2018/05/23/react-v-16-4.html#bugfix-for-getderivedstatefromprops" rel="noreferrer">Bugfix for getDerivedStateFromProps</a> </p> <p>This <a href="http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/" rel="noreferrer">interactive version of the React lifecycle diagram</a> created by Wojciech Maj allows you to select React version >16.04 with the latest behavior (still accurate as of React 16.8.6, March 27, 2019). Make sure you check the "Show less common lifecycles" option.</p>
43,308,319
How can I run bash in a new container of a docker image?
<p>I am able to run arbitrary shell commands in a container created from docker/whalesay image.</p> <pre><code>$ docker run docker/whalesay ls -l total 56 -rw-r--r-- 1 root root 931 May 25 2015 ChangeLog -rw-r--r-- 1 root root 385 May 25 2015 INSTALL -rw-r--r-- 1 root root 1116 May 25 2015 LICENSE -rw-r--r-- 1 root root 445 May 25 2015 MANIFEST -rw-r--r-- 1 root root 1610 May 25 2015 README -rw-r--r-- 1 root root 879 May 25 2015 Wrap.pm.diff drwxr-xr-x 2 root root 4096 May 25 2015 cows -rwxr-xr-x 1 root root 4129 May 25 2015 cowsay -rw-r--r-- 1 root root 4690 May 25 2015 cowsay.1 -rw-r--r-- 1 root root 54 May 25 2015 install.pl -rwxr-xr-x 1 root root 2046 May 25 2015 install.sh -rw-r--r-- 1 root root 631 May 25 2015 pgp_public_key.txt $ docker run docker/whalesay lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 14.04.2 LTS Release: 14.04 Codename: trusty </code></pre> <p>However, I am unable to run a shell in a container created from this image.</p> <pre><code>$ docker run docker/whalesay bash $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES $ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 7ce600cc9904 docker/whalesay "bash" 5 seconds ago Exited (0) 3 seconds ago loving_mayer </code></pre> <p>Why did it not work? How can I make it work?</p>
43,309,168
1
2
null
2017-04-09 15:07:52.4 UTC
42
2021-02-10 18:52:58.73 UTC
2017-04-09 16:08:15.207 UTC
null
1,175,080
null
1,175,080
null
1
193
bash|docker
230,072
<p>If you <code>docker run</code> without attaching a tty, and only call <code>bash</code>, then bash finds nothing to do, and it exits. That's because by default, a container is non-interactive, and a shell that runs in non-interactive mode expects a script to run. Absent that, it will exit.</p> <p>To run a disposable new container, you can simply attach a tty and standard input:</p> <pre><code>docker run --rm -it --entrypoint bash &lt;image-name-or-id&gt; </code></pre> <p>Or to prevent the above container from being disposed, run it without <code>--rm</code>.</p> <p>Or to enter a running container, use <code>exec</code> instead:</p> <pre><code>docker exec -it &lt;container-name-or-id&gt; bash </code></pre> <hr /> <p>In comments you asked</p> <blockquote> <p>Do you know what is the difference between this and <code>docker run -it --entrypoint bash docker/whalesay</code>?</p> </blockquote> <p>In the two commands above, you are specifying <code>bash</code> as the <code>CMD</code>. In this command, you are specifying <code>bash</code> as the <code>ENTRYPOINT</code>.</p> <p>Every container is run using a combination of <code>ENTRYPOINT</code> and <code>CMD</code>. If you (or the image) does not specify <code>ENTRYPOINT</code>, the default entrypoint is <code>/bin/sh -c</code>.</p> <p>So in the earlier two commands, if you run <code>bash</code> as the <code>CMD</code>, and the default <code>ENTRYPOINT</code> is used, then the container will be run using</p> <pre><code>/bin/sh -c bash </code></pre> <p>If you specify <code>--entrypoint bash</code>, then instead it runs</p> <pre><code>bash &lt;command&gt; </code></pre> <p>Where <code>&lt;command&gt;</code> is the <code>CMD</code> specified in the image (if any is specified).</p>
9,264,773
Ruby RSpec : No color on output with a Mac
<p>Developing with my first Mac and I noticed that my Rspec output isn't colorized in my terminal even though I'm using the '<code>-c</code>' flag in the command: <code>bundle exec rspec -c -fd</code>. Any ideas? </p>
9,264,868
3
1
null
2012-02-13 17:11:49.087 UTC
5
2014-07-08 01:15:32.447 UTC
null
null
null
null
925,881
null
1
29
ruby|rspec
7,718
<p>Add the following contents to a .rspec file to your project dir root.</p> <p><code>--color</code></p>
45,847,392
Pure CSS Continuous Horizontal Text Scroll Without Break
<p>I'm trying to create a news ticker with horizontal text that scrolls continuously without a break between loops. Ideally, the solution would be pure css/html, but I don't know if that's possible. Here's my rudimentary attempt so far: <a href="http://jsfiddle.net/lgants/ncgsrnza/" rel="noreferrer">http://jsfiddle.net/lgants/ncgsrnza/</a>. Note that the fiddle contains an unwanted break between each loop.</p> <pre class="lang-css prettyprint-override"><code>&lt;p class=&quot;marquee&quot;&gt;&lt;span&gt;This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text&lt;/span&gt;&lt;/p&gt; .marquee { margin: 0 auto; white-space: nowrap; overflow: hidden; } .marquee span { display: inline-block; padding-left: 100%; animation: marquee 5s linear infinite; } </code></pre>
45,847,760
2
4
null
2017-08-23 18:53:11.203 UTC
15
2021-11-18 17:52:55.717 UTC
2021-11-13 16:55:15.773 UTC
null
17,002,772
null
6,090,736
null
1
33
html|css
75,378
<p>You could try having two marquees and set one of them with a delayed animation of 2.5s which is half the time of the full animation (5s).</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>.marquee { margin: 0 auto; white-space: nowrap; overflow: hidden; position: absolute; } .marquee span { display: inline-block; padding-left: 100%; animation: marquee 5s linear infinite; } .marquee2 span { animation-delay: 2.5s; } @keyframes marquee { 0% { transform: translate(0, 0); } 100% { transform: translate(-100%, 0); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p class="marquee"&gt; &lt;span&gt;This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text -&amp;nbsp;&lt;/span&gt; &lt;/p&gt; &lt;p class="marquee marquee2"&gt; &lt;span&gt;This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text - This is text -&amp;nbsp;&lt;/span&gt; &lt;/p&gt;</code></pre> </div> </div> </p>
34,043,384
Easiest way to parse JSON response
<p>Is there any easy way to parse below JSOn in c#</p> <pre><code>{"type":"text","totalprice":"0.0045","totalgsm":"1","remaincredit":"44.92293","messages": [ {"status":"1","messageid":"234011120530636881","gsm":"923122699633"} ]} </code></pre> <p>and in case Multiple results.</p>
34,043,484
4
5
null
2015-12-02 12:58:32.307 UTC
12
2017-08-22 05:10:28.697 UTC
2015-12-02 13:07:00.27 UTC
null
993,547
null
788,592
null
1
32
c#|asp.net|json
95,809
<p>Follow these steps:</p> <ol> <li>Convert your JSON to C# using <a href="http://json2csharp.com/">json2csharp.com</a>;</li> <li>Create a class file and put the above generated code in there;</li> <li>Add the <code>Newtonsoft.Json</code> library to your project using the Nuget Package Manager;</li> <li><p>Convert the JSON received from your service using this code:</p> <pre><code> RootObject r = JsonConvert.DeserializeObject&lt;RootObject&gt;(json); </code></pre></li> </ol> <p>(Feel free to rename <code>RootObject</code> to something more meaningful to you. The other classes should remain unchanged.)</p>
210,097
Are Sql Triggers synchronous or asynchronous?
<p>I have a table that has an insert trigger on it. If I insert in 6000 records into this table in one insert statement from a stored procedure, will the stored procedure return before the insert trigger completes?</p> <p>Just to make sure that I'm thinking correctly, the trigger should only be called (i know 'called' isn't the right word) once because there was only 1 insert statement, right?</p> <p>My main question is: will the sproc finish even if the trigger hasn't completed?</p>
210,113
5
0
null
2008-10-16 20:12:12.417 UTC
3
2019-03-27 14:08:51.137 UTC
2009-01-01 18:55:14.25 UTC
Joel Spolsky
4
Miles
21,828
null
1
28
sql|stored-procedures|triggers|timing
14,413
<p>Your insert trigger will run once for the entire insert statement. This is why it is important to use the <code>inserted</code> temporary table to see what has actually been inserted, and not just select the most recent single record, or something like that.</p> <p>I just tested an insert and update trigger and indeed, they are considered part of the insert by sql server. the process will not finish until the trigger finishes.</p>
861,877
Reading date values from excel cell using POI HSSF API
<p>I'm using POI HSSF API for my excel manipulations in Java. I've a date value "8/1/2009" in one of my excel cell and while I try to read this value using HSSF API, it detects the cell type as Numeric and returns the 'Double' value of my date. See the sample code below:</p> <pre><code>cell = row.getCell(); // date in the cell '8/1/2009' switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: cellValue = cell.getRichStringCellValue().getString(); break; case HSSFCell.CELL_TYPE_NUMERIC: cellValue = new Double(cell.getNumericCellValue()).toString(); break; default: } </code></pre> <p>Cell.getCellType() returns NUMERIC_TYPE and thus this code converts the date to double! :(</p> <p>Is there any way to read the date as it is in HSSF POI !?</p>
861,934
5
0
null
2009-05-14 06:43:34.657 UTC
12
2017-08-21 11:07:36.027 UTC
2011-06-12 14:20:16.07 UTC
null
761,828
null
42,372
null
1
31
java|excel|apache-poi|poi-hssf
78,175
<p>You could take a look at:</p> <pre><code>HSSFDateUtil.isCellDateFormatted() </code></pre> <p>See the POI Horrible Spreadsheet Format API for more details on HSSFDateUtil:</p> <p><a href="http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFDateUtil.html" rel="noreferrer">http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFDateUtil.html</a></p> <p>That also provides some helper methods for returning Excel <code>getExcelDate()</code> and Java dates <code>getJavaDate()</code>. You need to be somewhat wary of different date formats though...</p>
761,824
Python : How to convert markdown formatted text to text
<p>I need to convert markdown text to plain text format to display summary in my website. I want the code in python. </p>
761,847
5
1
null
2009-04-17 19:21:18.967 UTC
23
2022-01-12 08:34:04.343 UTC
2009-04-17 19:46:50.983 UTC
null
41,665
null
43,056
null
1
46
python|parsing|markdown
31,174
<p>The <a href="https://pypi.org/project/Markdown/" rel="nofollow noreferrer">Markdown</a> and <a href="https://pypi.org/project/beautifulsoup4/" rel="nofollow noreferrer">BeautifulSoup</a> (now called <em>beautifulsoup4</em>) modules will help do what you describe.</p> <p>Once you have converted the markdown to HTML, you can use a HTML parser to strip out the plain text.</p> <p>Your code might look something like this:</p> <pre><code>from bs4 import BeautifulSoup from markdown import markdown html = markdown(some_html_string) text = ''.join(BeautifulSoup(html).findAll(text=True)) </code></pre>
372,980
Do you use the TR 24731 'safe' functions?
<p>The ISO C committee (<a href="http://www.open-std.org/JTC1/SC22/WG14/" rel="noreferrer">ISO/IEC JTC1/SC21/WG14</a>) has published <a href="http://www.open-std.org/JTC1/SC22/WG14/www/projects#24731-1" rel="noreferrer">TR 24731-1</a> and is working on <a href="http://www.open-std.org/JTC1/SC22/WG14/www/projects#24731-1" rel="noreferrer">TR 24731-2</a>:</p> <blockquote> <h3>TR 24731-1: Extensions to the C Library Part I: Bounds-checking interfaces</h3> <p>WG14 is working on a TR on safer C library functions. This TR is oriented towards modifying existing programs, often by adding an extra parameter with the buffer length. The latest draft is in document N1225. A rationale is in document N1173. This is to become a Technical Report type 2.</p> <h3>TR 24731-2: Extensions to the C Library - Part II: Dynamic allocation functions</h3> <p>WG14 is working on a TR on safer C library functions. This TR is oriented towards new programs using dynamic allocation instead of an extra parameter for the buffer length. The latest draft is in document N1337. This is to become a Technical Report type 2.</p> </blockquote> <h2>Questions</h2> <ul> <li>Do you use a library or compiler with support for the TR24731-1 functions?</li> <li>If so, which compiler or library and on which platform(s)?</li> <li>Did you uncover any bugs as a result of fixing your code to use these functions?</li> <li>Which functions provide the most value?</li> <li>Are there any that provide no value or negative value?</li> <li>Are you planning to use the library in the future?</li> <li>Are you tracking the TR24731-2 work at all?</li> </ul>
373,085
5
11
null
2008-12-16 22:21:00.2 UTC
28
2019-09-20 05:08:37.757 UTC
2011-05-08 08:20:40.713 UTC
BCS
511,601
Jonathan Leffler
15,168
null
1
84
c|security|coding-style|tr24731
15,573
<p>I have been a vocal critic of these TRs since their inception (when it was a single TR) and would never use them in any of my software. They mask symptoms instead of addressing causes and it is my opinion that if anything they will have a negative impact on software design as they provide a false sense of security instead of promoting existing practices that can accomplish the same goals much more effectively. I am not alone, in fact I am not aware of a single major proponent outside of the committee developing these TRs.</p> <p>I use glibc and as such know that I will be spared having to deal with this nonsense, as Ulrich Drepper, lead maintainer for glibc, <a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1106.txt" rel="noreferrer">said about the topic</a>:</p> <blockquote> <p>The proposed safe(r) ISO C library fails to address to issue completely. ... Proposing to make the life of a programmer even harder is not going to help. But this is exactly what is proposed. ... They all require more work to be done or are just plain silly.</p> </blockquote> <p>He goes on to detail problems with a number of the proposed functions and has elsewhere indicated that glibc would never support this.</p> <p>The Austin Group (responsible for maintaining POSIX) provided a very critical review of the TR, their comments and the committee responses available <a href="http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1118.htm" rel="noreferrer">here</a>. The Austin Group review does a very good job detailing many of the problems with the TR so I won't go into individual details here.</p> <p>So the bottom line is: I don't use an implementation that supports or will support this, I don't plan on ever using these functions, and I see no positive value in the TR. I personally believe that the only reason the TR is still alive in any form is because it is being pushed hard by Microsoft who has recently proved very capable of getting things rammed though standards committees despite wide-spread opposition. If these functions are ever standardized I don't think they will ever become widely used as the proposal has been around for a few years now and has failed to garner any real community support.</p>
52,841,620
Parameter 0 of constructor in required a bean of type 'java.lang.String' that could not be found
<p>I am working on spring batch with spring boot 2.X application, actually its existing code i am checked out from git. While running the application it fails due to below error only for me and same code is working for others.</p> <pre><code>s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'inputItemReader' defined in file [C:\Users\XYZ\git\main\batch\CBatchProcessing\target\classes\com\main\batchprocessing\batch\reader\InputItemReader.class]: Unsatisfied dependency expressed through **constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.String' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations**: {} Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2018-10-16 23:23:37.411 ERROR 2384 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: **Parameter 0 of constructor in com.main.batchprocessing.batch.reader.InputItemReader required a bean of type 'java.lang.String' that could not be found.** Action: Consider defining a bean of type 'java.lang.String' in your configuration. </code></pre> <p>I have checked below </p> <ol> <li>All Spring components are correctly annotated with @Component, @Service, @Controller,@Repository, etc...</li> <li>@ComponentScan &amp; @EnableAutoCOnfiguration is also provided.</li> <li>Tried giving "java.lang.String" in declarations.</li> </ol> <p>Code:</p> <pre><code> import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.mapping.JsonLineMapper; import org.springframework.batch.item.file.separator.JsonRecordSeparatorPolicy; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.core.io.FileSystemResource; import org.springframework.stereotype.Component; @Component public class InputItemReader extends FlatFileItemReader&lt;Map&lt;String, Object&gt;&gt; implements StepExecutionListener { @Autowired private InputFileHeaderValidator inputFileHeaderValidator; @Autowired private FileAuditService fileAuditService; private final Logger log = LoggerFactory.getLogger(InputItemReader.class); private java.lang.String inputFilePath; public InputItemReader(String inputFilePath) { setLineMapper(new JsonLineMapper()); setRecordSeparatorPolicy(new JsonRecordSeparatorPolicy()); setResource(new FileSystemResource(inputFilePath)); this.inputFilePath = inputFilePath; } } </code></pre>
52,843,150
20
8
null
2018-10-16 18:13:42.943 UTC
8
2022-07-04 17:15:42.137 UTC
2018-10-16 19:51:45.623 UTC
null
472,495
null
2,726,766
null
1
58
java|spring-boot|spring-batch|spring-annotations
208,390
<p>Since you do not provide the public default constructor and you added your own non-default constructor the instantiation will fail. I would suggest you to define the input file path as property like <code>@Value("${inputFilePath}")</code>. If you need further initialization in your bean define a void method and annotate it with <code>@PostConstruct</code> and do the initialization within.</p>
21,263,786
Change file type in PyCharm
<p>I created a text file, and renamed it into testTreeGen.py.</p> <p><img src="https://i.stack.imgur.com/f5YJy.png" alt="enter image description here"></p> <p>The problem is that PyCharm does not detect it as a python source so that I can't execute it. </p> <p>How can I teach PyCharm that this is python script? I tried remove the file and recreated it, and created another python file and renamed it; all ends up being the file as text file not Python script. </p> <p>The version is 3.0.2.</p> <p><img src="https://i.stack.imgur.com/1MfqP.png" alt="enter image description here"></p> <h2>EDIT</h2> <p>Refactoring does <strong>not</strong> working.</p> <p><img src="https://i.stack.imgur.com/HFRNr.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/bue0w.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/h0xLO.png" alt="enter image description here"></p> <p>The file property comes back to text (the original file property that I created before the first <em>refactoring</em>) even after I renamed it as python script. </p> <p>The weird thing is that no matter where I create the <code>testTreeGen.py</code>, PyCharm creates it as a text file as if it remembers the name of the file should be text file. I can create python script anything but the <code>testTreeGen.py</code>. </p>
21,281,563
5
4
null
2014-01-21 16:30:13.897 UTC
8
2021-02-28 02:18:21.397 UTC
2014-01-21 17:34:22.55 UTC
null
260,127
null
260,127
null
1
34
python|pycharm
12,441
<p><strong>Settings (Preferences on Mac) | Editor | File Types | Text</strong></p> <p>Check patterns there (bottom list) -- you must have had <code>testTreeGen</code> or similar pattern. Just remove it.</p> <p><strong>UPDATE 2021-02-28:</strong></p> <p><strong>Since 2020.3</strong> version you should also check under <code>Auto-detect file type by content</code> file type.</p> <p>See a bit more / with screenshots in this answer: <a href="https://stackoverflow.com/questions/65700794/webstorm-file-association-system-does-not-recognize-a-file">WebStorm File association system does not recognize a file</a></p> <hr /> <p>This usually happens when creating new file and instead of using specific file template you use <code>New | File</code> and forgetting to enter file extension (which is required here as opposed to specific file template which adds file extension automatically) -- this is to allow to create ANY file with any extension (e.g. <code>.htaccess</code> or just <code>README</code>).</p> <p>Since such file (<code>testTreeGen</code> in your case) does not have extension, IDE does not know how to treat it and treats it as plain text (not automatically though -- it asking you to choose correct file type with &quot;text file&quot; type preselected, but vast majority of users just hitting enter instead of reading what that screen says -- <em>&quot;relax, I'm a professional and I know what I'm doing&quot;</em>).</p> <p>Now, since the <code>testTreeGen</code> pattern is there and it is bigger/more precise that generic <code>*.rb</code> or <code>*.py</code>, file is treated as Text file regardless of file extension -- renaming will not help.</p> <hr /> <p><strong>Conclusion / advice</strong> -- pay a bit more attention to confirmation dialogs.</p>
44,223,988
How to rename multiple files in vscode (visual studio code)?
<p>I wonder, if there is way to rename multiple files in visual studio code? I have tried to use find and replace, no luck.</p>
62,852,258
10
2
null
2017-05-28 05:05:25.91 UTC
7
2022-08-04 06:37:39.487 UTC
null
null
null
null
1,897,222
null
1
51
visual-studio-code
88,698
<p>There are a few Visual Studio Extensions that try to provide this functionality. The first two I tried did not appear to work. There is an extension called Batch Rename which worked for me: <a href="https://marketplace.visualstudio.com/items?itemName=JannisX11.batch-rename-extension" rel="noreferrer">https://marketplace.visualstudio.com/items?itemName=JannisX11.batch-rename-extension</a>.</p> <p>Here is how the extension works.</p> <ol> <li>You highlight the files in the explorer, right-click, and select Batch Rename</li> <li>The extension creates a text file with the names of the files you want to rename, one each line. Update the text file with the new names</li> <li>Save the temporary text file from step 2 and the extension performs the rename.</li> </ol>
18,108,521
many-to-many in list display django
<pre class="lang-py prettyprint-override"><code>class Product(models.Model): products = models.CharField(max_length=256) def __unicode__(self): return self.products class PurchaseOrder(models.Model): product = models.ManyToManyField('Product') vendor = models.ForeignKey('VendorProfile') dollar_amount = models.FloatField(verbose_name='Price') </code></pre> <p>I have that code. Unfortunately, the error comes in admin.py with the <code>ManyToManyField</code></p> <pre><code>class PurchaseOrderAdmin(admin.ModelAdmin): fields = ['product', 'dollar_amount'] list_display = ('product', 'vendor') </code></pre> <p>The error says:</p> <blockquote> <p>'PurchaseOrderAdmin.list_display[0]', 'product' is a ManyToManyField which is not supported.</p> </blockquote> <p>However, it compiles when I take <code>'product'</code> out of <code>list_display</code>. So how can I display <code>'product'</code> in <code>list_display</code> without giving it errors?</p> <p><strong>edit</strong>: Maybe a better question would be how do you display a <code>ManyToManyField</code> in <code>list_display</code>?</p>
18,108,586
3
0
null
2013-08-07 16:18:22.98 UTC
33
2022-05-01 17:21:13.17 UTC
2022-03-25 22:23:16.743 UTC
null
8,172,439
null
2,611,440
null
1
121
python|django|django-admin|admin|django-queryset
76,841
<p>You may not be able to do it directly. <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display" rel="noreferrer">From the documentation of <code>list_display</code></a></p> <blockquote> <p>ManyToManyField fields aren’t supported, because that would entail executing a separate SQL statement for each row in the table. If you want to do this nonetheless, give your model a custom method, and add that method’s name to list_display. (See below for more on custom methods in list_display.)</p> </blockquote> <p>You can do something like this:</p> <pre><code>class PurchaseOrderAdmin(admin.ModelAdmin): fields = ['product', 'dollar_amount'] list_display = ('get_products', 'vendor') def get_products(self, obj): return "\n".join([p.products for p in obj.product.all()]) </code></pre> <p>OR define a model method, and use that</p> <pre><code>class PurchaseOrder(models.Model): product = models.ManyToManyField('Product') vendor = models.ForeignKey('VendorProfile') dollar_amount = models.FloatField(verbose_name='Price') def get_products(self): return "\n".join([p.products for p in self.product.all()]) </code></pre> <p>and in the admin <code>list_display</code></p> <pre><code>list_display = ('get_products', 'vendor') </code></pre>
17,788,685
Python saving multiple figures into one PDF file
<p>In python (for one figure created in a GUI) I was able to save the figure under .jpg and also .pdf by either using: </p> <pre><code>plt.savefig(filename1 + '.pdf') </code></pre> <p>or</p> <pre><code>plt.savefig(filename1 + '.jpg') </code></pre> <p>Using one file I would like to save multiple figures in either .pdf or .jpg (just like its done in math lab). Can anybody please help with this?</p>
17,788,764
3
2
null
2013-07-22 13:19:47.687 UTC
15
2021-07-01 16:44:01.02 UTC
2013-07-22 13:37:20.093 UTC
null
380,231
null
2,592,091
null
1
57
python|matplotlib
110,193
<p>Use <a href="http://matplotlib.org/api/backend_pdf_api.html#matplotlib.backends.backend_pdf.PdfPages" rel="noreferrer"><code>PdfPages</code></a> to solve your problem. Pass your <code>figure</code> object to the <code>savefig</code> method.</p> <p>For example, if you have a whole pile of <code>figure</code> objects open and you want to save them into a multi-page PDF, you might do:</p> <pre><code>import matplotlib.backends.backend_pdf pdf = matplotlib.backends.backend_pdf.PdfPages("output.pdf") for fig in xrange(1, figure().number): ## will open an empty extra figure :( pdf.savefig( fig ) pdf.close() </code></pre>
46,962,775
Android SDK missing with Android Studio 3
<p>I've just downloaded <strong>Android Studio 3</strong> for Windows from the <a href="https://developer.android.com/studio/index.html" rel="noreferrer">official website</a>, but when it starts, it displays an error message about a <strong>missing Android SDK</strong>:</p> <p><a href="https://i.stack.imgur.com/9pqoR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9pqoR.png" alt="Android SDK missing. You can obtain it from d.android.com/sdk"></a></p> <p>When I click that link, it just redirects to the same official website. There isn't a separate link there for SDK download.</p> <p>Where could I get it from? Shouldn't the Android SDK be installed during Android Studio 3 setup?</p>
46,965,692
10
5
null
2017-10-26 19:58:11.32 UTC
5
2022-01-11 07:55:41.08 UTC
null
null
null
null
3,160,869
null
1
28
android|sdk|installation|android-studio-3.0
64,195
<p>Apparently, the problem was that Android Studio 3.0 had already been installed and uninstalled before this. The SDK got removed, but Android Studio's config didn't.</p> <p><strong>Removing the config from a previous install</strong> (<code>C:\Users\&lt;user&gt;\.AndroidStudio3.0</code> folder) did the trick. When Android Studio started up, it opened a dialog about which parts of the SDK to download, and then proceeded as expected.</p>
11,467,341
Today's date JSP
<p>I've found myself working on some old JSP and want to do something simple like display today's date in dd/mm/yyyy format</p> <p>Doesn't seem to be that simple, </p> <p>So far I've imported java.util.*</p> <p>And I've tried various things like</p> <pre><code>String df = new SimpleDateFormat("dd/MM/yy"); </code></pre> <p>However, to no avail...</p>
11,467,429
5
2
null
2012-07-13 09:04:09.547 UTC
1
2017-05-09 20:19:49.787 UTC
null
null
null
null
234,468
null
1
2
jsp
46,096
<p>You can use this:</p> <pre><code>Calendar now = Calendar.getInstance(); </code></pre> <p>and then use some of the Calendar fields as needed, e.g.:</p> <pre><code>int dayOfMonth = now.get(Calendar.DAY_OF_MONTH); String dayOfMonthStr = ((dayOfMonth &lt; 10) ? "0" : "") + month; int month = now.get(Calendar.MONTH) + 1; String monthStr = ((month &lt; 10) ? "0" : "") + month; System.out.print(dayOfMonthStr+"/"+monthStr+"/"+now.get(Calendar.Year)); </code></pre> <p>To follow your original idea, I think you should do something like:</p> <pre><code>SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy"); sdf.format(new Date()); </code></pre>
33,359,740
Random number between 0 and 1?
<p>I want a random number between 0 and 1, like 0.3452. I used <code>random.randrange(0, 1)</code> but it is always 0 for me. What should I do?</p>
33,359,801
7
3
null
2015-10-27 03:59:10.753 UTC
19
2022-05-15 18:44:23 UTC
2022-05-15 18:44:23 UTC
null
355,230
null
5,425,511
null
1
214
python|random
546,889
<p>You can use <code>random.uniform</code></p> <pre><code>import random random.uniform(0, 1) </code></pre>
1,408,901
ASP.NET MVC vs Spring MVC
<p>Can anyone please make a comparison of <code>ASP.NET MVC</code> vs <code>Spring MVC</code>. </p> <p>Which technology is better in performance, productivity, maintenance, features,...</p> <p>Regards, sirmak</p>
1,411,978
5
7
null
2009-09-11 03:57:59.067 UTC
14
2016-02-16 18:27:23.907 UTC
2016-02-15 07:21:00.697 UTC
null
3,146,132
null
170,692
null
1
53
java|.net|asp.net-mvc|comparison|spring-mvc
78,261
<p>It's hard to say which one is "better"....</p> <p>First - there's the whole underlying "Java vs. .NET" argument - you can't really compare the frameworks ignoring this. </p> <p>The whole history of web development in Java with "heavyweight" J2EE apps vs. "lightweight" Spring apps. That in Java there are a ton of web frameworks (MVC and not, open-source vs. Sun-developed) and that Spring MVC had a lot to be based on.</p> <p>And on the ASP.NET MVC side - the whole history of ASP -> ASP.NET -> ASP.NET MVC. And the lack of <em>widely-used</em> non-Microsoft .NET frameworks - web or otherwise.</p> <p>Now into the opinionated part...</p> <p>I'm somewhat the opposite of @Luke101 as I've worked mostly with Spring MVC and very little with ASP.NET MVC. </p> <p>I have to say I prefer MVC-style web development over component-based web development.</p> <p>I have worked with JSF, which is similar to ASP.NET webforms. (I have to say I liked ASP.NET more than JSF - though this probably has more to do with the maturity of each framework when I used it, and tools available - I used JSF 1.0/1.1 and just Eclipse with no JSF specific support vs. ASP.NET 2.0/.NET 3.5 with Visual Studio 2008.) </p> <p>As far as MVC frameworks I prefer Spring MVC - but that's entirely because I'm just more familiar with Java - language-wise and development-wise, as opposed to ASP.NET MVC / C# /.NET. Also, Spring MVC requires Spring, and I like to develop using Spring's whole IOC pattern and use things already integrated into Spring.</p> <p>I haven't tried using Spring.NET and ASP.NET MVC - maybe this would be similar to Spring MVC / Spring / Java. </p> <p>In the Spring.NET repo there are some examples of integrating Spring.NET into ASP.NET MVC <a href="https://github.com/spring-projects/spring-net/tree/master/examples/Spring/Spring.Mvc3QuickStart" rel="noreferrer">version 3</a>, <a href="https://github.com/spring-projects/spring-net/tree/master/examples/Spring/Spring.Mvc4QuickStart" rel="noreferrer">version 4</a> and <a href="https://github.com/spring-projects/spring-net/tree/master/examples/Spring/Spring.Mvc5QuickStart" rel="noreferrer">version 5</a>.</p>
2,080,731
Google goggles API
<p>Does anyone know if there is a google goggles API for Android? If not, is there one coming any time soon? With an API for this thing the possibilities are endless...</p> <p>So far all I've been able to find on this subject is a discussion about not currently having a version for the iPhone due to it's "google labs" status (iPhone version coming once it's more "complete"). I'm hoping an API may be released then. Anybody have any info on this at all? </p>
2,642,064
5
1
null
2010-01-17 10:55:17.867 UTC
26
2016-08-24 14:11:56.147 UTC
2010-05-12 10:32:41.813 UTC
null
132,858
null
132,858
null
1
69
android|google-goggles
64,914
<p>Google Goggles to Become App Platform <a href="http://phandroid.com/2010/04/14/google-goggles-to-become-app-platform/" rel="noreferrer">http://phandroid.com/2010/04/14/google-goggles-to-become-app-platform/</a></p>
1,626,636
Connecting C# to Oracle
<p>What is the best library/driver to connect C# (.NET) application to Oracle 10g and 11g.<br> Current options that I found are:</p> <ol> <li>Oracle client that comes with database installation </li> <li>Oracle Instant Client (which is a bit confusing since it has 6-8 versions for number of operating systems)</li> <li>Microsoft ODBC ? (Can this be used?)</li> <li>ODP.Net - is this separate product or is it included in 1. and 2. ?</li> </ol> <p>Can somebody explain differences?</p> <p>I am planning C# application that will do basic CRUD operations on Oracle database. Which library/driver is smallest and easiest to install? </p> <p><strong>Edit:</strong><br> General recommendation is to use ODP.Net. Now, can somebody please explain or point to answer about differences between client install packages. I found 3 different clients for Oracle 11g:</p> <ul> <li>Oracle client - client drivers package that ships as part of database installation </li> <li><a href="http://www.oracle.com/technology/software/tech/windows/odpnet/index.html" rel="noreferrer">ODAC - Oracle data access components</a>, contains lots of things, among them are ODP.Net and Oracle Instant Client </li> <li><a href="http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/winsoft.html" rel="noreferrer">Oracle Instant Client</a> which also contains many things, including ODP.Net</li> </ul> <p>So, which of those is enough for development? Oracle documentation is painfully detailed, but says nothing about differences between those client packages. I would go with smallest (Instant Client). Is it best choice?</p> <p><strong>Edit 2:</strong><br> I am using .Net 3.5</p>
1,644,306
7
2
null
2009-10-26 18:48:02.397 UTC
11
2015-03-13 20:10:48.937 UTC
2009-10-27 10:55:58.383 UTC
null
25,732
null
25,732
null
1
12
c#|oracle
15,541
<p>To connect C# to oracle you need a data provider for .net. This can be one of the following:</p> <ul> <li>ODP.Net (Oracle)</li> <li>System.Data.OracleClient (Microsoft)</li> <li>ODBC (Oracle)</li> <li>OLEDB (Oracle)</li> <li>DataDirect ADO.NET Data Provider for Oracle (DataDirect)</li> <li>may be some other provider</li> </ul> <p><strong>All</strong> of this data provider need an oracle client installed. There is no standalone library as jdbc14.jar as in java. You have 2 choices deploying an oracle client:</p> <ul> <li>full client (may be from database installation)</li> <li>instant client</li> </ul> <p>ODP.Net, ODBC, OLEDB are part of full client. This is the "hard" way because an installation process must be run on every client runing your software. This is where the most megabytes are put on the client.<br> The <a href="http://www.oracle.com/technetwork/database/features/instant-client" rel="nofollow noreferrer">instant client</a> is provided in different packages. This is the smallest way for deployment of an oracle client.</p> <p><strong>I would suggest using ODP.Net with Oracle Instant Client</strong>, because this easy to deploy and very very light weight.</p> <p>Which instant client packages do you need:</p> <ul> <li>Pick version 11.1.0.6.0 (or newer where ODAC is provided)</li> <li>Instant Client Package - Basic (if you need full language support)</li> <li>Instant Client Package - ODAC </li> </ul> <p>There are a lot of articles on stackoverflow about deployment of oracle instant client with c# applications.</p> <p><em>EDIT:</em> updated links and versions</p>
1,477,500
How do I get the output of an external command in Perl?
<p>I want to have output of Windows command-line program (say, <code>powercfg -l</code>) written into a file which is created using Perl and then read the file line by line in a for loop and assign it to a string.</p>
1,477,621
7
1
null
2009-09-25 14:09:22.147 UTC
3
2010-03-07 18:21:31.203 UTC
2010-03-07 18:21:31.203 UTC
null
164,901
null
73,073
null
1
21
perl|command-line|batch-file
78,706
<pre><code>my $output = qx(powercfg -l); ## You've got your output loaded into the $output variable. ## Still want to write it to a file? open my $OUTPUT, '&gt;', 'output.txt' or die "Couldn't open output.txt: $!\n"; print $OUTPUT $output; close $OUTPUT ## Now you can loop through each line and ## parse the $line variable to extract the info you are looking for. foreach my $line (split /[\r\n]+/, $output) { ## Regular expression magic to grab what you want } </code></pre>
2,280,688
Taking the address of a temporary object
<p>§5.3.1 Unary operators, Section 3</p> <blockquote> <p>The result of the unary &amp; operator is a pointer to its operand. <strong>The operand shall be an lvalue</strong> or a qualified-id.</p> </blockquote> <p>What exactly does "shall be" mean in this context? Does it mean it's an error to take the address of a temporary? I was just wondering, because g++ only gives me a warning, whereas comeau refuses to compile the following program:</p> <pre><code>#include &lt;string&gt; int main() { &amp;std::string("test"); } </code></pre> <p>g++ <strong>warning</strong>: <code>taking address of temporary</code></p> <p>comeau <strong>error</strong>: <code>expression must be an lvalue or a function designator</code></p> <p>Does anyone have a Microsoft compiler or other compilers and can test this program, please?</p>
2,281,928
7
2
null
2010-02-17 12:51:24.327 UTC
11
2019-08-18 20:03:57.953 UTC
2019-08-18 20:03:57.953 UTC
null
1,839,439
null
252,000
null
1
33
c++|rvalue
36,902
<p>The word "shall" in the standard language means a strict requirement. So, yes, your code is ill-formed (it is an error) because it attempts to apply address-of operator to a non-lvalue.</p> <p>However, the problem here is not an attempt of taking address of a <em>temporary</em>. The problem is, again, taking address of a <em>non-lvalue</em>. Temporary object can be lvalue or non-lvalue depending on the expression that produces that temporary or provides access to that temporary. In your case you have <code>std::string("test")</code> - a functional style cast to a non-reference type, which by definition produces a non-lvalue. Hence the error.</p> <p>If you wished to take address of a temporary object, you could have worked around the restriction by doing this, for example</p> <pre><code>const std::string &amp;r = std::string("test"); &amp;r; // this expression produces address of a temporary </code></pre> <p>whith the resultant pointer remaining valid as long as the temporary exists. There are other ways to legally obtain address of a temporary object. It is just that your specific method happens to be illegal.</p>
1,504,797
php : echo"", print(), printf()
<p>Is there a better way to output data to html page with PHP?</p> <p>If I like to make a div with some var in php, I will write something like that</p> <pre><code>print ('&lt;div&gt;'.$var.'&lt;/div&gt;'); </code></pre> <p>or</p> <pre><code>echo "'&lt;div&gt;'.$var.'&lt;/div&gt;'"; </code></pre> <p>What is the proper way to do that?</p> <p>Or a better way, fill a <code>$tempvar</code> and print it once? like that:</p> <pre><code>$tempvar = '&lt;div&gt;'.$var.'&lt;/div&gt;' print ($tempvar); </code></pre> <p>In fact, in real life, the var will be fill with much more!</p>
1,504,813
8
2
null
2009-10-01 15:54:32.703 UTC
8
2017-04-11 07:16:02.807 UTC
2017-04-11 07:16:02.807 UTC
null
890,669
null
71,830
null
1
29
php|syntax
51,627
<p>There are 2 differences between <code>echo</code> and <code>print</code> in PHP:</p> <ul> <li><p><code>print</code> returns a value. It always returns 1.</p></li> <li><p><code>echo</code> can take a comma delimited list of arguments to output.</p></li> </ul> <p>Always returning 1 doesn't seem particularly useful. And a comma delimited list of arguments can be simulated with multiple calls or string concatenation. So the choice between <code>echo</code> and <code>print</code> pretty much comes down to style. Most PHP code that I've seen uses <code>echo</code>.</p> <p><code>printf()</code> is a direct analog of c's <code>printf()</code>. If you're comfortable in the c idiom, you might use <code>printf()</code>. A lot of people in the younger generation though, find <code>printf()</code>'s special character syntax to be less readable than the equivalent <code>echo</code> code.</p> <p>There are probably differences in performance between <code>echo</code>, <code>print</code> and <code>printf</code>, but I wouldn't get too hung up on them since in a database driven web application (PHP's typical domain), printing strings to the client is almost certainly not your bottleneck. The bottom line is that any of the 3 will get the job done and one is not better than another. It's just a matter of style. </p>
1,447,842
What happens if the meta tags are present in the document body?
<p>I am working on a ASP application and the code, template and files are organized in a way that does not allow me to alter anything outside the body tag. So I am thinking about inserting the meta tags inside the body -- like this:</p> <pre><code>&lt;!-- FEW ASP INCLUDES --&gt; &lt;html&gt; &lt;head&gt; &lt;!-- FALLBACK TITLE AND DESCRIPTION --&gt; &lt;title&gt;Default Title&lt;/title&gt; &lt;meta name="description" content="Default Description"&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- SOME HTML MARKUP --&gt; &lt;div class="dynamic-content"&gt; &lt;!-- InstanceBeginEditable name="dynamic-content" --&gt; &lt;!-- THIS IS WHERE I CAN WRITE ASP CODE --&gt; &lt;title&gt;&lt;%= Page.Meta.GetTitle( yada, yada ) %&gt;&lt;/title&gt; &lt;meta name="description" content="&lt;%= Page.Meta.GetDescription( yada, yada ) %&gt;"&gt; &lt;!-- InstanceEndEditable --&gt; &lt;/div&gt; &lt;!-- SOME MORE HTML MARKUP --&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I am wondering how good it is to put meta tags inside the body of an HTML document. How does it affect:</p> <ol> <li>search engines</li> <li>browsers</li> </ol>
1,447,933
9
0
null
2009-09-19 05:26:39.907 UTC
8
2019-01-18 05:32:06.223 UTC
null
null
null
null
87,015
null
1
69
html|templates|asp-classic|seo|meta-tags
90,304
<p>This is of course <strong>invalid</strong> as per HTML4.01. META tags are <a href="http://www.w3.org/TR/REC-html40/sgml/dtd.html#head.misc" rel="noreferrer">only allowed within HEAD</a> (just like, say, TITLE) so by putting it into a BODY, you're essentially creating an invalid markup.</p> <p>From the cursory tests, it seems that some browsers (e.g. Firefox 3.5 and Safari 4) actually put these elements into HEAD when creating a document tree. This is not very surprising: browsers are known to tolerate and try to interpret all kinds of broken markup.</p> <p>Having <strong>invalid markup is rarely a good idea</strong>. Non-standard handling by browsers might lead to various hard-to-pin rendering (and behavioral) inconsistencies. Instead of relying on browser guessing, it's best to follow a standard.</p> <p>I don't know how search engines react to such tag soup, but I wouldn't risk experimenting to find out :) Perhaps they only parse HEAD tag for certain information and will skip your BODY-contained tags altogether. Or maybe they consider these to be some malicious gambling attempts and black-list pages containing such markup. Who knows. </p> <p>The bottom line — avoid this whenever possible.</p>
2,189,098
embedding short python scripts inside a bash script
<p>I'd like to embed the text of short python scripts inside of a bash script, for use in say, my <code>.bash_profile</code>. What's the best way to go about doing such a thing?</p> <p>The solution I have so far is to call the python interpreter with the <code>-c</code> option, and tell the interpreter to <code>exec</code> whatever it reads from <code>stdin</code>. From there, I can build simple tools like the following, allowing me to process text for use in my interactive prompt:</p> <pre><code>function pyexec() { echo "$(/usr/bin/python -c 'import sys; exec sys.stdin.read()')" } function traildirs() { pyexec &lt;&lt;END trail=int('${1:-3}') import os home = os.path.abspath(os.environ['HOME']) cwd = os.environ['PWD'] if cwd.startswith(home): cwd = cwd.replace(home, '~', 1) parts = cwd.split('/') joined = os.path.join(*parts[-trail:]) if len(parts) &lt;= trail and not joined.startswith('~'): joined = '/'+joined print joined END } export PS1="\h [\$(traildirs 2)] % " </code></pre> <p>This approach smells slightly funny to me though, and I'm wondering what alternatives to doing it this way might be. </p> <p>My bash scripting skills are pretty rudimentary, so I'm particularly interested to hear if I'm doing something silly from the bash interpreter's perspective.</p>
2,189,118
9
4
null
2010-02-03 01:36:41.567 UTC
37
2019-05-17 12:28:59.053 UTC
null
null
null
null
196,970
null
1
70
python|bash
77,287
<p>The python interpreter accepts <code>-</code> on the command line as a synonym for <code>stdin</code> so you can replace the calls to pyexec with:</p> <pre><code>python - &lt;&lt;END </code></pre> <p>See command line reference <a href="http://docs.python.org/using/cmdline.html#command-line" rel="noreferrer">here</a>.</p>
1,676,012
Should I be obfuscating database IDs from my users?
<p>I'm being told that I shouldn't be using database IDs directly in HTML code in web applications.</p> <p>Currently I use the IDs on things like table row IDs (tableRow-454 where 454 is the ID of the row in the DB), in hidden or selects fields in forms or in URLs. (I'm not referring to telling people visually on a page that they are ####.)</p> <p>The recommendation I was given was to use some math to obfuscate the ID from the user. I'm thinking this will only make things more complicated and add unnecessary complexity. But I can see some good reasons to make it more difficult to determine a database ID from the HTML.</p> <p>Do you obfuscate the IDs from the user? Or do you care?</p>
1,676,031
12
0
null
2009-11-04 19:22:24.82 UTC
3
2009-11-07 18:18:41.017 UTC
2009-11-07 17:42:00.407 UTC
null
5,441
null
5,441
null
1
31
database|obfuscation
6,992
<p>No, you're just making extra work for yourself.</p> <p>As long as you're doing enough testing that changing an ID here or there won't give the users access to something they shouldn't then you're fine having the IDs visible.</p> <p>In some situations it can be beneficial to hide them or have non-sequential numbers, or maybe not starting counting from zero. For example if someone got order number 3 they might start asking questions...</p>
2,276,200
Changing default encoding of Python?
<p>I have many "can't encode" and "can't decode" problems with <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="noreferrer">Python</a> when I run my applications from the console. But in the <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29" rel="noreferrer">Eclipse</a> <a href="http://en.wikipedia.org/wiki/PyDev" rel="noreferrer">PyDev</a> IDE, the default character encoding is set to <a href="http://en.wikipedia.org/wiki/UTF-8" rel="noreferrer">UTF-8</a>, and I'm fine.</p> <p>I searched around for setting the default encoding, and people say that Python deletes the <code>sys.setdefaultencoding</code> function on startup, and we can not use it.</p> <p>So what's the best solution for it?</p>
17,628,350
13
2
null
2010-02-16 20:46:28.627 UTC
82
2022-08-14 20:07:03.27 UTC
2014-11-11 18:45:57.86 UTC
null
63,550
null
233,535
null
1
171
python|encoding|utf-8|console
361,720
<p>Here is a simpler method (hack) that gives you back the <code>setdefaultencoding()</code> function that was deleted from <code>sys</code>:</p> <pre><code>import sys # sys.setdefaultencoding() does not exist, here! reload(sys) # Reload does the trick! sys.setdefaultencoding('UTF8') </code></pre> <p>(Note for Python 3.4+: <code>reload()</code> is in the <code>importlib</code> library.)</p> <p><strong>This is not a safe thing to do</strong>, though: this is obviously a hack, since <code>sys.setdefaultencoding()</code> is purposely removed from <code>sys</code> when Python starts. Reenabling it and changing the default encoding <a href="https://anonbadger.wordpress.com/2015/06/16/why-sys-setdefaultencoding-will-break-code/" rel="nofollow noreferrer">can break code that relies on ASCII being the default</a> (this code can be third-party, which would generally make fixing it impossible or dangerous).</p> <p>PS: This hack doesn't seem to work with Python 3.9 anymore.</p>