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
40,972,594
How to find all possible subarrays of an array?
<p>Let's suppose I am given an array; <code>A[] = {1,2,3}</code> and I want to find all the sub-arrays of this array. The answer should be</p> <pre><code>{1} {1,2} {1,2,3} {2} {2,3} {3} </code></pre> <p>How to find all possible subarrays of an array efficiently?</p>
41,010,266
5
0
null
2016-12-05 10:55:06.427 UTC
1
2022-01-18 15:55:51.893 UTC
2022-01-18 15:55:51.893 UTC
null
1,447,978
null
6,714,430
null
1
8
arrays|data-structures
43,070
<p>Subarray of an array A is <code>A[i..j]</code> where <code>0 &lt;= i &lt;= j &lt; n</code> where n is length of array.</p> <p>In C language it can be calculated like this:</p> <pre><code>#include &lt;stdio.h&gt; int main(){ int A[] = {1,2,3,4,5}; int len=sizeof(A)/sizeof(int); for( int i=0; i&lt;len; i++ ){ for( int j=i; j&lt;len; j++ ){ // Now A[i..j] is the subarray for( int k=i; k&lt;=j; k++ ) printf("%d ", A[k]); printf("\n"); } } return 0; } </code></pre>
38,121,454
How to mock react-router context
<p>I've got fairly simple react component (Link wrapper which adds 'active' class if route is active):</p> <pre><code>import React, { PropTypes } from 'react'; import { Link } from 'react-router'; const NavLink = (props, context) =&gt; { const isActive = context.router.isActive(props.to, true); const activeClass = isActive ? 'active' : ''; return ( &lt;li className={activeClass}&gt; &lt;Link {...props}&gt;{props.children}&lt;/Link&gt; &lt;/li&gt; ); } NavLink.contextTypes = { router: PropTypes.object, }; NavLink.propTypes = { children: PropTypes.node, to: PropTypes.string, }; export default NavLink; </code></pre> <p>How am I supposed to test it? My only attempt was:</p> <pre><code>import NavLink from '../index'; import expect from 'expect'; import { mount } from 'enzyme'; import React from 'react'; describe('&lt;NavLink /&gt;', () =&gt; { it('should add active class', () =&gt; { const renderedComponent = mount(&lt;NavLink to="/home" /&gt;, { router: { pathname: '/home' } }); expect(renderedComponent.hasClass('active')).toEqual(true); }); }); </code></pre> <p>It doesn't work and returns <code>TypeError: Cannot read property 'isActive' of undefined</code>. It definitely needs some router mocking, but I have no idea how to write it.</p>
38,122,471
4
0
null
2016-06-30 11:12:40.967 UTC
8
2017-09-06 13:17:08.447 UTC
null
null
null
null
2,041,318
null
1
31
reactjs|react-router|enzyme
26,905
<p>Thanks @Elon Szopos for your answer but I manage to write something much more simple (following <a href="https://github.com/airbnb/enzyme/pull/62">https://github.com/airbnb/enzyme/pull/62</a>):</p> <pre><code>import NavLink from '../index'; import expect from 'expect'; import { shallow } from 'enzyme'; import React from 'react'; describe('&lt;NavLink /&gt;', () =&gt; { it('should add active class', () =&gt; { const context = { router: { isActive: (a, b) =&gt; true } }; const renderedComponent = shallow(&lt;NavLink to="/home" /&gt;, { context }); expect(renderedComponent.hasClass('active')).toEqual(true); }); }); </code></pre> <p>I have to change <code>mount</code> to <code>shallow</code> in order not to evaluate <code>Link</code> which gives me an error connected with the react-router <code>TypeError: router.createHref is not a function</code>.</p> <p>I would rather have "real" react-router than just an object but I have no idea how to create it.</p>
30,575,293
CoordinatorLayout: Hiding/Showing half visible toolbar?
<p>Id like to achieve a similar effect as the one you can see in <strong>Google Play store</strong>, where by scrolling the content the <code>Toolbar</code> goes off-screen as you scroll. </p> <p>This works fine with the <code>CoordinatorLayout</code> (<a href="http://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.html" rel="noreferrer">1</a>) introduced at <strong>#io15</strong>, however: If you stop the scroll "mid-way" the Toolbar remains on screen, but is cut in half: I want it to animate off-screen, just like in the Google Play store. <strong>How can I achieve that?</strong> </p>
33,182,883
3
0
null
2015-06-01 13:49:16.463 UTC
12
2015-10-17 04:53:42.77 UTC
null
null
null
null
2,279,862
null
1
10
android|android-toolbar
2,862
<p>Now the Android Support Library 23.1.0 has a new scroll flag <code>SCROLL_FLAG_SNAP</code> which allows you to achieve this effect.</p> <blockquote> <p>AppBarLayout supports a number of scroll flags which affect how children views react to scrolling (e.g. scrolling off the screen). New to this release is SCROLL_FLAG_SNAP, ensuring that when scrolling ends, the view is not left partially visible. Instead, it will be scrolled to its nearest edge, making fully visible or scrolled completely off the screen.</p> </blockquote>
49,182,862
Preset files are not allowed to export objects
<p>I have a carousel file in which I want to get <code>index.js</code> and build <code>block.build.js</code>, so my <code>webpack.config.js</code> is:</p> <pre class="lang-js prettyprint-override"><code>var config = { entry: './index.js', output: { path: __dirname, filename: 'block.build.js', }, devServer: { contentBase: './Carousel' }, module : { rules : [ { test: /.js$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['react', 'es2015'], plugins: ['transform-class-properties'] } } ] } }; module.exports = config; </code></pre> <p>The <code>package.json</code> which I use is below:</p> <pre class="lang-json prettyprint-override"><code>{ "name": "carousel", "version": "1.0.0", "description": "", "main": "webpack.config.js", "dependencies": { "@babel/core": "^7.0.0-beta.40", "babel-cli": "^6.26.0", "babel-loader": "^8.0.0-beta.0", "babel-plugin-lodash": "^3.3.2", "babel-plugin-react-transform": "^3.0.0", "babel-preset-react": "^6.24.1", "cross-env": "^5.1.3", "lodash": "^4.17.5", "react": "^16.2.0", "react-dom": "^16.2.0", "react-swipeable": "^4.2.0", "styled-components": "^3.2.1" }, "scripts": { "test": "echo \"Error: no test specified\" &amp;&amp; exit 1", "watch": "webpack --watch", "start": "webpack-dev-server --open", "build": "webpack" }, "devDependencies": { "webpack": "^4.1.1", "webpack-cli": "^2.0.10", "webpack-dev-server": "^3.1.0" }, "author": "brad traversy", "license": "ISC" } </code></pre> <p>&hellip; but I get this error message:</p> <pre class="lang-none prettyprint-override"><code>ERROR in ./index.js Module build failed: Error: Plugin/Preset files are not allowed to export objects, only functions. </code></pre> <p>Does anyone know how to solve this?</p>
49,183,337
12
1
null
2018-03-08 21:35:15.79 UTC
19
2021-12-29 18:23:46.893 UTC
2019-06-05 13:49:01.273 UTC
null
3,427,252
null
6,485,567
null
1
121
reactjs|webpack|babeljs
135,861
<p>You're using a combination of Babel 6 and Babel 7. There is no guarantee of compatibility across versions:</p> <pre><code>"@babel/core": "^7.0.0-beta.40", "babel-cli": "^6.26.0", "babel-loader": "^8.0.0-beta.0", "babel-plugin-lodash": "^3.3.2", "babel-plugin-react-transform": "^3.0.0", "babel-preset-react": "^6.24.1", </code></pre> <p>should be</p> <pre><code>"@babel/core": "^7.0.0-beta.40", "@babel/cli": "^7.0.0-beta.40", "babel-loader": "^8.0.0-beta.0", "babel-plugin-lodash": "^3.3.2", "babel-plugin-react-transform": "^3.0.0", "@babel/preset-react": "^7.0.0-beta.40", </code></pre> <p>and</p> <pre><code> query: { presets: ['react', 'es2015'], plugins: ['transform-class-properties'] } </code></pre> <p>would be</p> <pre><code> query: { presets: ['@babel/react', '@babel/es2015'], plugins: ['@babel/proposal-class-properties'] } </code></pre> <p>I'm also confused because you didn't mention <code>@babel/proposal-class-properties</code> in your <code>package.json</code>, but assuming it is in there it should also be updated.</p>
21,422,782
Prevent git from popping up gnome password box
<p>I have not asked a question of this nature before, so this may not be the correct site for this.</p> <p>I use the xfce terminal in drop-down mode connected to a hotkey. It closes when another window becomes active, which is just fine. What is not fine, however, is that when I use git and have it pull or push to an https url, it pops up a fun box to ask me for my password instead of just letting me enter it directly on the command line.</p> <p>Normally I would google around to find the answer to this, but sadly most people are trying to get git to stop asking for a password altogether rather than prevent a dialog box, so this is hard for me to google (trust me; I've tried for a couple months now on and off when I get annoyed enough).</p> <p>How can I prevent git from popping up any graphical windows for things like passwords? Git says that it is using <code>/usr/lib/seahorse/seahorse-ssh-askpass</code> for asking the password, so if there is some configuration option to prevent it from using that (or that has an equivalent effect), that would be great.</p> <p>Thanks very much for any help.</p>
21,423,400
2
1
null
2014-01-29 05:23:24.613 UTC
6
2017-06-02 21:37:17 UTC
null
null
null
null
1,124,529
null
1
29
linux|git|https|passwords|gnome
11,163
<p>It seems like git is probably using the <code>GIT_ASKPASS</code> or <code>SSH_ASKPASS</code> environment variables to figure out if it should use a separate program to prompt for passwords.</p> <p>Try running <code>unset GIT_ASKPASS</code> or <code>unset SSH_ASKPASS</code>. Now try pushing or pulling from a git repository. If that works, add the appropriate command to <code>.bashrc</code>, <code>.zshrc</code>, or whatever file you use to run a command when your shell starts.</p> <p>You can also override the value of git's <code>core.askpass</code> setting with <code>git config --global core.askpass YOUR_PREFERRED_PROMPT_COMMAND</code>.</p> <p><strong>Relevant information from the <a href="http://git-scm.com/docs/git-config" rel="noreferrer">git-config man page</a>:</strong></p> <blockquote> <p>core.askpass</p> <p>Some commands (e.g. svn and http interfaces) that interactively ask for a password can be told to use an external program given via the value of this variable. Can be overridden by the GIT_ASKPASS environment variable. If not set, fall back to the value of the SSH_ASKPASS environment variable or, failing that, a simple password prompt. The external program shall be given a suitable prompt as command line argument and write the password on its STDOUT.</p> </blockquote> <p><strong>Original source:</strong> <a href="http://kartzontech.blogspot.com/2011/04/how-to-disable-gnome-ssh-askpass.html" rel="noreferrer">http://kartzontech.blogspot.com/2011/04/how-to-disable-gnome-ssh-askpass.html</a></p>
9,510,359
Set size of HTML page and browser window
<p>I have a div element with ID="container". I want to set this element to be the size of the viewable area in the browser window. I am using the following JS to do so.</p> <pre><code>var container= document.getElementById("container"); container.style.height=(window.innerHeight); container.style.width=window.innerWidth; </code></pre> <p>However, the browser window size is larger than the viewable size and horizontal and vertical scroll bars appear. How do I make it so that my HTML page fits into the browser window without a need for scroll bars?</p> <p>EDIT:</p> <p>I am basically asking, how can I make the document size the same as the viewport size?</p>
9,511,244
5
0
null
2012-03-01 03:48:42.037 UTC
4
2022-03-10 12:17:54.567 UTC
2012-03-01 05:07:42.043 UTC
null
106,224
null
1,190,419
null
1
14
html|css|resize|scrollbar
308,819
<p>This should work.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Hello World&lt;/title&gt; &lt;style&gt; html, body { width: 100%; height: 100%; margin: 0; padding: 0; background-color: green; } #container { width: inherit; height: inherit; margin: 0; padding: 0; background-color: pink; } h1 { margin: 0; padding: 0; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="container"&gt; &lt;h1&gt;Hello World&lt;/h1&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The background colors are there so you can see how this works. Copy this code to a file and open it in your browser. Try playing around with the CSS a bit and see what happens.</p> <p>The <code>width: inherit; height: inherit;</code> pulls the width and height from the parent element. This <em>should</em> be the default and is not truly necessary.</p> <p>Try removing the <code>h1 { ... }</code> CSS block and see what happens. You might notice the layout reacts in an odd way. This is because the <code>h1</code> element is influencing the layout of its container. You could prevent this by declaring <code>overflow: hidden;</code> on the container or the body.</p> <p>I'd also suggest you do some reading on the <a href="http://goo.gl/JBh2j" rel="noreferrer">CSS Box Model</a>.</p>
9,402,924
how to load view into another view codeigniter 2.1?
<p>Ive been working with CI and I saw on the website of CI you can load a view as a variable part of the data you send to the "main" view, so, according the site (that says a lot of things, and many are not like they say ...ej pagination and others) i did something like this</p> <pre><code>$data['menu'] = $this-&gt;load-&gt;view('menu'); $this-&gt;load-&gt;view ('home',data); </code></pre> <p>the result of this is that I get an echo of the menu in the top of the site (before starts my body and all) and where should be its nothing, like if were printed before everything... I have no idea honestly of this problem, did anybody had the same problem before?</p>
9,403,558
2
0
null
2012-02-22 21:02:04.41 UTC
19
2014-03-11 12:31:21.757 UTC
null
null
null
null
1,143,482
null
1
25
codeigniter|view|load
36,269
<p>Two ways of doing this:</p> <ol> <li><p>Load it in advance (like you're doing) and pass to the other view</p> <pre><code>&lt;?php // the "TRUE" argument tells it to return the content, rather than display it immediately $data['menu'] = $this-&gt;load-&gt;view('menu', NULL, TRUE); $this-&gt;load-&gt;view ('home', $data); </code></pre></li> <li><p>Load a view "from within" a view:</p> <pre><code>&lt;?php // put this in the controller $this-&gt;load-&gt;view('home'); // put this in /application/views/home.php $this-&gt;view('menu'); echo 'Other home content'; </code></pre></li> </ol>
30,129,486
Set img src from Byte Array
<p>I need to set the <code>img src</code> property from a byte array that I have in a Object.</p> <pre><code>&lt;img id="profileImage"&gt; &lt;spring:bind path="object.profilePicture"&gt; &lt;input type="file" name="profilePicture" id="profilePicture" path="profilePicture"&gt; &lt;/spring:bind&gt; </code></pre> <p>I need to display that byte array in the <code>img</code> above the input tag.</p>
30,130,095
3
3
null
2015-05-08 17:23:36.917 UTC
2
2019-01-24 19:05:32.977 UTC
2015-05-08 17:53:54.633 UTC
null
1,408,143
null
4,709,823
null
1
15
java|javascript|html|image|jsp
57,986
<p>Replace the <code>jpg</code> with the type of image, and <code>[your byte array]</code> with your <code>byte array</code>. You need to convert it to <code>base64</code> if it isn't already. </p> <pre><code>&lt;img id="profileImage" src="data:image/jpg;base64, [your byte array]"&gt; </code></pre>
30,874,676
How to get Mocha to fail a test
<p>I have the following test:</p> <pre><code>it.only('validation should fail', function(done) { var body = { title: "dffdasfsdfsdafddfsadsa", description: "Postman Description", beginDate: now.add(3, 'd').format(), endDate: now.add(4, 'd').format() } var rules = eventsValidation.eventCreationRules(); var valMessages = eventsValidation.eventCreationMessages(); indicative .validateAll(rules, body, valMessages) .then(function(data) { console.log("SHOULD NOT GET HERE"); should.fail("should not get here"); done(); }) .catch(function(error) { console.log("SHOULD GET HERE"); console.log(error); }); done(); }); </code></pre> <p>The test execution path is correct. When I have validating data, it goes to "SHOULD NOT GET HERE". The test is really to make sure it doesn't. And when I put in non validating data the code does go to "SHOULD GET HERE". So the validation rules work.</p> <p>What I'm trying to do is make sure the test fails when when I have bad validation data and it validates. However when I run it as it is with good data it validates, runs the fail, but mocha still marks it as the passing. I want it to fail if the execution gets to "SHOULD NOT GET HERE". </p> <p>I've tried throw new Error("fail"); as well with no luck. In both cases it actually seems to run the code in the .catch block as well.</p> <p>Any suggestions? I found solutions for this in a <a href="https://stackoverflow.com/questions/14879181/force-mocha-test-to-fail">similar question</a>. This question is written because those solutions don't seem to be working for me.</p>
30,874,811
4
2
null
2015-06-16 17:50:25.82 UTC
9
2020-11-11 01:17:55.1 UTC
2017-08-08 06:37:50.147 UTC
null
2,311,366
null
4,211,297
null
1
46
javascript|node.js|mocha.js
43,799
<p>Use <code>chai-as-promised</code>, with native Mocha promise handlers.</p> <pre class="lang-js prettyprint-override"><code>var chai = require('chai').use(require('chai-as-promised')); var should = chai.should(); // This will enable .should for promise assertions </code></pre> <p>You no longer need <code>done</code>, simply return the promise.</p> <pre class="lang-js prettyprint-override"><code>// Remove `done` from the line below it.only('validation should fail', function(/* done */) { var body = { title: "dffdasfsdfsdafddfsadsa", description: "Postman Description", beginDate: now.add(3, 'd').format(), endDate: now.add(4, 'd').format() } var rules = eventsValidation.eventCreationRules(); var valMessages = eventsValidation.eventCreationMessages(); // Return the promise return indicative .validateAll(rules, body, valMessages) .should.be.rejected; // The test will pass only if the promise is rejected // Remove done, we no longer need it // done(); }); </code></pre>
10,456,581
undefined reference to symbol even when nm indicates that this symbol is present in the shared library
<p>What could be wrong here? I have the following simple class:</p> <pre><code>#include "libmnl/libmnl.h" int main() { struct mnl_socket *a = mnl_socket_open(12); } </code></pre> <p>And after running a simple <code>gcc</code> compile (<code>gcc -lmnl main.c</code>) I get the following errors:</p> <pre><code>/tmp/cch3GjuS.o: In function `main': main.c:(.text+0xe): undefined reference to `mnl_socket_open' collect2: ld returned 1 exit status </code></pre> <p>Running nm on the shared library shows that it's actually found:</p> <pre><code>aatteka@aatteka-Dell1:/tmp$ nm -D /usr/lib/libmnl.so | grep mnl_socket_open 0000000000001810 T mnl_socket_open </code></pre> <p>This is happening on Ubuntu 12.04. The <em>libmnl-dev</em> and <em>libmnl0</em> packages are installed. The <code>strace</code> output of <code>gcc</code> indicates that <code>ld</code> is using exactly that *.so file:</p> <pre><code>[pid 10988] stat("/usr/lib/gcc/x86_64-linux-gnu/4.6/libmnl.so", 0x7fff2a39b470) = -1 ENOENT (No such file or directory) [pid 10988] open("/usr/lib/gcc/x86_64-linux-gnu/4.6/libmnl.so", O_RDONLY) = -1 ENOENT (No such file or directory) [pid 10988] stat("/usr/lib/gcc/x86_64-linux-gnu/4.6/libmnl.a", 0x7fff2a39b4d0) = -1 ENOENT (No such file or directory) [pid 10988] open("/usr/lib/gcc/x86_64-linux-gnu/4.6/libmnl.a", O_RDONLY) = -1 ENOENT (No such file or directory) [pid 10988] stat("/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/libmnl.so", 0x7fff2a39b470) = -1 ENOENT (No such file or directory) [pid 10988] open("/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/libmnl.so", O_RDONLY) = -1 ENOENT (No such file or directory) [pid 10988] stat("/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/libmnl.a", 0x7fff2a39b4d0) = -1 ENOENT (No such file or directory) [pid 10988] open("/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/libmnl.a", O_RDONLY) = -1 ENOENT (No such file or directory) [pid 10988] stat("/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../lib/libmnl.so", {st_mode=S_IFREG|0644, st_size=18608, ...}) = 0 [pid 10988] open("/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../../lib/libmnl.so", O_RDONLY) = 7 </code></pre>
10,456,630
1
1
null
2012-05-04 21:50:58.143 UTC
6
2013-11-07 15:11:54.19 UTC
2013-11-07 15:11:54.19 UTC
null
447,015
null
1,730,237
null
1
31
linux|gcc|linker|shared-libraries
16,629
<p>Libraries must be listed after the objects that use them (more precisely, a library will be used only if it contains a symbol that satisfies an undefined reference known at the time it is encountered). Move the <code>-lmnl</code> to the end of the command.</p>
57,941,342
Button can't be clicked while keyboard is visible - react native
<p>I have an textInput and a button. While the textInput is focused, the keyboard comes up but if you tap the button with keyboard visible, first the keyboard disappears and then only you can tap button. Why is it? How can I make it work so that the button can be tapped with keyboard visible? The apps developed in android studio (android native) can get the click listener with keyboard visible. But in react native, it is not working. If you tap anywhere but button, then the keyboard should disappear, isn't it? But if you tap on the button with keyboard visible, the btn should receive the listener. I'm testing it in android devices.</p> <p>P.S you can try it here: <a href="https://snack.expo.io/@codebyte99/addcomponents" rel="noreferrer">https://snack.expo.io/@codebyte99/addcomponents</a></p> <pre><code>&lt;TextInput placeholder={'Type smth'} style={[{ borderBottomColor: 'gray', borderBottomWidth: 1 }]} /&gt; &lt;TouchableOpacity onPress={() =&gt; { this._onPressOut(); }}&gt; &lt;Text&gt;click here&lt;/Text&gt; &lt;/TouchableOpacity&gt; </code></pre>
57,941,568
3
0
null
2019-09-15 05:12:18.253 UTC
6
2020-12-30 12:56:18.087 UTC
null
null
null
null
4,947,216
null
1
35
react-native
13,997
<p>The scrollview contains a prop <code>keyboardShouldPersistTaps</code> which handles the keyboard tap behaviour inside a scrollview.</p> <p>For your case give it as <code>&lt;ScrollView keyboardShouldPersistTaps='handled'&gt;</code></p> <p>Here is a expo link <a href="https://snack.expo.io/@karthik.01/addcomponents" rel="noreferrer">scrollview with keyboard</a></p>
7,424,519
Using VisualVM to connect to a remote jstatd instance through a firewall
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1609961/visualvm-over-ssh">VisualVM over ssh</a> </p> </blockquote> <p>I'm writing this question and answering it because I spent a few hours getting this to work today and no answer I found on here worked for me. Hopefully this is helpful for others. If you have another solution than the one I ended up using, please feel free to answer the question as well. If yours is better I'll accept yours instead.</p> <p>The problem: I'm trying to monitor some home made java applications on my FreeBSD server (this should apply to Linux servers as well) using VisualVM and jstatd, but I can't get VisualVM to list the processes on the server even after I forwarded the assigned and random jstatd ports in my firewall and can see a connection being made using sockstat.</p>
7,424,527
2
0
null
2011-09-15 00:18:19.82 UTC
11
2012-02-25 13:52:53.09 UTC
2017-05-23 12:16:40.297 UTC
null
-1
null
299,262
null
1
21
java|linux|freebsd
39,058
<p>Instead of creating a firewall rule every time I run jstatd (because it annoyingly chooses a new random port each time), I got it to work with SSH tunnels.</p> <p>First I ran jstatd on the server to find which ports I needed to tunnel. That is done by (in my case) first creating a policy file called tools.policy with the following contents:</p> <pre><code>grant codebase "file:${java.home}/../lib/tools.jar" { permission java.security.AllPermission; }; </code></pre> <p>Then running the following command: <code>jstatd -J-Djava.security.policy=tools.policy</code></p> <p>Then I determined the random port jstatd was using by running <code>sockstat | grep jstat</code> (may need to use <code>netstat</code> instead on Linux, I'm not sure).</p> <p>Then lets say the random port is 55663, I created two SSH tunnels on my local machine, one for the standard jstatd port 1099 and the other for 55663 by running the following commands in two terminal windows (haven't done this on Windows, but I'm pretty sure putty can do it):</p> <p><code>ssh -L 1099:localhost:1099 login_name@host_name</code></p> <p><code>ssh -L 55663:localhost:55663 login_name@host_name</code></p> <p>Once the two tunnels were open, I opened VisualVM and right clicked on the "Local" machine on the left side and chose "Add jstatd Connection". I clicked the "Add Default" button on the right and made sure the port was set to 1099. I hit the "OK" button to save it and immediately saw my remote Java processes show up in the "Local" section.</p>
32,040,396
How to use ES6 Fat Arrow to .filter() an array of objects
<p>I'm trying to use ES6 arrow function with <code>.filter</code> to return adults (Jack &amp; Jill). It appears I cannot use an if statement. </p> <p>What do I need to know in order to do this in ES6?</p> <pre><code>var family = [{"name":"Jack", "age": 26}, {"name":"Jill", "age": 22}, {"name":"James", "age": 5 }, {"name":"Jenny", "age": 2 }]; let adults = family.filter(person =&gt; if (person.age &gt; 18) person); // throws error (8:37) SyntaxError: unknown: Unexpected token (8:37) |let adults = family.filter(person =&gt; if (person.age &gt; 18) person); </code></pre> <p>My working ES5 example:</p> <pre><code>let adults2 = family.filter(function (person) { if (person.age &gt; 18) { return person; } }); </code></pre>
32,040,486
6
1
null
2015-08-16 22:05:40.73 UTC
42
2022-07-28 14:11:51.697 UTC
2015-08-16 22:09:54.903 UTC
null
1,332,608
null
1,332,608
null
1
161
javascript|ecmascript-6|higher-order-functions
254,603
<blockquote> <p>It appears I cannot use an if statement.</p> </blockquote> <p>Arrow functions either allow to use an <strong>expression</strong> <em>or</em> a <strong>block</strong> as their body. Passing an expression</p> <pre><code>foo =&gt; bar </code></pre> <p>is equivalent to the following block</p> <pre><code>foo =&gt; { return bar; } </code></pre> <p>However, </p> <pre><code>if (person.age &gt; 18) person </code></pre> <p>is not an expression, <code>if</code> is a statement. Hence you would have to use a block, if you wanted to use <code>if</code> in an arrow function:</p> <pre><code>foo =&gt; { if (person.age &gt; 18) return person; } </code></pre> <hr> <p>While that technically solves the problem, this a confusing use of <code>.filter</code>, because it suggests that you have to return the value that should be contained in the output array. However, the callback passed to <code>.filter</code> should return a <em>Boolean</em>, i.e. <code>true</code> or <code>false</code>, indicating whether the element should be included in the new array or not.</p> <p>So all you need is</p> <pre><code>family.filter(person =&gt; person.age &gt; 18); </code></pre> <p>In ES5:</p> <pre><code>family.filter(function (person) { return person.age &gt; 18; }); </code></pre>
31,771,194
How to freeze the =today() function once data has been entered
<p>I would like to use the =TODAY() function in a table in excel. However, once data has been entered into that table row, I would like it never to change dates again (effectively capturing the date the row's data was added). </p> <p>This will be used on every row in the table, so as data is entered into the table down the rows, each date will be captured.</p> <p>Is this possible, how do I do it?</p> <p>EDIT - pnuts it is not the same as <a href="https://stackoverflow.com/questions/29032063/insert-todays-date-with-button-as-date-not-function" title="this">this</a> question. I do not want to use a button, rather a cell formula.</p>
31,771,724
2
1
null
2015-08-02 11:01:36.473 UTC
3
2018-12-27 11:32:20.11 UTC
2017-05-23 11:54:07.933 UTC
null
-1
null
4,827,818
null
1
9
excel|excel-formula
98,548
<p>Rather than entering the formula</p> <pre><code>=TODAY() </code></pre> <p>touch <kbd>Ctrl</kbd> + <kbd>;</kbd></p> <p>instead. This will put a "frozen" date in the cell.</p>
32,122,586
CURL escape single quote
<p>How can I make this work?</p> <pre><code>curl -XPOST 'http://localhost:9290/location/place' -d '{"geoloc": {"lat": "38.1899", "lon": "-76.5087"}, "longitude": "-76.5087", "admin_name1": "Maryland", "admin_name2": "St. Mary's", "admin_name3": "", "postal_code": "20692", "admin_code3": "", "country_code": "US", "admin_code1": "MD", "latitude": "38.1899", "admin_code2": "037", "accuracy": null, "place_name": "Valley Lee"}' </code></pre> <p>The <code>'</code> in <code>Mary's</code> is causing this to fail. I am running it from a file like <code>cat curl-cmd.txt | sh</code> but it won't work from the command line either. I've tried using <code>\'</code> and <code>\\'</code> and <code>\u0027</code> (the unicode <code>'</code>)</p> <p>I'm stuck</p>
39,802,572
2
2
null
2015-08-20 15:40:33.507 UTC
18
2020-05-19 12:44:07.53 UTC
2017-11-23 11:05:27.157 UTC
null
4,279,440
null
1,022,260
null
1
56
bash|shell|curl|elasticsearch
91,000
<p>I had the same problem. The simplest solution is to escape the apostrophe with a backslash in addition to wrapping it in a set of single quotes. <code>'\''</code></p> <p>For your use case, change <code>Mary's</code> to <code>Mary'\''s</code> and it should work.</p> <pre><code>curl -XPOST 'http://localhost:9290/location/place' -d '{"geoloc": {"lat": "38.1899", "lon": "-76.5087"}, "longitude": "-76.5087", "admin_name1": "Maryland", "admin_name2": "St. Mary'\''s", "admin_name3": "", "postal_code": "20692", "admin_code3": "", "country_code": "US", "admin_code1": "MD", "latitude": "38.1899", "admin_code2": "037", "accuracy": null, "place_name": "Valley Lee"}' </code></pre> <blockquote> <p>An alternate approach is to wrap the POST data (<code>-d</code>) in double quotes while escaping all nested occurrences of double quotes in the JSON string with a backslash.</p> </blockquote> <pre><code>curl -XPOST 'http://localhost:9290/location/place' -d "{\"geoloc\": {\"lat\": \"38.1899\", \"lon\": \"-76.5087\"}, \"longitude\": \"-76.5087\", \"admin_name1\": \"Maryland\", \"admin_name2\": \"St. Mary's\", \"admin_name3\": \"\", \"postal_code\": \"20692\", \"admin_code3\": \"\", \"country_code\": \"US\", \"admin_code1\": \"MD\", \"latitude\": \"38.1899\", \"admin_code2\": \"037\", \"accuracy\": null, \"place_name\": \"Valley Lee\"}" </code></pre>
18,920,614
Plot cross section through heat map
<p>I have an array of shape(201,201), I would like to plot some cross sections through the data, but I am having trouble accessing the relevant points. For example say I want to plot the cross section given by the line in the figure produced by,</p> <pre><code>from pylab import * Z = randn(201,201) x = linspace(-1,1,201) X,Y = meshgrid(x,x) pcolormesh(X,Y,Z) plot(x,x*.5) </code></pre> <p>I'd like to plot these at various orientations but they will always pass through the origin if that helps...</p>
18,921,524
1
1
null
2013-09-20 15:35:16.593 UTC
8
2014-07-22 07:28:53.973 UTC
2014-07-22 07:28:53.973 UTC
null
553,095
null
1,331,107
null
1
7
python|numpy|matplotlib
6,767
<p>Basically, you want to interpolate a 2D grid along a line (or an arbitrary path).</p> <p>First off, you should decide if you want to interpolate the grid or just do nearest-neighbor sampling. If you'd like to do the latter, you can just use indexing.</p> <p>If you'd like to interpolate, have a look at <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.interpolation.map_coordinates.html" rel="noreferrer"><code>scipy.ndimage.map_coordinates</code></a>. It's a bit hard to wrap your head around at first, but it's perfect for this. (It's much, much more efficient than using an interpolation routine that assumes that the data points are randomly distributed.)</p> <p>I'll give an example of both. These are adapted from an <a href="https://stackoverflow.com/a/7880726/325565">answer I gave to another question.</a> However, in those examples, everything is plotted in "pixel" (i.e. row, column) coordinates.</p> <p>In your case, you're working in a different coordinate system than the "pixel" coordinates, so you'll need to convert from "world" (i.e. x, y) coordinates to "pixel" coordinates for the interpolation.</p> <p>First off, here's an example of using cubic interpolation with <code>map_coordinates</code>:</p> <pre><code>import numpy as np import scipy.ndimage import matplotlib.pyplot as plt # Generate some data... x, y = np.mgrid[-5:5:0.1, -5:5:0.1] z = np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2) # Coordinates of the line we'd like to sample along line = [(-3, -1), (4, 3)] # Convert the line to pixel/index coordinates x_world, y_world = np.array(zip(*line)) col = z.shape[1] * (x_world - x.min()) / x.ptp() row = z.shape[0] * (y_world - y.min()) / y.ptp() # Interpolate the line at "num" points... num = 1000 row, col = [np.linspace(item[0], item[1], num) for item in [row, col]] # Extract the values along the line, using cubic interpolation zi = scipy.ndimage.map_coordinates(z, np.vstack((row, col))) # Plot... fig, axes = plt.subplots(nrows=2) axes[0].pcolormesh(x, y, z) axes[0].plot(x_world, y_world, 'ro-') axes[0].axis('image') axes[1].plot(zi) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/a1YDO.png" alt="enter image description here"></p> <p>Alternately, we could use nearest-neighbor interpolation. One way to do this would be to pass <code>order=0</code> to <code>map_coordinates</code> in the example above. Instead, I'll use indexing just to show another approach. If we just change the line</p> <pre><code># Extract the values along the line, using cubic interpolation zi = scipy.ndimage.map_coordinates(z, np.vstack((row, col))) </code></pre> <p>To:</p> <pre><code># Extract the values along the line, using nearest-neighbor interpolation zi = z[row.astype(int), col.astype(int)] </code></pre> <p>We'll get:</p> <p><img src="https://i.stack.imgur.com/VYlgR.png" alt="enter image description here"></p>
37,969,332
How to get last inserted id in Laravel?
<p>Here is my code</p> <pre><code> $users = DB::table('users')-&gt;insert(array( 'email_id' =&gt; $email_id, 'name' =&gt; $name, )); $lastInsertedID = $users-&gt;lastInsertId(); return $lastInsertedID; </code></pre> <p>I want to get last inserted id for particular record. I have tried using Eloquent ORM. but it didn't work.</p> <p>Any help would be grateful.</p> <p>Thank You.</p>
37,969,423
5
1
null
2016-06-22 13:20:32.223 UTC
2
2022-04-08 11:35:01.77 UTC
2021-12-06 16:36:58.843 UTC
null
14,807,111
null
4,644,335
null
1
9
php|laravel
38,486
<p>Use <a href="https://laravel.com/docs/5.2/queries#inserts" rel="noreferrer">insertGetId()</a></p> <pre><code>$id = DB::table('users')-&gt; insertGetId(array( 'email_id' =&gt; $email_id, 'name' =&gt; $name, )); </code></pre>
20,989,317
Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat
<p>If I run <code>gradle assembleDebug</code> from the command line, I am suddenly getting this error:</p> <pre><code>UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dx.util.DexException: Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl; at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:592) at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:550) at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:531) at com.android.dx.merge.DexMerger.mergeDexBuffers(DexMerger.java:168) at com.android.dx.merge.DexMerger.merge(DexMerger.java:186) at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:300) at com.android.dx.command.dexer.Main.run(Main.java:232) at com.android.dx.command.dexer.Main.main(Main.java:174) at com.android.dx.command.Main.main(Main.java:91) </code></pre> <p>If I grep for v4 I see two files inside my build folder.</p> <pre><code>Binary file build/pre-dexed/debug/support-v4-19.0.0-2ba5fdd60a6c3836b3104a863fe42897da1fa9d1.jar matches Binary file build/pre-dexed/debug/support-v4-r7-227d905d79b23b20866531d4f700446c040a2ccb.jar matches </code></pre> <p>My gradle file includes only this support library:</p> <pre><code>compile 'com.android.support:support-v13:19.0.0' </code></pre> <p>I am stumped as to how the r7 library is included somehow. I've run <code>gradle clean</code> and it always appears there when I rerun assembleDebug.</p> <p>If I grep for r7 inside the build directory, I see it inside the file: </p> <pre><code>Binary file build/exploded-bundles/ComGoogleAndroidGmsPlayServices4030.aar/classes.jar matches </code></pre> <p>If I don't include v13, then other things don't compile.</p> <p>But doesn't v13 include v4 support library?</p> <p>Is this an incompatibility between play services AAR bundle and the v13 library?</p> <p>I grabbed the gradle file from gradleplease.appspot.com.</p> <p>Removing play services does not fix it; same error.</p> <p>My dependencies inside build.gradle:</p> <pre><code> dependencies { // Google Play Services //compile 'com.google.android.gms:play-services:4.0.30' // Support Libraries //compile 'com.android.support:support-v4:19.0.0' ///compile 'com.android.support:appcompat-v7:19.0.0' //compile 'com.android.support:gridlayout-v7:19.0.0' compile 'com.android.support:support-v13:19.0.0' compile 'org.eclipse.mylyn.github:org.eclipse.egit.github.core:2.1.5' compile 'commons-codec:commons-codec:1.9' compile 'com.madgag:markdownj-core:0.4.1' compile 'com.wu-man:android-oauth-client:0.0.2' compile 'com.google.http-client:google-http-client-jackson2:1.17.0-rc' compile 'org.apache.commons:commons-lang3:3.2' compile 'com.google.code.gson:gson:2.2.4' } </code></pre>
21,100,040
26
2
null
2014-01-08 07:20:45.763 UTC
99
2021-04-14 21:13:36.91 UTC
2014-01-13 19:08:50.44 UTC
null
115,145
null
105,589
null
1
214
android|gradle|android-support-library|android-gradle-plugin
172,775
<p>Run <strong><code>gradle -q dependencies</code></strong> (or <strong><code>gradle -q :projectName:dependencies</code></strong>) to generate a dependency report. You should see where <code>r7</code> is coming from, such as:</p> <pre><code>compile - Classpath for compiling the main sources. +--- com.commonsware.cwac:camera-v9:0.5.4 | +--- com.actionbarsherlock:actionbarsherlock:4.4.0 | | \--- com.google.android:support-v4:r7 | +--- com.commonsware.cwac:camera:0.5.4 | \--- com.android.support:support-v4:18.0.+ -&gt; 18.0.0 \--- com.android.support:support-v4:18.0.+ -&gt; 18.0.0 </code></pre> <p>Then, use the <code>exclude</code> directive to block that dependency. In my case, it is coming from my CWAC-Camera library, and so I use:</p> <pre><code>dependencies { compile('com.commonsware.cwac:camera-v9:0.5.4') { exclude module: 'support-v4' } compile 'com.android.support:support-v4:18.0.+' } </code></pre> <p>(where the second <code>compile</code> statement indicates what version you actually want)</p> <p>That should clear matters up, as you will see if you run the dependency report again:</p> <pre><code>compile - Classpath for compiling the main sources. +--- com.commonsware.cwac:camera-v9:0.5.4 | +--- com.actionbarsherlock:actionbarsherlock:4.4.0 | \--- com.commonsware.cwac:camera:0.5.4 \--- com.android.support:support-v4:18.0.+ -&gt; 18.0.0 </code></pre>
20,908,438
How can I secure passwords stored inside web.config?
<p>I have added the following settings inside my web.config file to initiate an API call to external system. So I am storing the API URL + username + password as follows:-</p> <pre><code>&lt;appSettings&gt; &lt;add key="ApiURL" value="https://...../servlets/AssetServlet" /&gt; &lt;add key="ApiUserName" value="tmsservice" /&gt; &lt;add key="ApiPassword" value="test2test2" /&gt; </code></pre> <p>Then inside my action method I will be referencing these values when building the web client as follows:-</p> <pre><code>public ActionResult Create(RackJoin rj, FormCollection formValues) { XmlDocument doc = new XmlDocument(); using (var client = new WebClient()) { var query = HttpUtility.ParseQueryString(string.Empty); foreach (string key in formValues) { query[key] = this.Request.Form[key]; } query["username"] = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiUserName"]; query["password"] = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiPassword"]; string apiurl = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiURL"]; </code></pre> <p>But in this was I will be exposing the username and password and these can be captured by users, so my question is how I can secure the API username and password?</p>
20,908,560
6
3
null
2014-01-03 16:37:54.207 UTC
11
2021-01-27 07:09:26.237 UTC
2018-09-27 13:42:39.09 UTC
null
5,407,188
null
1,146,775
null
1
42
c#|asp.net|asp.net-mvc|iis|web-config
79,256
<p>Generally, web.config is a secure file and IIS does not serve it, therefore it will not be exposed to users who are making requests to web server. Web server only serves specific type of files and web.config is surely not one of 'em.</p> <p>Quite often you save your database connection string in it which includes password. Now imagine an scenario where web.config was not secure. You have created a major security threat to your application.</p> <p>Therefore, specially as long as your project is not too big, you should not be worrying about it.</p> <p>Yet, you may have a better approach but creating a project called "Resources" and save all the critical information such as settings, consts, enums and etc in there. That would be a slick and organized approach.</p> <p>If you are passing the username/password over the wire though (for example in case of a secured API call), you may want to use https to make sure that information that are travelling are encrypted but that has nothing to do with the security of web.config file.</p>
21,369,876
What is the idiomatic Rust way to copy/clone a vector in a parameterized function?
<p>I'm trying to write a parameterized function that takes an immutable vector, clones or copies it, does something to the new vector (such as shuffle it) and returns it as a new owned vector. How can this be done and what is the most idiomatic way to do it? </p> <p><strong>Attempt #1</strong></p> <pre><code>pub fn shuffle&lt;T&gt;(vec: &amp;mut [T]) { // ... contents removed: it shuffles the vector in place // ... so needs a mutable vector } pub fn shuffle_create_new&lt;T: Clone&gt;(vec: &amp;[T]) -&gt; Vec&lt;T&gt; { let mut newvec = vec.clone(); shuffle(&amp;mut newvec); return newvec.to_owned(); } </code></pre> <p>Fails with:</p> <pre class="lang-none prettyprint-override"><code>error[E0596]: cannot borrow immutable borrowed content as mutable --&gt; src/main.rs:8:13 | 8 | shuffle(&amp;mut newvec); | ^^^^^^^^^^^ cannot borrow as mutable </code></pre> <p>even though I declared <code>newvec</code> as mutable. I don't understand why.</p> <p><strong>Attempt #2</strong></p> <pre><code>pub fn shuffle_owned&lt;T: Clone&gt;(mut vec: Vec&lt;T&gt;) -&gt; Vec&lt;T&gt; { shuffle(&amp;mut vec); return vec; } </code></pre> <p>While this compiles, it doesn't do what I want. The vector you pass into <code>shuffle_owned</code> gets <strong>moved</strong> into the function, shuffled and then has its ownership transferred back to the caller (via the return value). So the original vector is <em>modified</em>.</p> <p>I want to know how to pass in a vector that will <strong>not</strong> be mutated, but have the values cloned into a new boxed vector and returned when finished - as you do in a functional programming language that has immutable data (such as Clojure).</p>
21,373,782
2
3
null
2014-01-26 22:03:59.437 UTC
11
2017-08-29 17:16:54.697 UTC
2017-08-29 17:11:50.117 UTC
null
155,423
null
871,012
null
1
101
rust
101,806
<p>Your attempt #1 is almost correct, you just have to move <code>to_owned()</code> to the first line:</p> <pre><code>fn shuffle&lt;T&gt;(vec: &amp;mut [T]) { // ... } fn shuffle_create_new&lt;T: Clone&gt;(vec: &amp;[T]) -&gt; Vec&lt;T&gt; { let mut newvec = vec.to_vec(); shuffle(&amp;mut newvec); newvec } </code></pre> <p>This happens because calling <code>clone()</code> on a slice will return you a slice (i.e. <code>&amp;[T]</code>), and you cannot go from <code>&amp;[T]</code> to <code>&amp;mut [T]</code> because you cannot choose mutability of a reference (borrowed pointer). When you call <code>to_owned()</code>, however, you are getting a fresh instance of <code>Vec&lt;T&gt;</code> and you can put it into a mutable variable to get mutable vector.</p> <p>As of Rust 1.0, either <a href="https://doc.rust-lang.org/std/primitive.slice.html#method.to_vec" rel="noreferrer"><code>slice::to_vec</code></a> or <a href="http://doc.rust-lang.org/std/borrow/trait.ToOwned.html#tymethod.to_owned" rel="noreferrer"><code>to_owned()</code></a> method from the <code>ToOwned</code> trait can be used to create <code>Vec&lt;T&gt;</code> from <code>&amp;[T]</code>.</p> <p>There are also now several ways to obtain <code>&amp;mut [T]</code> from <code>Vec&lt;T&gt;</code>: the slicing notation (<code>&amp;mut vec[..]</code>), the deref conversion (<code>&amp;mut *vec</code>) or the direct method call (<code>vec.as_mut_slice()</code>, though this one is deprecated):</p>
18,406,967
Can I execute a procedure with default null parameters?
<p>I recently created a procedure that is defined like this:</p> <pre><code>create or replace PACKAGE pkg_dml_legal_transactions AS PROCEDURE spm_update_court_cost( p_court_state IN legal_court_cost.state%TYPE, p_tran_code IN legal_court_cost.transaction_code%TYPE, p_legal_court IN legal_court_cost.court%TYPE default null, p_end_date IN legal_court_cost.end_date%TYPE, p_cost_min IN legal_court_cost.cost_range_min%TYPE, p_cost_max IN legal_court_cost.cost_range_max%TYPE, p_bal_min IN legal_court_cost.bal_range_min%TYPE DEFAULT NULL, p_bal_max IN legal_court_cost.bal_range_max%TYPE DEFAULT NULL); end pkg_dml_legal_transactions; </code></pre> <p>When I attempt to <code>execute</code> the procedure, I get an error stating that:</p> <pre><code>PLS-00306: wrong number or types of arguments in call to 'SPM_UPDATE_COURT_COST' </code></pre> <p>Here is what my execute statement looks like:</p> <pre><code>execute pkg_dml_legal_transactions.spm_update_court_cost('NJ',1,sysdate,1000,40000); </code></pre> <p>Now I understand what the error means, but I figured if the parameters are defaulted to null then I could just skip them over, but apparently not. Is there a way around this?</p>
18,407,044
2
4
null
2013-08-23 15:50:12.39 UTC
4
2013-08-25 19:18:48.083 UTC
null
null
null
null
2,405,778
null
1
10
oracle|plsql|procedure
55,560
<p>In PL/SQL, you can call a procedure using either named parameter notation or positional notation. If you want to skip some parameters, you'll need to use named parameter notation</p> <pre><code>execute pkg_dml_legal_transactions.spm_update_court_cost( p_court_state =&gt; 'NJ', p_tran_code =&gt; 1, p_end_date =&gt; sysdate, p_cost_min =&gt; 1000, p_cost_max =&gt; 40000 ); </code></pre> <p>Generally, when you're designing a procedure, you would put all the optional parameters at the end so that the caller could also use positional notation.</p>
1,798,285
parsing "*" - Quantifier {x,y} following nothing
<p>fails when I try <code>Regex.Replace()</code> method. how can i fix it? </p> <pre><code>Replace.Method (String, String, MatchEvaluator, RegexOptions) </code></pre> <p>I try code</p> <pre><code>&lt;%# Regex.Replace( (Model.Text ?? "").ToString(), patternText, "&lt;b&gt;" + patternText + "&lt;/b&gt;", RegexOptions.IgnoreCase | RegexOptions.Multiline)%&gt; </code></pre>
1,798,372
3
2
null
2009-11-25 16:47:23.187 UTC
2
2009-11-26 17:31:11.25 UTC
2009-11-25 16:58:44.817 UTC
null
211,452
null
211,452
null
1
31
c#|.net
55,361
<p>Did you try using only the string <code>"*"</code> as a regular expression? At least that's what causes your error here:</p> <pre><code>PS Home:\&gt; "a" -match "*" The '-match' operator failed: parsing "*" - Quantifier {x,y} following nothing.. At line:1 char:11 + "a" -match &lt;&lt;&lt;&lt; "*" </code></pre> <p>The character <code>*</code> is special in regular expressions as it allows the <em>preceding</em> token to appear zero or more times. But there actually has to be something preceding it.</p> <p>If you want to match a literal asterisk, then use <code>\*</code> as regular expression. Otherwise you need to specify <em>what</em> may get repeated. For example the regex <code>a*</code> matches either nothing or arbitrary many <code>a</code>s in a row.</p>
1,895,185
How to ssh from within a bash script?
<p>I am trying to create an ssh connection and do some things on the remote server from within the script.</p> <p>However the terminal prompts me for a password, then opens the connection in the terminal window instead of the script. The commands don't get executed until I exit the connection.</p> <p>How can I ssh from within a bash script?</p>
1,895,195
3
1
null
2009-12-13 00:33:49.13 UTC
23
2022-02-20 02:48:07.077 UTC
2014-06-01 14:28:33.083 UTC
null
385,273
null
48,523
null
1
77
bash|ssh
187,293
<ol> <li><p>If you want the password prompt to go away then use key based authentication (<a href="http://www.cyberciti.biz/tips/ssh-public-key-based-authentication-how-to.html" rel="noreferrer">described here</a>).</p></li> <li><p>To run commands remotely over ssh you have to give them as an argument to ssh, like the following:</p></li> </ol> <blockquote> <p>root@host:~ # ssh root@www 'ps -ef | grep apache | grep -v grep | wc -l'</p> </blockquote>
8,538,205
How do I read and change the value of a TEdit control?
<p>I have a Form <code>TForm1</code> having 5 <code>TEdit</code> and 2 <code>TBitBtn</code>. </p> <p>I also need the Program so that after inputting Numeric Data in <code>Edit1</code> and <code>Edit2</code> on <code>BitBtn1Click</code>, <code>Edit1</code> and <code>Edit2</code> value will summed and will be displayed in <code>Edit3</code>.</p>
8,538,315
3
1
null
2011-12-16 17:59:29.49 UTC
null
2011-12-16 21:42:15.03 UTC
2011-12-16 21:39:20.197 UTC
null
650,492
null
1,100,485
null
1
6
delphi
46,490
<p>You want to do something like this:</p> <pre><code>var val1, val2, sum: Integer; ... val1 := StrToInt(Edit1.Text); val2 := StrToInt(Edit2.Text); sum := val1 + val2; Edit3.Text := IntToStr(sum); </code></pre> <p>If you want floating point arithmetic do it like this</p> <pre><code>var val1, val2, sum: Double; ... val1 := StrToFloat(Edit1.Text); val2 := StrToFloat(Edit2.Text); sum := val1 + val2; Edit3.Text := FloatToStr(sum); </code></pre>
1,052,531
Get user group in a template
<p>I want to display a menu that changes according to the user group of the currently logged in user, with this logic being inside of my view, and then set a variable to check in the template to determine which menu items to show....I'd asked this question before, but my logic was being done in the template. So now I want it in my view...The menu looks as below</p> <pre><code> &lt;ul class="sidemenu"&gt; &lt;li&gt;&lt;a href="/"&gt;General List &lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/sales_list"&gt;Sales List &lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/add_vehicle"&gt;Add a New Record &lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/edit_vehicle"&gt;Edit Existing Record &lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/filter"&gt;Filter Records &lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/logout"&gt;Logout &lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Suppossing the user is management, they'll see everything...But assuming the user is in the group sales, they'll only see the first two and the last two items...and so on. I also want a dynamic redirect after login based on the user's group. Any ideas?</p>
1,052,667
4
0
null
2009-06-27 10:02:57.057 UTC
11
2021-06-15 12:20:07.137 UTC
2016-03-10 07:43:40.033 UTC
null
3,127,057
Stephen
null
null
1
22
django|dynamic|permissions|menu
27,127
<p>The standard Django way of checking permissions is by the individual permission flags rather than testing for the group name.</p> <p>If you must check group names, being aware that Users to Groups is a many-to-many relationship, you can get the <strong>first</strong> group in the list of groups in your template with something like this:</p> <pre><code>{{ user.groups.all.0 }} </code></pre> <p>or using it like this in a conditional (untested but should work):</p> <pre><code>{% ifequal user.groups.all.0 'Sales' %} ... {% endif %} </code></pre> <p>If you go with the preferred permission model you would do something like the following.</p> <pre><code>... {% if perms.vehicle.can_add_vehicle %} &lt;li&gt;&lt;a href="/add_vehicle"&gt;Add a New Record &lt;/a&gt;&lt;/li&gt; {% endif %} {% if perms.vehicle.can_change_vehicle %} &lt;li&gt;&lt;a href="/edit_vehicle"&gt;Edit Existing Record &lt;/a&gt;&lt;/li&gt; {% endif %} ... </code></pre> <p>These are the permissions automatically created for you by <code>syncdb</code> assuming your app is called <code>vehicle</code> and the model is called <code>Vehicle</code>.</p> <p>If the user is a superuser they automatically have all permissions.</p> <p>If the user is in a Sales group they won't have those vehicle permissions (unless you've added those to the group of course).</p> <p>If the user is in a Management group they can have those permissions, but you need to add them to the group in the Django admin site.</p> <p>For your other question, redirect on login based on user group: Users to Groups is a many-to-many relationship so it's not really a good idea to use it like a one-to-many.</p>
744,870
How can you change an age-mismatched PDB to match properly?
<p>Our nightly build process was broken for a long time, such that it generated PDB files that were a few hours different in age than the corresponding image files. I have since fixed the problem.</p> <p>However, I would like to start using a symbol server, but cannot due to having to use these age-mismatched pdb files. I work around this issue by using the .symopt +0x40 method in windbg. That means I have to organize all my pdb files by hand, and after years upon years of releases, that adds up.</p> <p>I am looking for a way to modify the mechanism that windbg uses to mark a pdb's age, and force it to match my image file. The utility <a href="http://www.debuginfo.com/tools/chkmatch.html" rel="noreferrer">ChkMatch</a> does something similar, but for pdb signatures. The developer states on the page "ChkMatch is capable of making an executable and PDB file match if they have different signatures but the same age (see this article for more information about PDB signature and age). If the age differs, the tool cannot make the files match."</p> <p>I took a look inside a hexeditor, and even found what looked like the bits corresponding to the age, but it must pull some more tricks internally, cause I couldn't get it to work.</p> <p>Any ideas?</p> <p><strong>EDIT</strong>: I don't know if this helps, but in my particular case the age difference was caused by unnecessarily relinking dll's, which would recreate the PDB files as well. However, our build process was storing the original dlls (before the relink), and the pdb after the relink. I thought about somehow recreating such a situation by hand. Meaning, forcing a relink on a DLL, but saving off the pdb in both cases. Then I could do a binary compare of the two files to see how they changed. Perhaps run some sort of patching software that does this automatically? By seeing what exactly changed in my control case, perhaps I could do the same to the DLLs and PDBs saved in my companies build process? </p> <p><strong>EDIT</strong>: I FIGURED IT OUT!!!! Thanks to one of the comments on the first answer, I checked out a link to the pdfs of the book "Undocumented Windows 2000 Secrets: A Programmers Cookbook". And the author goes into great detail about the pdb file format. As I said before, I had already loaded the pdb into a hex editor and flipped some bits around appearing that I made the age/signature match, but it didn't work. Well, after using the utility from the W2k secrets book to "explode" the pdb into the included streams, I found out that they hide another reference to the age in stream 3!!!!!!! Once I flipped that one as well, it matched up in windbg. THIS IS HUGE!!!! Thank you so much....symbol server HERE I COME!</p>
746,965
4
0
null
2009-04-13 18:19:10.853 UTC
15
2021-04-04 13:36:05.21 UTC
2010-04-14 21:24:36.593 UTC
null
294,313
null
88,734
null
1
33
windows|windbg|symbols|pdb-files|symbol-server
20,513
<p>the windbg will not modify pdb's age - it only looks it up to match that of executable - the compiler does when it (re)generates executable and debug files. <p>now, based on the debuginfo.com article, it is not too difficult to arrive at the proper debug directory (of type codeview), match it against PDB7 signature and make modifications to either age or GUID inside an executable. why is that not an option? <p>i guess, you want to update pdb instead? i'm afraid, pdb is a proprietary format. there're multiple read-only APIs (dbghelp.dll and dia sdk), but as far as modifications go, you need to guess the details to be able to modify.</p>
56,816,374
Context.Consumer vs useContext() to access values passed by Context.Provider
<pre><code>&lt;MyContext.Consumer&gt; {value =&gt; { }} &lt;/MyContext.Consumer&gt; VS let value = useContext(MyContext); </code></pre> <p>What is the difference between this two snippets, using Context.Consumer and using useContext hook to access values passed by the context Provider? I think useContext will subscribe to the context Provider, since we passed the Context as an argument, so that it will trigger a re-render, when the provider value changes.</p>
56,816,825
1
2
null
2019-06-29 09:12:35.25 UTC
16
2022-06-09 11:19:07.317 UTC
null
null
null
null
8,443,899
null
1
51
reactjs|react-hooks
20,329
<p>That is correct. They will do basically the same thing.</p> <p>In my opinion, the <code>useContext</code> hook has a much nicer and readable syntax.</p> <p><strong>From React Docs:</strong></p> <p><a href="https://reactjs.org/docs/hooks-reference.html#usecontext" rel="nofollow noreferrer">https://reactjs.org/docs/hooks-reference.html#usecontext</a></p> <blockquote> <p><strong>useContext</strong></p> </blockquote> <blockquote> <p>const value = useContext(MyContext); Accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest &lt;MyContext.Provider&gt; above the calling component in the tree.</p> </blockquote> <blockquote> <p><strong>When the nearest &lt;MyContext.Provider&gt; above the component updates, this Hook will trigger a rerender with the latest context value passed to that MyContext provider.</strong></p> </blockquote> <p><strong>Also from React Docs:</strong></p> <p><a href="https://reactjs.org/docs/context.html" rel="nofollow noreferrer">https://reactjs.org/docs/context.html</a></p> <blockquote> <p><strong>Context.Consumer</strong></p> </blockquote> <blockquote> <pre><code>&lt;MyContext.Consumer&gt; {value =&gt; /* render something based on the context value */} &lt;/MyContext.Consumer&gt; </code></pre> </blockquote> <blockquote> <p>A React component that subscribes to context changes. This lets you subscribe to a context within a function component.</p> </blockquote> <p><strong>UPDATE:</strong></p> <p><s><strong>From:</strong> <a href="http://brianyang.com/react-hooks-a-deeper-dive-featuring-usecontext-and-usereducer/" rel="nofollow noreferrer">http://brianyang.com/react-hooks-a-deeper-dive-featuring-usecontext-and-usereducer/</a></s></p> <p><strong>From:</strong> <a href="https://testdriven.io/blog/react-hooks-advanced/" rel="nofollow noreferrer">https://testdriven.io/blog/react-hooks-advanced/</a></p> <blockquote> <p>The new <code>useContext</code> hook to consume context <strong>does not change the concepts surrounding context,</strong> hence the plunge above. This context hook only gives us an extra, much prettier, way to consume context. It's amazingly helpful when applying it to components consuming multiple contexts.</p> </blockquote>
23,451,726
Saving binary data as file using JavaScript from a browser
<p>I am working on a business application using <code>angularJS</code>. One of my service method returning me a <code>byte[]</code> (inclding PDF file content) now i need to download this file as <code>PDF</code> to client machine using <code>JavaScript</code>.</p> <p>How is that possible using HTML5 Apis or any JavaScript API?</p> <p>I have used <code>window.atob(base64String)</code></p> <pre><code>JVBERi0xLjMNJeLjz9MNJVBERi1Xcml0ZXIuTkVUIGRiQXV0b1RyYWNrIEx0ZC4NMSAwIG9iag08PA0vVGl0bGUgKEludm9pY2UpDS9BdXRob3IgKFNlcnZpY2VNYW5hZ2VyUGx1cykNL0NyZWF0b3IgKFNlcnZpY2VNYW5hZ2VyUGx1cykNL0NyZWF0aW9uRGF0ZSAoRDoyMDE0MDUwNDE1MDQ0MiswNSczMCcpDS9Nb2REYXRlIChEOjIwMTQwNTA0MTUwNDQyKzA1JzMwJykNPj4NZW5kb2JqDTIgMCBvYmoNWy9QREYgL1RleHQgL0ltYWdlQ10NZW5kb2JqDTMgMCBvYmoNPDwNL1R5cGUgL1BhZ2VzDS9LaWRzIFsgNCAwIFIgNiAwIFIgXQ0vQ291bnQgMg0+Pg1lbmRvYmoNNCAwIG9iag08PA0vVHlwZSAvUGFnZSANL1BhcmVudCAzIDAgUiANL01lZGlhQm94IFsgMCAwIDU5NSA4NDIgXSANL1JvdGF0ZSAwDS9Db250ZW50cyA1IDAgUiANL1Jlc291cmNlcyA8PA0vUHJvY1NldFsvUERGL1RleHQvSW1hZ2VDXQ0vRm9udCA8PCANL0YwIDggMCBSIA0vRjEgMTAgMCBSIA0+Pg0+Pg0+Pg1lbmRvYmoNNSAwIG9iag08PCAvTGVuZ3RoIDEyOTkgL0ZpbHRlciAvRmxhdGVEZWNvZGUgPj4Nc3RyZWFtDQp4nJVZTW/jNhC9+1cQ6KU9rEJKpETllk02LdC0+bCLXAIUqq0kahxpK8vJ5t+XlCxpyKEoJw6CxczjzPO8ITngnlxSElGyeiQLSvSnflp8XS1CQUkiQ7LaLH6+v777nVzfXXy7+4Ws/l18W5HFiVrFulUKzKkCRx34ut7kNfnplCz/uPnCKJXJsKhHsgQg13WeNTnZqD+nhPETGp2ElHEjUzhkEmOiv8qXsnovyXn1+j0rPyao6QWsW8DUypQs909Zva2yR3Lz8v4BuSlonHbUCLEdh1LcPFdlThhIxsxksegifC2226J8ImebTZ3vdtPsYt5FPt/vmuo1r1kYEvBvm0fYhf8tz94+ivKtKtaqhldX5w4o8wZ+KF0xHsqQc3K2Xlf7stH8r7IyZ1ZkcajSMivJZZ2V62K3rnR4ZGBhxMVEsXQr9NVa5vWbYjFTrXaFv1yf+VYPpf7Y3dlX+LNf7lAa2CenRAjxRcRJPKD+Iy0qEkSo76U6uc7JPSl7u2CtncW9nQaJ5KT7y/TWtFGLR7CWGWtto4JqBSTa64kMKE8V2BTjpq7eCrVFIXlG3g9L737FCZaLW6J/NTA+OCmkhKyTnJiMApmIkdT6Od/st/mGLJusbiY54QyAVOgkhayTpEIZBiGPHaQui7LYPU+ywikAq8jJClknWUUpDThPBlZn62afbWfqhMMDRtzJCFknGXEpA8mkzWimSDg+7CdH4wlX44HtNVIf7cy2o8AQhDpaO6kvAkKh/psNgVCoWWZDIBRSdzYEQnnVgBUfgIMgPJXu847xY847iBrPO7TWAZ3YxokIUtWaQs8Ver6p6hdyke/WdfG9KarSe+AZGXwlmQKCetgNiu36ApT9/RemcRDH6vihvNtWF/c+qkY0H1U3cGSr5jXtTmy2SXKEegZqUA+vdUCnDuEkYGlEuIzaKtzlu2q7n9PNjO0rxhQQ+Ki7ENRzrEDMMeltHNAhttO77CguBHkJOIEDiUjtYcEEkRaJKI1bu78ZDNTQDNrKuDCbwTBONkMq1Y7ghNPD2FVXm/26IX9mr7mvG8zgsBqpaJ2hObbYVv/RkqQDoWNOFRwdnvcHp1Ee2zh9EdM0CAGdm1oNdtMzgR0WXhqcYh62cZqHiAOuprmex23zMT0G2EEhC9kxlMZcYhknWQiaBHrE71msqkZNJf6aoOCerWN2t7l5I0mt/THazd53BYYg1K6SWu3qbDCIQg2mnF4ONgh1xlwAG4REVT7pHUcskFcHWGtbh5i7dVD2eR0gCOmgnEfoAFFIB32UzeoAQEiHuQA2COmgfPM6AJBXB1hrWwcu3Too+7wOEIR0UM4jdIAopINyzusAQEiHuQA2COmgfPM6AJBXB1hrW4fDfY50UPZ5HSAI6aCcR+gAUUgH5ZzXAYCQDnMBbBDSQfnmdQAgrw6w1nC00jdkpPyHF7vl/p9GX02n8FbiUr/ThiRtn0NHNp+1W+xN0CT7SeDIXs3l3a2a/bB5h2qodfH7jB3RgSAvbycQ8I7BNIBKHgp3aT9jx4zEkSV3Aoe9G4aqn2j7Qmrs3ePt3aNlGPJA29uXb3sSYkR/ugY2AtjE54G3/Sspk8M4Wjb5ph3Xx8obVdBPgWxc8bf7Z1zbYmkQq+Svi/aL6Relg2WrqOghnY8Bl8VTmTX7GuTXT2p0NuWYswP3OTlLAxGhnLrT+ogX+v86jHdnOZlugHWYPosQPEhoYmT5H418ezgNZW5kc3RyZWFtDWVuZG9iag02IDAgb2JqDTw8DS9UeXBlIC9QYWdlIA0vUGFyZW50IDMgMCBSIA0vTWVkaWFCb3ggWyAwIDAgNTk1IDg0MiBdIA0vUm90YXRlIDANL0NvbnRlbnRzIDcgMCBSIA0vUmVzb3VyY2VzIDw8DS9Qcm9jU2V0Wy9QREYvVGV4dC9JbWFnZUNdDS9Gb250IDw8IA0vRjAgOCAwIFIgDT4+DT4+DT4+DWVuZG9iag03IDAgb2JqDTw8IC9MZW5ndGggMTA1IC9GaWx0ZXIgL0ZsYXRlRGVjb2RlID4+DXN0cmVhbQ0KeJwrVOAyNVAwMjNXMDUwAOOiVIVwhTyuQpIl9N0MFAwNFELSFLgMFECwKJ3LKYTL1ETB3NRUD6QwJIVLwzk/Nzc1r6RYQVMhJIvLNUQBZKChQjlUT5A7pulcwVyBCiBEvEogAgB61iybDWVuZHN0cmVhbQ1lbmRvYmoNOCAwIG9iag08PA0vVHlwZSAvRm9udCANL0Jhc2VGb250IC9DYWxpYnJpIA0vU3VidHlwZSAvVHJ1ZVR5cGUgDS9OYW1lIC9GMCANL0ZpcnN0Q2hhciAzMiANL0xhc3RDaGFyIDI1NSANL1dpZHRocyBbMjI2IDMyNSA0MDAgNDk4IDUwNiA3MTQgNjgyIDIyMCAzMDMgMzAzIDQ5OCA0OTggMjQ5IDMwNiAyNTIgMzg2IDUwNiANNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgMjY3IDI2NyA0OTggNDk4IDQ5OCA0NjMgODk0IA01NzggNTQzIDUzMyA2MTUgNDg4IDQ1OSA2MzAgNjIzIDI1MSAzMTggNTE5IDQyMCA4NTQgNjQ1IDY2MiA1MTYgDTY3MiA1NDIgNDU5IDQ4NyA2NDEgNTY3IDg4OSA1MTkgNDg3IDQ2OCAzMDYgMzg2IDMwNiA0OTggNDk4IDI5MSANNDc5IDUyNSA0MjIgNTI1IDQ5NyAzMDUgNDcwIDUyNSAyMjkgMjM5IDQ1NCAyMjkgNzk4IDUyNSA1MjcgNTI1IA01MjUgMzQ4IDM5MSAzMzQgNTI1IDQ1MSA3MTQgNDMzIDQ1MiAzOTUgMzE0IDQ2MCAzMTQgNDk4IDUwNiA1MDYgDTUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiANNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgMjI2IA0zMjUgNDk4IDUwNiA0OTggNTA2IDQ5OCA0OTggMzkyIDgzNCA0MDIgNTEyIDQ5OCAzMDYgNTA2IDM5NCAzMzggDTQ5OCAzMzUgMzM0IDI5MSA1NDkgNTg1IDI1MiAzMDcgMjQ2IDQyMiA1MTIgNjM2IDY3MSA2NzUgNDYzIDU3OCANNTc4IDU3OCA1NzggNTc4IDU3OCA3NjMgNTMzIDQ4OCA0ODggNDg4IDQ4OCAyNTEgMjUxIDI1MSAyNTEgNjI0IA02NDUgNjYyIDY2MiA2NjIgNjYyIDY2MiA0OTggNjYzIDY0MSA2NDEgNjQxIDY0MSA0ODcgNTE2IDUyNyA0NzkgDTQ3OSA0NzkgNDc5IDQ3OSA0NzkgNzcyIDQyMiA0OTcgNDk3IDQ5NyA0OTcgMjI5IDIyOSAyMjkgMjI5IDUyNSANNTI1IDUyNyA1MjcgNTI3IDUyNyA1MjcgNDk4IDUyOSA1MjUgNTI1IDUyNSA1MjUgNDUyIDUyNSA0NTIgXQ0vRW5jb2RpbmcgL1dpbkFuc2lFbmNvZGluZyANL0ZvbnREZXNjcmlwdG9yIDkgMCBSIA0+Pg1lbmRvYmoNOSAwIG9iag08PA0vVHlwZSAvRm9udERlc2NyaXB0b3IgDS9Bc2NlbnQgNzUwIA0vQ2FwSGVpZ2h0IDUwMCANL0Rlc2NlbnQgLTI1MCANL0ZsYWdzIDMyIA0vRm9udEJCb3ggWyAtNTAzIC0zMDcgMTI0MCA5NjQgXSANL0ZvbnROYW1lIC9DYWxpYnJpIA0vSXRhbGljQW5nbGUgMCANL1N0ZW1WIDAgDT4+DWVuZG9iag0xMCAwIG9iag08PA0vVHlwZSAvRm9udCANL0Jhc2VGb250IC9DYWxpYnJpLEJvbGQgDS9TdWJ0eXBlIC9UcnVlVHlwZSANL05hbWUgL0YxIA0vRmlyc3RDaGFyIDMyIA0vTGFzdENoYXIgMjU1IA0vV2lkdGhzIFsyMjYgMzI1IDQzOCA0OTggNTA2IDcyOSA3MDQgMjMzIDMxMSAzMTEgNDk4IDQ5OCAyNTcgMzA2IDI2NyA0MjkgNTA2IA01MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiAyNzUgMjc1IDQ5OCA0OTggNDk4IDQ2MyA4OTggDTYwNSA1NjAgNTI5IDYzMCA0ODcgNDU4IDYzNyA2MzAgMjY2IDMzMSA1NDYgNDIyIDg3NCA2NTggNjc2IDUzMiANNjg2IDU2MiA0NzIgNDk1IDY1MiA1OTEgOTA2IDU1MCA1MTkgNDc4IDMyNCA0MjkgMzI0IDQ5OCA0OTggMzAwIA00OTMgNTM2IDQxOCA1MzYgNTAzIDMxNiA0NzQgNTM2IDI0NSAyNTUgNDc5IDI0NSA4MTMgNTM2IDUzNyA1MzYgDTUzNiAzNTUgMzk4IDM0NiA1MzYgNDczIDc0NSA0NTkgNDczIDM5NyAzNDMgNDc1IDM0MyA0OTggNTA2IDUwNiANNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IA01MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiA1MDYgNTA2IDUwNiAyMjYgDTMyNSA0OTggNTA2IDQ5OCA1MDYgNDk4IDQ5OCA0MTQgODM0IDQxNiA1MzggNDk4IDMwNiA1MDYgMzkwIDM0MiANNDk4IDMzNyAzMzUgMzAwIDU2MyA1OTcgMjY3IDMwMyAyNTIgNDM1IDUzOCA2NTcgNjkwIDcwMSA0NjMgNjA1IA02MDUgNjA1IDYwNSA2MDUgNjA1IDc3NSA1MjkgNDg3IDQ4NyA0ODcgNDg3IDI2NiAyNjYgMjY2IDI2NiA2MzkgDTY1OCA2NzYgNjc2IDY3NiA2NzYgNjc2IDQ5OCA2ODAgNjUyIDY1MiA2NTIgNjUyIDUxOSA1MzIgNTU0IDQ5MyANNDkzIDQ5MyA0OTMgNDkzIDQ5MyA3NzQgNDE4IDUwMyA1MDMgNTAzIDUwMyAyNDUgMjQ1IDI0NSAyNDUgNTM2IA01MzYgNTM3IDUzNyA1MzcgNTM3IDUzNyA0OTggNTQzIDUzNiA1MzYgNTM2IDUzNiA0NzMgNTM2IDQ3MyBdDS9FbmNvZGluZyAvV2luQW5zaUVuY29kaW5nIA0vRm9udERlc2NyaXB0b3IgMTEgMCBSIA0+Pg1lbmRvYmoNMTEgMCBvYmoNPDwNL1R5cGUgL0ZvbnREZXNjcmlwdG9yIA0vQXNjZW50IDc1MCANL0NhcEhlaWdodCA1MDAgDS9EZXNjZW50IC0yNTAgDS9GbGFncyAzMiANL0ZvbnRCQm94IFsgLTUxOSAtMzA2IDEyNDAgOTcxIF0gDS9Gb250TmFtZSAvQ2FsaWJyaSxCb2xkIA0vSXRhbGljQW5nbGUgMCANL1N0ZW1WIDAgDT4+DWVuZG9iag0xMiAwIG9iag08PA0vVHlwZSAvQ2F0YWxvZyANL1BhZ2VzIDMgMCBSIA0vUGFnZU1vZGUgL1VzZU5vbmUgDS9WaWV3ZXJQcmVmZXJlbmNlcyA8PA0vSGlkZVRvb2xiYXIgZmFsc2UgDS9IaWRlTWVudWJhciBmYWxzZSANL0hpZGVXaW5kb3dVSSBmYWxzZSANL0ZpdFdpbmRvdyBmYWxzZSANL0NlbnRlcldpbmRvdyBmYWxzZSANL0Rpc3BsYXlEb2NUaXRsZSBmYWxzZSANL05vbkZ1bGxTY3JlZW5QYWdlTW9kZSAvVXNlTm9uZSANPj4NPj4NZW5kb2JqDXhyZWYNMCAxMw0wMDAwMDAwMDAwIDY1NTM1IGYgDTAwMDAwMDAwNDggMDAwMDAgbiANMDAwMDAwMDIyMCAwMDAwMCBuIA0wMDAwMDAwMjU2IDAwMDAwIG4gDTAwMDAwMDAzMjEgMDAwMDAgbiANMDAwMDAwMDUwNCAwMDAwMCBuIA0wMDAwMDAxODc3IDAwMDAwIG4gDTAwMDAwMDIwNDggMDAwMDAgbiANMDAwMDAwMjIyNiAwMDAwMCBuIA0wMDAwMDAzMzEyIDAwMDAwIG4gDTAwMDAwMDM0OTEgMDAwMDAgbiANMDAwMDAwNDU4NCAwMDAwMCBuIA0wMDAwMDA0NzY5IDAwMDAwIG4gDXRyYWlsZXINPDwNL1NpemUgMTMgDS9Sb290IDEyIDAgUiANL0luZm8gMSAwIFIgDS9JRFs8QzFEMTBFNDk4OTQ2QkU0RUJFODUzRUNCRDk4OEM1Q0Q+PEMxRDEwRTQ5ODk0NkJFNEVCRTg1M0VDQkQ5ODhDNUNEPl0NPj4Nc3RhcnR4cmVmDTUwMjMNJSVFT0YN </code></pre> <p>but getting this following error <code>Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.</code></p>
23,451,803
4
1
null
2014-05-04 01:48:32.447 UTC
40
2021-03-30 07:38:58.833 UTC
2016-11-30 19:42:06.137 UTC
null
511,736
null
3,389,203
null
1
67
javascript|html|blob
172,654
<p>This is possible if the browser supports the <code>download</code> property in anchor elements.<br></p> <pre><code>var sampleBytes = new Int8Array(4096); var saveByteArray = (function () { var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; return function (data, name) { var blob = new Blob(data, {type: "octet/stream"}), url = window.URL.createObjectURL(blob); a.href = url; a.download = name; a.click(); window.URL.revokeObjectURL(url); }; }()); saveByteArray([sampleBytes], 'example.txt'); </code></pre> <p><br> <strong>JSFiddle</strong>: <a href="http://jsfiddle.net/VB59f/2">http://jsfiddle.net/VB59f/2</a></p>
47,038,101
Save data as a *.dat file?
<p>I am writing a program in Python which should import <code>*.dat</code> files, subtract a specific value from certain columns and subsequently save the file in <code>*.dat</code> format in a different directory. </p> <p>My current tactic is to load the datafiles in a <code>numpy</code> array, perform the calculation and then save it. I am stuck with the saving part. I do not know how to save a file in python in the <code>*.dat</code> format. Can anyone help me? Or is there an alternative way without needing to import the <code>*.dat</code> file as a <code>numpy</code> array? Many thanks!</p>
47,038,298
5
3
null
2017-10-31 14:42:28.753 UTC
1
2018-05-13 20:20:31.253 UTC
null
null
null
null
8,746,303
null
1
0
python|database|save
44,316
<p>assuming your file looks like</p> <pre><code>file = open(filename, "r") </code></pre> <p>all you need to do is open another file with "w" as the second parameter</p> <pre><code>file = open(new_file-path,"w") file.write(data) file.close() </code></pre> <p>if your data is not a string, either make it a string, or use</p> <pre><code>file = open(filename, "rb") file = open(filename, "wb") </code></pre> <p>when reading and writing, since these read and write raw bytes</p>
54,971,245
Change indentation level in Google Colab
<p>I am using <a href="https://colab.research.google.com" rel="nofollow noreferrer">Google Colab</a> to write Python code in their notebooks. Whenever I hit <code>enter</code> after a loop or conditional, the new line is automatically indented, which is good, but it uses only 2 whitespaces by default. This is contrary to the <a href="https://www.python.org/dev/peps/pep-0008/#indentation" rel="nofollow noreferrer">PEP-8 standard</a> which recommends 4 whitespaces.</p> <p>Why is this the case and how can I change this setting within Colab?</p>
57,770,479
1
3
null
2019-03-03 16:49:52.193 UTC
6
2022-05-14 14:15:52.593 UTC
2022-05-13 15:03:18.757 UTC
null
11,483,646
null
8,565,438
null
1
34
python|google-colaboratory|indentation|pep8
26,295
<p>You can change it to 4 whitespaces through settings:</p> <p><code>Tools</code> &gt; <code>Settings</code> &gt; <code>Editor</code> &gt; <code>Indentation width in spaces</code> &gt; Select <code>4</code></p>
20,335,878
Is it possible to run a VBScript in UNIX environment?
<p>I've a Vbscript for merging excel sheet into a single workbook. I would like to know whether we could execute vbscript (.vbs) file in unix system. If yes, please help me with the procedures. Thanks in advance.</p>
24,048,673
4
1
null
2013-12-02 19:05:25.827 UTC
4
2019-03-27 13:25:39.383 UTC
null
null
null
null
1,966,207
null
1
10
unix|vbscript|scripting|scheduling|execution
41,132
<p>Not sure about Unices, but <strong>on GNU/Linux</strong> <strong>it is possible to run VBScript using <a href="http://www.winehq.org/" rel="noreferrer" title="Wine">Wine</a></strong>, but <strong>VBScript support is limited</strong>.</p> <p>On Debian/Ubuntu you can install as follows:</p> <pre><code>$ sudo apt-get install wine ... $ </code></pre> <p><strong>To run</strong> from command line:</p> <pre><code>$ wine cscript some-script.vbs </code></pre> <p>or </p> <pre><code>$ wine wscript some-script.vbs </code></pre> <p>For example I can run following script using Wine 1.7.19 from <a href="https://launchpad.net/~ubuntu-wine/+archive/ppa" rel="noreferrer" title="Ubuntu-wine PPA">Ubuntu Wine PPA</a>:</p> <pre><code>' test.vbs 'WScript.Echo "Echo test" ' doesn't work 'MsgBox "Message box!" ' look like doesn't work either ' Write to file - works Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.CreateTextFile("out.txt", True) objFile.Write "Output to file test" &amp; vbCrLf objFile.Close </code></pre> <p>run:</p> <pre><code>$ wine cscript test.vbs fixme:vbscript:VBScript_SetScriptState unimplemented SCRIPTSTATE_INITIALIZED fixme:scrrun:textstream_Close (0x13e208): stub $ cat out.txt Output to file test $ </code></pre>
7,648,967
Python multiprocessing - How to release memory when a process is done?
<p>I encountered a weird problem while using python multiprocessing library. </p> <p>My code is sketched below: I spawn a process for each "symbol, date" tuple. I combine the results afterwards. </p> <p>I expect that when a process has done computing for a "symbol, date" tuple, it should release its memory? apparently that's not the case. I see dozens of processes (though I set the process pool to have size 7) that are suspended¹ in the machine. They consume no CPU, and they don't release the memory. </p> <p>How do I let a process release its memory, after it has done its computation?</p> <p>Thanks!</p> <p>¹ by "suspended" I mean their status in ps command is shown as "S+"</p> <pre><code>def do_one_symbol( symbol, all_date_strings ): pool = Pool(processes=7) results = []; for date in all_date_strings: res = pool.apply_async(work, [symbol, date]) results.append(res); gg = mm = ss = 0; for res in results: g, m, s = res.get() gg += g; mm += m; ss += s; </code></pre>
7,650,252
3
0
null
2011-10-04 13:52:11.013 UTC
6
2016-05-02 02:46:06.467 UTC
2011-10-22 17:07:00.517 UTC
null
6,899
null
509,205
null
1
33
python|memory|multiprocessing
24,847
<p>Did you try to close pool by using <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.close" rel="noreferrer"><code>pool.close</code></a> and then wait for process to finish by <a href="http://docs.python.org/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.join" rel="noreferrer"><code>pool.join</code></a>, because if parent process keeps on running and does not wait for child processes they will become <a href="http://en.wikipedia.org/wiki/Zombie_process" rel="noreferrer">zombies</a></p>
7,104,985
Testing private method using power mock which return list of Integers
<p>I have a private method which take a list of integer value returns me a list of integer value. How can i use power mock to test it. I am new to powermock.Can i do the test with easy mock..? how..</p>
7,105,941
4
1
null
2011-08-18 09:12:23.263 UTC
1
2018-03-23 13:27:37.353 UTC
null
null
null
null
882,196
null
1
21
java|easymock|powermock
41,141
<p>From <a href="https://github.com/jayway/powermock/wiki/BypassEncapsulation" rel="noreferrer">the documentation</a>, in the section called "Common - Bypass encapsulation":</p> <blockquote> <p>Use Whitebox.invokeMethod(..) to invoke a private method of an instance or class.</p> </blockquote> <p>You can also find examples in the same section.</p>
7,500,644
Elegant indexing up to end of vector/matrix
<p>Is it possible in R to say - I want all indices from position <code>i</code> to the end of vector/matrix? Say I want a submatrix from 3rd column onwards. I currently only know this way:</p> <pre><code>A = matrix(rep(1:8, each = 5), nrow = 5) # just generate some example matrix... A[,3:ncol(A)] # get submatrix from 3rd column onwards </code></pre> <p>But do I really need to write <code>ncol(A)</code>? Isn't there any elegant way how to say "from the 3rd column onwards"? Something like <code>A[,3:]</code>? (or <code>A[,3:...]</code>)?</p>
7,500,961
4
0
null
2011-09-21 13:33:21.953 UTC
14
2022-03-30 00:07:22.05 UTC
2018-06-16 15:44:04.23 UTC
null
684,229
null
684,229
null
1
88
r|matrix|dataframe|indexing
114,632
<p>Sometimes it's easier to tell R what you <strong>don't</strong> want. In other words, exclude columns from the matrix using negative indexing:</p> <p>Here are two alternative ways that both produce the same results:</p> <pre><code>A[, -(1:2)] A[, -seq_len(2)] </code></pre> <p>Results:</p> <pre><code> [,1] [,2] [,3] [,4] [,5] [,6] [1,] 3 4 5 6 7 8 [2,] 3 4 5 6 7 8 [3,] 3 4 5 6 7 8 [4,] 3 4 5 6 7 8 [5,] 3 4 5 6 7 8 </code></pre> <hr> <p>But to answer your question as asked: Use <code>ncol</code> to find the number of columns. (Similarly there is <code>nrow</code> to find the number of rows.)</p> <pre><code>A[, 3:ncol(A)] [,1] [,2] [,3] [,4] [,5] [,6] [1,] 3 4 5 6 7 8 [2,] 3 4 5 6 7 8 [3,] 3 4 5 6 7 8 [4,] 3 4 5 6 7 8 [5,] 3 4 5 6 7 8 </code></pre>
21,448,766
Adding Navigation Bar programmatically iOS
<p>I am trying to make an App with a Navigation Bar (Back button, title, etc) and a Tab Bar (Toolbar on the bottom). I am using subviews so I don't have to worry about the status bar, navigation bar, tab bar heights, etc. But I think it's causing me trouble because I can't seem to figure out how to setup the Nav and Tab Bars.</p> <p>Here is what I have. What am I doing wrong?</p> <p>AppDelegate.h</p> <pre><code>(default for single view app) </code></pre> <p>AppDelegate.m</p> <pre><code>(default for single view app) </code></pre> <p>ViewController.h</p> <pre><code>#import &lt;UIKit/UIKit.h&gt; @interface ViewController : UIViewController @property (strong, nonatomic) UIView *contentSubview; @end </code></pre> <p>ViewController.m</p> <pre><code>#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)loadView{} - (void)viewDidLoad { [super viewDidLoad]; UIView *view = [[UIView alloc] init]; view.backgroundColor = [UIColor greenColor]; self.contentSubview = [[UIView alloc] init]; self.contentSubview.backgroundColor = [UIColor orangeColor]; [view addSubview:self.contentSubview]; self.view = view; } - (void)viewWillLayoutSubviews { [super viewWillLayoutSubviews]; self.contentSubview.frame = CGRectMake( 0, self.topLayoutGuide.length, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame)-self.topLayoutGuide.length-self.bottomLayoutGuide.length ); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end </code></pre>
21,448,861
5
2
null
2014-01-30 05:43:54.593 UTC
12
2020-09-05 18:07:10.503 UTC
2017-07-04 06:53:42.077 UTC
null
2,783,370
null
3,208,560
null
1
28
ios|objective-c|iphone|swift|xcode
65,738
<pre><code>-(void)ViewDidLoad { UINavigationBar* navbar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)]; UINavigationItem* navItem = [[UINavigationItem alloc] initWithTitle:@"karthik"]; // [navbar setBarTintColor:[UIColor lightGrayColor]]; UIBarButtonItem* cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(onTapCancel:)]; navItem.leftBarButtonItem = cancelBtn; UIBarButtonItem* doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(onTapDone:)]; navItem.rightBarButtonItem = doneBtn; [navbar setItems:@[navItem]]; [self.view addSubview:navbar]; } -(void)onTapDone:(UIBarButtonItem*)item{ } -(void)onTapCancel:(UIBarButtonItem*)item{ } </code></pre> <p><strong>Swift3</strong></p> <pre><code>let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height:44)) // Offset by 20 pixels vertically to take the status bar into account navigationBar.backgroundColor = UIColor.white // Create a navigation item with a title let navigationItem = UINavigationItem() navigationItem.title = "Title" // Create left and right button for navigation item let leftButton = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(ViewController.btn_clicked(_:))) let rightButton = UIBarButtonItem(title: "Right", style: .plain, target: self, action: nil) // Create two buttons for the navigation item navigationItem.leftBarButtonItem = leftButton navigationItem.rightBarButtonItem = rightButton // Assign the navigation item to the navigation bar navigationBar.items = [navigationItem] // Make the navigation bar a subview of the current view controller self.view.addSubview(navigationBar) func btn_clicked(_ sender: UIBarButtonItem) { // Do something } </code></pre> <p><strong>Swift</strong></p> <pre><code> // Create the navigation bar let navigationBar = UINavigationBar(frame: CGRectMake(0, 0, self.view.frame.size.width, 44)) // Offset by 20 pixels vertically to take the status bar into account navigationBar.backgroundColor = UIColor.whiteColor() navigationBar.delegate = self; // Create a navigation item with a title let navigationItem = UINavigationItem() navigationItem.title = "Title" // Create left and right button for navigation item let leftButton = UIBarButtonItem(title: "Save", style: UIBarButtonItemStyle.Plain, target: self, action: "btn_clicked:") let rightButton = UIBarButtonItem(title: "Right", style: UIBarButtonItemStyle.Plain, target: self, action: nil) // Create two buttons for the navigation item navigationItem.leftBarButtonItem = leftButton navigationItem.rightBarButtonItem = rightButton // Assign the navigation item to the navigation bar navigationBar.items = [navigationItem] // Make the navigation bar a subview of the current view controller self.view.addSubview(navigationBar) func btn_clicked(sender: UIBarButtonItem) { // Do something } </code></pre>
1,945,589
A procedure imported by {myassembly} could not be loaded
<p>when running a prorgam, it seems that I am missing a library, when I launch the output of my project I get an exception at startup.</p> <pre><code>A first chance exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll An unhandled exception of type 'System.IO.FileLoadException' occurred in mscorlib.dll Additional information: A procedure imported by 'my assembly, Version=xx.1.1.0, Culture=neutral, PublicKeyToken=7292581204d9e04a' could not be loaded. 'ScriptX.vshost.exe' (Managed): Loaded 'C:\WINDOWS\assembly\GAC_MSIL\System.Configuration\2.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', No symbols loaded. </code></pre> <p>My question is: how can I determine which library is missing because, at this point, I cannot see the values passed to:</p> <pre><code>mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) + 0x3a bytes </code></pre>
24,652,463
4
1
null
2009-12-22 10:49:42.243 UTC
7
2020-08-12 20:14:01.713 UTC
null
null
null
null
221,342
null
1
29
c#|debugging|assemblies
27,004
<p>There is in fact a built in mechanism for just these diagnostics.</p> <p>(1) In your project properties/Debug, make sure 'Enable native code debugging' is checked:</p> <p><img src="https://i.stack.imgur.com/C4vL2.png" alt="enter image description here" /></p> <p>(2) Raise the <a href="https://msdn.microsoft.com/en-us/library/windows/hardware/ff556886(v=vs.85).aspx" rel="noreferrer">show-loader-snaps</a> flag - it is a registry key in the IFEO, and is accessible via the 'GlobalFlags' GUI:</p> <p><img src="https://i.stack.imgur.com/2SgTe.png" alt="enter image description here" /></p> <p>(3) Run the app from a debugger - or attach before the load error. Inspect the (<em>very</em>) verbose output pane. You can mostly skip to the end or look for 'ERROR'.</p> <p>More details <a href="http://ofekshilon.com/2013/06/22/entry-point-not-found-and-other-dll-loading-problems/" rel="noreferrer">here</a>.</p>
2,006,351
Gettext .po files under version control
<p>Currently using Gettext on a project and the .po files are nicely kept under version control.</p> <p>PO files of course contain translations, but in addition to that they also contain some metadata - information about the exact files and line numbers where the translatable strings are located.</p> <p>The problem is that each time you update the PO files the metadata changes a whole lot more than the actual translations. This makes it really hard to later see from version control diff what actually was changed - you just see a myriad of changes to file names and line numbers. Like that:</p> <pre><code>- #: somefile.js:43 - #: somefile.js:45 - #: somefile.js:118 + #: somefile.js:203 + #: somefile.js:215 msgid "Translate me please" msgstr "Tõlgi mind palun" - #: somefile.js:23 - #: somefile.js:135 + #: otherfile.js:23 + #: otherfile.js:135 msgid "Note" msgstr "Märkus" - #: andThatFile.js:18 #: orThisFile.js:131 - msgid "Before I was like this" - msgstr "Selline olin ma enne" + msgid "I happen to be changed" + msgstr "Paistab, et mind muudeti" </code></pre> <p>Of course, a simple fix would be to just disable the generation of filename/linenumber comments in xgettext output. But I actually find those file names to be quite useful hints when translating.</p> <p>I surely cannot be the only one who doesn't like the diffs of his PO files. Suggestions?</p>
2,021,154
4
2
null
2010-01-05 13:46:01.907 UTC
13
2012-07-02 09:27:33.16 UTC
2010-01-08 13:23:13.277 UTC
null
121,332
null
15,982
null
1
37
git|version-control|diff|gettext|po-file
4,690
<p>A simple fix would be to apply a grep filter to remove comment metadata from the viewed diff. You can either do this to the <em>output</em> of the version control diff utility:</p> <pre><code>myVersionControl diff REV1 REV2 filea | grep -v '^..#' </code></pre> <p>or you may be able to instruct the version control diff utility to ignore these before it makes the comparison, which will likely result in a more reliable and prettier output:</p> <p>I don't know what version control system you use, but git (for example) allows you to preprocess the input to diff <em>and remove the comment lines</em> for certain file types (thanks VonC), see <code>man gitattributes</code> and search for <em>Performing text diffs of binary files</em>. Here's the body of a sample script to save as <code>/usr/local/bin/strippocomments</code> which will do that:</p> <pre><code>grep -v '^#:' $1 </code></pre> <p>You can then tell git to use this script to preprocess po files, by adding the following to the file <code>.git/info/attributes</code> in your repository:</p> <pre><code>*.po diff=podiff </code></pre> <p>and to the file <code>.git/config</code> in your repository:</p> <pre><code>[diff "podiff"] textconv = /usr/local/bin/strippocomments </code></pre> <p>Using git diff should then not include any lines starting with <code>#:</code>.</p> <p>Note that the diffs generated from <code>git diff</code> using this approach should not be used for patching - but <code>git format-patch</code> will still use the default diff, so patches generated for emailing will still be ok.</p>
52,785,101
seaborn scatterplot marker size for ALL markers
<p>I can't find out anywhere how to change the marker size on seaborn scatterplots. There is a <code>size</code> option listed in the <a href="https://seaborn.pydata.org/generated/seaborn.scatterplot.html" rel="noreferrer">documentation</a> but it is only for when you want variable size across points. I want the same size for all points but larger than the default!</p> <p>I tried making a new column of integers in my dataframe and set that as the size, but it looks like the actual value doesn't matter, it changes the marker size on a relative basis, so in this case all the markers were still the same size as the default.</p> <p>Edit: here's some code</p> <pre><code>ax = sns.scatterplot(x="Data Set Description", y="R Squared", data=mean_df) plt.show() </code></pre> <p>I just tried something and it worked, not sure if it's the best method though. I added size=[1, 1, 1, 1, 1, 1] and sizes=(500, 500). So essentially I'm setting all sizes to be the same, and the range of sizes to be only at 500.</p>
52,785,672
2
3
null
2018-10-12 18:19:33.727 UTC
7
2021-10-12 19:08:21.07 UTC
2018-10-12 18:27:26.043 UTC
null
8,020,900
null
8,020,900
null
1
95
python|matplotlib|seaborn
117,847
<p>You can do so by giving a value to the <code>s</code> argument to change the marker size.</p> <p>Example:</p> <pre><code>ax = sns.scatterplot(x="Data Set Description", y="R Squared", data=mean_df, s=10) </code></pre>
10,391,856
Difference between jQuery and jQuery Mobile?
<p>I'm new to mobile web development, and I just made a mobile-app with PhoneGap, employing frequent use of jQuery.</p> <p>But there were naturally a couple of glitches related to how I formatted things and the way they actually appeared on the mobile device screens I was testing with, and in trying to work these out I stumbled across many suggestions to make things easier on myself by using jQuery mobile.</p> <p>Now this confuses me-- jQuery had no roll in formatting. That was just my beginner's level knowledge of mobile CSS that caused the problems.</p> <p>So what exactly does jQuery mobile do, and how is it different from ordinary jQuery? If I already know jQuery, what's going to be new to me?</p>
10,392,109
4
2
null
2012-04-30 23:30:34.22 UTC
27
2015-02-09 23:57:32.7 UTC
2015-02-09 23:57:32.7 UTC
null
1,029,146
null
1,029,146
null
1
93
jquery|jquery-mobile
61,427
<p><strong>jQuery</strong> is purely designed to simplify and standardise scripting across browsers. It focuses on the low-level stuff: creating elements, manipulating the DOM, managing attributes, performing HTTP requests, etc.</p> <p><strong>jQueryUI</strong> is a set of user interface components &amp; features built on top of jQuery (i.e. it needs jQuery to work): buttons, dialog boxes, sliders, tabs, more advanced animations, drag/drop functionality.</p> <p>jQuery and jQueryUI are both designed to be 'added' to your site (desktop or mobile) - if you want to add a particular feature, jQuery or jQueryUI might be able to help.</p> <p><strong>jQuery Mobile</strong>, however, is a full framework. It's intended to be your starting point for a mobile site. It requires jQuery and makes use of features of both jQuery and jQueryUI to provide both UI components and API features for building mobile-friendly sites. You can still use as much or as little of it as you like, but jQuery Mobile <em>can</em> control the whole viewport in a mobile-friendly way if you let it.</p> <p>Another major difference is that jQuery and jQueryUI aim to be a layer on top of your HTML and CSS. You should be able to just leave your markup alone and enhance it with jQuery. However, jQuery Mobile provides ways to define where you want components to appear using HTML alone - e.g. (from the jQuery Mobile site):</p> <pre><code>&lt;ul data-role="listview" data-inset="true" data-filter="true"&gt; &lt;li&gt;&lt;a href="#"&gt;Acura&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Audi&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;BMW&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Cadillac&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Ferrari&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>The <code>data-role</code> attribute tells jQuery Mobile to turn this list into a mobile-friendly UI component and the <code>data-inset</code> and <code>data-filter</code> attributes set properties of that - without writing a single line of JavaScript. jQueryUI components, on the other hand, are normally created by writing a few lines of JavaScript to instantiate the component in the DOM.</p>
26,274,082
"The frameborder attribute on the iframe element is obsolete. Use CSS instead."
<p>I'm trying to validate my website with the W3C validator but it doesn't work. I have a YouTube iframe and this is the error:</p> <blockquote> <p>The frameborder attribute on the iframe element is obsolete. Use CSS instead.</p> </blockquote> <p>Screenshot:</p> <p><a href="https://i.stack.imgur.com/VCiJV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VCiJV.png" alt="enter image description here" /></a></p> <p>And this is my index.html (cropped):</p> <pre><code>&lt;!-- Video --&gt; &lt;div class=&quot;video-container box-size&quot;&gt; &lt;iframe width=&quot;700&quot; height=&quot;312&quot; src=&quot;http://www.youtube.com/embed/OfUPsnAtZMI&quot; frameborder=&quot;0&quot; allowfullscreen&gt;&lt;/iframe&gt; &lt;/div&gt; </code></pre> <p>How can I correct it?</p>
26,274,377
5
1
null
2014-10-09 08:47:19.22 UTC
5
2022-04-16 08:20:25.92 UTC
2020-06-28 19:47:49.31 UTC
null
183,704
null
4,124,469
null
1
35
html|iframe|w3c-validation
45,880
<p>As they state themselves "The frameborder attribute is not supported in HTML5. Use CSS instead."</p> <p>The equivalent of frameborder in css is <code>border: 0px;</code>. Add it to your iframe in css.</p>
36,575,229
Android Studio 2.0 - pause/white screen on App first run
<p>Since upgrading to Android Studio 2.0 (stable) I've noticed an issue that wasn't there in the previous version of Android Studio 1.5 I had installed.</p> <p>I'm working on a current project, which I would build (debug version) and run, both on a real device, and an emulator, I was doing this in Android Studio 1.5.</p> <p>Since upgrading Android Studio 2.0 whenever I make a build (debug) the same project/app and run it I have noticed that I get a pause on the device, or emulator. I get a white screen for a couple seconds before the app opens, which I didn't have before in AS 1.5, the app would open straight away, no pause, no white screen - this happens whether the phone is plugged in using ADB, or unplugged. If the App is still in phones memory it opens straight away, but if phone is restarted I get the pause, and white screen when the app is opened.</p> <p>Is their a solution to this? Has anyone else experienced this? I may be a bit premature with this as I haven't done a release build yet, however this seems like a strange issue - if it is an issue!</p> <p><strong>Edit:</strong></p> <p>I am using Instant Run, however this happens whether a device is plugged in or not. Would Instant Run make a difference to its execution if it wasn't plugged in?</p> <p><strong>Update:</strong></p> <p>As below answer turning off 'Instant Run' options in Android Studio 2.0 cures the problem. Interestingly however, comments suggest that when using Instant Run APK sizes are smaller. What does this mean? Could it be that Instant Run uses the older Dalvik/JIT compiler rather than ART? This could explain the Apk size difference, and the lag (Dalvik compiles on the fly - JIT). Also ART would need to install/compile each time the app was Run, meaning its Apk size would be larger, and slower to execute, as is the case. </p> <p>Hopefully someone with more experience and knowledge maybe able to confirm or debunk this..</p>
36,593,849
2
13
null
2016-04-12 13:46:36.17 UTC
12
2021-03-05 17:54:57.693 UTC
2016-04-18 21:30:37.427 UTC
null
4,252,352
null
4,252,352
null
1
31
android|android-studio
10,897
<p><a href="https://i.stack.imgur.com/W1pVD.png" rel="nofollow noreferrer">Check image for reference</a> Turn off Instant Run in Settings. File&gt;Settings&gt;Build,Deployment&gt;Instant Run Deselect all options shown there.</p> <p>Now white screen problem is solved.</p> <p>In android studio 2.0,My APK size was 16 MB while using Instant Run. Without using Instant Run it became 27 MB. While in 1.5 .. the size was 27 MB.</p> <p>Instant Run is the culprit.</p> <ul> <li>White screen Issue/ Instant Run is only for Debug builds .. Issue will not affect release builds.</li> </ul>
49,092,985
Difference between Javascript async functions and Web workers?
<p>Threading-wise, what's the difference between web workers and functions declared as </p> <pre><code>async function xxx() { } </code></pre> <p>?</p> <p>I am aware web workers are executed on separate threads, but what about async functions? Are such functions threaded in the same way as a function executed through setInterval is, or are they subject to yet another different kind of threading?</p>
49,093,472
6
3
null
2018-03-04 07:20:15.443 UTC
10
2021-06-18 15:08:57.097 UTC
null
null
null
null
2,276,379
null
1
29
javascript|async-await|web-worker
8,771
<p><code>async</code> functions are just syntactic sugar around Promises and they are wrappers for callbacks.</p> <pre><code>// v await is just syntactic sugar // v Promises are just wrappers // v functions taking callbacks are actually the source for the asynchronous behavior await new Promise(resolve =&gt; setTimeout(resolve)); </code></pre> <p>Now a callback could be called back immediately by the code, e.g. if you <code>.filter</code> an array, or the engine could store the callback internally somewhere. Then, when a specific <em>event</em> occurs, it executes the callback. One could say that these are <em>asynchronous callbacks</em>, and those are usually the ones we wrap into Promises and <code>await</code> them.</p> <p>To make sure that two callbacks do not run at the same time (which would make concurrent modifications possible, which causes a lot of trouble) whenever an event occurs the event does not get processed immediately, instead a <a href="https://262.ecma-international.org/11.0/#sec-jobs" rel="noreferrer"><em>Job</em></a> (callback with arguments) gets placed into a <em>Job Queue</em>. Whenever the JavaScript <a href="https://262.ecma-international.org/11.0/#sec-agents" rel="noreferrer"><em>Agent</em></a> (= thread²) finishes execution of the current job, it looks into that queue for the next job to process¹.</p> <p>Therefore one could say that an <code>async function</code> is just a way to express a <em>continuous series of jobs</em>.</p> <pre><code> async function getPage() { // the first job starts fetching the webpage const response = await fetch(&quot;https://stackoverflow.com&quot;); // callback gets registered under the hood somewhere, somewhen an event gets triggered // the second job starts parsing the content const result = await response.json(); // again, callback and event under the hood // the third job logs the result console.log(result); } // the same series of jobs can also be found here: fetch(&quot;https://stackoverflow.com&quot;) // first job .then(response =&gt; response.json()) // second job / callback .then(result =&gt; console.log(result)); // third job / callback </code></pre> <p>Although two jobs cannot run in parallel on one agent (= thread), the job of one async function might run between the jobs of another. Therefore, two async functions can run <a href="https://en.wikipedia.org/wiki/Concurrent_computing" rel="noreferrer"><em>concurrently</em></a>.</p> <p>Now who does produce these asynchronous events? That depends on what you are awaiting in the <code>async</code> function (or rather: what callback you registered). If it is a timer (<code>setTimeout</code>), an internal timer is set and the JS-thread continues with other jobs until the timer is done and then it executes the callback passed. Some of them, especially in the Node.js environment (<code>fetch</code>, <code>fs.readFile</code>) will start another thread <em>internally</em>. You only hand over some arguments and receive the results when the thread is done (through an event).</p> <p>To get real parallelism, that is running two jobs at the same time, multiple agents are needed. <code>WebWorkers</code> are exactly that - agents. The code in the WebWorker therefore runs independently (has it's own job queues and executor).</p> <p>Agents can communicate with each other via events, and you can react to those events with callbacks. For sure you can <code>await</code> actions from another agent too, if you wrap the callbacks into Promises:</p> <pre class="lang-js prettyprint-override"><code>const workerDone = new Promise(res =&gt; window.onmessage = res); (async function(){ const result = await workerDone; //... })(); </code></pre> <p>TL;DR:</p> <pre><code>JS &lt;---&gt; callbacks / promises &lt;--&gt; internal Thread / Webworker </code></pre> <hr /> <p>¹ There are other terms coined for this behavior, such as <em>event loop / queue</em> and others. The term <em>Job</em> is specified by ECMA262.</p> <p>² How the engine implements agents is up to the engine, though as one agent may only execute one Job at a time, it very much makes sense to have one thread per agent.</p>
7,389,394
How do I download a file with php and the Amazon S3 sdk?
<p>I'm trying to make it so that my script will show test.jpg in an Amazon S3 bucket through php. Here's what I have so far:</p> <pre><code>require_once('library/AWS/sdk.class.php'); $s3 = new AmazonS3($key, $secret); $objInfo = $s3-&gt;get_object_headers('my_bucket', 'test.jpg'); $obj = $s3-&gt;get_object('my_bucket', 'test.jpg', array('headers' =&gt; array('content-disposition' =&gt; $objInfo-&gt;header['_info']['content_type']))); echo $obj-&gt;body; </code></pre> <p>This just dumps out the file data on the page. I think I need to also send the content-disposition header, which I thought was being done in the get_object() method, but it isn't.</p> <p>Note: I'm using the SDK available here: <a href="http://aws.amazon.com/sdkforphp/">http://aws.amazon.com/sdkforphp/</a></p>
7,389,781
6
2
null
2011-09-12 14:22:55.41 UTC
6
2020-03-20 14:23:44.997 UTC
2012-07-24 17:38:02.28 UTC
null
76,835
null
361,833
null
1
18
php|amazon-s3
54,799
<p>Got it to work by echo'ing out the content-type header before echo'ing the $object body.</p> <pre><code>$objInfo = $s3-&gt;get_object_headers('my_bucket', 'test.jpg'); $obj = $s3-&gt;get_object('my_bucket', 'test.jpg'); header('Content-type: ' . $objInfo-&gt;header['_info']['content_type']); echo $obj-&gt;body; </code></pre>
7,289,769
Ellipsis for overflow text in dropdown boxes
<p>I'm fixing the width of one of my dropdown boxes (yes I know there are cross-browser issues with doing this).</p> <p>Is there a non-js way to cut off overflowing text and append ellipses? text-overflow:ellipsis doesn't work for <code>&lt;select&gt;</code> elements (at least in Chrome).</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>select, div { width:100px; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!--works for a div--&gt; &lt;div&gt; A long option that gets cut off &lt;/div&gt; &lt;!--but not for a select--&gt; &lt;select&gt; &lt;option&gt;One - A long option that gets cut off&lt;/option&gt; &lt;option&gt;Two - A long option that gets cut off&lt;/option&gt; &lt;/select&gt;</code></pre> </div> </div> </p> <p>Example here: <a href="http://jsfiddle.net/t5eUe/" rel="noreferrer">http://jsfiddle.net/t5eUe/</a></p>
7,313,425
9
2
null
2011-09-02 22:21:54.383 UTC
7
2021-06-01 07:01:14.143 UTC
2018-03-27 00:04:53.983 UTC
null
782,034
null
683,200
null
1
81
html|css
133,992
<p><strong>NOTE:</strong> As of July 2020, <code>text-overflow: ellipsis</code> works for <code>&lt;select&gt;</code> on Chrome</p> <p>HTML is limited in what it specifies for form controls. That leaves room for operating system and browser makers to do what they think is appropriate on that platform (like the iPhone’s modal <code>select</code> which, when open, looks totally different from the traditional pop-up menu).</p> <p>If it bugs you, you can use a customizable replacement, like <a href="http://harvesthq.github.com/chosen/" rel="noreferrer">Chosen</a>, which looks distinct from the native <code>select</code>.</p> <p>Or, file a bug against a major operating system or browser. For all we know, the way text is cut off in <code>select</code>s might be the result of a years-old oversight that everyone copied, and it might be time for a change.</p>
14,078,054
GAE webapp2 session: the correct process of creating and checking sessions
<p>I tried to implement GAE's webapp2 session, but there seems very little documentation about it. According to <a href="http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html">http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html</a>, my steps are as follows:</p> <p>1.Configure and add config to the main application:</p> <pre><code>config = {} config['webapp2_extras.sessions'] = { 'secret_key': 'my_secret_key', } app = webapp2.WSGIApplication([...], config=config) </code></pre> <p>2.Create session in the login handler</p> <pre><code># Delete existent session --&gt; not mention in the tutorial # member is found self.session_store = sessions.get_store(request=handler.request) self.session['account'] = member.account </code></pre> <p>3.Check if a session exists at various locations in my program</p> <pre><code>if self.session['account']: # Session exists </code></pre> <p>4.Delete session when user logs out</p> <pre><code>--&gt; not mentioned in the tutorial </code></pre> <p>My questions:</p> <ol> <li><p>I got error message " ... object has no attribute 'session'" during the session creation process (Step 2)</p></li> <li><p>How do I delete a session in steps 2 and 4?</p></li> <li><p>Is the overall session management process correct?</p></li> </ol> <p>Thanks.</p>
14,151,821
3
0
null
2012-12-29 01:59:25.087 UTC
16
2014-09-03 14:11:35.167 UTC
2012-12-29 13:10:24.673 UTC
null
1,802,305
null
1,802,305
null
1
15
google-app-engine|session|webapp2
8,733
<p>This may not be a direct answer to the question, but it is a solution I found using gaesessions instead of GAE's webapp2 session and I would like to share with everybody. Here we go:</p> <ol> <li><p>Download gaesessions from <a href="https://github.com/dound/gae-sessions" rel="nofollow">https://github.com/dound/gae-sessions</a> by clicking "Download ZIP" button. The downloaded file is "gae-sessions-master.zip".</p></li> <li><p>Unzip the file (a directory "gae-sessions-master" will be created), and copy the directory "gaessions" to the root directory of your application (i.e., where "app.yaml" is)</p></li> <li><p>Create a file called "appengine_config.py" in the root directory, with the following content (copied form <a href="https://github.com/dound/gae-sessions/tree/master/demo" rel="nofollow">https://github.com/dound/gae-sessions/tree/master/demo</a>):</p> <pre><code>from gaesessions import SessionMiddleware # Original comments deleted ... # Create a random string for COOKIE_KDY and the string has to # be permanent. "os.urandom(64)" function may be used but do # not use it *dynamically*. # For me, I just randomly generate a string of length 64 # and paste it here, such as the following: COOKIE_KEY = 'ppb52adekdhD25dqpbKu39dDKsd.....' def webapp_add_wsgi_middleware(app): from google.appengine.ext.appstats import recording app = SessionMiddleware(app, cookie_key=COOKIE_KEY) app = recording.appstats_wsgi_middleware(app) return app </code></pre></li> <li><p>Create a session when a user logs in (variable <em>account</em> is the user's account):</p> <pre><code>from gaesessions import get_current_session session = get_current_session() if session.is_active(): session.terminate() # start a session for the user (old one was terminated) session['account'] = account </code></pre></li> <li><p>Check if the user's session exists, if yes, return user's account:</p> <pre><code>from gaesessions import get_current_session def checkSession(): session = get_current_session() if session.is_active(): return session['account'] return False </code></pre></li> <li><p>Delete the session when the user logs out:</p> <pre><code>def logout(): session = get_current_session() if session.is_active(): session.terminate() </code></pre></li> <li><p>Finally, you may create a cron job to clean expired sessions periodically:</p></li> </ol> <p>cron.yaml:</p> <pre><code>- description: daily session cleanup url: /clean_up_sessions schedule: every day 3:00 timezone: ... (Your time zone) </code></pre> <p>Function:</p> <pre><code>from gaesessions import delete_expired_sessions class clean_up_sessions(webapp2.RequestHandler): def get(self): while not delete_expired_sessions(): pass </code></pre> <p>Hope this helps.</p>
14,068,944
Attempt to index local 'self' (a nil value)
<p>I have a problem with classes. I got below error: Attempt to index local 'self' (a nil value) When I call the getter method of below class. Item.lua file:</p> <pre><code>require "classlib" Item = class("Item") function Item:__init() self.interval = 1 end function Item:getInterval() return self.interval end </code></pre> <p>I'm calling this getter function like this:</p> <pre><code>dofile("../src/item.lua") item = Item() function test_item() assert_equal(1, item.getInterval()) end </code></pre> <p>What's the problem here?</p> <p>Kind regards...</p>
14,069,787
3
3
null
2012-12-28 11:39:27.293 UTC
2
2017-01-16 07:23:17.307 UTC
2012-12-28 22:30:07.72 UTC
null
221,509
null
1,320,039
null
1
17
lua
38,218
<p>In general, you should call member functions by <code>:</code>.</p> <p>In Lua, colon (<code>:</code>) represents a call of a function, supplying <code>self</code> as the first parameter.</p> <p>Thus</p> <pre><code>A:foo() </code></pre> <p>Is roughly equal to</p> <pre><code>A.foo(A) </code></pre> <p>If you don't specify A as in <code>A.foo()</code>, the body of the function will try to reference <code>self</code> parameter, which hasn't been filled neither explicitly nor implicitly.</p> <p>Note that if you call it from <em>inside</em> of the member function, <code>self</code> will be already available:</p> <pre><code>-- inside foo() -- these two are analogous self:bar() self.bar(self) </code></pre> <p>All of this information you'll find in any good Lua book/tutorial.</p>
14,130,104
How do I test if one array is a subset of another?
<p>What's the best (cleanest) way to provide this sort of logic?</p> <pre><code>var colors = ["red","white","blue"]; logic(colors,["red","green"]); //false logic(colors,["red"]); //true logic(colors,["red","purple"]); //false logic(colors,["red","white"]); //true logic(colors,["red","white","blue"]); //true logic(colors,["red","white","blue","green"]); //false logic(colors,["orange"]); //false </code></pre> <p>Possibly using <a href="http://underscorejs.org/">underscore.js</a>?</p>
14,130,166
2
3
null
2013-01-02 22:17:33.407 UTC
1
2013-01-02 23:24:54.317 UTC
2013-01-02 23:24:52.96 UTC
null
185,544
null
340,688
null
1
39
javascript|underscore.js
16,364
<p>Assuming each element in the array is unique: Compare the length of <code>hand</code> with the length of the intersection of both arrays. If they are the same, all elements in <code>hand</code> are also in <code>colors</code>.</p> <pre><code>var result = (hand.length === _.intersection(hand, colors).length); </code></pre> <p><a href="http://jsfiddle.net/GXGun/"><strong>DEMO</strong></a></p>
14,026,539
Can I append an array to 'formdata' in javascript?
<p>I'm using FormData to upload files. I also want to send an array of other data. </p> <p>When I send just the image, it works fine. When I append some text to the formdata, it works fine. When I try to attach the 'tags' array below, everything else works fine but no array is sent.</p> <p>Any known issues with FormData and appending arrays?</p> <p>Instantiate formData:</p> <p><code>formdata = new FormData();</code></p> <p>The array I create. Console.log shows everything working fine.</p> <pre><code> // Get the tags tags = new Array(); $('.tag-form').each(function(i){ article = $(this).find('input[name="article"]').val(); gender = $(this).find('input[name="gender"]').val(); brand = $(this).find('input[name="brand"]').val(); this_tag = new Array(); this_tag.article = article; this_tag.gender = gender; this_tag.brand = brand; tags.push(this_tag); console.log('This is tags array: '); console.log(tags); }); formdata.append('tags', tags); console.log('This is formdata: '); console.log(formdata); </code></pre> <p>How I send it: </p> <pre><code> // Send to server $.ajax({ url: "../../build/ajaxes/upload-photo.php", type: "POST", data: formdata, processData: false, contentType: false, success: function (response) { console.log(response); $.fancybox.close(); } }); </code></pre>
14,026,554
13
4
null
2012-12-24 23:43:55.643 UTC
9
2021-10-06 14:32:49.98 UTC
null
null
null
null
1,001,938
null
1
51
javascript|jquery|arrays|multipartform-data
185,723
<p>How about this?</p> <pre><code>formdata.append('tags', JSON.stringify(tags)); </code></pre> <p>... and, correspondingly, using <code>json_decode</code> on server to deparse it. See, the second value of FormData.append can be...</p> <blockquote> <p>a Blob, File, or a string, if neither, the value is converted to a string</p> </blockquote> <p>The way I see it, your <code>tags</code> array contains objects (@Musa is right, btw; making <code>this_tag</code> an Array, then assigning string properties to it makes no sense; use plain object instead), so native conversion (with <code>toString()</code>) won't be enough. JSON'ing should get the info through, though.</p> <p>As a sidenote, I'd rewrite the property assigning block just into this:</p> <pre><code>tags.push({article: article, gender: gender, brand: brand}); </code></pre>
14,186,245
Unit testing c++. How to test private members?
<p>I would like to make unit tests for my C++ application.</p> <p>What is the correct form to test private members of a class? Make a friend class which will test the private members, use a derived class, or some other trick?</p> <p>Which technique does the testing APIs use?</p>
14,186,518
8
15
null
2013-01-06 20:11:08.117 UTC
7
2021-10-20 05:53:54.85 UTC
2015-12-16 06:34:14.14 UTC
null
908,939
null
1,930,404
null
1
56
c++|unit-testing|testing
45,953
<p>Typically, one only tests the public interface as discussed in the question's comments. </p> <p>There are times however when it is helpful to test private or protected methods. For example, the implementation may have some non-trivial complexities that are hidden from users and that can be tested more precisely with access to non-public members. Often it's better to figure out a way to remove that complexity or figure out how to expose the relevant portions publicly, but not always.</p> <p>One way to allow unit tests access to non-public members is via the <a href="http://www.cplusplus.com/doc/tutorial/inheritance/" rel="noreferrer">friend</a> construct.</p>
29,148,374
How to Solve Low Disk Space for Android Studio?
<p>I am getting this error randomly and not sure as to why my disk space is getting low for Android Studio..</p> <blockquote> <p>Low disk space on a Android Studio system directory partition</p> </blockquote> <p><strong>Update</strong></p> <p>This Application is installed on a mac running 10.10.1 w/ 251GB internal storage and an OS restore Drive taking 10GB. </p> <p>I think the problem is, once the application was installed it was placed on the smaller partition. </p> <p>I will attempt to remove this application and all files associated to it, and reinstall. Hopefully this will solve the issue.</p>
32,056,012
10
3
null
2015-03-19 15:15:20.393 UTC
9
2021-11-28 15:20:39.56 UTC
2015-04-23 20:15:57.377 UTC
null
1,565,984
null
1,565,984
null
1
51
android|android-studio
76,547
<p>You can install studio and SDK separately into different partitions: <a href="http://developer.android.com/sdk/index.html#Other" rel="noreferrer">http://developer.android.com/sdk/index.html#Other</a></p> <p>Or you can move your existing SDK folder anywhere and then just point studio to it in preferences.</p> <p>Also consider that AVD files are actually stored in your system <strong>user</strong> folder (<code>user/.android/avd</code> on Windows, not sure where exactly on mac), not in SDK folder.</p>
32,878,283
Unable to profile app on device with iOS 9.0.1 using Xcode 7, 7.0.1 or 7.1 beta
<p>I have been trying unsuccessfully to profile my device (via Instruments) using the latest version of Xcode 7.0.1 (7A1001 released 9/28), as well as the previous version of Xcode 7 (7A218), as well as Xcode 7.1 Beta 2 (7B75).</p> <p>My device is an iPhone 6+ with iOS 9.0.1 installed - the latest GM release of iOS9. I am able to run / debug applications on this device without issues.</p> <p>In the screenshots below you can see that my device is disabled (greyed out) in all screenshots in all versions. I am able to profile other devices running iOS 8.4.1 without any issues. </p> <p>Does the current version of Xcode not support profiling against iOS 9.0.1 or is there some kind of configuration setting or known work around for this? </p> <p><strong>Xcode 7.0.1:</strong><br> <a href="https://i.stack.imgur.com/qTPVR.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qTPVR.png" alt="Xcode 7.0.1"></a></p> <p><strong>Xcode 7.0:</strong><br> <a href="https://i.stack.imgur.com/CWM6Y.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CWM6Y.png" alt="Xcode 7.0"></a></p> <p><strong>Xcode 7.1 beta 2:</strong><br> <a href="https://i.stack.imgur.com/l4RUD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/l4RUD.png" alt="Xcode 7.1 beta 2"></a></p>
33,035,618
4
4
null
2015-10-01 01:54:22.757 UTC
16
2019-10-11 10:29:58.497 UTC
null
null
null
null
1,470,581
null
1
42
ios|iphone|xcode|xcode7|xcode7.1beta
12,605
<p><strong>TL;DR</strong> - Perform a complete reboot of your device; restart Xcode &amp; instruments; select "Open Xcode" if prompted to enable the device for development.</p> <p><strong>Update 3/31/2016:</strong> I haven't encountered any issues with the latest version(s) of Xcode (7.2.x, 7.3), so it seems that the stability here has been improved. </p> <hr> <p>I believe I may have finally gotten this to work properly. Detailed steps:</p> <ol> <li>Unplug the device from your Mac &amp; power down the device completely (hold the power button for several seconds; slide to power off). </li> <li>Close Xcode and Instruments. </li> <li>Restart the device &amp; once it has booted completely re-connect it to your Mac. </li> <li>Re-launch Xcode. Here, my device showed as disabled and Xcode indicated that the device was not available for use.</li> <li>Open your project; clean (Shift+Command+K), Build (Command+B), Profile (Command+I).</li> <li>After Instruments launched I noticed that the device was enabled. Upon selecting it, a message was displayed with the title "Enable this device for development?" and message "This will open Xcode and enable this device for development." (Note that this only happened to me the first time I went through this process even though I had already been using the device for development - whereas some users have also reported that they are not presented with this dialogue.)</li> </ol> <p><a href="https://i.stack.imgur.com/ciAwX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ciAwX.png" alt="Enable this device for development?"></a></p> <ol start="7"> <li>Click "Open Xcode". Here Xcode did not prompt me for anything nor was anything displayed - no additional messages indicating anything had been done or that the device was or was not available for development. Opening the Devices window, the device appeared to be available. (I have not been presented with this option for subsequent occurrences.)</li> <li>Now I was able to select the device in Instruments and profile it. </li> </ol> <p>As a side note, I was also again able to delete installed apps from the Devices window (I realized that this was not possible to do previously).</p> <p>I'm unsure how my device ended up in this state however I will be on the lookout to see if this continues to occur.</p> <p>Please note that this was done using <strong>Xcode 7.0.1</strong>.</p> <hr> <p><strong>Update:</strong> My device seems to lapse back into not being able to be used for profiling some time after performing these steps - I've had to reboot my device again in order for it to be available for profiling. Not sure what is triggering this behavior but I will file a Radar for this.</p>
19,778,612
change color for two geom_point() in ggplot2
<p>Sample dataset:</p> <pre><code>library(ggplot2) df = read.table(text = "id year value1 value2 value3 1 2000 1 2000 2001 1 2001 2 NA NA 1 2002 2 2000 NA 1 2003 2 NA 2003 2 2000 1 2001 2003 2 2002 2 NA 2000 2 2003 3 2002 NA 3 2002 2 2001 NA ", sep = "", header = TRUE) df$value1 &lt;- as.factor(df$value1) </code></pre> <p>I know how to change color for a factor variable with three levels:</p> <pre><code>p &lt;- ggplot(df, aes(y=id)) p &lt;- p + scale_colour_manual(name="", values =c("yellow", "orange", "red")) p &lt;- p + geom_point(aes(x=year, color=value1), size=4) p </code></pre> <p>I can also change the color for two numeric variables:</p> <pre><code>p &lt;- ggplot(df, aes(y=id)) p &lt;- p + scale_colour_manual(name="", values =c("value3"="grey", "value2"="black")) p &lt;- p + geom_point(aes(x=value3, colour ='value3'), size=3) p &lt;- p + geom_point(aes(x=value2, colour ='value2'), size=5) p </code></pre> <p>But I do not know how to change the color for both in the same graph? Does it also work with scale_color_manual?</p> <pre><code>p &lt;- last_plot() + geom_point(aes(x=year, color=value1)) p </code></pre>
19,867,642
2
2
null
2013-11-04 22:36:10.463 UTC
4
2013-11-08 20:05:06.01 UTC
null
null
null
null
2,954,100
null
1
14
r|ggplot2
49,968
<p>Is this what you are looking for?</p> <pre><code>ggplot(df, aes(y=id)) + geom_point(aes(x=year, color=value1), size=4) + geom_point(aes(x=value3, colour ='value3'), size=3) + geom_point(aes(x=value2, colour ='value2'), size=5) + scale_colour_manual(name="", values = c("1"="yellow", "2"="orange", "3"="red", "value3"="grey", "value2"="black")) </code></pre> <p><img src="https://i.stack.imgur.com/mb3qB.png" alt="enter image description here"></p> <p>Basically, just putting all possible colour labels in a single list.</p>
19,322,962
How can I list ALL DNS records?
<p>Is there any way I can list ALL DNS records for a domain?</p> <p>I know about such things as dig and nslookup but they only go so far. For example, if I've got a subdomain A record as</p> <pre><code>test A somedomain.co.uk </code></pre> <p>then unless I specifically ask for it, eg. </p> <pre><code>dig any test.somedomain.co.uk </code></pre> <p>I can't see it.</p> <p>Is there any way (other than looking at the records by going to the DNS manager) to see exactly what all the DNS records are?</p>
19,324,947
10
2
null
2013-10-11 16:28:30.133 UTC
60
2022-07-21 12:51:51.79 UTC
null
null
null
null
1,788,394
null
1
244
dns
553,141
<p>The short answer is that it's usually not possible, unless you control the domain.</p> <h1>Option 1: ANY query</h1> <p>When you query for ANY, you will get a list of all records at that level but not below.</p> <pre><code># try this dig google.com any </code></pre> <p>This may return A records, TXT records, NS records, MX records, etc if the domain name is exactly &quot;google.com&quot;. However, it will not return child records (e.g., <a href="http://www.google.com" rel="noreferrer">www.google.com</a>). More precisely, you MAY get these records if they exist.</p> <p>The name server does not have to return these records if it chooses not to do so (for example, to reduce the size of the response). Most DNS servers reject ANY queries.</p> <h1>Option 2: AXFR query</h1> <p>An AXFR is a zone transfer, and is likely what you want. However, these are typically restricted and not available unless you control the zone. You'll usually conduct a zone transfer directly from the authoritative server (the @ns1.google.com below) and often from a name server that may not be published (a stealth name server).</p> <pre><code># This will return &quot;Transfer failed&quot; dig @ns1.google.com google.com axfr </code></pre> <p>If you have control of the zone, you can set it up to get transfers that are protected with a TSIG key. This is a shared secret the client can send to the server to authorize the transfer.</p> <h1>Option 3: Scrape with a script</h1> <p>Another option is to scrape all DNS records with a script. You'd have to iterate through all the DNS record types, and also through common subdomains, depending on your needs.</p> <h1>Option 4: Use specialized tooling</h1> <p>There are some online tools that enumerate subdomains, and online tools that <a href="https://www.nslookup.io/" rel="noreferrer">list all DNS records</a> for a DNS name. Note that subdomain enumeration is usually not exhaustive.</p>
24,687,061
Can I somehow share an asynchronous queue with a subprocess?
<p>I would like to use a queue for passing data from a parent to a child process which is launched via <code>multiprocessing.Process</code>. However, since the parent process uses Python's new <code>asyncio</code> library, the queue methods need to be non-blocking. As far as I understand, <code>asyncio.Queue</code> is made for inter-task communication and cannot be used for inter-process communication. Also, I know that <code>multiprocessing.Queue</code> has the <code>put_nowait()</code> and <code>get_nowait()</code> methods but I actually need coroutines that would still block the current task (but not the whole process). Is there some way to create coroutines that wrap <code>put_nowait()</code>/<code>get_nowait()</code>? On another note, are the threads that <code>multiprocessing.Queue</code> uses internally compatible after all with an event loop running in the same process?</p> <p>If not, what other options do I have? I know I could implement such a queue myself by making use of asynchronous sockets but I hoped I could avoid that… </p> <p><strong>EDIT:</strong> I also considered using pipes instead of sockets but it seems <code>asyncio</code> is not compatible with <a href="https://docs.python.org/dev/library/multiprocessing.html#multiprocessing.Pipe" rel="noreferrer"><code>multiprocessing.Pipe()</code></a>. More precisely, <code>Pipe()</code> returns a tuple of <a href="https://docs.python.org/dev/library/multiprocessing.html#multiprocessing.Connection" rel="noreferrer"><code>Connection</code></a> objects which are <em>not</em> file-like objects. However, <code>asyncio.BaseEventLoop</code>'s methods <a href="https://docs.python.org/3.4/library/asyncio-eventloop.html#watch-file-descriptors" rel="noreferrer"><code>add_reader()</code>/<code>add_writer()</code></a> methods and <a href="https://docs.python.org/3.4/library/asyncio-eventloop.html#connect-pipes" rel="noreferrer"><code>connect_read_pipe()</code>/<code>connect_write_pipe()</code></a> all expect file-like objects, so it is impossible to asynchronously read from/write to such a <code>Connection</code>. In contrast, the usual file-like objects that the <code>subprocess</code> package uses as pipes pose no problem at all and <a href="https://code.google.com/p/tulip/source/browse/examples/child_process.py" rel="noreferrer">can easily be used in combination with <code>asyncio</code></a>.</p> <p><strong>UPDATE:</strong> I decided to explore the pipe approach a bit further: I converted the <code>Connection</code> objects returned by <code>multiprocessing.Pipe()</code> into file-like objects by retrieving the file descriptor via <a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Connection.fileno" rel="noreferrer"><code>fileno()</code></a> and passing it to <code>os.fdopen()</code>. Finally, I passed the resulting file-like object to the event loop's <code>connect_read_pipe()</code>/<code>connect_write_pipe()</code>. (There is some <a href="https://groups.google.com/forum/#!topic/python-tulip/6tRswyRhwE4" rel="noreferrer">mailing list discussion</a> on a related issue if someone is interested in the exact code.) However, <code>read()</code>ing the stream gave me an <code>OSError: [Errno 9] Bad file descriptor</code> and I didn't manage to fix this. Also considering the <a href="https://docs.python.org/3/library/asyncio-eventloops.html#windows" rel="noreferrer">missing support for Windows</a>, I will not pursue this any further. </p>
24,704,950
3
2
null
2014-07-10 22:03:10.327 UTC
17
2020-10-20 14:46:41.49 UTC
2014-07-11 10:06:32.45 UTC
null
36,253
null
36,253
null
1
17
python|queue|multiprocessing|shared-memory|python-asyncio
13,427
<p>Here is an implementation of a <code>multiprocessing.Queue</code> object that can be used with <code>asyncio</code>. It provides the entire <code>multiprocessing.Queue</code> interface, with the addition of <code>coro_get</code> and <code>coro_put</code> methods, which are <code>asyncio.coroutine</code>s that can be used to asynchronously get/put from/into the queue. The implementation details are essentially the same as the second example of my other answer: <code>ThreadPoolExecutor</code> is used to make the get/put asynchronous, and a <code>multiprocessing.managers.SyncManager.Queue</code> is used to share the queue between processes. The only additional trick is implementing <code>__getstate__</code> to keep the object picklable despite using a non-picklable <code>ThreadPoolExecutor</code> as an instance variable.</p> <pre><code>from multiprocessing import Manager, cpu_count from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor def AsyncProcessQueue(maxsize=0): m = Manager() q = m.Queue(maxsize=maxsize) return _ProcQueue(q) class _ProcQueue(object): def __init__(self, q): self._queue = q self._real_executor = None self._cancelled_join = False @property def _executor(self): if not self._real_executor: self._real_executor = ThreadPoolExecutor(max_workers=cpu_count()) return self._real_executor def __getstate__(self): self_dict = self.__dict__ self_dict['_real_executor'] = None return self_dict def __getattr__(self, name): if name in ['qsize', 'empty', 'full', 'put', 'put_nowait', 'get', 'get_nowait', 'close']: return getattr(self._queue, name) else: raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name)) @asyncio.coroutine def coro_put(self, item): loop = asyncio.get_event_loop() return (yield from loop.run_in_executor(self._executor, self.put, item)) @asyncio.coroutine def coro_get(self): loop = asyncio.get_event_loop() return (yield from loop.run_in_executor(self._executor, self.get)) def cancel_join_thread(self): self._cancelled_join = True self._queue.cancel_join_thread() def join_thread(self): self._queue.join_thread() if self._real_executor and not self._cancelled_join: self._real_executor.shutdown() @asyncio.coroutine def _do_coro_proc_work(q, stuff, stuff2): ok = stuff + stuff2 print("Passing %s to parent" % ok) yield from q.coro_put(ok) # Non-blocking item = q.get() # Can be used with the normal blocking API, too print("got %s back from parent" % item) def do_coro_proc_work(q, stuff, stuff2): loop = asyncio.get_event_loop() loop.run_until_complete(_do_coro_proc_work(q, stuff, stuff2)) @asyncio.coroutine def do_work(q): loop.run_in_executor(ProcessPoolExecutor(max_workers=1), do_coro_proc_work, q, 1, 2) item = yield from q.coro_get() print("Got %s from worker" % item) item = item + 25 q.put(item) if __name__ == "__main__": q = AsyncProcessQueue() loop = asyncio.get_event_loop() loop.run_until_complete(do_work(q)) </code></pre> <p>Output:</p> <pre><code>Passing 3 to parent Got 3 from worker got 28 back from parent </code></pre> <p>As you can see, you can use the <code>AsyncProcessQueue</code> both synchronously and asynchronously, from either the parent or child process. It doesn't require any global state, and by encapsulating most of the complexity in a class, is more elegant to use than my original answer.</p> <p>You'll probably be able to get better performance using sockets directly, but getting that working in a cross-platform way seems to be pretty tricky. This also has the advantage of being usable across multiple workers, won't require you to pickle/unpickle yourself, etc.</p>
24,650,186
Choosing between java.util.Date or java.sql.Date
<p>Should I use java.util.Date or java.sql.Date?</p> <p>I have a VisualFox database and I have retrieved the entities with the IntelliJ Idea wizard using an appropiate jdbc type 4 driver.</p> <p>The ide (or the driver) has created the date fields as Timestamp. However, the date fields are not timestamps but Date fields, they store year, month and day only.</p> <p>So I wonder if I should switch to java.util.Date or java.sql.Date. At first glance I thought that java.sql.Date should be the appropiate one, but it has many methods declared as deprecated.</p>
24,661,790
4
2
null
2014-07-09 09:38:34.213 UTC
8
2018-08-07 20:51:58.32 UTC
null
null
null
null
2,235,103
null
1
21
java|jpa|entity
20,107
<h1>tl;dr</h1> <blockquote> <p>Should I use java.util.Date or java.sql.Date?</p> </blockquote> <p>Neither.</p> <p>Both are obsolete as of <a href="https://en.wikipedia.org/wiki/Java_Database_Connectivity" rel="noreferrer">JDBC</a> 4.2 and later. Use <em>java.time</em> classes instead.</p> <ul> <li><strong>date-only value</strong><br />For a database type akin to SQL-standard <code>DATE</code>, use <code>java.time.LocalDate</code>. <ul> <li><code>LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;</code></li> <li><code>myPreparedStatement.setObject( ld , … ) ;</code></li> </ul></li> <li><strong>date with time-of-day in UTC value</strong><br />For a database type akin to SQL-standard <code>TIMESTAMP WITH TIME ZONE</code>, use <code>java.time.Instant</code>. <ul> <li><code>Instant instant = myResultSet.getObject( … , Instant.class ) ;</code></li> <li><code>myPreparedStatement.setObject( instant , … ) ;</code></li> </ul></li> </ul> <h1>Details</h1> <p>The question and other answers seem to be over-thinking the issue. <strong>A <a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Date.html" rel="noreferrer">java.sql.Date</a> is merely a <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Date.html" rel="noreferrer">java.util.Date</a> with its time set to <code>00:00:00</code>.</strong></p> <p>From <a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Date.html" rel="noreferrer">the java.sql.Date doc</a> (italicized text is mine)…</p> <blockquote> <p>Class Date</p> <p>java.lang.Object</p> <p>    java.util.Date        <em>← Inherits from j.u.Date</em></p> <p>        java.sql.Date </p> <p>…</p> <p>A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT.  <em>← Time-of-day set to Zero, midnight GMT/UTC</em></p> <p>To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.</p> </blockquote> <h1>Date-Only versus Date-Time</h1> <p>The core problem is:</p> <ul> <li><strong>SQL</strong><br/>In SQL, the <code>DATE</code> data type stores a date-only, without a time-of-day. </li> <li><strong>JAVA</strong><br/>In the badly designed date-time library bundled with the early versions of Java, they failed to include a class to represent a date-only.</li> </ul> <p>Instead of creating a date-only class, the Java team made <em>a terrible hack</em>. They took their date-time class (the misnamed <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Date.html" rel="noreferrer"><code>java.util.Date</code></a> class, containing both date <em>and</em> time) and extended it to have an instance set its time-of-day to midnight <a href="http://en.wikipedia.org/wiki/Coordinated_Universal_Time" rel="noreferrer">UTC</a>, <code>00:00:00</code>. That hack, that subclass of j.u.Date, is <a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Date.html" rel="noreferrer"><code>java.sql.Date</code></a>.</p> <p>All this hacking, poor design, and misnaming has made a confusing mess.</p> <h1>Which To Use</h1> <p>So when to use which? Simple, after cutting through the confusion. </p> <ul> <li>When reading or writing to a database’s <strong>date-only column</strong>, use <code>java.sql.Date</code> as it clumsily tries to mask its time-of-day. </li> <li>Everywhere else in Java, where you need a <strong>time-of-day</strong> along with your date, use <code>java.util.Date</code>.</li> <li>When you have a java.sql.Date in hand but need a java.util.Date, simply pass the java.sql.Date. As a subclass, <strong>a java.sql.Date <em>is</em> a java.util.Date</strong>.</li> </ul> <h1>Even Better</h1> <p>In modern Java, you now have a choice of decent date-time libraries to supplant the old and notoriously troublesome java.util.Date, Calendar, SimpleTextFormat, and java.sql.Date classes bundled with Java. The main choices are:</p> <ul> <li><a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-Time</a></li> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html" rel="noreferrer">java.time</a><br/>(inspired by <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-Time</a>, defined by <a href="https://jcp.org/en/jsr/detail?id=310" rel="noreferrer">JSR 310</a>, bundled with <a href="http://en.wikipedia.org/wiki/Java_version_history#Java_SE_8_.28March_18.2C_2014.29" rel="noreferrer">Java 8</a>, extended by the <a href="https://github.com/ThreeTen/threeten-extra" rel="noreferrer">ThreeTen-Extra</a> project)</li> </ul> <p>Both offer a <code>LocalDate</code> class to represent a date only, with no time-of-day and no time zone.</p> <p>A <a href="https://en.wikipedia.org/wiki/JDBC_driver" rel="noreferrer">JDBC driver</a> updated to JDBC 4.2 or later can be used to directly exchange <em>java.time</em> objects with the database. Then we can completely abandon the ugly mess that is the date-time classes in the java.util.* and java.sql.* packages.</p> <h3>setObject | getObject</h3> <p><a href="http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html" rel="noreferrer">This article</a> published by Oracle explains that the JDBC in Java 8 has been updated transparently to map a SQL <code>DATE</code> value to the new java.time.LocalDate type if you call <code>getObject</code> and <code>setObject</code> methods.</p> <p>In obtuse language, the bottom of the <a href="https://jcp.org/aboutJava/communityprocess/maintenance/jsr221/JDBC4.2MR-Oct232013.pdf" rel="noreferrer">JDBC 4.2 update spec</a> confirms that article, with new mappings added to the <code>getObject</code> and <code>setObject</code> methods. </p> <pre><code>myPreparedStatement.setObject( … , myLocalDate ) ; </code></pre> <p>…and…</p> <pre><code>LocalDate myLocalDate = myResultSet.getObject( … , LocalDate.class ) ; </code></pre> <h3>Convert</h3> <p>The spec also says new methods have been added to the java.sql.Date class to convert back and forth to java.time.LocalDate.</p> <ul> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Date.html#toInstant--" rel="noreferrer"><code>public java.time.instant toInstant()</code></a></li> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Date.html#toLocalDate--" rel="noreferrer"><code>public java.time.LocalDate toLocalDate()</code></a> </li> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/sql/Date.html#valueOf-java.time.LocalDate-" rel="noreferrer"><code>public static java.sql.Date valueOf(java.time.LocalDate)</code></a></li> </ul> <h1>Time Zone</h1> <p>The old <code>java.util.Date</code>, <code>java.sql.Date</code>, and <code>java.sql.Timestamp</code> are always in <a href="https://en.wikipedia.org/wiki/Coordinated_Universal_Time" rel="noreferrer">UTC</a>. The first two (at least) have a time zone buried deep in their source code but is used only under-the-surface such as the <code>equals</code> method, and has no getter/setter. </p> <p>More confusingly, their <code>toString</code> methods apply the JVM’s current default time zone. So to the naïve programmer it <em>seems</em> like they have a time zone but they do not.</p> <p>Both the buried time zone and the <code>toString</code> behavior are two of many reasons to avoid these troublesome old legacy classes.</p> <p>Write your business logic using <a href="http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html" rel="noreferrer">java.time</a> (Java 8 and later). Where java.time lacks, use <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-Time</a>. Both java.time and Joda-Time have convenient methods for going back and forth with the old classes where need be.</p> <p>Replacements:</p> <ul> <li><code>java.util.Date</code> is replaced by <a href="https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html" rel="noreferrer"><code>java.time.Instant</code></a></li> <li><a href="https://docs.oracle.com/javase/10/docs/api/java/sql/Timestamp.html" rel="noreferrer"><code>java.sql.Timestamp</code></a> is replaced by <a href="https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html" rel="noreferrer"><code>java.time.Instant</code></a></li> <li><a href="https://docs.oracle.com/javase/10/docs/api/java/sql/Date.html" rel="noreferrer"><code>java.sql.Date</code></a> is replaced by <a href="https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html" rel="noreferrer"><code>java.time.LocalDate</code></a>. </li> <li><a href="https://docs.oracle.com/javase/10/docs/api/java/sql/Time.html" rel="noreferrer"><code>java.sql.Time</code></a> is replaced by <a href="https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html" rel="noreferrer"><code>java.time.LocalTime</code></a>.</li> </ul> <p>The <a href="http://docs.oracle.com/javase/10/docs/api/java/time/Instant.html" rel="noreferrer"><code>Instant</code></a> class represents a moment on the timeline in <a href="https://en.wikipedia.org/wiki/Coordinated_Universal_Time" rel="noreferrer">UTC</a> with a resolution of <a href="https://en.wikipedia.org/wiki/Nanosecond" rel="noreferrer">nanoseconds</a> (up to nine (9) digits of a decimal fraction). </p> <p>All three <code>java.time.Local…</code> classes are all lacking any concept of <a href="https://en.wikipedia.org/wiki/Time_zone" rel="noreferrer">time zone</a> or <a href="https://en.wikipedia.org/wiki/UTC_offset" rel="noreferrer">offset-from-UTC</a>.</p> <hr> <h1>About <em>java.time</em></h1> <p>The <a href="http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html" rel="noreferrer"><em>java.time</em></a> framework is built into Java 8 and later. These classes supplant the troublesome old <a href="https://en.wikipedia.org/wiki/Legacy_system" rel="noreferrer">legacy</a> date-time classes such as <a href="https://docs.oracle.com/javase/10/docs/api/java/util/Date.html" rel="noreferrer"><code>java.util.Date</code></a>, <a href="https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html" rel="noreferrer"><code>Calendar</code></a>, &amp; <a href="http://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer"><code>SimpleDateFormat</code></a>.</p> <p>The <a href="http://www.joda.org/joda-time/" rel="noreferrer"><em>Joda-Time</em></a> project, now in <a href="https://en.wikipedia.org/wiki/Maintenance_mode" rel="noreferrer">maintenance mode</a>, advises migration to the <a href="http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html" rel="noreferrer">java.time</a> classes.</p> <p>To learn more, see the <a href="http://docs.oracle.com/javase/tutorial/datetime/TOC.html" rel="noreferrer"><em>Oracle Tutorial</em></a>. And search Stack Overflow for many examples and explanations. Specification is <a href="https://jcp.org/en/jsr/detail?id=310" rel="noreferrer">JSR 310</a>.</p> <p>You may exchange <em>java.time</em> objects directly with your database. Use a <a href="https://en.wikipedia.org/wiki/JDBC_driver" rel="noreferrer">JDBC driver</a> compliant with <a href="http://openjdk.java.net/jeps/170" rel="noreferrer">JDBC 4.2</a> or later. No need for strings, no need for <code>java.sql.*</code> classes.</p> <p>Where to obtain the java.time classes? </p> <ul> <li><a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8" rel="noreferrer"><strong>Java SE 8</strong></a>, <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9" rel="noreferrer"><strong>Java SE 9</strong></a>, <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10" rel="noreferrer"><strong>Java SE 10</strong></a>, and later <ul> <li>Built-in. </li> <li>Part of the standard Java API with a bundled implementation.</li> <li>Java 9 adds some minor features and fixes.</li> </ul></li> <li><a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6" rel="noreferrer"><strong>Java SE 6</strong></a> and <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7" rel="noreferrer"><strong>Java SE 7</strong></a> <ul> <li>Much of the java.time functionality is back-ported to Java 6 &amp; 7 in <a href="http://www.threeten.org/threetenbp/" rel="noreferrer"><strong><em>ThreeTen-Backport</em></strong></a>.</li> </ul></li> <li><a href="https://en.wikipedia.org/wiki/Android_(operating_system)" rel="noreferrer"><strong>Android</strong></a> <ul> <li>Later versions of Android bundle implementations of the java.time classes.</li> <li>For earlier Android (&lt;26), the <a href="https://github.com/JakeWharton/ThreeTenABP" rel="noreferrer"><strong><em>ThreeTenABP</em></strong></a> project adapts <a href="http://www.threeten.org/threetenbp/" rel="noreferrer"><strong><em>ThreeTen-Backport</em></strong></a> (mentioned above). See <a href="http://stackoverflow.com/q/38922754/642706"><em>How to use ThreeTenABP…</em></a>.</li> </ul></li> </ul> <p>The <a href="http://www.threeten.org/threeten-extra/" rel="noreferrer"><strong>ThreeTen-Extra</strong></a> project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html" rel="noreferrer"><code>Interval</code></a>, <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html" rel="noreferrer"><code>YearWeek</code></a>, <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html" rel="noreferrer"><code>YearQuarter</code></a>, and <a href="http://www.threeten.org/threeten-extra/apidocs/index.html" rel="noreferrer">more</a>.</p>
35,286,303
PDF file to be displayed on the dialog modal via bootstrap
<p>My requirement is, on click of a button, a pdf file should be displayed on dialog modal. Please Help!</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;Bootstrap Example&lt;/title&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;h2&gt;View PDF&lt;/h2&gt; &lt;!-- Trigger the modal with a button --&gt; &lt;button type="button" href="A - Cover Page.pdf" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal"&gt;A - Cover Page&lt;/button&gt; &lt;!-- Modal --&gt; &lt;div class="modal fade" id="myModal" role="dialog"&gt; &lt;div class="modal-dialog"&gt; &lt;!-- Modal content--&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal"&gt;&amp;times;&lt;/button&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;p&gt;Some text in the modal.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
35,290,998
7
4
null
2016-02-09 07:34:24.583 UTC
7
2021-09-09 20:07:38.17 UTC
2016-02-09 07:56:33.65 UTC
null
2,686,013
null
5,340,686
null
1
11
javascript|jquery|twitter-bootstrap
131,297
<p>Sorry to disappoint you but one cannot just show the pdf inside a modal by default. It is not an intended behavior. Even using <code>&lt;iframe&gt;</code>, you cannot render the pdf inside the bootstrap modal. Also most of the hacks provided online does not support cross-browser. The more ideal way is to use plugins for the same and I will give you the links for few using which you can achieve what you want.</p> <p>1) Checkout <code>PDFObject</code> JS,</p> <pre><code>&lt;script src="https://github.com/pipwerks/PDFObject/blob/master/pdfobject.min.js"&gt;&lt;/script&gt; </code></pre> <p>PDFObject embeds PDF files into HTML documents. <a href="http://pdfobject.com/" rel="noreferrer">Link</a>.</p> <p>2) Easy Modal Plugin for Bootstrap. <a href="http://bootsnipp.com/snippets/VX7EN" rel="noreferrer">Demo Snippet</a> and <a href="http://saribe.github.io/eModal/#demo" rel="noreferrer">Website</a></p> <p>3) Using jQuery Dialog Modal Popup Window. <a href="http://www.aspsnippets.com/demos/1261/" rel="noreferrer">Demo</a>.</p> <p>Hope it helped.</p>
1,097,252
Grails - Lift: Which framework is better suited for which kind of applications?
<p>I have been using Grails for the past few months and I really like it, specially GORM. However, I am getting interested into Scala's Lift. Therefore, I would like to know your opinion about which kind of web apps are better suited for which of those two frameworks or it is just a matter of taste, which framework to use?</p> <p>Finally, which of those frameworks do you think will be more used in the future? I have the feeling that Grails is far from reaching a critical mass and it still remains very obscure (in the past few months I had the opportunity to work with middle size companies and IT startups working mostly with the JVM stack and only one person knew and used Grails) and I am not even sure if it can become the "RoR" of the Java world (Indeed reports a drop of growth in the last few months even if other frameworks have a positive growing rate). And I love Groovy, it is really easy to learn but I have noticed how slow it can be for some tasks.</p> <p>On the other hand, Scala seems to be more popular (Tiobe Index) and the fact that Twitter is using it now gave it even more presence in the blogosphere with lots of lovers and haters making buzz. It is famous for being fast and scalable. However, the language seems somewhat hard to understand and learn for lots of developers (so maybe it will never gain mainstream status). Lift is little known and I have read some reports that it is better suited for small apps (less than 20 domain classes).</p> <p>By seeing the number of books published Groovy-Grails dominate right now, but many publishers have Scala books on the works, so I think this advantage will not last long.</p> <p>Finally, we have the problem that both languages and frameworks still have poor IDE support (it is getting better by the day but far away from what Java shops expect to be productive). </p> <p>I do not want to start a flame wars, but I would be very interested to hear other users' opinions.</p>
1,145,242
5
3
null
2009-07-08 10:24:23.027 UTC
10
2012-01-26 06:12:20.74 UTC
2009-07-08 11:25:33.967 UTC
null
87,271
null
87,271
null
1
14
grails|lift
7,730
<p>Grails is a nice idea(but only "stolen" from rails) but the fact that the groovy guys are not interested in getting proper Eclipse support is hindering it's success a lot. I've even seen Eclipse questions not being answered at all on the grails lists.</p> <p>I agree with Tim that Netbeans 6.7 finally delivers the first half way usable Open Source IDE support for groovy/grails - and eventually, SpringIDE will also feature better groovy/grails support.</p> <p>The reason many Java folks love Java is the static typing, which enables tools to help you a lot with many things. This is lost with a language as groovy. Yes, I could write every really important piece of Code in Java and still use Grails - but then, why should I, just to save a bunch of lines of glue code, do that instead of learning to use a Java framework highly effectively?</p> <p>To come to an end: I did not yet look at scala, but built some simple apps with grails - and I tend to go back to java, even reimplementing every app that needs further development in a plain Java framework - I think wicket and Seam.</p> <p>I'll also look at Scala/Lift, I heard many good things about it!</p> <p>BTW: I'd compare communities and look at mailing lists - how many peope are there, do they get good answers on their important questions?</p> <p>Grails seems to have a non-answered rate from nearly 50%, which I feel is bad.</p>
654,634
How can I make a rounded-corners form in WPF?
<p>I am trying to make the corners of a Window (WPF) rounded and it doesn't work, I tried to make the window itself transparent and add an internal border with rounded corners and it doesn't work.</p> <p>Any ideas?</p>
654,671
5
0
null
2009-03-17 15:04:56.287 UTC
8
2021-02-25 13:52:11.73 UTC
2019-12-14 22:43:08.97 UTC
null
75,500
Shimmy
75,500
null
1
37
wpf|xaml|rounded-corners
50,478
<p>you need to set WindowStyle to WindowStyle.None, which will remove the chrome, then you can allow transparency which is an attribute int the Window element, and set the background color to transparent. All of this can be done as attributes to the window tag.</p> <pre><code>WindowStyle="None" AllowsTransparency="True" Background="Transparent" </code></pre> <p>To make the corners rounded, use a border and set the cornerRadius property</p>
593,364
varchar Fields - Is a Power of Two More Efficient?
<p>Is it more efficient to use a <code>varchar</code> field sized as a power of two vs. another number? I'm thinking no, because for SQL Server the default is 50.</p> <p>However, I've heard (but never confirmed) that sizing fields as a power of 2 is more efficient because they equate to even bytes, and computers process in bits &amp; bytes.</p> <p>So, does a field declared as <code>varchar(32)</code> or <code>varchar(64)</code> have any real benefit over <code>varchar(50)</code>?</p>
593,420
5
0
null
2009-02-27 03:06:33.577 UTC
10
2017-10-18 07:09:13.883 UTC
2017-10-18 07:08:12 UTC
null
1,862,812
HardCode
62,477
null
1
61
database-design|varchar
8,828
<p><strong>No.</strong></p> <p>In some other uses, there are some advantages to use structures with a power of two size, mostly because you can fit a nice (power of two) number of these inside another power-of-two-sized structure. But this doesn't apply to a DB fieldsize.</p> <p>The only power-of-two-sizing related to VARCHARs is about the exact type of varchar (or TEXT/BLOB in some SQL dialects): if it's less than 256, it can use a single byte to indicate length. if it's less than 65536 (64KB), two bytes are enough, three bytes work up to 16777216 (16MB), four bytes go to 4294967296 (4GB).</p> <p>Also, it can be argued that <code>VARCHAR(50)</code> is just as expensive as <code>VARCHAR(255)</code>, since both will need n+1 bytes of storage.</p> <p>Of course that's before thinking of Unicode...</p>
1,020,354
Injecting current git commit id into Java webapp
<p>We have a git repository which contains source for a few related Java WARs and JARs. It would be nice if the Java code could somehow:</p> <pre><code>System.err.println("I was built from git commit " + commitID); </code></pre> <p>(Obviously real code might be putting this into an HTTP header, logging it on startup, or whatever, that's not important right now)</p> <p>We are using Ant to build (at least for production builds, it seems some programmers do their testing from inside Eclipse which I know even less about) binaries.</p> <p>Is there a canonical way to get the commit id for the current git checkout into our Java at build time? If not, can people using Ant to build suggest how they'd do it and we'll see if a canonical solution emerges? I'm sure I can invent something myself entirely from whole cloth, but this seems like a re-usable building block, so I'd rather not.</p>
1,020,396
6
0
null
2009-06-19 22:42:58.39 UTC
9
2019-04-30 12:28:45.06 UTC
2009-06-20 01:06:12.25 UTC
null
9,654
null
9,654
null
1
19
java|git|ant
12,157
<p>I don't know if there are any Ant task for git (I googled a bit without success), anyway Ant can update a properties file with Piotr's option (<code>git rev-parse HEAD</code>) and then in runtime use that properties to get the revision number. This is cleaner and <em>IDE friendly</em> than having Ant generating a .java file.</p>
525,004
Short example of regular expression converted to a state machine?
<p>In the Stack Overflow podcast #36 (<a href="https://blog.stackoverflow.com/2009/01/podcast-36/">https://blog.stackoverflow.com/2009/01/podcast-36/</a>), this opinion was expressed: Once you understand how easy it is to set up a state machine, you’ll never try to use a regular expression inappropriately ever again.</p> <p>I've done a bunch of searching. I've found some academic papers and other complicated examples, but I'd like to find a simple example that would help me understand this process. I use a lot of regular expressions, and I'd like to make sure I never use one &quot;inappropriately&quot; ever again.</p>
525,029
6
1
null
2009-02-08 02:11:15.473 UTC
11
2014-10-15 21:46:53.73 UTC
2021-01-18 12:38:11.483 UTC
slothbear
-1
slothbear
2,464
null
1
22
regex|state-machine|fsm
23,819
<p>Sure, although you'll need more complicated examples to truly understand how REs work. Consider the following RE:</p> <pre><code>^[A-Za-z][A-Za-z0-9_]*$ </code></pre> <p>which is a typical identifier (must start with alpha and can have any number of alphanumeric and undescore characters following, including none). The following pseudo-code shows how this can be done with a finite state machine:</p> <pre><code>state = FIRSTCHAR for char in all_chars_in(string): if state == FIRSTCHAR: if char is not in the set "A-Z" or "a-z": error "Invalid first character" state = SUBSEQUENTCHARS next char if state == SUBSEQUENTCHARS: if char is not in the set "A-Z" or "a-z" or "0-9" or "_": error "Invalid subsequent character" state = SUBSEQUENTCHARS next char </code></pre> <p>Now, as I said, this is a very simple example. It doesn't show how to do greedy/nongreedy matches, backtracking, matching within a line (instead of the whole line) and other more esoteric features of state machines that are easily handled by the RE syntax.</p> <p>That's why REs are so powerful. The actual finite state machine code required to do what a one-liner RE can do is usually very long and complex.</p> <p>The best thing you could do is grab a copy of some lex/yacc (or equivalent) code for a specific simple language and see the code it generates. It's not pretty (it doesn't have to be since it's not supposed to be read by humans, they're supposed to be looking at the lex/yacc code) but it may give you a better idea as to how they work.</p>
915,338
How can I find the link URL by link text with XPath?
<p>I have a well formed <a href="http://en.wikipedia.org/wiki/XHTML" rel="noreferrer">XHTML</a> page. I want to find the destination URL of a link when I have the text that is linked.</p> <p>Example</p> <pre><code>&lt;a href="http://stackoverflow.com"&gt;programming questions site&lt;/a&gt; &lt;a href="http://cnn.com"&gt;news&lt;/a&gt; </code></pre> <p>I want an <a href="http://en.wikipedia.org/wiki/XPath" rel="noreferrer">XPath</a> expression such that if given <code>programming questions site</code> it will give <code>http://stackoverflow.com</code> and if I give it <code>news</code> it will give <code>http://cnn.com</code>.</p>
915,345
6
0
null
2009-05-27 12:05:42.473 UTC
29
2020-07-01 21:56:44.287 UTC
2017-08-17 14:33:47.117 UTC
null
562,769
null
63,051
null
1
93
xml|xhtml|xpath
165,867
<p>Should be something similar to:</p> <pre> //a[text()='text_i_want_to_find']/@href </pre>
42,426,960
How does one train multiple models in a single script in TensorFlow when there are GPUs present?
<p>Say I have access to a number of GPUs in a single machine (for the sake of argument assume 8GPUs each with max memory of 8GB each in one single machine with some amount of RAM and disk). I wanted to run in <strong>one single script</strong> and in one single machine a program that evaluates multiple models (say 50 or 200) in TensorFlow, each with a different hyper parameter setting (say, step-size, decay rate, batch size, epochs/iterations, etc). At the end of training assume we just record its accuracy and get rid of the model (if you want assume the model is being check pointed every so often, so its fine to just throw away the model and start training from scratch. You may also assume some other data may be recorded like the specific hyper params, train, validation, train errors are recorded as we train etc).</p> <p>Currently I have a (pseudo-)script that looks as follow:</p> <pre><code>def train_multiple_modles_in_one_script_with_gpu(arg): ''' trains multiple NN models in one session using GPUs correctly. arg = some obj/struct with the params for trianing each of the models. ''' #### try mutliple models for mdl_id in range(100): #### define/create graph graph = tf.Graph() with graph.as_default(): ### get mdl x = tf.placeholder(float_type, get_x_shape(arg), name='x-input') y_ = tf.placeholder(float_type, get_y_shape(arg)) y = get_mdl(arg,x) ### get loss and accuracy loss, accuracy = get_accuracy_loss(arg,x,y,y_) ### get optimizer variables opt = get_optimizer(arg) train_step = opt.minimize(loss, global_step=global_step) #### run session with tf.Session(graph=graph) as sess: # train for i in range(nb_iterations): batch_xs, batch_ys = get_batch_feed(X_train, Y_train, batch_size) sess.run(fetches=train_step, feed_dict={x: batch_xs, y_: batch_ys}) # check_point mdl if i % report_error_freq == 0: sess.run(step.assign(i)) # train_error = sess.run(fetches=loss, feed_dict={x: X_train, y_: Y_train}) test_error = sess.run(fetches=loss, feed_dict={x: X_test, y_: Y_test}) print( 'step %d, train error: %s test_error %s'%(i,train_error,test_error) ) </code></pre> <p>essentially it tries lots of models in one single run but it builds each model in a separate graph and runs each one in a separate session.</p> <p>I guess my main worry is that its unclear to me how tensorflow under the hood allocates resources for the GPUs to be used. For example, does it load the (part of the) data set only when a session is ran? When I create a graph and a model, is it brought in the GPU immediately or when is it inserted in the GPU? Do I need to clear/free the GPU each time it tries a new model? I don't actually care too much if the models are ran in parallel in multiple GPU (which can be a nice addition), but I want it to first run everything serially without crashing. Is there anything special I need to do for this to work?</p> <hr> <p>Currently I am getting an error that starts as follow:</p> <pre><code>I tensorflow/core/common_runtime/bfc_allocator.cc:702] Stats: Limit: 340000768 InUse: 336114944 MaxInUse: 339954944 NumAllocs: 78 MaxAllocSize: 335665152 W tensorflow/core/common_runtime/bfc_allocator.cc:274] ***************************************************xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx W tensorflow/core/common_runtime/bfc_allocator.cc:275] Ran out of memory trying to allocate 160.22MiB. See logs for memory state. W tensorflow/core/framework/op_kernel.cc:975] Resource exhausted: OOM when allocating tensor with shape[60000,700] </code></pre> <p>and further down the line it says:</p> <pre><code>ResourceExhaustedError (see above for traceback): OOM when allocating tensor with shape[60000,700] [[Node: standardNN/NNLayer1/Z1/add = Add[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](standardNN/NNLayer1/Z1/MatMul, b1/read)]] I tensorflow/core/common_runtime/gpu/gpu_device.cc:975] Creating TensorFlow device (/gpu:0) -&gt; (device: 0, name: Tesla P100-SXM2-16GB, pci bus id: 0000:06:00.0) </code></pre> <p>however further down the output file (where it prints) it seems to print fine the errors/messages that should show as training proceeds. Does this mean that it didn't run out of resources? Or was it actually able to use the GPU? If it was able to use the CPU instead of the CPU, when why is this an error only happening when GPU are about to be used?</p> <p>The weird thing is that the data set is really not that big (all 60K points are 24.5M) and when I run a single model locally in my own computer it seems that the process uses less than 5GB. The GPUs have at least 8GB and the computer with them has plenty of RAM and disk (at least 16GB). Thus, the errors that tensorflow is throwing at me are quite puzzling. What is it trying to do and why are they occurring? Any ideas?</p> <hr> <p>After reading the answer that suggests to use the multiprocessing library I came up with the following script:</p> <pre><code>def train_mdl(args): train(mdl,args) if __name__ == '__main__': for mdl_id in range(100): # train one model with some specific hyperparms (assume they are chosen randomly inside the funciton bellow or read from a config file or they could just be passed or something) p = Process(target=train_mdl, args=(args,)) p.start() p.join() print('Done training all models!') </code></pre> <p>honestly I am not sure why his answer suggests to use pool, or why there are weird tuple brackets but this is what would make sense for me. Would the resources for tensorflow be re-allocated every time a new process is created in the above loop?</p>
42,647,980
4
3
null
2017-02-23 21:57:13.193 UTC
16
2019-05-09 01:22:54.523 UTC
2017-03-09 23:17:25.4 UTC
null
1,601,580
null
1,601,580
null
1
29
python|machine-learning|tensorflow|neural-network
23,082
<p>I think that running all models in one single script can be bad practice in the long term (see my suggestion below for a better alternative). However, if you would like to do it, here is a solution: You can encapsulate your TF session into a process with the <code>multiprocessing</code> module, this will make sure TF releases the session memory once the process is done. Here is a code snippet:</p> <pre><code>from multiprocessing import Pool import contextlib def my_model((param1, param2, param3)): # Note the extra (), required by the pool syntax &lt; your code &gt; num_pool_worker=1 # can be bigger than 1, to enable parallel execution with contextlib.closing(Pool(num_pool_workers)) as po: # This ensures that the processes get closed once they are done pool_results = po.map_async(my_model, ((param1, param2, param3) for param1, param2, param3 in params_list)) results_list = pool_results.get() </code></pre> <p>Note from OP: The random number generator seed does not reset automatically with the multi-processing library if you choose to use it. Details here: <a href="https://stackoverflow.com/questions/9209078/using-python-multiprocessing-with-different-random-seed-for-each-process">Using python multiprocessing with different random seed for each process</a></p> <p>About TF resource allocation: Usually TF allocates much more resources than it needs. Many times you can restrict each process to use a fraction of the total GPU memory, and discover through trial and error the fraction your script requires.</p> <p>You can do it with the following snippet</p> <pre><code>gpu_memory_fraction = 0.3 # Choose this number through trial and error gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction,) session_config = tf.ConfigProto(gpu_options=gpu_options) sess = tf.Session(config=session_config, graph=graph) </code></pre> <p>Note that sometimes TF increases the memory usage in order to accelerate the execution. Therefore, reducing the memory usage might make your model run slower.</p> <p><strong>Answers to the new questions in your edit/comments:</strong></p> <ol> <li><p>Yes, Tensorflow will be re-allocated every time a new process is created, and cleared once a process ends.</p></li> <li><p>The for-loop in your edit should also do the job. I suggest to use Pool instead, because it will enable you to run several models concurrently on a single GPU. See my notes about setting <code>gpu_memory_fraction</code> and "choosing the maximal number of processes". Also note that: (1) The Pool map runs the loop for you, so you don't need an outer for-loop once you use it. (2) In your example, you should have something like <code>mdl=get_model(args)</code> before calling train()</p></li> <li><p>Weird tuple parenthesis: Pool only accepts a single argument, therefore we use a tuple to pass multiple arguments. See <a href="https://stackoverflow.com/questions/8521883/multiprocessing-pool-map-and-function-with-two-arguments/8523763#8523763">multiprocessing.pool.map and function with two arguments</a> for more details. As suggested in one answer, you can make it more readable with</p> <pre><code>def train_mdl(params): (x,y)=params &lt; your code &gt; </code></pre></li> <li><p>As @Seven suggested, you can use CUDA_VISIBLE_DEVICES environment variable to choose which GPU to use for your process. You can do it from within your python script using the following on the beginning of the process function (<code>train_mdl</code>).</p> <pre><code>import os # the import can be on the top of the python script os.environ["CUDA_VISIBLE_DEVICES"] = "{}".format(gpu_id) </code></pre></li> </ol> <p><strong>A better practice for executing your experiments</strong> would be to isolate your training/evaluation code from the hyper parameters/ model search code. E.g. have a script named <code>train.py</code>, which accepts a specific combination of hyper parameters and references to your data as arguments, and executes training for a single model.</p> <p>Then, to iterate through the all the possible combinations of parameters you can use a simple task (jobs) queue, and submit all the possible combinations of hyper-parametrs as separate jobs. The task queue will feed your jobs one at a time to your machine. Usually, you can also set the queue to execute number of processes concurrently (see details below).</p> <p>Specifically, I use <a href="http://vicerveza.homeunix.net/~viric/soft/ts/" rel="noreferrer">task spooler</a>, which is super easy to install and handful (doesn't requires admin privileges, details below).</p> <p>Basic usage is (see notes below about task spooler usage):</p> <pre><code>ts &lt;your-command&gt; </code></pre> <p>In practice, I have a separate python script that manages my experiments, set all the arguments per specific experiment and send the jobs to the <code>ts</code> queue.</p> <p><strong>Here are some relevant snippets of python code from my experiments manager:</strong></p> <p><code>run_bash</code> executes a bash command</p> <pre><code>def run_bash(cmd): p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, executable='/bin/bash') out = p.stdout.read().strip() return out # This is the stdout from the shell command </code></pre> <p>The next snippet sets the number of concurrent processes to be run (see note below about choosing the maximal number of processes):</p> <pre><code>max_job_num_per_gpu = 2 run_bash('ts -S %d'%max_job_num_per_gpu) </code></pre> <p>The next snippet iterates through a list of all combinations of hyper params / model params. Each element of the list is a dictionary, where the keys are the command line arguments for the <code>train.py</code> script</p> <pre><code>for combination_dict in combinations_list: job_cmd = 'python train.py ' + ' '.join( ['--{}={}'.format(flag, value) for flag, value in combination_dict.iteritems()]) submit_cmd = "ts bash -c '%s'" % job_cmd run_bash(submit_cmd) </code></pre> <p><strong>A note about about choosing the maximal number of processes:</strong></p> <p>If you are short on GPUs, you can use <code>gpu_memory_fraction</code> you found, to set the number of processes as <code>max_job_num_per_gpu=int(1/gpu_memory_fraction)</code></p> <p><strong>Notes about task spooler (<code>ts</code>):</strong></p> <ol> <li><p>You could set the number of concurrent processes to run ("slots") with:</p> <p><code>ts -S &lt;number-of-slots&gt;</code></p></li> <li><p>Installing <code>ts</code> doesn't requires admin privileges. You can download and compile it from source with a simple <code>make</code>, add it to your path and you're done.</p></li> <li><p>You can set up multiple queues (I use it for multiple GPUs), with</p> <p><code>TS_SOCKET=&lt;path_to_queue_name&gt; ts &lt;your-command&gt;</code></p> <p>e.g.</p> <p><code>TS_SOCKET=/tmp/socket-ts.gpu_queue_1 ts &lt;your-command&gt;</code></p> <p><code>TS_SOCKET=/tmp/socket-ts.gpu_queue_2 ts &lt;your-command&gt;</code></p></li> <li><p>See <a href="http://vicerveza.homeunix.net/~viric/soft/ts/article_linux_com.html" rel="noreferrer">here</a> for further usage example</p></li> </ol> <p><strong>A note about automatically setting the path names and file names:</strong> Once you separate your main code from the experiment manager, you will need an efficient way to generate file names and directory names, given the hyper-params. I usually keep my important hyper params in a dictionary and use the following function to generate a single chained string from the dictionary key-value pairs. Here are the functions I use for doing it:</p> <pre><code>def build_string_from_dict(d, sep='%'): """ Builds a string from a dictionary. Mainly used for formatting hyper-params to file names. Key-value pairs are sorted by the key name. Args: d: dictionary Returns: string :param d: input dictionary :param sep: key-value separator """ return sep.join(['{}={}'.format(k, _value2str(d[k])) for k in sorted(d.keys())]) def _value2str(val): if isinstance(val, float): # %g means: "Floating point format. # Uses lowercase exponential format if exponent is less than -4 or not less than precision, # decimal format otherwise." val = '%g' % val else: val = '{}'.format(val) val = re.sub('\.', '_', val) return val </code></pre>
35,610,242
Detecting changes in a Javascript array using the Proxy object
<p>It is relatively trivial to watch for changes in an array in Javascript.</p> <p>One method I use is like this:</p> <pre><code>// subscribe to add, update, delete, and splice changes Array.observe(viewHelpFiles, function(changes) { // handle changes... in this case, we'll just log them changes.forEach(function(change) { console.log(Object.keys(change).reduce(function(p, c) { if (c !== "object" &amp;&amp; c in change) { p.push(c + ": " + JSON.stringify(change[c])); } return p; }, []).join(", ")); }); }); </code></pre> <p>However, I have recently read that <code>Array.observe</code> is deprecated and we should use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe">proxy object instead.</a> </p> <p>How can we detect changes in an array the Proxy object? I am unable to find any examples, anyone interested in elaborating?</p>
35,610,685
2
3
null
2016-02-24 18:33:25.557 UTC
14
2017-12-20 17:23:18.89 UTC
2016-02-24 18:40:35.007 UTC
null
1,391,671
null
3,067,743
null
1
46
javascript
46,707
<p>From what I can read from the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy" rel="noreferrer">MDN page</a>, you can create a general handler where you can handle all the changes to any object.</p> <p>In a sense, you write an interceptor, that will intervene each time you get a value from the array or set a value. You can then write your own logic to follow the changes.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var arrayChangeHandler = { get: function(target, property) { console.log('getting ' + property + ' for ' + target); // property is index in this case return target[property]; }, set: function(target, property, value, receiver) { console.log('setting ' + property + ' for ' + target + ' with value ' + value); target[property] = value; // you have to return true to accept the changes return true; } }; var originalArray = []; var proxyToArray = new Proxy( originalArray, arrayChangeHandler ); proxyToArray.push('Test'); console.log(proxyToArray[0]); // pushing to the original array won't go through the proxy methods originalArray.push('test2'); // the will however contain the same data, // as the items get added to the referenced array console.log('Both proxy and original array have the same content? ' + (proxyToArray.join(',') === originalArray.join(','))); // expect false here, as strict equality is incorrect console.log('They strict equal to eachother? ' + (proxyToArray === originalArray));</code></pre> </div> </div> </p> <p>Which then outputs:</p> <pre><code>getting push for getting length for setting 0 for with value Test setting length for Test with value 1 getting 0 for Test Test </code></pre> <p>The caveat for the proxy, is that everything which is defined on an object, will be intercepted, which can be observed when using the <code>push</code> method.</p> <p>The original object that will be proxied doesn't mutate, and changes done to the original object will not be caught by the proxy.</p>
22,970,505
New-Object : Cannot find an overload for "PSCredential" and the argument count: "2"
<p>I am writing a PowerShell script on a Windows 8.1 machine. When trying to create a PSCredential object using New-Object cmdlet, I was presented with this error:</p> <p>New-Object : Cannot find an overload for "PSCredential" and the argument count: "2".</p> <p>Running the exact same script on another Windows 8.1 machine works fine for me. I have also verified that both machines are running the same version of PowerShell 4.0</p> <p>Both machines have the same .NET Framework installed 4.0.</p> <p>Any idea why this is happening and how I could resolve this issue?</p> <pre><code>$userPassword = ConvertTo-SecureString -String "MyPassword" -AsPlainText -Force $userCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "myUserName", $userPassword </code></pre> <p>After some more testing, I found out the problem. For my function, I intended to take the username and password from the user but also provide default values if the user decide to skip those input parameters.</p> <p>For that I achieved it by adding the following line in parameters section</p> <pre><code>[string][ValidateNotNullOrEmpty()] $userPassword = "myPassword", </code></pre> <p>It seems the problem is that I defined it to be a [String] in the parameter but later trying to be a SecureString, which resulted in the problem.</p> <p>Removing the [String] attribute in my parameter solved the problem.</p>
23,004,997
3
3
null
2014-04-09 18:02:34.207 UTC
5
2022-03-23 18:20:08.333 UTC
2014-04-09 18:52:11.503 UTC
null
3,516,420
null
3,516,420
null
1
54
.net|powershell
90,068
<p>In situation like this, you may want to check your parameter type. In this particular example, the input parameter was declared to be a String. However, the result from ConvertTo-SecureString returns a SecureString.</p> <p>The error message is a little misleading in this situation. The problem isn't because there is no constructor with 2 arguments <strong>but because <code>$userPassword</code> was declared to be a <code>String</code> but later was changed to <code>SecureString</code></strong>.</p> <pre><code>[string][ValidateNotNullOrEmpty()] $userPassword = "myPassword", $userPassword = ConvertTo-SecureString -String $userPassword -AsPlainText -Force $userCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "myUserName", $userPassword </code></pre>
2,080,860
MySQL/SQL retrieve first 40 characters of a text field?
<p>How can I retrieve a text field from mysql db table, but not the entire text, just the few 40 or so characters.</p> <p>Can this be done in sql or do I need to do it using php?</p> <p>basically what I am trying to do is show the first x characters and then let the user click on that to view the full content.</p>
2,080,871
5
0
null
2010-01-17 11:54:35.313 UTC
8
2021-04-09 14:14:07.107 UTC
2021-04-09 14:14:07.107 UTC
null
616,443
null
239,342
null
1
37
php|mysql|sql
41,603
<pre><code>SELECT LEFT(field, 40) AS excerpt FROM table(s) WHERE ... </code></pre> <p>See the <a href="http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_left" rel="noreferrer"><code>LEFT()</code></a> function.</p> <p>As a <em>rule of thumb</em>, you should never do in PHP what MySQL can do for you. Think of it this way: You don't want to transmit anything more than strictly necessary from the DB to the requesting applications.</p> <hr> <p><strong>EDIT</strong> <em>If</em> you're going to use the entire data <em>on the same page</em> (i.e., with no intermediate request) more often than not, there's no reason <em>not</em> to fetch the full text at once. (See comments and <a href="https://stackoverflow.com/questions/2080860/mysql-sql-retrieve-first-40-characters-of-a-text-field/2080906#2080906">Veger's answer</a>.)</p>
1,565,100
Casting to string versus calling ToString
<pre><code>object obj = "Hello"; string str1 = (string)obj; string str2 = obj.ToString(); </code></pre> <p>What is the difference between <code>(string)obj</code> and <code>obj.ToString()</code>?</p>
1,565,112
5
2
null
2009-10-14 09:02:59.857 UTC
11
2020-08-19 06:02:57.787 UTC
2009-10-14 09:17:10.743 UTC
null
24,874
null
68,287
null
1
40
c#
40,447
<ul> <li><code>(string)obj</code> <a href="http://msdn.microsoft.com/en-us/library/ms173105.aspx" rel="noreferrer">casts</a> <code>obj</code> into a <code>string</code>. <code>obj</code> must already be a <code>string</code> for this to succeed.</li> <li><code>obj.ToString()</code> gets a string representation of <code>obj</code> by calling the <a href="http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx" rel="noreferrer"><code>ToString()</code></a> method. Which is <code>obj</code> itself when <code>obj</code> is a <code>string</code>. This (should) never throw(s) an exception (unless <code>obj</code> happens to be <code>null</code>, obviously).</li> </ul> <p>So in your specific case, both are equivalent.</p> <p>Note that <code>string</code> is a <a href="http://msdn.microsoft.com/en-us/library/490f96s2.aspx" rel="noreferrer">reference type</a> (as opposed to a <a href="http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx" rel="noreferrer">value type</a>). As such, it inherits from object and no <a href="http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx" rel="noreferrer">boxing</a> ever occurs.</p>
2,332,515
How to get jersey logs at server?
<p>I am using jersey for a REST WS. How do I enable jersey logs at server side?</p> <p>Long story: I get a clientside exception - but I don't see anything in tomcat logs [It doesn't even reach my method]. Since the stack trace is saying "toReturnValue" it did get something from server. But I don't know what the server said.</p> <pre><code>Exception in thread "main" java.lang.IllegalArgumentException: source parameter must not be null at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:98) at com.sun.xml.internal.ws.message.AbstractMessageImpl.readPayloadAsJAXB(AbstractMessageImpl.java:100) **at com.sun.xml.internal.ws.client.dispatch.JAXBDispatch.toReturnValue(JAXBDispatch.java:74)** at com.sun.xml.internal.ws.client.dispatch.DispatchImpl.doInvoke(DispatchImpl.java:191) at com.sun.xml.internal.ws.client.dispatch.DispatchImpl.invoke(DispatchImpl.java:195) </code></pre>
2,362,106
5
0
null
2010-02-25 08:10:41.767 UTC
18
2018-04-12 10:10:51.78 UTC
2014-09-19 04:59:22.963 UTC
null
1,173,495
null
256,717
null
1
40
java|jersey
64,639
<p>If you want to turn on logging on the server side, you need to register the <a href="https://jersey.github.io/apidocs/2.23/jersey/org/glassfish/jersey/filter/LoggingFilter.html" rel="nofollow noreferrer">LoggingFilter Jersey filter</a> (on the container side).</p> <p>This filter will log <strong>request/response headers and entities</strong>.</p> <p>Here's what you need to add to your <code>ResourceConfig</code> class:</p> <pre><code>@ApplicationPath("/") public class MyApplication extends ResourceConfig { public MyApplication() { // Resources. packages(MyResource.class.getPackage().getName()); register(LoggingFilter.class); } } </code></pre> <p>Note that the same filter also works on the client side.</p> <pre><code>Client client = Client.create(); client.addFilter(new LoggingFilter()); </code></pre>
1,888,702
Are there problems that cannot be written using tail recursion?
<p>Tail recursion is an important performance optimisation stragegy in functional languages because it allows recursive calls to consume constant stack (rather than O(n)).</p> <p>Are there any problems that simply cannot be written in a tail-recursive style, or is it always possible to convert a naively-recursive function into a tail-recursive one?</p> <p>If so, one day might functional compilers and interpreters be intelligent enough to perform the conversion automatically?</p>
1,889,060
5
3
null
2009-12-11 15:13:00.49 UTC
26
2022-05-31 04:44:07.743 UTC
2009-12-11 15:26:36.12 UTC
null
172,211
null
111,495
null
1
54
functional-programming|recursion|tail-recursion
8,333
<p>Yes, actually you <em>can</em> take some code and convert every function call&mdash;and every return&mdash;into a tail call. What you end up with is called continuation-passing style, or CPS.</p> <p>For example, here's a function containing two recursive calls:</p> <pre><code>(define (count-tree t) (if (pair? t) (+ (count-tree (car t)) (count-tree (cdr t))) 1)) </code></pre> <p>And here's how it would look if you converted this function to continuation-passing style:</p> <pre><code>(define (count-tree-cps t ctn) (if (pair? t) (count-tree-cps (car t) (lambda (L) (count-tree-cps (cdr t) (lambda (R) (ctn (+ L R)))))) (ctn 1))) </code></pre> <p>The extra argument, <code>ctn</code>, is a procedure which <code>count-tree-cps</code> tail-calls <em>instead of returning</em>. (sdcvvc's answer says that you can't do everything in O(1) space, and that is correct; here each continuation is a closure which takes up some memory.)</p> <p>I didn't transform the calls to <code>car</code> or <code>cdr</code> or <code>+</code> into tail-calls. That could be done as well, but I assume those leaf calls would actually be inlined.</p> <p>Now for the fun part. <a href="http://www.call-with-current-continuation.org/" rel="noreferrer">Chicken Scheme</a> actually does this conversion on all code it compiles. Procedures compiled by Chicken <em>never return</em>. There's a classic paper explaining why Chicken Scheme does this, written in 1994 before Chicken was implemented: <a href="http://home.pipeline.com/~hbaker1/CheneyMTA.html" rel="noreferrer">CONS should not cons its arguments, Part II: Cheney on the M.T.A.</a></p> <p>Surprisingly enough, continuation-passing style is fairly common in JavaScript. You can use it <a href="http://marijn.haverbeke.nl/cps/" rel="noreferrer">to do long-running computation</a>, avoiding the browser's "slow script" popup. And it's attractive for asynchronous APIs. <a href="http://www.webmonkey.com/tutorial/Easy_XML_Consumption_using_jQuery?oldid=20032" rel="noreferrer"><code>jQuery.get</code></a> (a simple wrapper around XMLHttpRequest) is clearly in continuation-passing style; the last argument is a function.</p>
1,515,577
Factory methods in Ruby
<p><strong>What is the slickest, most Ruby-like way to have a single constructor return an object of the appropriate type?</strong></p> <p>To be more specific, here's a dummy example: say I have two classes <code>Bike</code> and <code>Car</code> which subclass <code>Vehicle</code>. I want this:</p> <pre><code>Vehicle.new('mountain bike') # returns Bike.new('mountain bike') Vehicle.new('ferrari') # returns Car.new('ferrari') </code></pre> <p>I've proposed a solution below, but it uses <code>allocate</code> which seems way too implementation-heavy. What are some other approaches, or is mine actually ok?</p>
1,516,824
6
4
null
2009-10-04 04:17:34.527 UTC
9
2016-03-22 18:54:53.21 UTC
null
null
null
null
157,237
null
1
19
ruby|factory
21,353
<p>If I make a factory method that is not called<sup>1</sup> <code>new</code> or <code>initialize</code>, I guess that doesn't really answer the question "how do I make a ... constructor ...", but I think that's how I would do it...</p> <pre><code>class Vehicle def Vehicle.factory vt { :Bike =&gt; Bike, :Car =&gt; Car }[vt].new end end class Bike &lt; Vehicle end class Car &lt; Vehicle end </code></pre> <hr> <pre><code>c = Vehicle.factory :Car c.class.factory :Bike </code></pre> <hr> <p><sup>1. Calling the method <em>factory</em> works really well in this instructional example but IRL you may want to consider <a href="https://stackoverflow.com/users/190135/alexchaffee">@AlexChaffee</a>'s advice in the comments.</sup></p>
1,985,955
Android SimpleCursorAdapter doesn't update when database changes
<p>I have an Android <code>ListActivity</code> that is backed by a database <code>Cursor</code> through a <code>SimpleCursorAdapter</code>.</p> <p>When the items are clicked, a flag field in the coresponding row in the database is toggled and the view in the list needs to be updated. </p> <p>The problem is, when the view that's updated goes off screen and is recycled, the old value is displayed on the view when it returns into view. The same thing happens whenever thr list is redrawb (orientation changes, etc). </p> <p>I use <code>notifydatasetchanged()</code> to refresh the cursor adapter but it seems ineffective.</p> <p>How should I be updating the database so the cursor is updated as well?</p>
1,986,071
6
0
null
2009-12-31 16:06:07.517 UTC
22
2021-12-22 19:46:06.573 UTC
2021-12-22 19:46:06.573 UTC
null
4,294,399
null
131,871
null
1
43
android|database|sqlite|listactivity
40,297
<p>Call <code>requery()</code> on the <code>Cursor</code> when you change data in the database that you want reflected in that <code>Cursor</code> (or things the <code>Cursor</code> populates, like a <code>ListView</code> via a <code>CursorAdapter</code>).</p> <p>A <code>Cursor</code> is akin to an ODBC client-side cursor -- it holds all of the data represented by the query result. Hence, just because you change the data in the database, the <code>Cursor</code> will not know about those changes unless you refresh it via <code>requery()</code>.</p> <hr> <p><strong>UPDATE</strong>: This whole question and set of answers should be deleted due to old age, but that's apparently impossible. Anyone seeking Android answers should bear in mind that the Android is a swiftly-moving target, and answers from 2009 are typically worse than are newer answers.</p> <p>The current solution is to obtain a fresh <code>Cursor</code> and use either <code>changeCursor()</code> or <code>swapCursor()</code> on the <code>CursorAdapter</code> to affect a data change.</p>
2,143,264
iPhone UITableView with a header area
<p>I have a view that was created with all of the default <code>UITableView</code> stuff, but now I need to add a header area above where the <code>UITableView</code> is (so the <code>UITableView</code> will scroll normally, but the top 100px of the screen or so will have static header content). I don't see where I can resize the <code>UITableView</code> in IB, and am not sure how to do this.</p> <p>Does anyone know?</p>
2,143,293
8
0
null
2010-01-26 22:44:36.123 UTC
11
2015-03-02 05:13:01.017 UTC
2013-02-01 14:54:03.677 UTC
null
119,895
null
259,631
null
1
38
iphone|uitableview
63,811
<p>Why don't you use the UITableView provided header?. As follow:</p> <pre><code>- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return @"My Title"; } </code></pre> <p>Additionally you may resize your table view in IB by dragging the borders.</p>
2,045,875
Pass by reference problem with PHP 5.3.1
<p>Ok, this is a weird problem, so please bear with me as I explain.</p> <p>We upgraded our dev servers from PHP 5.2.5 to 5.3.1.</p> <p>Loading up our code after the switch, we start getting errors like:</p> <p><code>Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference, value given in /home/spot/trunk/system/core/Database.class.php on line 105</code></p> <p>the line mentioned (105) is as follows:</p> <pre><code>call_user_func_array(Array($stmt, 'bind_param'), $passArray); </code></pre> <p>we changed the line to the following:</p> <pre><code>call_user_func_array(Array($stmt, 'bind_param'), &amp;$passArray); </code></pre> <p>at this point (because <code>allow_call_time_pass_reference</code>) is turned off, php throws this:</p> <p><code>Deprecated: Call-time pass-by-reference has been deprecated in /home/spot/trunk/system/core/Database.class.php on line 105</code></p> <p>After trying to fix this for some time, I broke down and set <code>allow_call_time_pass_reference</code> to on.</p> <p>That got rid of the <code>Deprecated</code> warning, but now the <code>Warning: Parameter 2 to mysqli_stmt::bind_param() expected to be a reference</code> warning is throwing every time, <b>with or without</b> the referencing.</p> <p>I have zero clue how to fix this. If the target method was my own, I would just reference the incoming vars in the func declaration, but it's a (relatively) native method (mysqli).</p> <p>Has anyone experienced this? How can I get around it?</p> <p>Thank you.</p>
2,045,918
9
2
null
2010-01-12 00:14:16.883 UTC
7
2015-05-04 10:02:41.52 UTC
2013-04-01 12:29:52.667 UTC
null
367,456
null
111,661
null
1
32
reference|mysqli|php
27,459
<p>You are passing an array of elements ($passArray). The second item <em>inside</em> the passed array needs to be a reference, since that is really the list of items you are passing to the function.</p>
1,484,473
How to find the lowest common ancestor of two nodes in any binary tree?
<p>The Binary Tree here is may not necessarily be a Binary Search Tree.<br> The structure could be taken as -</p> <pre><code>struct node { int data; struct node *left; struct node *right; }; </code></pre> <p>The maximum solution I could work out with a friend was something of this sort -<br> Consider <a href="http://lcm.csa.iisc.ernet.in/dsa/node87.html" rel="noreferrer">this binary tree</a> :</p> <p><a href="https://i.stack.imgur.com/Sz5KZ.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/Sz5KZ.gif" alt="Binary Tree"></a></p> <p>The inorder traversal yields - 8, 4, 9, 2, 5, 1, 6, 3, 7</p> <p>And the postorder traversal yields - 8, 9, 4, 5, 2, 6, 7, 3, 1</p> <p>So for instance, if we want to find the common ancestor of nodes 8 and 5, then we make a list of all the nodes which are between 8 and 5 in the inorder tree traversal, which in this case happens to be [4, 9, 2]. Then we check which node in this list appears last in the postorder traversal, which is 2. Hence the common ancestor for 8 and 5 is 2.</p> <p>The complexity for this algorithm, I believe is O(n) (O(n) for inorder/postorder traversals, the rest of the steps again being O(n) since they are nothing more than simple iterations in arrays). But there is a strong chance that this is wrong. :-)</p> <p>But this is a very crude approach, and I'm not sure if it breaks down for some case. Is there any other (possibly more optimal) solution to this problem?</p>
1,484,810
34
12
null
2009-09-27 21:01:41.943 UTC
142
2020-11-05 01:31:37.65 UTC
2019-04-26 22:04:43.853 UTC
null
4,751,173
null
179,729
null
1
189
algorithm|binary-tree|complexity-theory|least-common-ancestor
185,495
<p>Nick Johnson is correct that a an O(n) time complexity algorithm is the best you can do if you have no parent pointers.) For a simple recursive version of that algorithm see the code in <a href="https://stackoverflow.com/a/5000698/179917">Kinding's post</a> which runs in O(n) time.</p> <p>But keep in mind that if your nodes have parent pointers, an improved algorithm is possible. For both nodes in question construct a list containing the path from root to the node by starting at the node, and front inserting the parent.</p> <p>So for 8 in your example, you get (showing steps): {4}, {2, 4}, {1, 2, 4}</p> <p>Do the same for your other node in question, resulting in (steps not shown): {1, 2}</p> <p>Now compare the two lists you made looking for the first element where the list differ, or the last element of one of the lists, whichever comes first.</p> <p>This algorithm requires O(h) time where h is the height of the tree. In the worst case O(h) is equivalent to O(n), but if the tree is balanced, that is only O(log(n)). It also requires O(h) space. An improved version is possible that uses only constant space, with code shown in <a href="https://stackoverflow.com/a/6183069/179917">CEGRD's post</a></p> <hr> <p>Regardless of how the tree is constructed, if this will be an operation you perform many times on the tree without changing it in between, there are other algorithms you can use that require O(n) [linear] time preparation, but then finding any pair takes only O(1) [constant] time. For references to these algorithms, see the the lowest common ancestor problem page on <a href="http://en.wikipedia.org/wiki/Lowest_common_ancestor" rel="noreferrer">Wikipedia</a>. (Credit to Jason for originally posting this link)</p>
8,593,608
How can I copy a directory using Boost Filesystem
<p>How can I copy a directory using Boost Filesystem? I have tried boost::filesystem::copy_directory() but that only creates the target directory and does not copy the contents.</p>
8,594,696
4
2
null
2011-12-21 17:10:23.557 UTC
9
2018-11-28 03:58:01.393 UTC
null
null
null
null
203,719
null
1
28
c++|boost|filesystems|directory|copy
25,841
<pre><code>bool copyDir( boost::filesystem::path const &amp; source, boost::filesystem::path const &amp; destination ) { namespace fs = boost::filesystem; try { // Check whether the function call is valid if( !fs::exists(source) || !fs::is_directory(source) ) { std::cerr &lt;&lt; "Source directory " &lt;&lt; source.string() &lt;&lt; " does not exist or is not a directory." &lt;&lt; '\n' ; return false; } if(fs::exists(destination)) { std::cerr &lt;&lt; "Destination directory " &lt;&lt; destination.string() &lt;&lt; " already exists." &lt;&lt; '\n' ; return false; } // Create the destination directory if(!fs::create_directory(destination)) { std::cerr &lt;&lt; "Unable to create destination directory" &lt;&lt; destination.string() &lt;&lt; '\n' ; return false; } } catch(fs::filesystem_error const &amp; e) { std::cerr &lt;&lt; e.what() &lt;&lt; '\n'; return false; } // Iterate through the source directory for( fs::directory_iterator file(source); file != fs::directory_iterator(); ++file ) { try { fs::path current(file-&gt;path()); if(fs::is_directory(current)) { // Found directory: Recursion if( !copyDir( current, destination / current.filename() ) ) { return false; } } else { // Found file: Copy fs::copy_file( current, destination / current.filename() ); } } catch(fs::filesystem_error const &amp; e) { std:: cerr &lt;&lt; e.what() &lt;&lt; '\n'; } } return true; } </code></pre> <p><strong>Usage:</strong></p> <p><code>copyDir(boost::filesystem::path("/home/nijansen/test"), boost::filesystem::path("/home/nijansen/test_copy"));</code> (Unix)</p> <p><code>copyDir(boost::filesystem::path("C:\\Users\\nijansen\\test"), boost::filesystem::path("C:\\Users\\nijansen\\test2"));</code> (Windows)</p> <p>As far as I see, the worst that can happen is that nothing happens, but I won't promise anything! Use at your own risk.</p> <p>Please note that the directory you're copying to must not exist. If directories within the directory you are trying to copy can't be read (think rights management), they will be skipped, but the other ones should still be copied.</p> <p><strong>Update</strong></p> <p>Refactored the function respective to the comments. Furthermore the function now returns a success result. It will return <code>false</code> if the requirements for the given directories or any directory within the source directory are not met, but not if a single file could not be copied.</p>
8,384,237
Stop WPF ScrollViewer automatically scrolling to perceived content
<p><strong>The Application</strong></p> <p>I am building an application which includes a range selector. This consists of two custom drawn <code>Slider</code> controls contained within one <code>UserControl</code> derived class. The range selector control is then contained inside a <code>ScrollViewer</code> which has the HorizonalScrollBar visible most of the time.</p> <p><strong>Sample Application Code:</strong> ( appologies for the wall of text )</p> <p>Window.xaml ( the Window file ):</p> <pre><code>&lt;Grid&gt; &lt;ScrollViewer x:Name="ScrollViewer" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Disabled"&gt; &lt;local:SliderTest x:Name="slider" LowerValue="0" UpperValue="10" Minimum="0" Maximum="100" Width="900" Height="165" Padding="15,0,15,0" HorizontalAlignment="Left"&gt; &lt;/local:SliderTest&gt; &lt;/ScrollViewer&gt; &lt;/Grid&gt; </code></pre> <p>SliderTest.xaml:</p> <pre><code>&lt;UserControl x:Class="scrollviewerDemoProblem.SliderTest" 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="http://schemas.microsoft.com/expression/blend/2008" x:Name="root" xmlns:local="clr-namespace:scrollviewerDemoProblem" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"&gt; &lt;UserControl.Resources&gt; &lt;ControlTemplate x:Key="simpleSlider" TargetType="{x:Type Slider}"&gt; &lt;Border SnapsToDevicePixels="true" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;RowDefinition Height="Auto" MinHeight="{TemplateBinding MinHeight}"/&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;Track x:Name="PART_Track" Grid.Row="1"&gt; &lt;Track.Thumb&gt; &lt;Thumb x:Name="Thumb" FlowDirection="LeftToRight" Width="15"&gt; &lt;Thumb.Template&gt; &lt;ControlTemplate TargetType="Thumb"&gt; &lt;Canvas&gt; &lt;Path x:Name="test1" StrokeThickness="0" Fill="DarkGreen"&gt; &lt;Path.Data&gt; &lt;GeometryGroup FillRule="NonZero"&gt; &lt;PathGeometry&gt; &lt;PathGeometry.Figures&gt; &lt;PathFigure IsClosed="True" StartPoint="0,150" IsFilled="True"&gt; &lt;PathFigure.Segments&gt; &lt;PathSegmentCollection&gt; &lt;LineSegment Point="-15,150" /&gt; &lt;LineSegment Point="-15,0" /&gt; &lt;LineSegment Point="0,0" /&gt; &lt;/PathSegmentCollection&gt; &lt;/PathFigure.Segments&gt; &lt;/PathFigure&gt; &lt;/PathGeometry.Figures&gt; &lt;/PathGeometry&gt; &lt;/GeometryGroup&gt; &lt;/Path.Data&gt; &lt;/Path&gt; &lt;/Canvas&gt; &lt;/ControlTemplate&gt; &lt;/Thumb.Template&gt; &lt;/Thumb&gt; &lt;/Track.Thumb&gt; &lt;/Track&gt; &lt;/Grid&gt; &lt;/Border&gt; &lt;/ControlTemplate&gt; &lt;ControlTemplate x:Key="simpleSliderRight" TargetType="{x:Type Slider}"&gt; &lt;Border SnapsToDevicePixels="true" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;RowDefinition Height="Auto" MinHeight="{TemplateBinding MinHeight}"/&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Track x:Name="PART_Track" Grid.Row="1"&gt; &lt;Track.Thumb&gt; &lt;Thumb x:Name="Thumb" HorizontalAlignment="Center" HorizontalContentAlignment="Center" Width="15"&gt; &lt;Thumb.Template&gt; &lt;ControlTemplate TargetType="Thumb"&gt; &lt;Canvas&gt; &lt;Path Stroke="Black" StrokeThickness="0" Fill="DarkCyan"&gt; &lt;Path.Data&gt; &lt;GeometryGroup FillRule="NonZero"&gt; &lt;PathGeometry&gt; &lt;PathGeometry.Figures&gt; &lt;PathFigure IsClosed="True" StartPoint="0,150"&gt; &lt;PathFigure.Segments&gt; &lt;PathSegmentCollection&gt; &lt;LineSegment Point="15,150" /&gt; &lt;LineSegment Point="15,0" /&gt; &lt;LineSegment Point="0,0" /&gt; &lt;/PathSegmentCollection&gt; &lt;/PathFigure.Segments&gt; &lt;/PathFigure&gt; &lt;/PathGeometry.Figures&gt; &lt;/PathGeometry&gt; &lt;/GeometryGroup&gt; &lt;/Path.Data&gt; &lt;/Path&gt; &lt;/Canvas&gt; &lt;/ControlTemplate&gt; &lt;/Thumb.Template&gt; &lt;/Thumb&gt; &lt;/Track.Thumb&gt; &lt;/Track&gt; &lt;/Grid&gt; &lt;/Border&gt; &lt;/ControlTemplate&gt; &lt;/UserControl.Resources&gt; &lt;Grid x:Name="Gridd" VerticalAlignment="Top" Height="165" &gt; &lt;Border x:Name="timeScaleBorder" Width="auto" Height="15" VerticalAlignment="Top" Background="Black"&gt; &lt;Canvas x:Name="timeCanvas" Width="auto" Height="15"&gt; &lt;/Canvas&gt; &lt;/Border&gt; &lt;Border x:Name="background" BorderThickness="1,1,1,1" BorderBrush="Black" VerticalAlignment="Center" Height="150" Margin="0,15,0,0" Background="White" /&gt; &lt;Slider x:Name="LowerSlider" Minimum="{Binding ElementName=root, Path=Minimum}" Maximum="{Binding ElementName=root, Path=Maximum}" Value="{Binding ElementName=root, Path=LowerValue, Mode=TwoWay}" Template="{StaticResource simpleSlider}" Margin="0,15,0,0" /&gt; &lt;Slider x:Name="UpperSlider" Minimum="{Binding ElementName=root, Path=Minimum}" Maximum="{Binding ElementName=root, Path=Maximum}" Value="{Binding ElementName=root, Path=UpperValue, Mode=TwoWay}" Template="{StaticResource simpleSliderRight}" Margin="0,15,0,0" /&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p>SliderText.xaml.cs:</p> <pre><code>public partial class SliderTest : UserControl { public SliderTest() { InitializeComponent(); } #region Dependency properties, values etc. public static readonly DependencyProperty MinimumProperty = DependencyProperty.Register("Minimum", typeof(double), typeof(SliderTest), new UIPropertyMetadata(0d)); public double LowerValue { get { return (double)GetValue(LowerValueProperty); } set { SetValue(LowerValueProperty, value); } } public static readonly DependencyProperty LowerValueProperty = DependencyProperty.Register("LowerValue", typeof(double), typeof(SliderTest), new UIPropertyMetadata(0d)); public double UpperValue { get { return (double)GetValue(UpperValueProperty); } set { SetValue(UpperValueProperty, value); } } public static readonly DependencyProperty UpperValueProperty = DependencyProperty.Register("UpperValue", typeof(double), typeof(SliderTest), new UIPropertyMetadata(0d)); public double Maximum { get { return (double)GetValue(MaximumProperty); } set { SetValue(MaximumProperty, value); } } public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register("Maximum", typeof(double), typeof(SliderTest), new UIPropertyMetadata(1d)); public double Minimum { get { return (double)GetValue(MinimumProperty); } set { SetValue(MinimumProperty, value); } } #endregion } </code></pre> <p><strong>The Problem</strong> Most of the sample code provided is boring and the mechanics of it works pretty good. The problem I am having is a visual problem specifically with the <code>ScrollViewer</code> control that I have in the main Window. The <code>ScrollViewer</code> seems to be automatically adjusting the horizontal offset of the <code>ScrollViewer</code> when either of the <code>Slider</code>'s gains focus ( from a mouse click for example ).</p> <p><strong>Reproducing the behaviour</strong></p> <ol> <li>Run the application, you will see that the horizontal scroll bar of the ScrollViewer is visible.</li> <li>Click on the Green ( far left ) <code>Slider</code>, you will notice that the ScrollViewer automatically adjusts to shift the horizontal offset to where the perceived 'content' starts.</li> </ol> <p>These symptoms occur at either end of the scroll pane.</p> <p>Screenshot of application when it is run ( Application is Zoomed in 200% for detail clarity ):</p> <p><img src="https://i.stack.imgur.com/F33G0.jpg" alt="Screenshot1"></p> <p>Screenshot of the behavior when the left slider is clicked:</p> <p><img src="https://i.stack.imgur.com/W844A.jpg" alt="enter image description here"></p> <p><strong>What I want to happen:</strong></p> <p>When I click on either slider item ( at either end ) when a slider looks to be beyond end of the slider ( slider range is denoted by the black bar at the top ) I <em>don't</em> want the ScrollViewer to automatically adjust it's horizontal offset.</p> <p><strong>Suspected problem:</strong></p> <p>I suspect that the problem is that the ScrollViewer perceives the actual 'content' of it's childen starts 15 pixels ( the drawn width of both of my sliders ) in from where the actual drawn content does start. The Canvas only draws because I included a padding of 15 pixels inside of the <code>SliderTest</code> control on the main window, if this padding is removed the ScrollViewer does not show any of the Slider's Canvas.</p> <p><strong>EDIT</strong> : it appears the padding is not the problem, read the comments as to why.</p> <p><strong>Things I have tried</strong></p> <p>I have tried looking into overriding the OnPreviewMouseDown event of the main Window. The problem here is that I still want both Slider's to behave normally, setting the event to Handled causes the Slider to stop working completely.</p> <p><strong>Notes:</strong></p> <p>The Slider's within the range selector control ( Called SliderTest in this example ) must both have a width of 1 pixel. The slider's must be able to extend 15 pixels past the end of the time selection range ( see the black bar at the top for a reference ).</p> <p>Thank you for reading this novel-lengthed problem.</p>
8,387,765
2
2
null
2011-12-05 10:56:57.607 UTC
6
2019-10-03 20:53:49.89 UTC
2011-12-05 15:22:15.02 UTC
null
989,056
null
989,056
null
1
37
wpf|wpf-controls|scrollviewer
14,830
<p>By default when a control receives the logical focus, FrameworkElement calls its own <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.bringintoview.aspx">BringIntoView</a> method (from within its OnGotFocus method if it has keyboard focus). That results in a <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.requestbringintoview.aspx">RequestBringIntoView</a> event being generated that bubbles up the element tree to allow ancestor elements to bring that portion of the element into view. The ScrollViewer listens for this event and eventually will call MakeVisible on the associated IScrollInfo/ScrollContentPresenter which leaves it up to the panel to bring that portion into view (since the panel would know how it arranges its children). It then takes that returned rect it receives back and asks for that portion of itself to be brought into view (in case you had nested elements that would require some action to ensure the original element was brought into view). So one way to suppress this behavior would be to handle the RequestBringIntoView event on the sliders and mark the event handled.</p>
46,541,371
npm ERR! Refusing to delete / code EEXIST
<p>I'm just running a simple <code>npm install</code> and i get this error.</p> <pre><code>npm ERR! path /Users/jasonazoulay/Desktop/fabrick.io/delegation/node_modules/@angular/cli/node_modules/webpack/node_modules/yargs/node_modules/os-locale/node_modules/execa/node_modules/cross-spawn/node_modules/.bin/which npm ERR! code EEXIST npm ERR! Refusing to delete /Users/jasonazoulay/Desktop/fabrick.io/delegation/node_modules/@angular/cli/node_modules/webpack/node_modules/yargs/node_modules/os-locale/node_modules/execa/node_modules/cross-spawn/node_modules/.bin/which: is outside /Users/jasonazoulay/Desktop/fabrick.io/delegation/node_modules/@angular/cli/node_modules/webpack/node_modules/yargs/node_modules/os-locale/node_modules/execa/node_modules/cross-spawn/node_modules/which and not a link npm ERR! File exists: /Users/jasonazoulay/Desktop/fabrick.io/delegation/node_modules/@angular/cli/node_modules/webpack/node_modules/yargs/node_modules/os-locale/node_modules/execa/node_modules/cross-spawn/node_modules/.bin/which npm ERR! Move it away, and try again </code></pre> <p>This is the first time I get this error and I don't know what to do.</p>
46,541,654
15
3
null
2017-10-03 09:30:06.837 UTC
17
2022-02-03 21:24:36.093 UTC
2017-10-11 23:42:06.283 UTC
null
5,822,031
null
7,857,994
null
1
140
node.js|npm
155,196
<h2>Steps</h2> <ol> <li>Delete the <code>node_modules</code> directory completely. </li> <li>Run <code>npm install</code> again.</li> </ol> <p>This should help.</p>
17,740,904
How to update an array of object in javascript
<p>say I have a variable </p> <pre><code> data=[] //this variable is an array of object like data = [ {name:'a',value:'aa'}, {name:'b',value:'bb'} ] // the data structrue can not be changed and the initial value is empty </code></pre> <p>now I want to update the data</p> <pre><code> function updateData(){ if(!data.length){ data.push(arguments) } else{ //this parts really confuse me } } </code></pre> <p>this function must accept any number of arguments,and the order of the objects in data dose not matters <strong>update rule</strong>:</p> <ol> <li>update the objects value to the arguments value if they have the same name.</li> <li>add the arguments to the data if none of the object in data have the same name.</li> </ol> <p>how to write this function?</p> <pre><code> updateData([ {name:'a',value:'aa'}, {name:'b',value:'bb'} ]) // expect data = [ {name:'a',value:'aa'}, {name:'b',value:'bb'} ] updateData([ {name:'a',value:'aa'}, {name:'b',value:'DD'}, {name:'c',value:'cc'} ] ) // expect data = [ {name:'a',value:'aa'}, {name:'b',value:'DD'}, {name:'c',value:'cc'} ] </code></pre>
17,741,336
4
4
null
2013-07-19 07:55:49.663 UTC
3
2013-07-19 08:34:07.103 UTC
2013-07-19 08:10:29.043 UTC
null
2,488,550
null
1,305,860
null
1
3
javascript|arrays|object|data-structures
52,453
<p>As Ashutosh Upadhyay suggested use a name value pair instead of an array:</p> <pre><code>var data ={}; var updateData=function(){ var len = arguments.length, i=0; for(i=0;i&lt;len;i++){ data[arguments[i].name]=arguments[i].value; } }; updateData( {name:"a",value:"22"}, {name:"b",value:"2"}, {name:"c",value:"3"}, {name:"a",value:"1"} // the new value for a ); for(key in data){ if(data.hasOwnProperty(key)){ console.log(key + "=" + data[key]); } } </code></pre> <p>Just read your comment about the array, so if you have to have an array you can:</p> <pre><code>var data = []; function findIndex(name){ var i = 0; for(i=0;i&lt;data.length;i++){ if(data[i].name===name){ return i; } } return i; } function updateData(){ var i = 0; for(i=0;i&lt;arguments.length;i++){ data[findIndex(arguments[i].name)]=arguments[i]; } } updateData( {name:"a",value:"22"}, {name:"b",value:"2"}, {name:"c",value:"3"}, {name:"a",value:"1"} // the new value for a ); console.log(data); </code></pre>
18,037,835
Converting string to unsigned int returns the wrong result
<p>I have the following string:</p> <pre><code>sThis = "2154910440"; unsigned int iStart=atoi(sThis.c_str()); </code></pre> <p>However the result is</p> <pre><code>iStart = 2147483647 </code></pre> <p>Does anybody see my mistake?</p>
18,037,885
8
1
null
2013-08-03 22:18:49.167 UTC
3
2018-07-11 15:19:16.747 UTC
2016-04-17 19:33:10.5 UTC
null
102,937
null
1,390,192
null
1
24
c++|type-conversion
87,708
<p><code>atoi</code> converts a string to an <code>int</code>. On your system, an <code>int</code> is 32 bits, and its max value is 2147483647. The value you are trying to convert falls outside this range, so the return value of <code>atoi</code> is undefined. Your implementation, I guess, returns the max value of an <code>int</code> in this case.</p> <p>You could instead use <a href="http://en.cppreference.com/w/cpp/string/byte/atoi"><code>atoll</code></a>, which returns a long long, which is guaranteed to be at least 64 bits. Or you could use a function from the <a href="http://en.cppreference.com/w/cpp/string/basic_string/stol"><code>stoi/stol/stoll</code></a> family, or their <a href="http://en.cppreference.com/w/cpp/string/basic_string/stoul">unsigned counterparts</a>, which will actually give useful error reports on out of range values (and invalid values) in the form of exceptions.</p> <p>Personally, I like <a href="http://www.boost.org/doc/libs/1_54_0/doc/html/boost_lexical_cast.html"><code>boost::lexical_cast</code></a>. Even though it appears a bit cumbersome, it can be used in a more general context. You can use it in templates and just forward the type argument instead of having to have specializations</p>
17,703,710
Changing the color of a clicked table row using jQuery
<p>I need your help,</p> <p>How can I, using jQuery,</p> <p>Change the background color of the selected row in my table (for this example, let's use the the css class "highlighted"</p> <p>and if the same row is clicked on again, change it back to its default color (white) select the css class "nonhighlighted"</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; .highlighted { background: red; } .nonhighlighted { background: white; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;table id="data" border="1" cellspacing="1" width="500" id="table1"&gt; &lt;tr&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
17,703,978
9
2
null
2013-07-17 15:16:50.543 UTC
4
2020-01-10 16:08:26.16 UTC
null
null
null
null
2,009,040
null
1
16
javascript|jquery
111,122
<pre><code>.highlight { background-color: red; } </code></pre> <p>If you want multiple selections</p> <pre><code>$("#data tr").click(function() { $(this).toggleClass("highlight"); }); </code></pre> <p>If you want only 1 row in the table to be selected at a time</p> <pre><code>$("#data tr").click(function() { var selected = $(this).hasClass("highlight"); $("#data tr").removeClass("highlight"); if(!selected) $(this).addClass("highlight"); }); </code></pre> <p>Also note your TABLE tag has 2 ID attributes, you can't do that.</p>
18,070,177
How to get current instance name from T-SQL
<p>How can I get the SQL Server server and instance name of the current connection, using a T-SQL script?</p>
18,070,284
9
1
null
2013-08-06 00:57:20.597 UTC
20
2022-08-23 18:41:48.057 UTC
2022-08-23 18:31:42.55 UTC
null
8,172,439
null
806,975
null
1
110
sql|sql-server|database|tsql|sql-server-2008r2-express
267,916
<p>Just found the answer, in <a href="https://stackoverflow.com/questions/129861/how-can-i-query-the-name-of-the-current-sql-server-database-instance">this SO question</a> (literally, inside the question, not any answer):</p> <pre><code>SELECT @@servername </code></pre> <p>returns servername\instance as far as this is not the default instance</p> <pre><code>SELECT @@servicename </code></pre> <p>returns instance name, even if this is the default (MSSQLSERVER)</p>
45,915,379
How to setup angular 4 inside a maven based java war project
<p>I'm becoming a bit crazy because I can't find a guide to setup an angular 4 app inside a java war project that will be built with maven. This is because I want to run it into a wildfly server.</p> <p>Any help?</p> <p>Thanks</p>
45,943,326
3
7
null
2017-08-28 09:03:59.52 UTC
21
2019-02-11 12:38:38.347 UTC
2018-04-18 08:44:42.89 UTC
null
4,489,295
null
5,629,392
null
1
29
java|angular|maven|wildfly|war
48,570
<p>I had similar requirement to have one source project which has java web-services project as well as angular project(an angular-cli based project) and maven build should create a war with all angular files in it. I used <a href="https://github.com/eirslett/frontend-maven-plugin" rel="noreferrer">maven-frontend-plugin</a> with few configuration changes for base path.</p> <p>The goal was to create a war file with all the java code in it plus all the aot compiled angular code in root folder of war, all this with single command <code>mvn clean package</code>. </p> <p>One more thing for all this to work is to avoid conflict between angular-app router urls and your java application urls, You need to use HashLocationStrategy. one way set it up in app.module.ts like below</p> <p>app.module.ts - </p> <pre><code>providers: [ { provide: LocationStrategy, useClass: HashLocationStrategy }, ] </code></pre> <p>Folder structure for Angular App is below-</p> <h3>angular-project</h3> <ul> <li>dist</li> <li>e2e</li> <li>node_modules</li> <li>public</li> <li>src <ul> <li>app</li> <li>assets</li> <li>environments</li> <li>favicon.ico</li> <li>index.html</li> <li>main.ts</li> <li>polyfills.ts</li> <li>style.css</li> <li>tsconfig.json</li> <li>typings.d.ts</li> <li>etc-etc</li> </ul></li> <li>tmp</li> <li>.angular-cli.json</li> <li>.gitignore</li> <li>karma.conf.js</li> <li>package.json</li> <li>README.md</li> <li>tslint.json</li> <li>etc - etc</li> </ul> <h3>Maven Project -</h3> <ul> <li>src <ul> <li>main <ul> <li>java</li> <li>resources</li> <li>webapp <ul> <li>WEB-INF</li> <li>web.xml</li> </ul></li> </ul></li> </ul></li> <li>angular-project (<strong>place your angular project here</strong>)</li> <li>node_installation</li> <li>pom.xml</li> </ul> <p>Add maven-frontend-plugin configuration to pom.xml</p> <pre><code> &lt;properties&gt; &lt;angular.project.location&gt;angular-project&lt;/angular.project.location&gt; &lt;angular.project.nodeinstallation&gt;node_installation&lt;/angular.project.nodeinstallation&gt; &lt;/properties&gt; &lt;plugin&gt; &lt;groupId&gt;com.github.eirslett&lt;/groupId&gt; &lt;artifactId&gt;frontend-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;configuration&gt; &lt;workingDirectory&gt;${angular.project.location}&lt;/workingDirectory&gt; &lt;installDirectory&gt;${angular.project.nodeinstallation}&lt;/installDirectory&gt; &lt;/configuration&gt; &lt;executions&gt; &lt;!-- It will install nodejs and npm --&gt; &lt;execution&gt; &lt;id&gt;install node and npm&lt;/id&gt; &lt;goals&gt; &lt;goal&gt;install-node-and-npm&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;nodeVersion&gt;v6.10.0&lt;/nodeVersion&gt; &lt;npmVersion&gt;3.10.10&lt;/npmVersion&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;!-- It will execute command "npm install" inside "/e2e-angular2" directory --&gt; &lt;execution&gt; &lt;id&gt;npm install&lt;/id&gt; &lt;goals&gt; &lt;goal&gt;npm&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;arguments&gt;install&lt;/arguments&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;!-- It will execute command "npm build" inside "/e2e-angular2" directory to clean and create "/dist" directory --&gt; &lt;execution&gt; &lt;id&gt;npm build&lt;/id&gt; &lt;goals&gt; &lt;goal&gt;npm&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;arguments&gt;run build&lt;/arguments&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;!-- Plugin to copy the content of /angular/dist/ directory to output directory (ie/ /target/transactionManager-1.0/) --&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-resources-plugin&lt;/artifactId&gt; &lt;version&gt;2.4.2&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;default-copy-resources&lt;/id&gt; &lt;phase&gt;process-resources&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;copy-resources&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;overwrite&gt;true&lt;/overwrite&gt; &lt;!-- This folder is the folder where your angular files will be copied to. It must match the resulting war-file name. So if you have customized the name of war-file for ex. as "app.war" then below value should be ${project.build.directory}/app/ Value given below is as per default war-file name --&gt; &lt;outputDirectory&gt;${project.build.directory}/${project.artifactId}-${project.version}/&lt;/outputDirectory&gt; &lt;resources&gt; &lt;resource&gt; &lt;directory&gt;${project.basedir}/${angular.project.location}/dist&lt;/directory&gt; &lt;/resource&gt; &lt;/resources&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre> <p>As above plugin call 'npm run build' internally, make sure package.json should have build command in script like below -</p> <p>package.json</p> <pre><code>"scripts": { -----//-----, "build": "ng build --prod", -----//------ } </code></pre> <p>index.html should always be loaded when someone hit application from browser that's why make it a welcome file . For web services lets say we have path /rest-services/* will explain this later.</p> <p>web.xml - </p> <pre><code>&lt;welcome-file-list&gt; &lt;welcome-file&gt;index.html&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;restservices&lt;/servlet-name&gt; &lt;url-pattern&gt;/restservices/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p>The above configuration is enough if your application does not have any context path and is deployed on root path on server. But if your application has any context path like <a href="http://localhost:8080/myapplication/" rel="noreferrer">http://localhost:8080/myapplication/</a> then make changes to index.html file as well - </p> <p>angular-project/src/index.html - Here document.location will be myapplication/ (the context path of your app otherwise / if application has no context path )</p> <p>The purpose of making context path a base path for angular-app is that whenever you make ajax http call from angular, it will prepend base path to url. for example if i try to call 'restservices/persons' then it will actually make calls to '<a href="http://localhost:8080/myapplication/restservices/persons" rel="noreferrer">http://localhost:8080/myapplication/restservices/persons</a>'</p> <p>index.html</p> <pre><code> &lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;E2E&lt;/title&gt; &lt;script&gt;document.write('&lt;base href="' + document.location + '" /&gt;'); &lt;/script&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link rel="icon" type="image/x-icon" href="favicon.ico"&gt; &lt;/head&gt; &lt;body&gt; &lt;app-root&gt;&lt;/app-root&gt; &lt;/body&gt; </code></pre> <p></p> <p>After all above changes once you run <code>mvn clean package</code> it will create required war. Check if all the content of angular 'dist' folder is in root of war file.</p>
18,740,123
Difference b/w event.on() and event.once() in nodejs
<p>I'm testing the plus_one app, and while running it, I just wanted to clarify my concepts on event.once() and event.on()</p> <p>This is plus_one.js</p> <pre><code>&gt; process.stdin.resume(); process.stdin.on('data',function(data){ var number; try{ number=parseInt(data.toString(),10); number+=1; process.stdout.write(number+"\n"); } catch(err){ process.stderr.write(err.message+"\n"); } }); </code></pre> <p>and this is test_plus_one.js</p> <pre><code>var spawn=require('child_process').spawn; var child=spawn('node',['plus_one.js']); setInterval(function(){ var number=Math.floor(Math.random()*10000); child.stdin.write(number+"\n"); child.stdout.on('data',function(data){ console.log('child replied to '+number+' with '+data); }); },1000); </code></pre> <p>I get few maxlistener offset warning while using child.stdin.on() but this is not the case when using child.stdin.once(), why is this happening ?</p> <p>Is it because child.stdin is listening to previous inputs ? but in that case maxlistener offset should be set more frequently, but its only happening for once or twice in a minute.</p>
18,742,434
2
0
null
2013-09-11 11:38:07.023 UTC
7
2018-07-25 02:05:29.477 UTC
null
null
null
null
2,768,464
null
1
43
node.js|child-process|eventemitter
25,671
<p>Using <code>EventEmitter.on()</code>, you attach a full listener, versus when you use <code>EventEmitter.once()</code>, it is a one time listener that will detach after firing once. Listeners that only fire once don't count towards the max listener count.</p>
15,642,104
Array of Buttons in Android
<p>I want to map the buttons to an array of buttons and the code has no errors while compiling but there is force close when i run it:</p> <pre><code>Button buttons[]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.game_board_view); // Set OnClick listeners Button buttons[] = null; buttons[0] = (Button)findViewById(R.id.buttonOne); buttons[1] = (Button)findViewById(R.id.buttonTwo); buttons[2] = (Button)findViewById(R.id.buttonThree); buttons[3] = (Button)findViewById(R.id.buttonFour); buttons[4] = (Button)findViewById(R.id.buttonFive); buttons[5] = (Button)findViewById(R.id.buttonSix); buttons[6] = (Button)findViewById(R.id.buttonSeven); buttons[7] = (Button)findViewById(R.id.buttonEight); buttons[8] = (Button)findViewById(R.id.buttonMid); } </code></pre> <p><strong>LogCat:</strong></p> <pre><code>03-26 21:42:51.455: D/dalvikvm(1156): GC_EXTERNAL_ALLOC freed 55K, 53% free 2566K/5379K, external 1625K/2137K, paused 98ms 03-26 21:42:54.323: D/AndroidRuntime(1156): Shutting down VM 03-26 21:42:54.323: W/dalvikvm(1156): threadid=1: thread exiting with uncaught exception (group=0x40015560) 03-26 21:42:54.343: E/AndroidRuntime(1156): FATAL EXCEPTION: main 03-26 21:42:54.343: E/AndroidRuntime(1156): java.lang.RuntimeException: Unable to start activity ComponentInfo{edu.project.superwordwheel/edu.project.superwordwheel.GameView}: java.lang.NullPointerException 03-26 21:42:54.343: E/AndroidRuntime(1156): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) 03-26 21:42:54.343: E/AndroidRuntime(1156): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 03-26 21:42:54.343: E/AndroidRuntime(1156): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 03-26 21:42:54.343: E/AndroidRuntime(1156): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 03-26 21:42:54.343: E/AndroidRuntime(1156): at android.os.Handler.dispatchMessage(Handler.java:99) 03-26 21:42:54.343: E/AndroidRuntime(1156): at android.os.Looper.loop(Looper.java:123) 03-26 21:42:54.343: E/AndroidRuntime(1156): at android.app.ActivityThread.main(ActivityThread.java:3683) 03-26 21:42:54.343: E/AndroidRuntime(1156): at java.lang.reflect.Method.invokeNative(Native Method) 03-26 21:42:54.343: E/AndroidRuntime(1156): at java.lang.reflect.Method.invoke(Method.java:507) 03-26 21:42:54.343: E/AndroidRuntime(1156): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 03-26 21:42:54.343: E/AndroidRuntime(1156): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 03-26 21:42:54.343: E/AndroidRuntime(1156): at dalvik.system.NativeStart.main(Native Method) 03-26 21:42:54.343: E/AndroidRuntime(1156): Caused by: java.lang.NullPointerException 03-26 21:42:54.343: E/AndroidRuntime(1156): at edu.project.superwordwheel.GameView.onCreate(GameView.java:43) 03-26 21:42:54.343: E/AndroidRuntime(1156): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 03-26 21:42:54.343: E/AndroidRuntime(1156): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 03-26 21:42:54.343: E/AndroidRuntime(1156): ... 11 more </code></pre>
15,642,166
6
8
null
2013-03-26 16:17:43.467 UTC
8
2017-02-25 08:12:02.707 UTC
2013-03-26 16:24:44.01 UTC
null
1,401,895
null
1,433,420
null
1
11
android|arrays|android-button
47,956
<p>Your array is null and you're trying to get an index into it. That is what's causing the <code>NullPointerException</code>. Your array must be initialized before you can use it to store your buttons.</p> <p>If you want an array of nine buttons then change this line:</p> <pre><code>Button buttons[] = null; </code></pre> <p>To this:</p> <pre><code>Button buttons[] = new Button[9]; </code></pre> <p>Also, you have a class member <code>Button buttons[]</code> and a local function variable that is also named <code>Button buttons[]</code>. If this is intentional then by all means carry on. Otherwise, you'll want to further change your line to this:</p> <pre><code>buttons[] = new Button[9]; </code></pre>
19,196,728
AES 128 encryption in Java Decryption in PHP
<p>I have been trying to decrypt a string using AES-128 CBC which was originally crypted using JAVA AES encryption. In java PKCS7 padding is used. And I have tried to encrypt and decrypt using similar PHP code. But I am getting different result.</p> <p>My Java code </p> <pre><code>import java.security.MessageDigest; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import android.util.Base64; /** * @author vipin.cb , vipin.cb@experionglobal.com &lt;br&gt; * Sep 27, 2013, 5:18:34 PM &lt;br&gt; * Package:- &lt;b&gt;com.veebow.util&lt;/b&gt; &lt;br&gt; * Project:- &lt;b&gt;Veebow&lt;/b&gt; * &lt;p&gt; */ public class AESCrypt { private final Cipher cipher; private final SecretKeySpec key; private AlgorithmParameterSpec spec; public static final String SEED_16_CHARACTER = "U1MjU1M0FDOUZ.Qz"; public AESCrypt() throws Exception { // hash password with SHA-256 and crop the output to 128-bit for key MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(SEED_16_CHARACTER.getBytes("UTF-8")); byte[] keyBytes = new byte[32]; System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length); cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); key = new SecretKeySpec(keyBytes, "AES"); spec = getIV(); } public AlgorithmParameterSpec getIV() { byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; IvParameterSpec ivParameterSpec; ivParameterSpec = new IvParameterSpec(iv); return ivParameterSpec; } public String encrypt(String plainText) throws Exception { cipher.init(Cipher.ENCRYPT_MODE, key, spec); byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8")); String encryptedText = new String(Base64.encode(encrypted, Base64.DEFAULT), "UTF-8"); return encryptedText; } public String decrypt(String cryptedText) throws Exception { cipher.init(Cipher.DECRYPT_MODE, key, spec); byte[] bytes = Base64.decode(cryptedText, Base64.DEFAULT); byte[] decrypted = cipher.doFinal(bytes); String decryptedText = new String(decrypted, "UTF-8"); return decryptedText; } } </code></pre> <p>And the equivalent PHP code I am using.</p> <pre><code>&lt;?php class MCrypt { private $iv = '0000000000000000'; #Same as in JAVA private $key = 'U1MjU1M0FDOUZ.Qz'; #Same as in JAVA function __construct() { $this-&gt;key = hash('sha256', $this-&gt;key, true); } function encrypt($str) { $iv = $this-&gt;iv; $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); mcrypt_generic_init($td, $this-&gt;key, $iv); $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $pad = $block - (strlen($str) % $block); $str .= str_repeat(chr($pad), $pad); $encrypted = mcrypt_generic($td, $str); mcrypt_generic_deinit($td); mcrypt_module_close($td); return base64_encode($encrypted); } function decrypt($code) { $iv = $this-&gt;iv; $td = mcrypt_module_open('rijndael-128', '', 'cbc', ''); mcrypt_generic_init($td, $this-&gt;key, $iv); $str = mdecrypt_generic($td, base64_decode($code)); $block = mcrypt_get_block_size('rijndael-128', 'cbc'); mcrypt_generic_deinit($td); mcrypt_module_close($td); return $str; //return $this-&gt;strippadding($str); } /* For PKCS7 padding */ private function addpadding($string, $blocksize = 16) { $len = strlen($string); $pad = $blocksize - ($len % $blocksize); $string .= str_repeat(chr($pad), $pad); return $string; } private function strippadding($string) { $slast = ord(substr($string, -1)); $slastc = chr($slast); $pcheck = substr($string, -$slast); if (preg_match("/$slastc{" . $slast . "}/", $string)) { $string = substr($string, 0, strlen($string) - $slast); return $string; } else { return false; } } } $encryption = new MCrypt(); echo $encryption-&gt;encrypt('123456') . "&lt;br/&gt;"; echo $encryption-&gt;decrypt('tpyxISJ83dqEs3uw8bN/+w=='); </code></pre> <p>In Java<br> Plain text = 123456<br> Cipher text = tpyxISJ83dqEs3uw8bN/+w==</p> <p>In PHP </p> <p>Plain text = 123456<br> Cipher text = IErqfTCktrnmWndOpq3pnQ==</p> <p>When I tried to decrpt the Java encrypted text "tpyxISJ83dqEs3uw8bN/+w==" using PHP decryption I am getting an empty array if I removed the padding . Without removing the padding I am getting "::::::::::"</p> <p>I think there is some mistake with the IV bytes used in PHP and Java Can anyone help me on this. I have tried many combinations . Still no result. I am very new to Java concepts.</p> <p><strong>------Solution-------</strong></p> <p>I have modified my php class according to the comments given by owlstead. may be there is a better way. I am posting it here so that someone may find it helpful in future and your comments are welcome for further improvement.</p> <pre><code>&lt;?php class MCrypt { private $hex_iv = '00000000000000000000000000000000'; # converted Java byte code in to HEX and placed it here private $key = 'U1MjU1M0FDOUZ.Qz'; #Same as in JAVA function __construct() { $this-&gt;key = hash('sha256', $this-&gt;key, true); //echo $this-&gt;key.'&lt;br/&gt;'; } function encrypt($str) { $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); mcrypt_generic_init($td, $this-&gt;key, $this-&gt;hexToStr($this-&gt;hex_iv)); $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $pad = $block - (strlen($str) % $block); $str .= str_repeat(chr($pad), $pad); $encrypted = mcrypt_generic($td, $str); mcrypt_generic_deinit($td); mcrypt_module_close($td); return base64_encode($encrypted); } function decrypt($code) { $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, ''); mcrypt_generic_init($td, $this-&gt;key, $this-&gt;hexToStr($this-&gt;hex_iv)); $str = mdecrypt_generic($td, base64_decode($code)); $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); mcrypt_generic_deinit($td); mcrypt_module_close($td); return $this-&gt;strippadding($str); } /* For PKCS7 padding */ private function addpadding($string, $blocksize = 16) { $len = strlen($string); $pad = $blocksize - ($len % $blocksize); $string .= str_repeat(chr($pad), $pad); return $string; } private function strippadding($string) { $slast = ord(substr($string, -1)); $slastc = chr($slast); $pcheck = substr($string, -$slast); if (preg_match("/$slastc{" . $slast . "}/", $string)) { $string = substr($string, 0, strlen($string) - $slast); return $string; } else { return false; } } function hexToStr($hex) { $string=''; for ($i=0; $i &lt; strlen($hex)-1; $i+=2) { $string .= chr(hexdec($hex[$i].$hex[$i+1])); } return $string; } } $encryption = new MCrypt(); echo $encryption-&gt;encrypt('123456') . "&lt;br/&gt;"; echo $encryption-&gt;decrypt('tpyxISJ83dqEs3uw8bN/+w=='); </code></pre>
19,201,380
1
2
null
2013-10-05 10:29:44.52 UTC
10
2017-06-17 19:22:14.293 UTC
2017-06-17 19:22:14.293 UTC
null
3,885,376
null
2,286,174
null
1
17
java|php|android|encryption|aes
17,557
<p>Your IV is different, a byte with value zero is different from a character <code>'0'</code> which would translate into a byte with value <code>30</code> in hexadecimals or 48 in decimals (if you presume ASCII or UTF-8 encoding).</p>
57,458,460
Why is there a large performance impact when looping over an array with 240 or more elements?
<p>When running a sum loop over an array in Rust, I noticed a huge performance drop when <code>CAPACITY</code> >= 240. <code>CAPACITY</code> = 239 is about 80 times faster. </p> <p>Is there special compilation optimization Rust is doing for "short" arrays? </p> <p>Compiled with <code>rustc -C opt-level=3</code>.</p> <pre class="lang-rust prettyprint-override"><code>use std::time::Instant; const CAPACITY: usize = 240; const IN_LOOPS: usize = 500000; fn main() { let mut arr = [0; CAPACITY]; for i in 0..CAPACITY { arr[i] = i; } let mut sum = 0; let now = Instant::now(); for _ in 0..IN_LOOPS { let mut s = 0; for i in 0..arr.len() { s += arr[i]; } sum += s; } println!("sum:{} time:{:?}", sum, now.elapsed()); } </code></pre>
57,462,362
2
3
null
2019-08-12 09:16:34.857 UTC
47
2019-08-16 10:05:03.45 UTC
2019-08-15 02:35:39.703 UTC
null
1,543,618
null
593,425
null
1
252
arrays|performance|rust|llvm-codegen
21,986
<p><strong>Summary</strong>: below 240, LLVM fully unrolls the inner loop and that lets it notice it can optimize away the repeat loop, breaking your benchmark.</p> <p><br></p> <hr> <p><strong>You found a magic threshold above which LLVM stops performing certain optimizations</strong>. The threshold is 8 bytes * 240 = 1920 bytes (your array is an array of <code>usize</code>s, therefore the length is multiplied with 8 bytes, assuming x86-64 CPU). In this benchmark, one specific optimization – only performed for length 239 – is responsible for the huge speed difference. But let's start slowly:</p> <p><em>(All code in this answer is compiled with <code>-C opt-level=3</code>)</em></p> <pre class="lang-rust prettyprint-override"><code>pub fn foo() -&gt; usize { let arr = [0; 240]; let mut s = 0; for i in 0..arr.len() { s += arr[i]; } s } </code></pre> <p>This simple code will produce roughly the assembly one would expect: a loop adding up elements. However, if you change <code>240</code> to <code>239</code>, the emitted assembly differs quite a lot. <a href="https://rust.godbolt.org/z/VKL9MS" rel="noreferrer">See it on Godbolt Compiler Explorer</a>. Here is a small part of the assembly:</p> <pre class="lang-none prettyprint-override"><code>movdqa xmm1, xmmword ptr [rsp + 32] movdqa xmm0, xmmword ptr [rsp + 48] paddq xmm1, xmmword ptr [rsp] paddq xmm0, xmmword ptr [rsp + 16] paddq xmm1, xmmword ptr [rsp + 64] ; more stuff omitted here ... paddq xmm0, xmmword ptr [rsp + 1840] paddq xmm1, xmmword ptr [rsp + 1856] paddq xmm0, xmmword ptr [rsp + 1872] paddq xmm0, xmm1 pshufd xmm1, xmm0, 78 paddq xmm1, xmm0 </code></pre> <p>This is what's called <em>loop unrolling</em>: LLVM pastes the loop body a bunch of time to avoid having to execute all those "loop management instructions", i.e. incrementing the loop variable, check if the loop has ended and the jump to the start of the loop.</p> <p>In case you're wondering: the <code>paddq</code> and similar instructions are SIMD instructions which allow summing up multiple values in parallel. Moreover, two 16-byte SIMD registers (<code>xmm0</code> and <code>xmm1</code>) are used in parallel so that instruction-level parallelism of the CPU can basically execute two of these instructions at the same time. After all, they are independent of one another. In the end, both registers are added together and then horizontally summed down to the scalar result.</p> <p>Modern mainstream x86 CPUs (not low-power Atom) really can do 2 vector loads per clock when they hit in L1d cache, and <code>paddq</code> throughput is also at least 2 per clock, with 1 cycle latency on most CPUs. See <a href="https://agner.org/optimize/" rel="noreferrer">https://agner.org/optimize/</a> and also <a href="https://stackoverflow.com/questions/45113527/why-does-mulss-take-only-3-cycles-on-haswell-different-from-agners-instruction">this Q&amp;A</a> about multiple accumulators to hide latency (of FP FMA for a dot product) and bottleneck on throughput instead.</p> <p>LLVM does unroll small loops <em>some</em> when it's not <em>fully</em> unrolling, and still uses multiple accumulators. So usually, front-end bandwidth and back-end latency bottlenecks aren't a huge problem for LLVM-generated loops even without full unrolling.</p> <hr> <p><strong>But loop unrolling is not responsible for a performance difference of factor 80!</strong> At least not loop unrolling alone. Let's take a look at the actual benchmarking code, which puts the one loop inside another one:</p> <pre class="lang-rust prettyprint-override"><code>const CAPACITY: usize = 239; const IN_LOOPS: usize = 500000; pub fn foo() -&gt; usize { let mut arr = [0; CAPACITY]; for i in 0..CAPACITY { arr[i] = i; } let mut sum = 0; for _ in 0..IN_LOOPS { let mut s = 0; for i in 0..arr.len() { s += arr[i]; } sum += s; } sum } </code></pre> <p>(<a href="https://rust.godbolt.org/z/73xy5I" rel="noreferrer">On Godbolt Compiler Explorer</a>)</p> <p>The assembly for <code>CAPACITY = 240</code> looks normal: two nested loops. (At the start of the function there is quite some code just for initializing, which we will ignore.) For 239, however, it looks very different! We see that the initializing loop and the inner loop got unrolled: so far so expected.</p> <p><strong>The important difference is that for 239, LLVM was able to figure out that the result of the inner loop does not depend on the outer loop!</strong> As a consequence, LLVM emits code that basically first executes only the inner loop (calculating the sum) and then simulates the outer loop by adding up <code>sum</code> a bunch of times! </p> <p>First we see almost the same assembly as above (the assembly representing the inner loop). Afterwards we see this (I commented to explain the assembly; the comments with <code>*</code> are especially important):</p> <pre class="lang-none prettyprint-override"><code> ; at the start of the function, `rbx` was set to 0 movq rax, xmm1 ; result of SIMD summing up stored in `rax` add rax, 711 ; add up missing terms from loop unrolling mov ecx, 500000 ; * init loop variable outer loop .LBB0_1: add rbx, rax ; * rbx += rax add rcx, -1 ; * decrement loop variable jne .LBB0_1 ; * if loop variable != 0 jump to LBB0_1 mov rax, rbx ; move rbx (the sum) back to rax ; two unimportant instructions omitted ret ; the return value is stored in `rax` </code></pre> <p>As you can see here, the result of the inner loop is taken, added up as often as the outer loop would have ran and then returned. LLVM can only perform this optimization because it understood that the inner loop is independent of the outer one. </p> <p><strong>This means the runtime changes from <code>CAPACITY * IN_LOOPS</code> to <code>CAPACITY + IN_LOOPS</code></strong>. And this is responsible for the huge performance difference.</p> <hr> <p>An additional note: can you do anything about this? Not really. LLVM has to have such magic thresholds as without them LLVM-optimizations could take forever to complete on certain code. But we can also agree that this code was highly artificial. In practice, I doubt that such a huge difference would occur. The difference due to full loop unrolling is usually not even factor 2 in these cases. So no need to worry about real use cases.</p> <p>As a last note about idiomatic Rust code: <code>arr.iter().sum()</code> is a better way to sum up all elements of an array. And changing this in the second example does not lead to any notable differences in emitted assembly. You should use short and idiomatic versions unless you measured that it hurts performance.</p>
41,142,262
Why isn't IIS cleaning up the old worker processes (w3wp.exe) on pool recycle leading to website out of memory exception?
<p>I have an asp.net-mvc site and recently I am getting an out of memory exceptions on my web server. I only have 1 application pool and we recent set IIS to recycle after it hits a certain limit. I went in the other day and saw <strong>4 w3wp.exe processes running</strong> (each with ~1.8GB memory being used)</p> <p>I assume that during the recycle process, it's not killing the old worker process and eventually I get out of memory exceptions on my website because the box only has 8GB memory. I can add memory to the box but I am concerned why these old processes are not being cleaned up. </p> <p>Are there any recommendations to figure out why this recycle process is not killing the old w3wp.exe processes and leaving them running? Any suggestions around understand both root cause or even workarounds to avoid this risk going forward?</p>
41,519,323
5
4
null
2016-12-14 12:08:10.323 UTC
3
2021-10-12 18:02:38.827 UTC
2017-02-18 18:02:54.077 UTC
null
4,549,952
null
4,653
null
1
29
asp.net-mvc|iis|out-of-memory|recycle|w3wp
10,300
<p>I had similar issue when I was running things like FFMpeg.exe or some PDF conversion with WPF graphics, IIS process won't shutdown and would issue memory not found errors. The problem is not with IIS, but some deadlocks in the process which blocks even after crashing.</p> <p>Workaround is, divide your website in to two separate websites, one should only do transaction processing with database which usually does not have crashes. The logic like video/photo conversion, PDF conversion, or any other logic that may cause crash should be moved to other web service. And use HTTP call from your website internally to process them over web services.</p> <p>Now, in this case, there is still no way to get around web service process crashing, so I decided to recycle application pool worker every 100 requests (I chose this number after watching few requests, on an average it would go beyond 1GB only after hitting 200 requests) and I turned application pool into Web Garden by making 4 process per pool.</p> <p>Advantage of this setup is, you can move your web service process to other machines easily in future, you can increase/decrease number of processes per pool. And your main website, which is simply doing transaction process becomes highly responsive as it is not affected by process recycles of web services.</p>
5,169,253
How do I generate One time passwords (OTP / HOTP)?
<p>We have decided to start work on Multi-factor authentication, by way of releasing an iPhone, Android and Blackberry app for our customers.</p> <p>Think <a href="http://www.google.com/support/a/bin/answer.py?hlrm=en&amp;answer=1037451" rel="noreferrer">Google Authenticator</a>'s one-time password system.</p> <p>I can get how I could generate a unique <strong>string</strong> by hashing using a SALT based on the account secret key plus the device serial number (or other unique identifier). </p> <p>But does anyone have any idea how you could generate a unique, short number, in the way that google does? And/or does anyone have any good links to articles on achieving this kind of thing?</p> <p>Many thanks</p>
5,476,520
2
0
null
2011-03-02 14:55:34.39 UTC
9
2013-02-15 05:42:10.417 UTC
2011-03-29 17:29:50.963 UTC
null
431,880
null
431,880
null
1
13
c#|security
28,824
<p>In the end I found that this was very well documented in <a href="https://www.rfc-editor.org/rfc/rfc4226" rel="nofollow noreferrer">RFC 4226</a> and regarding the integer conversion, this can be done using the bitwise operation <a href="https://www.rfc-editor.org/rfc/rfc4226#page-7" rel="nofollow noreferrer">shown on page 7</a>, essentially it is the same as that shown in the answer below.</p> <p>There was <a href="https://stackoverflow.com/questions/4308003/hmac-based-one-time-password-in-c-rfc-4226-hotp">another post on stackoverflow</a> regarding this in a C# context, which may be worth a read if you are in a similar position.</p> <p>In C# I basically, hashed a time identifier (i.e. the current time in seconds divided by 30 - to get a long which is valid for the current 30-second interval). Then hashed this using my secret key as the SALT.</p> <p>And then...</p> <pre><code>// Use a bitwise operation to get a representative binary code from the hash // Refer section 5.4 at https://www.rfc-editor.org/rfc/rfc4226#page-7 int offset = hashBytes[19] &amp; 0xf; int binaryCode = (hashBytes[offset] &amp; 0x7f) &lt;&lt; 24 | (hashBytes[offset + 1] &amp; 0xff) &lt;&lt; 16 | (hashBytes[offset + 2] &amp; 0xff) &lt;&lt; 8 | (hashBytes[offset + 3] &amp; 0xff); // Generate the OTP using the binary code. As per RFC 4426 [link above] &quot;Implementations MUST extract a 6-digit code at a minimum // and possibly 7 and 8-digit code&quot; int otp = binaryCode % (int)Math.Pow(10, 6); // where 6 is the password length return otp.ToString().PadLeft(6, '0'); </code></pre> <p>For those of you who didn't know, Google Authenticator is an open source project - you can <a href="http://code.google.com/p/google-authenticator/source/browse/?repo=android" rel="nofollow noreferrer">browse the source code here</a>.</p>
5,314,532
How to set margin with jquery?
<p>I am doing this:</p> <pre><code>var sId=id.toString(); var index=sId.substring(3); var mrg=index*221; var el=$(id); el.css('margin-left',mrg+'px'); and el.css('marginLeft',mrg+'px'); </code></pre> <p>el is the element i want to set the margin to (correctly retrieved) and mrg is the value of the new margin</p> <p>If i do $<code>('#test1').css('margin-left',200);</code> or <code>$('#test1').css('marginLeft',200);</code> it works in both ways, it's something wrong with the way i set the property. </p> <p>The correct way is var <code>el=$('#'+id);</code></p>
5,314,570
2
2
null
2011-03-15 16:06:49.843 UTC
5
2014-06-26 15:51:46.833 UTC
2013-02-14 06:02:10.63 UTC
null
1,372,224
null
170,197
null
1
43
javascript|jquery
112,391
<p>try </p> <pre><code>el.css('margin-left',mrg+'px'); </code></pre>
16,079,490
How to include page title of wordpress post in the content possibly with a shortcode
<p>in the wordpress admin, i would like to do the following when creating a page:</p> <p>Page Title: Test</p> <p>Page content:</p> <p>Lorem ipsum dolor <strong>[page_title]</strong> sit amet, consectetur adipiscing elit. Nunc et lectus sit amet ante vulputate ultrices at sit amet <strong>[page_title]</strong> tortor. Nam mattis commodo mi in semper. Suspendisse ut eros dolor. Morbi at odio feugiat <strong>[page_title]</strong> nunc vestibulum venenatis sit amet vitae neque. Nam ullamcorper ante ac risus malesuada id iaculis nibh ultrices.</p> <hr> <p>Where it says [page_title] I would like it to print the page title (Test)</p> <p>This needs to be achieved through the admin system, not hard-coded in the template.</p>
16,079,707
3
2
null
2013-04-18 09:40:10.85 UTC
5
2017-12-11 02:40:45.367 UTC
null
null
null
null
2,062,739
null
1
8
php|html|wordpress|shortcode
44,103
<p>Refer to the codex: <a href="http://codex.wordpress.org/Shortcode_API" rel="noreferrer">Shortcode API</a></p> <pre><code>function myshortcode_title( ){ return get_the_title(); } add_shortcode( 'page_title', 'myshortcode_title' ); </code></pre> <p>Add this to your theme's functions.php file.</p> <p>Note that per the comments exchange between S.Visser and I in his answer - this solution will only work inside The Loop, while his will also work outside The Loop and so his is the more complete answer.</p>
16,110,143
What are some useful tips/tools for monitoring/tuning memcached health?
<p>Yesterday, I found this cool script '<a href="https://code.google.com/p/memcache-top/">memcache-top</a>' which nicely prints out stats of memcached live. It looks like,</p> <pre><code>memcache-top v0.6 (default port: 11211, color: on, refresh: 3 seconds) INSTANCE USAGE HIT % CONN TIME EVICT/s READ/s WRITE/s 127.0.0.1:11211 88.8% 94.8% 20 0.8ms 9.0 311.3K 162.8K AVERAGE: 88.8% 94.8% 20 0.8ms 9.0 311.3K 162.8K TOTAL: 1.8GB/ 2.0GB 20 0.8ms 9.0 311.3K 162.8K (ctrl-c to quit.) </code></pre> <p>it even makes certain text red when you should pay attention to something!</p> <p>Q. Broadly, what are some useful tools/techniques you've used to check that memcached is set up well?</p>
16,158,996
2
0
null
2013-04-19 17:19:01.713 UTC
9
2014-02-21 04:52:56.183 UTC
2014-02-21 04:52:56.183 UTC
null
1,093,174
null
1,093,174
null
1
12
memcached
24,928
<p>Good interface to accessing Memcached server instances is <a href="https://code.google.com/p/phpmemcacheadmin/">phpMemCacheAdmin</a>.</p> <p>I prefer access from the command line using <code>telnet</code>.</p> <p>To make a connection to Memcached using Telnet, use the following <code>telnet localhost 11211</code> command from the command line.</p> <p>If at any time you wish to terminate the Telnet session, simply type <code>quit</code> and hit return.</p> <p>You can get an overview of the important statistics of your Memcached server by running the <code>stats</code> command once connected.</p> <p>Memory is allocated in chunks internally and constantly reused. Since memory is broken into different size slabs, you do waste memory if your items do not fit perfectly into the slab the server chooses to put it in.</p> <p>So Memcached allocates your data into different "slabs" (think of these as partitions) of memory automatically, based on the size of your data, which in turn makes memory allocation more optimal.</p> <p>To list the slabs in the instance you are connected to, use the <code>stats slab</code> command.</p> <p>A more useful command is the <code>stats items</code>, which will give you a list of slabs which includes a count of the items store within each slab.</p> <p>Now that you know how to list slabs, you can browse inside each slab to list the items contained within by using the <code>stats cachedump [slab ID] [number of items, 0 for all items]</code> command.</p> <p>If you want to get the actual value of that item, you can use the <code>get [key]</code> command.</p> <p>To delete an item from the cache you can use the <code>delete [key]</code> command.</p>
353,817
Should every class have a virtual destructor?
<p>Java and C# support the notion of classes that can't be used as base classes with the <code>final</code> and <code>sealed</code> keywords. In C++ however there is no good way to prevent a class from being derived from which leaves the class's author with a dilemma, should every class have a virtual destructor or not?</p> <hr> <p><strong>Edit:</strong> Since C++11 this is no longer true, you can specify that a class is <a href="http://en.cppreference.com/w/cpp/language/final" rel="noreferrer"><code>final</code></a>.</p> <hr> <p>On the one hand giving an object a virtual destructor means it will have a <code>vtable</code> and therefore consume 4 (or 8 on 64 bit machines) additional bytes per-object for the <code>vptr</code>.</p> <p>On the other hand if someone later derives from this class and deletes a derived class via a pointer to the base class the program will be ill-defined (due to the absence of a virtual destructor), and frankly optimizing for a pointer per object is ridiculous. </p> <p>On the <a href="http://en.wikipedia.org/wiki/Gripping_hand" rel="noreferrer">gripping hand </a> having a virtual destructor (arguably) advertises that this type is meant to be used polymorphically.</p> <p>Some people think you need an explicit reason to not use a virtual destructor (as is the subtext of <a href="https://stackoverflow.com/questions/300986">this question</a>) and others say that you should use them only when you have reason to believe that your class is to be derived from, what do <em>you</em> think?</p>
353,890
7
7
null
2008-12-09 18:56:10.27 UTC
35
2020-02-22 21:20:17.45 UTC
2017-05-23 10:31:25.21 UTC
null
-1
Motti
3,848
null
1
56
c++|virtual-destructor
50,587
<p>The question is really, do you want to <em>enforce</em> rules about how your classes should be used? Why? If a class doesn't have a virtual destructor, anyone using the class knows that it is not intended to be derived from, and what limitations apply if you try it anyway. Isn't that good enough?</p> <p>Or do you need the compiler to throw a hard error if anyone <em>dares</em> to do something you hadn't anticipated?</p> <p>Give the class a virtual destructor if you intend for people to derive from it. Otherwise don't, and assume that anyone using your code is intelligent enough to use your code correctly.</p>
246,233
Dot Matrix printing in C#?
<p>I'm trying to print to Dot Matrix printers (various models) out of C#, currently I'm using Win32 API (you can find alot of examples online) calls to send escape codes directly to the printer out of my C# application. This works great, but...</p> <p>My problem is because I'm generating the escape codes and not relying on the windows print system the printouts can't be sent to any "normal" printers or to things like PDF print drivers. (This is now causing a problem as we're trying to use the application on a 2008 Terminal Server using Easy Print [Which is XPS based])</p> <p>The question is: How can I print formatted documents (invoices on pre-printed stationary) to Dot Matrix printers (Epson, Oki and Panasonic... various models) out of C# not using direct printing, escape codes etc.</p> <p>**Just to clarify, I'm trying things like GDI+ (System.Drawing.Printing) but the problem is that its very hard, to get things to line up like the old code did. (The old code sent the characters direct to the printer bypassing the windows driver.) Any suggestions how things could be improved so that they could use GDI+ but still line up like the old code did?</p>
249,763
8
1
null
2008-10-29 09:34:34.813 UTC
12
2015-08-10 03:04:17.41 UTC
2008-10-30 07:11:11.56 UTC
null
32,305
null
32,305
null
1
9
c#|printing|xps
30,073
<p>You should probably use a reporting tool to make templates that allow you or users to correctly position the fields with regards to the pre-printed stationery.</p> <p>Using dot-matrix printers, you basically have to work in either of 2 modes:</p> <ul> <li>simple type-writer mode of line/column text where you send escape sequences to manage a small number of fonts that are included in the printer hardware and have to manage line returns, etc.</li> <li>graphic output where the page is rasterized and the printer driver just drives the print head and pins to output the dots.</li> </ul> <p>The first usage is mostly deprecated under Windows as it does not offer much in the way of controlling the output, and each printer having its own characteristics it becomes unwieldy and difficult for the software to predict and position things on the page (no WYSIWYG).</p> <p>The second just uses a graphic page paradigm that makes positioning text and graphics independent of the actual capabilities of the printer.<br> When using pre-printed stationery, your job s to correctly position the data on the page.<br> Doing this by hand is resource-consuming and creating the layout in code is certainly not recommended since you'll get stuck with code to change should your printer, page format or printed stationery change.</p> <p>The best is to just use the standard printing model offered by .Net and a reporting tool that allows you to define models and templates where the correct text and graphics will be positioned, and then drive this from code.</p> <p>Visual Studio is shipped with a version of Crystal Reports but there are other, better reporting systems (I use the one from <a href="http://devexpress.com/" rel="noreferrer">developer express</a> for instance), some of them are even <a href="http://www.fyireporting.com/" rel="noreferrer">free</a>.</p>
29,004
Parsing XML using unix terminal
<p>Sometimes I need to quickly extract some arbitrary data from XML files to put into a CSV format. What's your best practices for doing this in the Unix terminal? I would love some code examples, so for instance how can I get the following problem solved?</p> <p>Example XML input:</p> <pre class="lang-html prettyprint-override"><code>&lt;root&gt; &lt;myel name=&quot;Foo&quot; /&gt; &lt;myel name=&quot;Bar&quot; /&gt; &lt;/root&gt; </code></pre> <p>My desired CSV output:</p> <pre><code>Foo, Bar, </code></pre>
29,032
8
0
null
2008-08-26 20:09:40.303 UTC
4
2021-02-12 13:05:44.047 UTC
2021-01-19 08:19:39.093 UTC
Rob Cooper
5,123,537
Mattias
261
null
1
13
xml|unix|parsing|shell|csv
48,303
<p>If you just want the name attributes of any element, here is a quick but incomplete solution.</p> <p>(Your example text is in the file <em>example</em>)</p> <blockquote> <p>grep "name" example | cut -d"\"" -f2,2 | xargs -I{} echo "{},"</p> </blockquote>
544,296
As a programmer, what do I need to worry about when moving to 64-bit windows?
<p>Most of my recent programming has been on 32-bit Windows using C/C++/C#/VB6 . Lately, my customers are asking if my code will run on 64-bit Windows.</p> <p>I'm wondering what legacy features I might be using that will break on 64-bit Windows? What are some real-world issues I need to think about and worry about?</p> <p>Obviously, I will test my code on the 64-bit OS, but I'd like to know what common issues to look for. I more concerned with the existing binaries, but I am open to comments about what to worry about when recompiling (where possible).</p> <p>EDIT: Here is a <a href="http://software.intel.com/en-us/articles/collection-of-examples-of-64-bit-errors-in-real-programs/" rel="noreferrer">nice list</a> of 64-bit porting bugs.</p>
549,456
8
3
null
2009-02-13 01:03:43.903 UTC
25
2020-08-26 18:37:35.21 UTC
2012-03-17 11:56:18.823 UTC
null
21,234
jm
814
null
1
32
windows|32bit-64bit
12,232
<p>Articles:</p> <p><a href="https://www.viva64.com/en/a/0004/" rel="nofollow noreferrer">20 issues of porting C++ code on the 64-bit platform</a></p> <p><a href="https://www.viva64.com/en/a/0010/" rel="nofollow noreferrer">The forgotten problems of 64-bit programs development</a></p> <p><a href="https://www.viva64.com/en/a/0021/" rel="nofollow noreferrer">64 bits, Wp64, Visual Studio 2008, Viva64 and all the rest...</a></p> <p><a href="https://www.viva64.com/en/a/0012/" rel="nofollow noreferrer">Traps detection during migration of C and C++ code to 64-bit Windows</a></p> <p><a href="https://www.viva64.com/en/a/0029/" rel="nofollow noreferrer">AMD64 (EM64T) architecture</a></p> <p>And</p> <p>Viva64 tool - for check 64-bit programs:</p> <p><a href="https://www.viva64.com/en/a/0009/" rel="nofollow noreferrer">Viva64: what is it and for whom is it meant?</a></p>
479,819
Bulk insert, SQL Server 2000, unix linebreaks
<p>I am trying to insert a .csv file into a database with unix linebreaks. The command I am running is:</p> <pre><code>BULK INSERT table_name FROM 'C:\file.csv' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' ) </code></pre> <p>If I convert the file into Windows format the load works, but I don't want to do this extra step if it can be avoided. Any ideas?</p>
4,207,050
8
0
null
2009-01-26 13:37:17.24 UTC
10
2011-11-15 17:45:18.97 UTC
2009-01-26 14:50:15.58 UTC
Cade Roux
18,255
John Oxley
24,108
null
1
35
sql|sql-server|bulkinsert
28,478
<p>I felt compelled to contribute as I was having the same issue, and I need to read 2 UNIX files from SAP at least a couple of times a day. Therefore, instead of using unix2dos, I needed something with less manual intervention and more automatic via programming.</p> <p>As noted, the Char(10) works within the sql string. I didn't want to use an sql string, and so I used ''''+Char(10)+'''', but for some reason, this didn't compile.</p> <p>What did work very slick was: with (ROWTERMINATOR = '0x0a')</p> <p>Problem solved with Hex!</p> <p>Hope this helps someone.</p>
1,126,783
What are design patterns to support custom fields in an application?
<p>We develop a commercial application. Our customers are asking for custom fields support. For instance, they want to add a field to the Customer form.</p> <p>What are the known design patterns to store the field values and the meta-data about the fields?</p> <p>I see these options for now:</p> <p><strong>Option 1</strong>: Add Field1, Field2, Field3, Field4 columns of type varchar to my Customer table.</p> <p><strong>Option 2</strong>: Add a single column of type XML in the customer table and store the custom fields' values in xml.</p> <p><strong>Option 3</strong>: Add a CustomerCustomFieldValue table with a column of type varchar and store values in that column. That table would also have a CustomerID, a CustomFieldID.</p> <pre><code>CustomerID, CustomFieldID, Value 10001, 1001, '02/12/2009 8:00 AM' 10001, 1002, '18.26' 10002, 1001, '01/12/2009 8:00 AM' 10002, 1002, '50.26' </code></pre> <p>CustomFieldID would be an ID from another table called CustomField with these columns: CustomFieldID, FieldName, FieldValueTypeID.</p> <p><strong>Option 4</strong>: Add a CustomerCustomFieldValue table with a column of each possible value type and store values in the right column. Similar to #3 but field values are stored using a strongly-type column.</p> <pre><code>CustomerID, CustomFieldID, DateValue, StringValue, NumericValue 10001, 1001, 02/12/2009 8:00 AM, null, null 10001, 1002, null, null, 18.26 10002, 1001, 01/12/2009 8:00 AM, null, null 10002, 1002, null, null, 50.26 </code></pre> <p><strong>Option 5</strong>: Options 3 and 4 use a table specific to a single concept (Customer). Our clients are asking for custom field in other forms as well. Should we instead have a system-wide custom field storage system? So instead of having multiple tables such as CustomerCustomFieldValue, EmployeeCustomFieldValue, InvoiceCustomFieldValue, we would have a single table named CustomFieldValue? Although it seems more elegant to me, wouldn't that cause a performance bottleneck?</p> <p>Have you used any of those approaches? Were you successful? What approach would you select? Do you know any other approach that I should consider?</p> <p>Also, my clients want the custom field to be able to refer to data in other tables. For instance a client might want to add a &quot;Favorite Payment Method&quot; field to the Customer. Payment methods are defined elsewhere in the system. That brings the subject of &quot;foreign keys&quot; in the picture. Should I try to create constraints to ensure that values stored in the custom field tables are valid values?</p>
1,127,083
8
3
null
2009-07-14 17:18:20.717 UTC
63
2022-05-21 23:22:52.747 UTC
2022-05-21 23:22:52.747 UTC
null
4,157,124
null
121,445
null
1
73
database-design|data-modeling
23,875
<p>I do agree with posters below that Options 3, 4, or 5 are most likely to be appropriate. However, each of your suggested implementations has its benefits and costs. I'd suggest choosing one by matching it to your specific requirements. For example:</p> <ol> <li>Option 1 pros: Fast to implement. Allows DB actions on custom fields (searching, sorting.)<br> Option 1 cons: Custom fields are generic, so no strongly-typed fields. Database table is inefficient, size-wise with many extraneous fields that will never be used. Number of custom fields allowed needs to be anticipated.</li> <li>Option 2 pros: Fast to implement. Flexible, allowing arbitrary number and type of custom fields.<br> Option 2 cons: No DB actions possible on custom fields. This is best if all you need to do is display the custom fields, later, or do minor manipulations of the data only on a per-Customer basis.</li> <li>Option 3 pros: Both flexible and efficient. DB actions can be performed, but the data is normalized somewhat to reduce wasted space. I agree with unknown (google)'s suggestion that you add an additional column that can be used to specify type or source information. Option 3 cons: Slight increase in development time and complexity of your queries, but there really aren't too many cons, here.</li> <li>Option 4 is the same as Option 3, except that your typed data can be operated on at the DB level. The addition of type information to the link table in Option 3 allows you to do more operations at our application level, but the DB won't be able to do comparisons or sort, for example. The choice between 3 and 4 depends on this requirement.</li> <li>Option 5 is the same as 3 or 4, but with even more flexibility to apply the solution to many different tables. The cost in this case will be that the size of this table will grow much larger. If you are doing many expensive join operations to get to your custom fields, this solution may not scale well. </li> </ol> <p>P.S. As noted below, the term "design pattern" usually refers to object-oriented programming. You're looking for a solution to a database design problem, which means that most advice regarding design patterns won't be applicable.</p>
24,723
Best regex to catch XSS (Cross-site Scripting) attack (in Java)?
<p>Jeff actually posted about this in <a href="http://refactormycode.com/codes/333-sanitize-html" rel="noreferrer">Sanitize HTML</a>. But his example is in C# and I'm actually more interested in a Java version. Does anyone have a better version for Java? Is his example good enough to just convert directly from C# to Java?</p> <p>[Update] I have put a bounty on this question because SO wasn't as popular when I asked the question as it is today (*). As for anything related to security, the more people look into it, the better it is!</p> <p>(*) In fact, I think it was still in closed beta</p>
535,022
9
1
null
2008-08-24 00:21:10.413 UTC
24
2022-01-10 21:40:10.09 UTC
2020-06-20 09:12:55.06 UTC
Eldimo
-1
Eldimo
1,406
null
1
31
java|html|regex|xss
89,005
<p>Don't do this with regular expressions. Remember, you're not protecting just against valid HTML; you're protecting against the DOM that web browsers create. Browsers can be tricked into producing valid DOM from invalid HTML quite easily. </p> <p>For example, see this list of <a href="http://ha.ckers.org/xss.html" rel="noreferrer">obfuscated XSS attacks</a>. Are you prepared to tailor a regex to prevent this real world attack on <a href="http://www.greymagic.com/security/advisories/gm005-mc/" rel="noreferrer">Yahoo and Hotmail</a> on IE6/7/8?</p> <pre><code>&lt;HTML&gt;&lt;BODY&gt; &lt;?xml:namespace prefix="t" ns="urn:schemas-microsoft-com:time"&gt; &lt;?import namespace="t" implementation="#default#time2"&gt; &lt;t:set attributeName="innerHTML" to="XSS&amp;lt;SCRIPT DEFER&amp;gt;alert(&amp;quot;XSS&amp;quot;)&amp;lt;/SCRIPT&amp;gt;"&gt; &lt;/BODY&gt;&lt;/HTML&gt; </code></pre> <p>How about this attack that works on IE6? </p> <pre><code>&lt;TABLE BACKGROUND="javascript:alert('XSS')"&gt; </code></pre> <p>How about attacks that are not listed on this site? The problem with Jeff's approach is that it's not a whitelist, as claimed. As someone on <a href="http://refactormycode.com/codes/333-sanitize-html#refactor_13642" rel="noreferrer">that page</a> adeptly notes:</p> <blockquote> <p>The problem with it, is that the html must be clean. There are cases where you can pass in hacked html, and it won't match it, in which case it'll return the hacked html string as it won't match anything to replace. This isn't strictly whitelisting.</p> </blockquote> <p>I would suggest a purpose built tool like <a href="http://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project" rel="noreferrer">AntiSamy</a>. It works by actually parsing the HTML, and then traversing the DOM and removing anything that's not in the <em>configurable</em> whitelist. The major difference is the ability to gracefully handle malformed HTML. </p> <p>The best part is that it actually unit tests for all the XSS attacks on the above site. Besides, what could be easier than this API call:</p> <pre><code>public String toSafeHtml(String html) throws ScanException, PolicyException { Policy policy = Policy.getInstance(POLICY_FILE); AntiSamy antiSamy = new AntiSamy(); CleanResults cleanResults = antiSamy.scan(html, policy); return cleanResults.getCleanHTML().trim(); } </code></pre>
908,543
How to convert from System.Enum to base integer?
<p>I'd like to create a generic method for converting any System.Enum derived type to its corresponding integer value, without casting and preferably without parsing a string.</p> <p>Eg, what I want is something like this:</p> <pre><code>// Trivial example, not actually what I'm doing. class Converter { int ToInteger(System.Enum anEnum) { (int)anEnum; } } </code></pre> <p>But this doesn't appear to work. Resharper reports that you can not cast expression of type 'System.Enum' to type 'int'.</p> <p>Now I've come up with this solution but I'd rather have something more efficient.</p> <pre><code>class Converter { int ToInteger(System.Enum anEnum) { return int.Parse(anEnum.ToString("d")); } } </code></pre> <p>Any suggestions?</p>
908,590
9
3
null
2009-05-26 01:17:29.867 UTC
10
2021-01-08 20:27:47.773 UTC
2009-05-27 00:59:11.583 UTC
null
20,480
null
20,480
null
1
103
c#|enums|type-conversion
103,869
<p>If you don't want to cast,</p> <pre><code>Convert.ToInt32() </code></pre> <p>could do the trick. </p> <p>The direct cast (via <code>(int)enumValue</code>) is not possible. Note that this would also be "dangerous" since an enum can have different underlying types (<code>int</code>, <code>long</code>, <code>byte</code>...). </p> <p>More formally: <code>System.Enum</code> has no direct inheritance relationship with <code>Int32</code> (though both are <code>ValueType</code>s), so the explicit cast cannot be correct within the type system</p>
1,275,735
How to access a dictionary element in a Django template?
<p>I would like to print out the number of votes that each choice got. I have this code in a template: </p> <pre><code>{% for choice in choices %} {{choice.choice}} - {{votes[choice.id]}} &lt;br /&gt; {% endfor %} </code></pre> <p><code>votes</code> is just a dictionary while <code>choices</code> is a model object.</p> <p>It raises an exception with this message:</p> <pre class="lang-none prettyprint-override"><code>"Could not parse the remainder" </code></pre>
1,275,999
9
0
null
2009-08-14 02:24:58.657 UTC
50
2021-01-28 19:32:20.823 UTC
2019-04-21 18:49:27.4 UTC
user212218
5,250,453
null
58,135
null
1
216
python|django|django-templates
251,664
<p>To echo / extend upon Jeff's comment, what I think you should aim for is simply a property in your Choice class that calculates the number of votes associated with that object:</p> <pre><code>class Choice(models.Model): text = models.CharField(max_length=200) def calculateVotes(self): return Vote.objects.filter(choice=self).count() votes = property(calculateVotes) </code></pre> <p>And then in your template, you can do:</p> <pre><code>{% for choice in choices %} {{choice.choice}} - {{choice.votes}} &lt;br /&gt; {% endfor %} </code></pre> <p>The template tag, is IMHO a bit overkill for this solution, but it's not a terrible solution either. The goal of templates in Django is to insulate you from code in your templates and vice-versa.</p> <p>I'd try the above method and see what SQL the ORM generates as I'm not sure off the top of my head if it will pre-cache the properties and just create a subselect for the property or if it will iteratively / on-demand run the query to calculate vote count. But if it generates atrocious queries, you could always populate the property in your view with data you've collected yourself.</p>