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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6,259,844 | ASP.NET Validation of viewstate MAC failed | <p>I've a listView to show list of data. It was all good and suddendly we are receiving the error message below:</p>
<blockquote>
<p>Validation of viewstate MAC failed. If
this application is hosted by a Web
Farm or cluster, ensure that
configuration specifies the same
validationKey and validation
algorithm. AutoGenerate cannot be used
in a cluster.Invalid viewstate. Client
IP...User-Agent: Mozilla/4.0
(compatible; MSIE 7.0; Windows NT 5.1;
.NET CLR 1.1.4322; .NET CLR 2.0.50727;
.NET CLR 3.0.4506.2152; .NET CLR
3.5.30729; InfoPath.3) ViewState:</p>
</blockquote>
<p>Could anyone please guide me through how to fix this issue. Please note:
1. Our IIS Server is standalone not a farmed.</p>
<p>Update:
The ListView has hyperlink to records where uses can click.
Thanks heaps.</p> | 6,260,201 | 5 | 1 | null | 2011-06-07 01:42:32.8 UTC | 11 | 2020-12-10 16:23:34.823 UTC | 2011-06-07 01:48:10.833 UTC | null | 656,348 | null | 656,348 | null | 1 | 16 | asp.net | 37,876 | <p>It could be that IIS recycled your app and therefore you get new keys for the session/view state. To alleviate this, add a machine static key in the web.config.</p>
<p>Generate a key from <a href="http://www.eggheadcafe.com/articles/GenerateMachineKey/GenerateMachineKey.aspx" rel="noreferrer">http://www.eggheadcafe.com/articles/GenerateMachineKey/GenerateMachineKey.aspx</a></p>
<p>And place the keys in your web.config example as below</p>
<pre><code><machineKey
validationKey="56AB7132992003EE87F74AE4D9675D65EED8018D3528C0B8874905B51940DEAF6B85F1D922D19AB8F69781B2326A2F978A064708822FD8C54ED74CADF8592E17"
decryptionKey="A69D80B92A16DFE1698DFE86D4CED630FA56D7C1661C8D05744449889B88E8DC"
validation="SHA1" decryption="AES" />
</code></pre>
<p>The <code><machineKey></code> should be put inside <code><system.web></code> section.</p> |
6,235,794 | jQuery mobile- For every live tap event should there be an equivalent click event? | <p>I have replaced the jQuery live click events to jQuery mobile tap events to increase responsiveness.</p>
<p>I have a feeling this was a bad idea for compatibility reasons.</p>
<p>Is it necessary to have both events, and is there any way to write them both for the same function?</p>
<p>Such as ('click','tap')</p> | 6,237,462 | 5 | 0 | null | 2011-06-04 09:04:14.267 UTC | 22 | 2018-08-24 10:24:41.383 UTC | 2011-07-11 21:30:20.33 UTC | null | 63,550 | null | 720,785 | null | 1 | 26 | jquery|jquery-selectors|jquery-mobile | 38,615 | <p>Billy's answer is incredibly complete and actually worked quite well the few times I used it. Additionally however, you may want to look at the vmouse plugin in <a href="http://en.wikipedia.org/wiki/JQuery_Mobile" rel="nofollow noreferrer">JQuery Mobile</a>, it is an attempt to abstract mouse events:</p>
<pre><code> // This plugin is an experiment for abstracting away the touch and mouse
// events so that developers don't have to worry about which method of input
// the device their document is loaded on supports.
</code></pre>
<p>-- <a href="https://github.com/jquery/jquery-mobile/blob/master/js/vmouse.js" rel="nofollow noreferrer">https://github.com/jquery/jquery-mobile/blob/master/js/vmouse.js</a></p>
<p>I've been playing with it on a project I'm working on, it seems pretty responsive these days. To use, something like:</p>
<pre><code>$('selector').bind('vclick', function () { ...
</code></pre>
<p>or</p>
<pre><code>$('selector').bind('vmousedown', function () { ...
</code></pre> |
6,283,632 | How to know if the next character is EOF in C++ | <p>I'm need to know if the next char in <code>ifstream</code> is the end of file. I'm trying to do this with <code>.peek()</code>:</p>
<pre><code>if (file.peek() == -1)
</code></pre>
<p>and </p>
<pre><code>if (file.peek() == file.eof())
</code></pre>
<p>But neither works. There's a way to do this?</p>
<p><strong>Edit:</strong> What I'm trying to do is to add a letter to the end of each word in a file. In order to do so I ask if the next char is a punctuation mark, but in this way the last word is left without an extra letter. I'm working just with <code>char</code>, not <code>string</code>.</p> | 6,283,787 | 8 | 3 | null | 2011-06-08 18:43:51.097 UTC | 4 | 2020-04-12 15:05:48.113 UTC | 2011-06-08 19:10:44.08 UTC | null | 259,517 | null | 259,517 | null | 1 | 12 | c++|eof | 66,565 | <p><a href="http://www.cplusplus.com/reference/iostream/istream/peek/" rel="noreferrer"><code>istream::peek()</code></a> returns the constant <code>EOF</code> (which is <em>not</em> guaranteed to be equal to -1) when it detects end-of-file <em>or error</em>. To check robustly for end-of-file, do this:</p>
<pre><code>int c = file.peek();
if (c == EOF) {
if (file.eof())
// end of file
else
// error
} else {
// do something with 'c'
}
</code></pre>
<p>You should know that the underlying OS primitive, <a href="http://linux.die.net/man/2/read" rel="noreferrer"><code>read(2)</code></a>, only signals EOF when you try to read <em>past</em> the end of the file. Therefore, <code>file.eof()</code> will not be true when you have merely read <em>up to</em> the last character in the file. In other words, <code>file.eof()</code> being false does not mean the next read operation will succeed.</p> |
6,258,521 | Clear icon inside input text | <p>Is there a quick way to create an input text element with an icon on the right to clear the input element itself (like the google search box)?</p>
<p>I looked around but I only found how to put an icon as background of the input element. Is there a jQuery plugin or something else?</p>
<p>I want the icon inside the input text element, something like:</p>
<pre><code>--------------------------------------------------
| X|
--------------------------------------------------
</code></pre> | 6,258,628 | 18 | 6 | null | 2011-06-06 22:00:35.55 UTC | 76 | 2021-10-14 06:28:35.937 UTC | 2018-07-01 23:12:11.823 UTC | null | 1,287,812 | null | 257,092 | null | 1 | 220 | javascript|jquery|html|css | 324,875 | <p>Add a <code>type="search"</code> to your input<br />
The support is pretty decent but will <strong>not work in IE<10</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="search"></code></pre>
</div>
</div>
</p>
<hr>
<h2>Older browsers</h2>
<p>If you need <strong>IE9 support</strong> here are some workarounds</p>
<h3>Using a standard <code><input type="text"></code> and some HTML elements:</h3>
<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>/**
* Clearable text inputs
*/
$(".clearable").each(function() {
const $inp = $(this).find("input:text"),
$cle = $(this).find(".clearable__clear");
$inp.on("input", function(){
$cle.toggle(!!this.value);
});
$cle.on("touchstart click", function(e) {
e.preventDefault();
$inp.val("").trigger("input");
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Clearable text inputs */
.clearable{
position: relative;
display: inline-block;
}
.clearable input[type=text]{
padding-right: 24px;
width: 100%;
box-sizing: border-box;
}
.clearable__clear{
display: none;
position: absolute;
right:0; top:0;
padding: 0 8px;
font-style: normal;
font-size: 1.2em;
user-select: none;
cursor: pointer;
}
.clearable input::-ms-clear { /* Remove IE default X */
display: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="clearable">
<input type="text" name="" value="" placeholder="">
<i class="clearable__clear">&times;</i>
</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script></code></pre>
</div>
</div>
</p>
<h2>Using only a <code><input class="clearable" type="text"></code> (No additional elements)</h2>
<p><img src="https://i.stack.imgur.com/mwIK2.jpg" alt="Clear icon inside input element" /></p>
<p>set a <code>class="clearable"</code> and play with it's background image:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/**
* Clearable text inputs
*/
function tog(v){return v ? "addClass" : "removeClass";}
$(document).on("input", ".clearable", function(){
$(this)[tog(this.value)]("x");
}).on("mousemove", ".x", function( e ){
$(this)[tog(this.offsetWidth-18 < e.clientX-this.getBoundingClientRect().left)]("onX");
}).on("touchstart click", ".onX", function( ev ){
ev.preventDefault();
$(this).removeClass("x onX").val("").change();
});
// $('.clearable').trigger("input");
// Uncomment the line above if you pre-fill values from LS or server</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*
Clearable text inputs
*/
.clearable{
background: #fff url(http://i.stack.imgur.com/mJotv.gif) no-repeat right -10px center;
border: 1px solid #999;
padding: 3px 18px 3px 4px; /* Use the same right padding (18) in jQ! */
border-radius: 3px;
transition: background 0.4s;
}
.clearable.x { background-position: right 5px center; } /* (jQ) Show icon */
.clearable.onX{ cursor: pointer; } /* (jQ) hover cursor style */
.clearable::-ms-clear {display: none; width:0; height:0;} /* Remove IE default X */</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input class="clearable" type="text" name="" value="" placeholder="" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script></code></pre>
</div>
</div>
</p>
<p>The trick is to set some right padding (I used 18px) to the <code>input</code> and push the background-image right, out of sight (I used <code>right -10px center</code>).<br />
That 18px padding will prevent the text hide underneath the icon (while visible).<br />
jQuery will add the class <code>"x"</code> (if <code>input</code> has value) showing the clear icon.<br />
Now all we need is to target with jQ the inputs with class <code>x</code> and detect on <code>mousemove</code> if the mouse is inside that 18px "x" area; if inside, add the class <code>onX</code>.<br />
Clicking the <code>onX</code> class removes all classes, resets the input value and hides the icon.</p>
<hr>
<p>7x7px gif: <img src="https://i.stack.imgur.com/mJotv.gif" alt="Clear icon 7x7" /></p>
<p>Base64 string:</p>
<pre><code>data:image/gif;base64,R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs=
</code></pre> |
6,200,533 | How to set TextView textStyle such as bold, italic | <p>How to set <code>TextView</code> style (bold or italic) within Java and without using the XML layout?</p>
<p>In other words, I need to write <code>android:textStyle</code> with Java.</p> | 6,200,841 | 27 | 0 | null | 2011-06-01 11:41:19.843 UTC | 126 | 2020-03-12 10:54:20.77 UTC | 2019-11-12 11:50:57.893 UTC | null | 6,717,610 | null | 778,037 | null | 1 | 941 | android|textview|styles | 552,189 | <pre><code>textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setTypeface(null, Typeface.BOLD);
textView.setTypeface(null, Typeface.ITALIC);
textView.setTypeface(null, Typeface.NORMAL);
</code></pre>
<p>To keep the previous typeface</p>
<pre><code>textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC)
</code></pre> |
39,158,552 | ignore eslint error: 'import' and 'export' may only appear at the top level | <p>Is it possible to deactivate this error in eslint?</p>
<pre><code>Parsing error: 'import' and 'export' may only appear at the top level
</code></pre> | 39,173,590 | 4 | 2 | null | 2016-08-26 04:59:17.917 UTC | 8 | 2022-02-26 11:43:20.317 UTC | 2016-08-26 05:12:53.24 UTC | null | 103,081 | null | 3,142,695 | null | 1 | 50 | lint|eslint | 69,056 | <p>ESLint natively doesnt support this because this is against the spec. But if you use <code>babel-eslint</code> parser then inside your eslint config file you can do this:</p>
<pre><code>{
"parser": "babel-eslint",
"parserOptions": {
"sourceType": "module",
"allowImportExportEverywhere": true
}
}
</code></pre>
<p>Doc ref: <a href="https://github.com/babel/babel-eslint#configuration" rel="noreferrer">https://github.com/babel/babel-eslint#configuration</a></p> |
19,531,262 | Can't phpize or configure an extension in OS X 10.9 Mavericks | <p>I am trying to build the memcached extension on OS X 10.9 Mavericks for use with the built in PHP 5.4, initially I tried <code>pecl install memcached</code> but that threw the following.</p>
<pre><code>checking for zlib location... configure: error: memcached support requires ZLIB. Use --with-zlib-dir=<DIR> to specify the prefix where ZLIB headers and library are located
ERROR: `/private/tmp/pear/install/memcached/configure' failed
</code></pre>
<p>So I created a tmp directory and executed <code>pecl download memcached</code>, unzipped the code and cd'd to the appropriate directory. </p>
<p>Trying to phpize it returned the following:</p>
<pre><code>grep: /usr/include/php/main/php.h: No such file or directory
grep: /usr/include/php/Zend/zend_modules.h: No such file or directory
grep: /usr/include/php/Zend/zend_extensions.h: No such file or directory
Configuring for:
PHP Api Version:
Zend Module Api No:
Zend Extension Api No:
</code></pre>
<p>I had brew installed zlib a while ago and pointed ./configure at my installation.
<code>./configure --with-zlib-dir=/usr/local/Cellar/zlib/1.2.8</code> I was greeted with the following error message:</p>
<pre><code>checking for session includes... configure: error: Cannot find php_session.h
</code></pre>
<p>So now I'm wondering the best course of action here... <code>/usr/include/</code> doesn't exist at all... is this a Mavericks thing? I don't remember having this problem in 10.8 at all.</p>
<p>I could try brew installing <code>php-devel</code> but I presume that isn't going to be the right version of what I need? Any help would be greatly appreciated here</p>
<h3>Update</h3>
<p><code>locate php_session.h</code> reveals</p>
<p><code>/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/usr/include/php/ext/session/php_session.h</code></p>
<p>should I just <code>ln -s</code> this to the expected location or is there some way to do this via XCode? I have the command line tools installed...</p> | 19,531,985 | 4 | 0 | null | 2013-10-23 01:34:51.477 UTC | 15 | 2014-11-18 02:12:15.117 UTC | 2013-10-23 01:48:21.87 UTC | null | 345,350 | null | 345,350 | null | 1 | 34 | php|macos|php-extension|osx-mavericks | 48,436 | <p>run <code>xcode-select --install</code> to install the XCode5 Command Line Tools, then <code>sudo pecl install memcache</code>. You should be good to go.</p> |
19,512,088 | How to generate apk file programmatically through java code | <p>I need to generate or build an APK file through some Java program where I select the Android source project. Suppose I have a button on a web page. When clicked, it generates an <code>.apk</code> file.</p>
<p>I have seen we can build the APK file through Ant and Gradle. But this runs through the command shell. I don't want to do it in a command shell. I want to write a Java program. Or maybe I can run shell commands through a Java program.</p>
<p>Could anybody guide me on this? Thanks</p>
<p>Thanks for the answers you have provided. For those answers I need to go through Gradle or Ant. I will do that if I have to. But, I am looking for alternatives.</p> | 19,517,909 | 4 | 0 | null | 2013-10-22 07:51:53.357 UTC | 8 | 2015-12-15 21:38:47.453 UTC | 2015-12-15 20:54:10.097 UTC | null | 266,531 | null | 2,327,111 | null | 1 | 8 | android|apk | 12,639 | <p>You can use the ANT jars <code>ant.jar</code> and <code>ant-launcher.jar</code>.<br>
In this case the path for <code>build.xml</code> should be fully specified.
Call it from your Java class this way:</p>
<pre><code>public class AntTest {
public static void main(String[] args) {
String build = "D:/xampp/htdocs/aud/TempProject/build.xml";
generateApkThroughAnt(build);
}
/*
* Generate APK through ANT API Method
*/
public static void generateApkThroughAnt(String buildPath) {
File antBuildFile = new File(buildPath);
Project p = new Project();
p.setUserProperty("ant.file", antBuildFile.getAbsolutePath());
DefaultLogger consoleLogger = new DefaultLogger();
consoleLogger.setErrorPrintStream(System.err);
consoleLogger.setOutputPrintStream(System.out);
consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
p.addBuildListener(consoleLogger);
BuildException ex = null;
try {
p.fireBuildStarted();
p.init();
ProjectHelper helper = ProjectHelper.getProjectHelper();
p.addReference("ant.projectHelper", helper);
helper.parse(p, antBuildFile);
p.executeTarget("clean");
p.executeTarget("release");
} catch (BuildException e) {
ex = e;
} finally {
p.fireBuildFinished(ex);
}
}
}
</code></pre>
<p>To create a <code>build.xml</code> file go to Eclipse=>Your Project=>Right click=>Export=>General=>Ant Buildfiles.
After that then you will need to run:</p>
<pre><code>android update project --name <project_name> --target <target_ID> --path <path_to_your_project>
</code></pre> |
45,380,280 | How to reverse a Map in Kotlin? | <p>I am trying to reverse a Map in Kotlin. So far, I have come up with:</p>
<pre><code>mapOf("foo" to 42)
.toList()
.map { (k, v) -> v to k }
.toMap()
</code></pre>
<p>Is there any better way of doing this without using a middleman(middlelist)?</p> | 45,380,326 | 6 | 0 | null | 2017-07-28 18:36:51.44 UTC | 4 | 2022-06-02 22:26:00.7 UTC | null | null | null | null | 2,229,438 | null | 1 | 36 | dictionary|kotlin|bimap | 13,646 | <p>Since the <code>Map</code> consists of <code>Entry</code>s and it is not <code>Iterable</code> you can use <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/entries.html" rel="noreferrer">Map#entries</a> instead. It will be mapped to <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Map.html#entrySet--" rel="noreferrer">Map#entrySet</a> to create a backed view of <code>Set<Entry></code>, for example:</p>
<pre><code>val reversed = map.entries.associateBy({ it.value }) { it.key }
</code></pre>
<p><strong>OR</strong> use <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/associate.html" rel="noreferrer">Iterable#associate</a>, which will create additional <code>Pair</code>s.</p>
<pre><code>val reversed = map.entries.associate{(k,v)-> v to k}
</code></pre>
<p><strong>OR</strong> using <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/for-each.html#foreach" rel="noreferrer">Map#forEach</a>:</p>
<pre><code>val reversed = mutableMapOf<Int, String>().also {
// v-- use `forEach` here
map.forEach { (k, v) -> it.put(v, k) }
}.toMap()
// ^--- you can add `toMap()` to create an immutable Map.
</code></pre> |
32,799,282 | Does the Enum#values() allocate memory on each call? | <p>I need to convert an ordinal <code>int</code> value to an enum value in Java. Which is simple:</p>
<pre><code>MyEnumType value = MyEnumType.values()[ordinal];
</code></pre>
<p>The <code>values()</code> method is implicit, and I cannot locate the source code for it, hence the question.</p>
<p>Does the <code>MyEnumType.values()</code> allocate a new array or not? And if it does, should I cache the array when first called? Suppose that the conversion will be called quite often.</p> | 32,799,324 | 2 | 0 | null | 2015-09-26 16:22:50.233 UTC | 6 | 2020-05-27 17:01:21.513 UTC | 2015-09-26 21:09:28.75 UTC | null | 63,550 | null | 1,671,081 | null | 1 | 31 | java|memory-management|enums | 3,588 | <p>Yes.</p>
<p>Java doesn't have mechanism which lets us create unmodifiable array. So if <code>values()</code> would return same mutable array, we risk that someone could change its content for everyone.</p>
<p>So until unmodifiable arrays will be introduced to Java, for safety <code>values()</code> must return new/separate array holding all values.</p>
<p>We can test it with <code>==</code> operator:</p>
<pre><code>MyEnumType[] arr1 = MyEnumType.values();
MyEnumType[] arr2 = MyEnumType.values();
System.out.println(arr1 == arr2); //false
</code></pre>
<hr>
<p>If you want to avoid recreating this array you can simply store it and reuse result of <code>values()</code> later. There are few ways to do it, like. </p>
<ul>
<li><p>you can create private array and allow access to its content only via getter method like </p>
<pre><code>private static final MyEnumType[] VALUES = values();// to avoid recreating array
MyEnumType getByOrdinal(int){
return VALUES[int];
}
</code></pre></li>
<li><p>you can store result of <code>values()</code> in unmodifiable collection like <code>List</code> to ensure that its content will not be changed (now such list can be public).</p>
<pre><code>public static final List<MyEnumType> VALUES = Collections.unmodifiableList(Arrays.asList(values()));
</code></pre></li>
</ul> |
33,021,802 | Why is a generic typed property nullable? | <p>I am trying to create a parameterized class with a <code>lateinit</code> non-nullable property of the generic type:</p>
<pre><code>class Test<T> {
private lateinit var t : T
private lateinit var s : String
}
</code></pre>
<p>The latter is allowed, but the former is not. The compiler returns the following error:</p>
<blockquote>
<p>Error:(7, 11) ''lateinit'' modifier is not allowed on nullable properties</p>
</blockquote>
<p>Since I didn't declare <code>T?</code>, I am confused as to why this is the case.</p> | 33,022,160 | 4 | 0 | null | 2015-10-08 16:58:11.98 UTC | 12 | 2020-12-21 22:12:04.19 UTC | 2020-09-05 21:48:02.42 UTC | null | 1,788,806 | null | 675,383 | null | 1 | 80 | kotlin | 15,189 | <blockquote>
<p>The default upper bound (if none specified) is <code>Any?</code> (<a href="http://kotlinlang.org/docs/reference/generics.html#generic-constraints" rel="noreferrer">Source</a>)</p>
</blockquote>
<p>In other words, when you use <code>T</code>, Kotlin assumes that this might be <em>any</em> type, be it primitive, object or a nullable reference.</p>
<p>To fix this add an upper type:</p>
<pre><code>class Test<T: Any> { ... }
</code></pre> |
42,362,027 | Model help using Scikit-learn when using GridSearch | <p>As part of the Enron project, built the attached model, Below is the summary of the steps,</p>
<h3>Below model gives highly perfect scores</h3>
<pre><code>cv = StratifiedShuffleSplit(n_splits = 100, test_size = 0.2, random_state = 42)
gcv = GridSearchCV(pipe, clf_params,cv=cv)
gcv.fit(features,labels) ---> with the full dataset
for train_ind, test_ind in cv.split(features,labels):
x_train, x_test = features[train_ind], features[test_ind]
y_train, y_test = labels[train_ind],labels[test_ind]
gcv.best_estimator_.predict(x_test)
</code></pre>
<h3>Below model gives more reasonable but low scores</h3>
<pre><code>cv = StratifiedShuffleSplit(n_splits = 100, test_size = 0.2, random_state = 42)
gcv = GridSearchCV(pipe, clf_params,cv=cv)
gcv.fit(features,labels) ---> with the full dataset
for train_ind, test_ind in cv.split(features,labels):
x_train, x_test = features[train_ind], features[test_ind]
y_train, y_test = labels[train_ind],labels[test_ind]
gcv.best_estimator_.fit(x_train,y_train)
gcv.best_estimator_.predict(x_test)
</code></pre>
<ol>
<li><p>Used Kbest to find out the scores and sorted the features and trying a combination of higher and lower scores.</p></li>
<li><p>Used SVM with a GridSearch using a StratifiedShuffle </p></li>
<li><p>Used the best_estimator_ to predict and calculate the precision and recall. </p></li>
</ol>
<p>The problem is estimator is spitting out perfect scores, in some case 1 </p>
<p>But when I refit the best classifier on training data then run the test it gives reasonable scores. </p>
<p>My doubt/question was what exactly GridSearch does with the test data after the split using the Shuffle split object we send in to it. I assumed it would not fit anything on Test data, if that was true then when I predict using the same test data, it should not give this high scores right.? since i used random_state value, the shufflesplit should have created the same copy for the Grid fit and also for the predict. </p>
<p>So, is using the same Shufflesplit for two wrong? </p> | 42,362,895 | 2 | 0 | null | 2017-02-21 08:20:50.29 UTC | 11 | 2018-08-24 16:28:39.467 UTC | 2018-08-24 16:28:39.467 UTC | null | 3,374,996 | null | 5,574,692 | null | 1 | 5 | python|machine-learning|scikit-learn|cross-validation|grid-search | 5,894 | <p>Basically the grid search will:</p>
<ul>
<li>Try every combination of your parameter grid</li>
<li>For each of them it will do a K-fold cross validation</li>
<li>Select the best available.</li>
</ul>
<p>So your second case is the good one. Otherwise you are actually predicting data that you trained with (which is not the case in the second option, there you only keep the best parameters from your gridsearch)</p> |
33,125,669 | Uncaught ReferenceError: ReactDOM is not defined | <p>So i have Rails applications, i installed react-rails gem, set it up and try to run test application.</p>
<p>Freshly installed, when i tryed to run hello world program, this error hapened: </p>
<blockquote>
<p>Uncaught ReferenceError: ReactDOM is not defined</p>
</blockquote>
<p>This is my react: </p>
<pre><code>var HelloWorld = React.createClass({
render: function() {
return (
<p>
Hello, <input type="text" placeholder="Your name here" />!
It is {this.props.date.toTimeString()}
</p>
);
}
});
setInterval(function() {
ReactDOM.render(
<HelloWorld date={new Date()} />,
document.getElementById('example')
);
}, 500);
</code></pre>
<p>Its saved inside /app/assets/javascripts/components/test.js.jsx file.</p>
<p>Rails 4.2.4 With Ruby 2.2.3</p> | 33,125,828 | 6 | 0 | null | 2015-10-14 12:44:08.09 UTC | 10 | 2022-01-18 16:20:35.25 UTC | 2016-11-27 01:14:46.967 UTC | null | 1,368,342 | null | 2,831,700 | null | 1 | 50 | javascript|ruby-on-rails|ruby|ruby-on-rails-4|reactjs | 87,040 | <p><code>ReactDOM</code> available since version <strong>0.14.0</strong>, so you need to use <code>React.render</code> (because you have a React version <strong>0.13.3</strong>) instead, </p>
<pre><code>setInterval(function() {
React.render(
<HelloWorld date={new Date()} />,
document.getElementById('example')
);
}, 500);
</code></pre>
<p>or upgrade your <code>React</code> version and include <code>ReactDOM</code></p>
<blockquote>
<p><a href="https://facebook.github.io/react/blog/2015/10/07/react-v0.14.html" rel="nofollow noreferrer">Changes in React 0.14</a></p>
</blockquote> |
21,608,025 | How to set up theano config | <p>I'm new to Theano.
Trying to set up a config file.</p>
<p>First of all, I notice that I have no .theanorc file:</p>
<ol>
<li><code>locate .theanorc</code> - returns nothing</li>
<li><code>echo $THEANORC</code> - returns nothing</li>
<li><code>theano.test()</code> - passes ok</li>
</ol>
<p>I'm guessing some default configuration was created wen i installed theano. Where is it?</p> | 21,703,319 | 5 | 0 | null | 2014-02-06 16:07:51.887 UTC | 6 | 2017-12-03 13:47:55.66 UTC | null | null | null | null | 1,724,926 | null | 1 | 38 | theano | 45,590 | <p>Theano does not create any configuration file by itself, but has default values for all its configuration flags. You only need such a file if you want to modify the default values.</p>
<p>This can be done by creating a .theanorc file in your home directory. For example, if you want floatX to be always float32, you can do this:</p>
<pre><code>echo -e "\n[global]\nfloatX=float32\n" >> ~/.theanorc
</code></pre>
<p>under Linux and Mac. Under windows, this can also be done. See this page for more details:</p>
<p><a href="http://deeplearning.net/software/theano/library/config.html" rel="noreferrer">http://deeplearning.net/software/theano/library/config.html</a></p> |
21,791,482 | Split list into different variables | <p>I have a list like this: </p>
<pre><code>[('love', 'yes', 'no'), ('valentine', 'no', 'yes'), ('day', 'yes','yes')]
</code></pre>
<p>How do I split this list into three variables with each variable holding respectively</p>
<ul>
<li><code>('love', 'yes', 'no')</code></li>
<li><code>('valentine', 'no', 'yes')</code></li>
<li><code>('day', 'yes','yes')</code></li>
</ul> | 21,791,491 | 1 | 0 | null | 2014-02-14 23:48:27.89 UTC | 2 | 2017-12-29 04:40:51.423 UTC | 2017-03-17 19:12:59.28 UTC | null | 1,897,495 | null | 2,608,194 | null | 1 | 25 | python|list | 46,931 | <p>Assign to three names:</p>
<pre><code>var1, var2, var3 = listobj
</code></pre>
<p>Demo:</p>
<pre><code>>>> listobj = [('love', 'yes', 'no'), ('valentine', 'no', 'yes'), ('day', 'yes','yes')]
>>> var1, var2, var3 = listobj
>>> var1
('love', 'yes', 'no')
>>> var2
('valentine', 'no', 'yes')
>>> var3
('day', 'yes', 'yes')
</code></pre> |
20,400,870 | chmod 775 on a folder but not all files under that folder | <p>by assigning 775 rights of user to a folder (project) does that impact the files permissions under the folder?</p>
<pre><code># chown -R root:user1 /var/www/project/
# chmod 775 -R /var/www/project/
</code></pre>
<p>Meaning, if <code>/project/config.html</code> used to have a 664 right does that mean that 664 right disappears and grants 775?
How to avoid this to happen? There are files and folders with different rights under <code>/project/</code> and I do not want these to be overridden.</p> | 20,400,916 | 2 | 0 | null | 2013-12-05 13:08:07.717 UTC | 1 | 2013-12-05 13:12:59.37 UTC | 2013-12-05 13:12:59.37 UTC | null | 1,223,693 | null | 2,976,220 | null | 1 | 12 | unix|chmod|chown | 63,495 | <p>Remove the <code>-R</code> <a href="http://ss64.com/bash/chmod.html">flag</a>. That means it changes all files and folders in the subdirectory as well.</p>
<pre><code># chown root:user1 /var/www/project/
# chmod 775 /var/www/project/
</code></pre> |
19,161,093 | Convert integer to string Jinja | <p>I have an integer</p>
<pre><code>{% set curYear = 2013 %}
</code></pre>
<p>In <code>{% if %}</code> statement I have to compare it with some string. I can't set <code>curYear</code> to string at the beginning because I have to decrement it in loop.</p>
<p>How can I convert it?</p> | 19,162,679 | 3 | 0 | null | 2013-10-03 13:53:56.193 UTC | 13 | 2022-09-23 09:57:10.863 UTC | 2016-10-26 13:59:03.44 UTC | null | 3,943,954 | null | 1,950,327 | null | 1 | 161 | python|jinja2|nunjucks | 170,087 | <p>I found the answer. </p>
<p>Cast integer to string:</p>
<pre><code>myOldIntValue|string
</code></pre>
<p>Cast string to integer:</p>
<pre><code>myOldStrValue|int
</code></pre> |
42,880,987 | Serverless Framework with AWS Lambda error "Cannot find module" | <p>I'm trying to use the Serverless Framework to create a Lambda function that uses open weather NPM module. However, I'm getting the following exception, but my node_modules contain the specific library.</p>
<p>I have managed to run the sample, (<a href="https://github.com/serverless/examples/tree/master/aws-node-rest-api-with-dynamodb" rel="noreferrer">https://github.com/serverless/examples/tree/master/aws-node-rest-api-with-dynamodb</a>) successfully, now hacking to add node module to integrate open weather API. </p>
<pre><code>Endpoint response body before transformations: {"errorMessage":"Cannot find module 'Openweather-Node'","errorType":"Error","stackTrace":["Module.require (module.js:353:17)","require (internal/module.js:12:17)","Object.<anonymous> (/var/task/todos/weather.js:4:17)","Module._compile (module.js:409:26)","Object.Module._extensions..js
</code></pre>
<p>My code </p>
<pre><code>'use strict';
const AWS = require('aws-sdk'); // eslint-disable-line import/no-extraneous-dependencies
var weather = require('Openweather-Node');
const dynamoDb = new AWS.DynamoDB.DocumentClient();
module.exports.weather = (event, context, callback) => {
const params = {
TableName: process.env.DYNAMODB_TABLE,
Key: {
id: event.pathParameters.id,
},
};
weather.setAPPID("mykey");
//set the culture
weather.setCulture("fr");
//set the forecast type
weather.setForecastType("daily");
const response = {
statusCode: 200,
body: "{test response}",
};
callback(null, response);
};
</code></pre> | 42,881,471 | 12 | 0 | null | 2017-03-18 23:11:57.17 UTC | 1 | 2022-08-03 00:58:50.273 UTC | 2017-03-21 11:16:46.73 UTC | null | 2,593,745 | null | 718,149 | null | 1 | 35 | node.js|amazon-web-services|aws-lambda|aws-sdk|serverless-framework | 66,454 | <p>Did you <code>npm install</code> in your working directory before doing your <code>serverless deploy</code>? The <code>aws-sdk</code> node module is available to all lambda functions, but for all other node dependencies you must install them so they will be packaged with your lambda when you deploy.</p>
<p>You may find this issue on the serverless repository helpful (<a href="https://github.com/serverless/serverless/issues/948" rel="noreferrer">https://github.com/serverless/serverless/issues/948</a>).</p> |
33,322,832 | ~/Library/Developer/Xcode/iOS DeviceSupport/<iOS Version>/Symbols/System/Library consuming 14+GB of my Mac disk space | <p>I have entries in here ranging back to a large number of iOS versions (many GB are for old iOS 8 versions and there are many iOS 6 and 7 versions as well). </p>
<p>I don't expect to care about building apps in Xcode to support these iOS versions any more (maybe I will care about iOS 8.4 for a few more months), I might build an app for some of the older iOS versions on a whim, but certainly am happy to give up the ability to do so if I can reclaim 10 or so GB of my disk.</p>
<p>Does anyone know how safe it is to remove these directories? What of value can possibly be contained within them?</p> | 33,323,148 | 2 | 1 | null | 2015-10-24 20:13:41.803 UTC | 27 | 2015-10-25 05:30:57.697 UTC | null | null | null | null | 340,947 | null | 1 | 50 | ios|xcode|macos | 18,417 | <p>It's the symbols of the operating system, one for each version for each architecture. It's used for debugging. If you don't need to support those devices any more, you can delete the directory without ill effect. </p> |
9,382,099 | What is the proper way to dismiss a modal when using storyboards? | <p>Using storyboards, what is the proper way to dismiss a modal?</p>
<ul>
<li>using IBAction and writing code to dismiss after a button click?</li>
<li>using segue and notify the parent view controller after a button click?</li>
</ul> | 9,382,189 | 6 | 0 | null | 2012-02-21 17:22:55.057 UTC | 5 | 2018-04-19 17:55:08.683 UTC | 2018-04-19 17:31:02.973 UTC | null | 600,753 | null | 242,769 | null | 1 | 44 | ios|storyboard|modal-dialog | 41,377 | <p>See Here <a href="https://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ModalViewControllers/ModalViewControllers.html" rel="noreferrer">Dismissing a Presented View Controller</a> about halfway down</p>
<blockquote>
<p>When it comes time to dismiss a presented view controller, the preferred approach is to let the presenting view controller dismiss it.</p>
</blockquote>
<p>So you should use an IBAction and writing code to dismiss after a button click</p> |
52,320,831 | cURL send JSON as x-www-form-urlencoded | <p>I want to post the following JSON:</p>
<pre><code>{
"cities": {
"chicago": 123,
"boston": 245
}
}
</code></pre>
<p>Using <code>curl</code> as <code>x-www-form-urlencoded</code> without using a .json file. I cannot figure out how to build the <code>curl -F ...</code> </p> | 52,320,948 | 2 | 2 | null | 2018-09-13 19:49:27.257 UTC | 3 | 2018-09-14 03:07:43.95 UTC | 2018-09-14 03:07:43.95 UTC | null | 1,255,289 | null | 834,045 | null | 1 | 30 | bash|curl | 62,427 | <p>For <code>application/x-www-form-urlencoded</code> you could try:</p>
<pre><code>curl -d "param1=value1&param2=value2" -X POST http://localhost:3000/blahblah
</code></pre>
<p>Where <code>param1=value...</code> have to be your JSON data as <code>chicago=123&boston=245</code></p>
<p>Or explicit form:</p>
<pre><code>curl -d "param1=value1&param2=value2" -H "Content-Type: application/x-www-form-urlencoded" -X POST http://localhost:3000/blahblah
</code></pre>
<p>Instead of <code>http://localhost:3000/blahblah</code> you should provide real URL of your service.</p> |
10,781,880 | dynamically created iframe triggers onload event twice | <p>I created an iframe dynamically and found that this iframe trigger onload event twice.</p>
<pre><code>var i=0;
frameOnload=function(){
console.log(i++);
};
var ifr=document.createElement("iframe");
ifr.src="javascript:(function(){document.open();document.write('test');document.close();})();";
ifr.onload=frameOnload;
document.body.appendChild(ifr);
</code></pre>
<p>Why i finally is 1?<br>
How to prevent iframe's onload twice instead of pointing onload function to null inside itself?</p> | 15,880,489 | 8 | 1 | null | 2012-05-28 08:55:24.883 UTC | 11 | 2021-03-18 06:36:32.99 UTC | 2017-12-10 12:17:24.377 UTC | null | 1,033,581 | null | 612,428 | null | 1 | 43 | javascript|iframe | 33,275 | <p>I've also encountered the same problem, but get no answer anywhere, so I tested by myself.</p>
<p>The iframe onload event will be triggered twice in webkit browsers ( safari/chrome ), if you attach the onload event BEFORE the iframe is appended to the body.</p>
<p>So you can prevent iframe onload twice by change your codes in the following way.</p>
<pre><code>document.body.appendChild(ifr);
ifr.onload=frameOnload; // attach onload event after the iframe is added to the body
</code></pre>
<p>Then, you will only get one onload event, which is the event the document really loaded.</p> |
57,744,392 | How to make hyperlinks in SwiftUI | <p>In Swift, as shown <a href="https://stackoverflow.com/questions/39238366/uitextview-with-hyperlink-text">here</a>, you can use <code>NSMutableAttributedString</code> to embed links in text.</p>
<p>How can I achieve this with <code>SwiftUI</code>?</p>
<p>I implemented it as the following, but it does not look how I want it to. <img src="https://i.stack.imgur.com/2ALYN.png" alt="this" />.</p>
<pre><code>import SwiftUI
struct ContentView: View {
var body: some View {
HStack {
Text("By tapping Done, you agree to the ")
Button(action: {}) {
Text("privacy policy")
}
Text(" and ")
Button(action: {}) {
Text("terms of service")
}
Text(" .")
}
}
}
</code></pre> | 57,760,247 | 10 | 1 | null | 2019-09-01 08:28:07.537 UTC | 5 | 2022-08-03 07:07:28.373 UTC | 2022-06-11 10:34:46.083 UTC | null | 8,292,178 | null | 12,003,672 | null | 1 | 32 | swiftui | 21,584 | <p><a href="https://stackoverflow.com/users/5623035/mojtaba-hosseini">Motjaba Hosseni</a> is right so far there is nothing that resembles NSAttributedString in SwiftUI.
This should solve your problem for the time being:</p>
<pre><code>import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Text("By tapping Done, you agree to the ")
HStack(spacing: 0) {
Button("privacy policy") {}
Text(" and ")
Button("terms of service") {}
Text(".")
}
}
}
}
</code></pre> |
7,496,913 | How to load XML from URL on XmlDocument() | <p>I have this code :</p>
<pre><code>string m_strFilePath = "http://www.google.com/ig/api?weather=12414&hl=it";
XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.LoadXml(m_strFilePath);
foreach (XmlNode RootNode in myXmlDocument.ChildNodes)
{
}
</code></pre>
<p>but when I try to execute it, I get this error :</p>
<p><strong>Exception Details: System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1.</strong></p>
<p>Why? Where am I wrong? And how can I fix this problem on C#? </p>
<p>Also tried with :</p>
<pre><code>myXmlDocument.Load(m_strFilePath);
</code></pre>
<p>but I get :</p>
<p><strong>Exception Details: System.Xml.XmlException: Invalid character in the given encoding. Line 1, position 503.</strong></p> | 7,496,968 | 2 | 0 | null | 2011-09-21 08:40:44.79 UTC | 4 | 2020-10-06 17:04:50.55 UTC | 2011-09-21 08:46:45.07 UTC | null | 365,251 | null | 365,251 | null | 1 | 20 | c#|xml | 67,580 | <blockquote>
<p><strong>NOTE</strong>: You're really better off using <a href="https://docs.microsoft.com/en-us/dotnet/standard/linq/xdocument-class-overview" rel="nofollow noreferrer"><code>XDocument</code></a> for most XML parsing needs nowadays.</p>
</blockquote>
<p>It's telling you that the value of <code>m_strFilePath</code> is not valid XML. Try:</p>
<pre><code>string m_strFilePath = "http://www.google.com/ig/api?weather=12414&hl=it";
XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.Load(m_strFilePath); //Load NOT LoadXml
</code></pre>
<p>However, this is failing (for unknown reason... seems to be choking on the <code>à</code> of <code>Umidità</code>). The following works (still trying to figure out what the difference is though):</p>
<pre><code>var m_strFilePath = "http://www.google.com/ig/api?weather=12414&hl=it";
string xmlStr;
using(var wc = new WebClient())
{
xmlStr = wc.DownloadString(m_strFilePath);
}
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlStr);
</code></pre> |
7,522,034 | Node.js/Express form post req.body not working | <p>I'm using express and having trouble getting form data from the bodyParser. No matter what I do it always comes up as an empty object. Here is my express generated app.js code (the only thing I added was the app.post route at the bottom):</p>
<pre><code>var express = require('express');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
// Routes
app.get('/', function(req, res){
res.sendfile('./public/index.html');
});
app.post('/', function(req, res){
console.log(req.body);
res.sendfile('./public/index.html');
});
app.listen(3010);
</code></pre>
<p>Here is my HTML form:</p>
<pre><code><!doctype html>
<html>
<body>
<form id="myform" action="/" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" id="mytext" />
<input type="submit" id="mysubmit" />
</form>
</body>
</html>
</code></pre>
<p>When I submit the form, req.body is an empty object {}</p>
<p>Its worth noting that this happens even if I remove the enctype attribute from the form tag</p>
<p>...Is there something I am missing/doing wrong?</p>
<p>I am using node v0.4.11 and express v2.4.6</p> | 7,522,084 | 2 | 0 | null | 2011-09-22 22:05:02.603 UTC | 7 | 2013-07-21 10:27:47.333 UTC | null | null | null | null | 350,664 | null | 1 | 29 | post|node.js|express | 41,473 | <pre><code><form id="myform" action="/" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="I_appear_in_req_body" id="mytext" />
<input type="submit" id="mysubmit" />
</form>
</code></pre>
<p>The body of a HTTP post is a key/value hash of all the form controls with a <code>name</code> attribute, and the value is the value of the control.</p>
<p>You need to give names to all your inputs.</p> |
23,011,547 | WebService Client Generation Error with JDK8 | <p>I need to consume a web service in my project. I use NetBeans so I right-clicked on my project and tried to add a new "Web Service Client". Last time I checked, this was the way to create a web service client. But it resulted in an AssertionError, saying:</p>
<blockquote>
<p>java.lang.AssertionError: org.xml.sax.SAXParseException; systemId: jar:file:/path/to/glassfish/modules/jaxb-osgi.jar!/com/sun/tools/xjc/reader/xmlschema/bindinfo/binding.xsd; lineNumber: 52; columnNumber: 88; schema_reference: Failed to read schema document '<strong>xjc.xsd</strong>', because 'file' access is not allowed due to restriction set by the <strong>accessExternalSchema</strong> property.</p>
</blockquote>
<p>The default Java platform for NetBeans was JDK8 (Oracle's official version), so when I changed my netbeans.conf file and made JDK7 (from Oracle, as well) as my default, everything worked fine. So I think the problem is with JDK8. Here is my <code>java -version</code> output:</p>
<blockquote>
<p>java version "1.8.0"<br>
Java(TM) SE Runtime Environment (build 1.8.0-b132)<br>
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b70, mixed mode)</p>
</blockquote>
<p>For now, I'm keeping JDK7 as my default Java platform. If there is a way to make JDK8 work please share.</p> | 23,012,746 | 24 | 1 | null | 2014-04-11 11:39:05.63 UTC | 79 | 2022-08-23 08:01:20.28 UTC | 2017-12-25 16:07:18.047 UTC | null | 918,959 | null | 300,858 | null | 1 | 242 | webservice-client|java-8|netbeans-8 | 188,018 | <p>Well, I found the solution. (based on <a href="http://docs.oracle.com/javase/7/docs/api/javax/xml/XMLConstants.html#ACCESS_EXTERNAL_SCHEMA" rel="noreferrer">http://docs.oracle.com/javase/7/docs/api/javax/xml/XMLConstants.html#ACCESS_EXTERNAL_SCHEMA</a>)</p>
<p>Create a file named <code>jaxp.properties</code> (if it doesn't exist) under <code>/path/to/jdk1.8.0/jre/lib</code> and then write this line in it:</p>
<pre><code>javax.xml.accessExternalSchema = all
</code></pre>
<p>That's all. Enjoy JDK 8.</p> |
37,919,328 | SearchView hint not showing | <p>I'm trying to display hint text in a search view in my Main Activity. The onqueryTextSubmit launches another activity called SearchResultsActivity which will display the results of the query. My problem is that I cannot display the hint text. My searchable.xml code</p>
<pre><code><searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="@string/search_hint"
android:label="@string/app_name"
/>
</code></pre>
<p>and the manifest code
</p>
<pre><code><application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<meta-data
android:name="android.app.default_searchable1"
android:value=".SearchResultsActivity"
android:resource="@xml/searchable"/>
</activity>
<activity android:name=".SearchResultsActivity">
<meta-data android:name="android.app.searchable"
android:resource="@xml/searchable">
</meta-data>
</activity>
</application>
</manifest>
</code></pre>
<p>and finaly my onQueryTextSubmit code</p>
<pre><code>@Override
public boolean onQueryTextSubmit(String query)
{
Anniversaries tempResults;
tempResults = mainAnniversariesManager.searchManager.searchAnniversaries(query);
if (tempResults.entries.size() == 0)
{
snackbar = Snackbar.make(findViewById(R.id.coordinator), getString(R.string.no_results_found) + query, Snackbar.LENGTH_INDEFINITE);
snackbar.show();
return true;
} else
{
snackbar = null;
if (!searchView.isIconified())
{
searchView.setIconified(true);
}
menuItem.collapseActionView();
Intent intent=new Intent(getApplicationContext(),SearchResultsActivity.class);
Bundle args=new Bundle();
args.putSerializable("serialized_Anniversaries",tempResults);
intent.putExtra("args",args);
startActivity(intent);
return false;
}
}
</code></pre>
<p>Thanks in advance</p> | 37,919,598 | 6 | 2 | null | 2016-06-20 09:48:01.507 UTC | 1 | 2022-08-21 07:02:59.803 UTC | null | null | null | null | 6,372,784 | null | 1 | 38 | android|android-manifest|searchview | 38,736 | <p>To add SearchView hint text use the following code :</p>
<pre><code>search.setQueryHint("Custom Search Hint");
</code></pre> |
18,032,879 | MongoDB difference between error code 11000 and 11001 | <p>According to this <em>HIGHLY incomplete</em> list <a href="http://www.mongodb.org/about/contributors/error-codes/">http://www.mongodb.org/about/contributors/error-codes/</a> they're both related to duplicate keys. But I was not able to get a 11001 error. All of the following threw a 11000 error:</p>
<ul>
<li>inserting a document with an <code>_id</code> that already existed</li>
<li>inserting a document with duplicate fields where the fields had a compound unique index</li>
<li>updating a document with said compound unique index</li>
</ul>
<p>So this goes completely against the linked page, which says 11000 is for <code>_id</code> and 11001 would occur on updates (not inserts).</p>
<p>So my question is: When does 11001 occur?</p> | 18,061,379 | 2 | 1 | null | 2013-08-03 12:29:42.233 UTC | 3 | 2020-05-12 07:41:54.193 UTC | null | null | null | null | 1,422,124 | null | 1 | 30 | mongodb | 36,173 | <p>The code <code>11001</code> does not exist in the 2.5/2.6 branch on GitHub, so if you're trying a 2.5 version than you can't create it. I did have a look at the code, but I can't find any path that shows the <code>11001</code> code either directly.</p>
<p>The following few lines will show code <code>11001</code>:</p>
<pre><code>db.so.drop();
db.so.insert( { foo: 5 } );
db.so.ensureIndex( { foo: 1 }, { unique: true } );
db.so.insert( { foo: 6 } );
</code></pre>
<p>The expected <code>11000</code>:</p>
<pre><code>db.so.insert( { foo: 5 } );
E11000 duplicate key error index: test.so.$foo_1 dup key: { : 5.0 }
</code></pre>
<p>And now to reach the <code>11001</code>:</p>
<pre><code>db.so.insert( { foo: 6 } );
db.so.update( { foo: 6 }, { $set: { foo: 5 } } );
E11000 duplicate key error index: test.so.$foo_1 dup key: { : 5.0 }
</code></pre>
<p>Still the original <code>11000</code>, but:</p>
<pre><code>db.getPrevError();
{
"err" : "E11000 duplicate key error index: test.so.$foo_1 dup key: { : 5.0 }",
"code" : 11001,
"n" : 0,
"nPrev" : 1,
"ok" : 1
}
</code></pre>
<p>That the original textual error message shows <code>E11000</code> is a bug: <a href="https://jira.mongodb.org/browse/SERVER-5978" rel="noreferrer">https://jira.mongodb.org/browse/SERVER-5978</a></p> |
17,853,105 | difference between async.series and async.parallel | <p>What is the difference between async.series and async.parallel. Consider the following exmaple, and i've got the same result.</p>
<pre><code>async.parallel([
function(callback){
setTimeout(function(){
callback(null, 'one');
}, 200);
},
function(callback){
setTimeout(function(){
callback(null, 'two');
}, 100);
},
function(callback){
setTimeout(function(){
var err = new Error('I am the error');
callback(err);
}, 400);
},
function(callback){
setTimeout(function(){
callback(null, 'three');
}, 600);
},
],
// optional callback
function(err, results){
if(err){
console.log('Error');
} else {
}
console.log(results);
//results is now equal to [ 'one', 'two', undefined ]
// the second function had a shorter timeout.
});
</code></pre>
<p>and </p>
<pre><code>async.series([
function(callback){
setTimeout(function(){
callback(null, 'one');
}, 200);
},
function(callback){
setTimeout(function(){
callback(null, 'two');
}, 100);
},
function(callback){
setTimeout(function(){
var err = new Error('I am the error');
callback(err);
}, 400);
},
function(callback){
setTimeout(function(){
callback(null, 'three');
}, 600);
}
],
// optional callback
function(err, results){
//results is now equal to [ 'one', 'two', undefined ]
if(err){
console.log('Error');
} else {
}
console.log(results);
});
</code></pre>
<p>i don't see the difference. Maybe is my sample bad? I read the documentation about these two function on github async repository, you can find for async.parallel function:</p>
<blockquote>
<p>If any of the functions pass an error to its callback, the main
callback is immediately called with the value of the error</p>
</blockquote>
<p>what is the main callback in async.parallel?</p> | 17,853,217 | 2 | 0 | null | 2013-07-25 08:42:43.973 UTC | 8 | 2017-12-26 07:43:49.19 UTC | null | null | null | null | 1,743,843 | null | 1 | 23 | node.js | 13,719 | <p><code>async.series</code> invokes your functions serially (waiting for each preceding one to finish before starting next). <code>async.parallel</code> will launch them all simultaneously (or whatever passes for simultaneous in one-thread land, anyway).</p>
<p>The main callback is the one optionally supplied in the call to <code>async.parallel</code> or <code>async.series</code> (The signature is <code>async.parallel(tasks, [callback])</code>)</p>
<p>So what actually happens is this:</p>
<h2>parallel:</h2>
<ul>
<li><code>parallel</code> launches all the tasks, then waits</li>
<li>all four tasks schedule their timeouts</li>
<li>timeout 100 fires, adds its result (result is now <code>[ , "Two"]</code>)</li>
<li>timeout 200 fires, adds its result (result is now <code>["One", "Two"]</code>)</li>
<li>timeout 400 fires, returns error and <code>undefined</code> as result (result is now <code>["One", "Two", undefined]</code>)</li>
<li><code>parallel</code> notices an error, immediately returns the result it received so far</li>
<li>timeout 600 fires, but no-one cares about the return result</li>
</ul>
<h2>series:</h2>
<ul>
<li><code>series</code> fires the first task; it schedules its timeout.</li>
<li><code>series</code> waits till callback is called 200ms later, then adds the result. (result is now <code>["One"]</code>)</li>
<li><code>series</code> fires the second task; it schedules its timeout.</li>
<li><code>series</code> waits till callback is called 100ms later, then adds the result. (result is now <code>["One", "Two"]</code>)</li>
<li><code>series</code> fires the third task; it schedules its timeout.</li>
<li><code>series</code> waits till callback is called 400ms later, then adds the result and exits due to error. (result is now <code>["One", "Two", undefined]</code>)</li>
<li>the fourth task is never executed, and its timeout is never scheduled.</li>
</ul>
<p>The fact that you got the same result is due to the fact that you rely on <code>setTimeout</code> in your tasks.</p>
<p>As to how to use <code>parallel</code> usefully, try to download a hundred web pages with <code>parallel</code>; then do the same with <code>series</code>. See what happens.</p> |
20,991,605 | How to remove white spaces from a string in Python? | <p>I need to remove spaces from a string in python. For example.</p>
<pre><code>str1 = "TN 81 NZ 0025"
str1sp = nospace(srt1)
print(str1sp)
>>>TN81NZ0025
</code></pre> | 20,991,634 | 6 | 2 | null | 2014-01-08 09:28:52.83 UTC | 5 | 2017-09-14 19:07:02.977 UTC | 2016-09-22 21:03:02.247 UTC | null | 846,892 | null | 2,797,563 | null | 1 | 4 | python|string|python-2.7|python-3.x|whitespace | 65,942 | <p>Use <code>str.replace</code>:</p>
<pre><code>>>> s = "TN 81 NZ 0025"
>>> s.replace(" ", "")
'TN81NZ0025'
</code></pre>
<p>To remove all types of white-space characters use <code>str.translate</code>:</p>
<pre><code>>>> from string import whitespace
>>> s = "TN 81 NZ\t\t0025\nfoo"
# Python 2
>>> s.translate(None, whitespace)
'TN81NZ0025foo'
# Python 3
>>> s.translate(dict.fromkeys(map(ord, whitespace)))
'TN81NZ0025foo'
</code></pre> |
41,059,264 | Simple CSV to XML Conversion - Python | <p>I am looking for a way to automate the conversion of CSV to XML. </p>
<p>Here is an example of a CSV file, containing a list of movies:</p>
<p><a href="https://i.stack.imgur.com/Htvuy.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Htvuy.jpg" alt="Movies Csv"></a></p>
<p>Here is the file in XML format:</p>
<pre><code><collection shelf="New Arrivals">
<movietitle="Enemy Behind">
<type>War, Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>Talk about a US-Japan war</description>
</movie>
<movietitle="Transformers">
<type>Anime, Science Fiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>8</stars>
<description>A schientific fiction</description>
</movie>
<movietitle="Trigun">
<type>Anime, Action</type>
<format>DVD</format>
<episodes>4</episodes>
<rating>PG</rating>
<stars>10</stars>
<description>Vash the Stampede!</description>
</movie>
<movietitle="Ishtar">
<type>Comedy</type>
<format>VHS</format>
<rating>PG</rating>
<stars>2</stars>
<description>Viewable boredom</description>
</movie>
</collection>
</code></pre>
<p>I've tried a few examples where I am able to read the csv and XML format using Python using DOM and SAX but yet am to find a simple example of the conversion. So far I have:</p>
<pre><code>import csv
f = open('movies2.csv')
csv_f = csv.reader(f)
def convert_row(row):
return """<movietitle="%s">
<type>%s</type>
<format>%s</format>
<year>%s</year>
<rating>%s</rating>
<stars>%s</stars>
<description>%s</description>
</movie>""" % (
row.Title, row.Type, row.Format, row.Year, row.Rating, row.Stars, row.Description)
print ('\n'.join(csv_f.apply(convert_row, axis=1)))
</code></pre>
<p>But I get the error: </p>
<pre><code> File "moviesxml.py", line 16, in module
print ('\n'.join(csv_f.apply(convert_row, axis=1)))
AttributeError: '_csv.reader' object has no attribute 'apply'
</code></pre>
<p>I am pretty new to Python, so any help would be much appreciated!</p>
<p>I am using Python 3.5.2.</p>
<p>Thanks!</p>
<p>Lisa</p> | 41,059,491 | 2 | 2 | null | 2016-12-09 11:19:56.403 UTC | 12 | 2022-02-08 20:34:56.667 UTC | 2016-12-09 11:58:19.577 UTC | null | 6,788,162 | null | 6,788,162 | null | 1 | 10 | python|xml|csv|parsing | 40,464 | <p>A possible solution is to first load the csv into Pandas and then convert it row by row into XML, as so:</p>
<pre><code>import pandas as pd
df = pd.read_csv('untitled.txt', sep='|')
</code></pre>
<p>With the sample data (assuming separator and so on) loaded as:</p>
<pre><code> Title Type Format Year Rating Stars \
0 Enemy Behind War,Thriller DVD 2003 PG 10
1 Transformers Anime,Science Fiction DVD 1989 R 9
Description
0 Talk about...
1 A Schientific fiction
</code></pre>
<p>And then converting to xml with a custom function:</p>
<pre><code>def convert_row(row):
return """<movietitle="%s">
<type>%s</type>
<format>%s</format>
<year>%s</year>
<rating>%s</rating>
<stars>%s</stars>
<description>%s</description>
</movie>""" % (
row.Title, row.Type, row.Format, row.Year, row.Rating, row.Stars, row.Description)
print '\n'.join(df.apply(convert_row, axis=1))
</code></pre>
<p>This way you get a string containing the xml:</p>
<pre><code><movietitle="Enemy Behind">
<type>War,Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>Talk about...</description>
</movie>
<movietitle="Transformers">
<type>Anime,Science Fiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>9</stars>
<description>A Schientific fiction</description>
</movie>
</code></pre>
<p>that you can dump in to a file or whatever.</p>
<p>Inspired by <a href="https://stackoverflow.com/a/18576067/3402367">this great answer.</a></p>
<hr>
<p>Edit: Using the loading method you posted (or a version that actually loads the data to a variable):</p>
<pre><code>import csv
f = open('movies2.csv')
csv_f = csv.reader(f)
data = []
for row in csv_f:
data.append(row)
f.close()
print data[1:]
</code></pre>
<p>We get:</p>
<pre><code>[['Enemy Behind', 'War', 'Thriller', 'DVD', '2003', 'PG', '10', 'Talk about...'], ['Transformers', 'Anime', 'Science Fiction', 'DVD', '1989', 'R', '9', 'A Schientific fiction']]
</code></pre>
<p>And we can convert to XML with minor modifications:</p>
<pre><code>def convert_row(row):
return """<movietitle="%s">
<type>%s</type>
<format>%s</format>
<year>%s</year>
<rating>%s</rating>
<stars>%s</stars>
<description>%s</description>
</movie>""" % (row[0], row[1], row[2], row[3], row[4], row[5], row[6])
print '\n'.join([convert_row(row) for row in data[1:]])
</code></pre>
<p>Getting identical results:</p>
<pre><code><movietitle="Enemy Behind">
<type>War</type>
<format>Thriller</format>
<year>DVD</year>
<rating>2003</rating>
<stars>PG</stars>
<description>10</description>
</movie>
<movietitle="Transformers">
<type>Anime</type>
<format>Science Fiction</format>
<year>DVD</year>
<rating>1989</rating>
<stars>R</stars>
<description>9</description>
</movie>
</code></pre> |
28,212,380 | Why docker container exits immediately | <p>I run a container in the background using</p>
<pre><code> docker run -d --name hadoop h_Service
</code></pre>
<p>it exits quickly. But if I run in the foreground, it works fine. I checked logs using</p>
<pre><code>docker logs hadoop
</code></pre>
<p>there was no error. Any ideas?</p>
<p><strong>DOCKERFILE</strong></p>
<pre><code> FROM java_ubuntu_new
RUN wget http://archive.cloudera.com/cdh4/one-click-install/precise/amd64/cdh4-repository_1.0_all.deb
RUN dpkg -i cdh4-repository_1.0_all.deb
RUN curl -s http://archive.cloudera.com/cdh4/ubuntu/precise/amd64/cdh/archive.key | apt-key add -
RUN apt-get update
RUN apt-get install -y hadoop-0.20-conf-pseudo
RUN dpkg -L hadoop-0.20-conf-pseudo
USER hdfs
RUN hdfs namenode -format
USER root
RUN apt-get install -y sudo
ADD . /usr/local/
RUN chmod 777 /usr/local/start-all.sh
CMD ["/usr/local/start-all.sh"]
</code></pre>
<p>start-all.sh</p>
<pre><code> #!/usr/bin/env bash
/etc/init.d/hadoop-hdfs-namenode start
/etc/init.d/hadoop-hdfs-datanode start
/etc/init.d/hadoop-hdfs-secondarynamenode start
/etc/init.d/hadoop-0.20-mapreduce-tasktracker start
sudo -u hdfs hadoop fs -chmod 777 /
/etc/init.d/hadoop-0.20-mapreduce-jobtracker start
/bin/bash
</code></pre> | 28,214,133 | 16 | 2 | null | 2015-01-29 10:30:21.35 UTC | 99 | 2021-08-19 22:35:03.073 UTC | 2017-02-01 03:01:14.413 UTC | null | 1,718,174 | null | 2,694,184 | null | 1 | 370 | docker | 477,230 | <p>A docker container exits when its main process finishes. </p>
<p>In this case it will exit when your <code>start-all.sh</code> script ends. I don't know enough about hadoop to tell you how to do it in this case, but you need to either leave something running in the foreground or use a process manager such as runit or supervisord to run the processes.</p>
<p>I think you must be mistaken about it working if you don't specify <code>-d</code>; it should have exactly the same effect. I suspect you launched it with a slightly different command or using <code>-it</code> which will change things.</p>
<p>A simple solution may be to add something like:</p>
<p><code>while true; do sleep 1000; done
</code></p>
<p>to the end of the script. I don't like this however, as the script should really be monitoring the processes it kicked off.</p>
<p>(I should say I stole that code from <a href="https://github.com/sequenceiq/hadoop-docker/blob/master/bootstrap.sh">https://github.com/sequenceiq/hadoop-docker/blob/master/bootstrap.sh</a>)</p> |
1,751,856 | How do you select all columns, plus the result of a CASE statement in oracle 11g? | <p>I want to select *, and not have to type out all individual columns, but I also want to include a custom column with a case statement. I tried the following:</p>
<pre><code>select *, (case when PRI_VAL = 1 then 'High'
when PRI_VAL = 2 then 'Med'
when PRI_VAL = 3 then 'Low'
end) as PRIORITY
from MYTABLE;
</code></pre>
<p>But it is complaining that</p>
<pre><code>ORA-00923: FROM keyword not found where expected
</code></pre> | 1,751,878 | 3 | 0 | null | 2009-11-17 21:16:46.913 UTC | 10 | 2016-03-14 15:34:41.42 UTC | 2011-04-01 05:40:00.46 UTC | null | 135,152 | null | 19,269 | null | 1 | 31 | sql|oracle|ora-00923 | 34,541 | <p>Add an alias for mytable like this:</p>
<pre><code>select t.*, (case when PRI_VAL = 1 then 'High'
when PRI_VAL = 2 then 'Med'
when PRI_VAL = 3 then 'Low'
end) as PRIORITY
from MYTABLE t;
</code></pre>
<p>This is not dependent on any specific Oracle version, not sure about other databases.</p> |
8,651,346 | Sorted String Table (SSTable) or B+ Tree for a Database Index? | <p>Using two databases to illustrate this example: <a href="http://couchdb.apache.org/">CouchDB</a> and <a href="http://cassandra.apache.org/">Cassandra</a>.</p>
<h2><strong>CouchDB</strong></h2>
<p>CouchDB uses a B+ Tree for document indexes (using <a href="https://plus.google.com/u/0/107397941677313236670/posts/CyvwRcvh4vv">a clever modification</a> to work in their append-only environment) - more specifically as documents are modified (insert/update/delete) they are appended to the running database file as well as a full Leaf -> Node path from the B+ tree of all the nodes effected by the updated revision right after the document.</p>
<p>These piece-mealed index revisions are inlined right alongside the modifications such that the full index is a union of the most recent index modifications appended at the end of the file along with additional pieces further back in the data file that are still relevant and haven't been modified yet.</p>
<blockquote>
<p>Searching the <a href="http://en.wikipedia.org/wiki/B+_tree">B+ tree </a> is O(logn).</p>
</blockquote>
<h2><strong>Cassandra</strong></h2>
<p>Cassandra keeps record keys sorted, in-memory, in tables (let's think of them as arrays for this question) and writes them out as separate (sorted) <a href="http://wiki.apache.org/cassandra/ArchitectureSSTable">sorted-string tables</a> from time to time.</p>
<p>We can think of the collection of all of these tables as the "index" (from what I understand).</p>
<p>Cassandra is required to <a href="http://www.datastax.com/dev/blog/leveled-compaction-in-apache-cassandra">compact/combine these sorted-string tables</a> from time to time, creating a more complete file representation of the index.</p>
<blockquote>
<p>Searching <a href="http://en.wikipedia.org/wiki/Sorted_array">a sorted array</a> is O(logn).</p>
</blockquote>
<h2><strong>Question</strong></h2>
<p>Assuming a similar level of complexity between either maintaining partial B+ tree chunks in CouchDB versus partial sorted-string indices in Cassandra and given that both provide O(logn) search time which one do you think would make a better representation of a database index and why?</p>
<p>I am specifically curious if there is an implementation detail about one over the other that makes it <em>particularly</em> attractive or if they are both a wash and you just pick whichever data structure you prefer to work with/makes more sense to the developer.</p>
<p>Thank you for the thoughts.</p> | 8,654,903 | 4 | 1 | null | 2011-12-28 02:47:59.21 UTC | 33 | 2019-10-25 07:47:22.173 UTC | null | null | null | null | 553,524 | null | 1 | 45 | database|indexing|nosql|couchdb|cassandra | 21,245 | <p>When comparing a BTree index to an SSTable index, you should consider the write complexity: </p>
<ul>
<li><p>When writing randomly to a copy-on-write BTree, you will incur random reads (to do the copy of the leaf node and path). So while the writes my be sequential on disk, for datasets larger than RAM, these random reads will quickly become the bottle neck. For a SSTable-like index, no such read occurs on write - there will only be the sequential writes.</p></li>
<li><p>You should also consider that in the worse case, every update to a BTree could incur log_b N IOs - that is, you could end up writing 3 or 4 blocks for every key. If key size is much less than block size, this is extremely expensive. For an SSTable-like index, each write IO will contain as many fresh keys as it can, so the IO cost for each key is more like 1/B.</p></li>
</ul>
<p>In practice, this make SSTable-like thousands of times faster (for random writes) than BTrees.</p>
<p>When considering implementation details, we have found it a lot easier to implement SSTable-like indexes (almost) lock-free, where as locking strategies for BTrees has become quite complicated.</p>
<p>You should also re-consider your read costs. You are correct than a BTree is O(log_b N) random IOs for random point reads, but a SSTable-like index is actually O(#sstables . log_b N). Without an decent merge scheme, #sstables is proportional to N. There are various tricks to get round this (using Bloom Filters, for instance), but these don't help with small, random range queries. This is what we found with Cassandra:</p>
<p><a href="http://www.acunu.com/blogs/richard-low/cassandra-under-heavy-write-load-part-ii/" rel="noreferrer">Cassandra under heavy write load</a></p>
<p>This is why Castle, our (GPL) storage engine, does merges slightly differently, and can achieve a lot better (O(log^2 N)) range queries performance with a slight trade off in write performance (O(log^2 N / B)). In practice we find it to be quicker than Cassandra's SSTable index for writes as well.</p>
<p>If you want to know more about this, I've given a talk about how it works:</p>
<ul>
<li><a href="http://skillsmatter.com/podcast/nosql/castle-big-data" rel="noreferrer">podcast</a></li>
<li><a href="http://www.slideshare.net/acunu/in-the-brain-of-tom-wilkie" rel="noreferrer">slides</a> </li>
</ul> |
8,448,711 | See Everything In The Terminal/Command Prompt After Long Output | <p>I'm new to ubuntu using the terminal to code some ruby. </p>
<p>Everytime I run this command it outputs like 600 lines of data that I need to analyze. </p>
<p>But when I try to scroll up to see everything alot of the output is cut off.</p>
<p>Is there any way to change the settings of the terminal or another command prompt program or any other options that I can use to take a look all of the data?</p> | 8,449,567 | 10 | 1 | null | 2011-12-09 16:39:27.997 UTC | 4 | 2022-03-12 14:53:47.347 UTC | null | null | null | null | 251,234 | null | 1 | 46 | ubuntu|command-line|terminal | 69,004 | <p>Inside your Terminal Window, go to <code>Edit | Profile Preferences</code>, click on the <code>Scrolling</code> tab, and check the <code>Unlimited</code> checkbox underneath the <code>Scrollback XXX lines</code> row. Click <code>Close</code> and be happy.</p> |
19,334,374 | How to convert a string of space- and comma- separated numbers into a list of int? | <p>I have a string of numbers, something like:</p>
<pre><code>example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
</code></pre>
<p>I would like to convert this into a list:</p>
<pre><code>example_list = [0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]
</code></pre>
<p>I tried something like:</p>
<pre><code>for i in example_string:
example_list.append(int(example_string[i]))
</code></pre>
<p>But this obviously does not work, as the string contains spaces and commas. However, removing them is not an option, as numbers like '19' would be converted to 1 and 9. Could you please help me with this?</p> | 19,334,399 | 6 | 1 | null | 2013-10-12 12:50:30.52 UTC | 16 | 2021-08-27 21:32:33.947 UTC | 2021-08-27 21:32:33.947 UTC | null | 2,745,495 | null | 2,874,010 | null | 1 | 49 | python|string|list|integer | 157,298 | <p>Split on commas, then map to integers:</p>
<pre><code>map(int, example_string.split(','))
</code></pre>
<p>Or use a list comprehension:</p>
<pre><code>[int(s) for s in example_string.split(',')]
</code></pre>
<p>The latter works better if you want a list result, or you can wrap the <code>map()</code> call in <code>list()</code>.</p>
<p>This works because <code>int()</code> tolerates whitespace:</p>
<pre><code>>>> example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
>>> list(map(int, example_string.split(','))) # Python 3, in Python 2 the list() call is redundant
[0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]
>>> [int(s) for s in example_string.split(',')]
[0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11]
</code></pre>
<p>Splitting on <em>just</em> a comma also is more tolerant of variable input; it doesn't matter if 0, 1 or 10 spaces are used between values.</p> |
62,215,454 | How to get enum key by value in Typescript? | <p>I have an enum like this:</p>
<pre><code>export enum Colors {
RED = "RED COLOR",
BLUE = "BLUE COLOR",
GREEN = "GREEN COLOR"
}
</code></pre>
<p>Could you let me know how to get enum key by value please? i.e., I need to pass "BLUE COLOR" and get 'BLUE'.</p>
<p><code>Colors["BLUE COLOR"]</code> gives error <code>Element implicitly has an 'any' type because expression of type '"BLUE COLOR"' can't be used to index type 'typeof Colors'. Property 'BLUE COLOR' does not exist on type 'typeof Colors'.</code></p> | 62,215,827 | 7 | 1 | null | 2020-06-05 12:32:23.24 UTC | 9 | 2022-09-11 16:57:00.517 UTC | 2020-06-05 13:00:19.487 UTC | null | 10,959,940 | null | 9,905,102 | null | 1 | 51 | typescript|enums | 74,702 | <blockquote>
<p>If you want to get your <code>enum key</code> by <code>value</code> in that case you have to
re write your enum in following manners: But same format also might be work in older version as well.</p>
</blockquote>
<p><em><strong><code>For Vanilla Js it should be like below:</code></strong></em></p>
<pre><code> enum Colors {
RED = "RED COLOR",
BLUE = "BLUE COLOR",
GREEN = "GREEN COLOR"
}
</code></pre>
<p><em><strong><code>For .tsx it should be like below:</code></strong></em></p>
<pre><code> enum Colors {
RED = "RED COLOR" as any,
BLUE = "BLUE COLOR" as any,
GREEN = "GREEN COLOR" as any
}
</code></pre>
<p><em><strong><code>For .ts it should be like below:</code></strong></em></p>
<pre><code>enum Colors {
RED = <any>"RED COLOR",
BLUE = <any>"BLUE COLOR",
GREEN = <any>"GREEN COLOR"
}
</code></pre>
<p>Then you can get like this way:</p>
<p><em><strong><code>Retrieve enum key by value: </code></strong></em></p>
<pre><code>let enumKey = Colors["BLUE COLOR"];
console.log(enumKey);
</code></pre>
<p><em><strong><code>Output:</code></strong></em></p>
<p><a href="https://i.stack.imgur.com/M3b4n.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M3b4n.gif" alt="enter image description here" /></a></p>
<p><em><strong><code>Another way: Retrieve enum key by value:</code></strong></em></p>
<pre><code>let enumKey = Object.keys(Colors)[Object.values(Colors).indexOf("BLUE COLOR")];
console.log(enumKey);
</code></pre>
<p><em><strong><code>Output:</code></strong></em></p>
<p><a href="https://i.stack.imgur.com/PZpu2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PZpu2.png" alt="enter image description here" /></a></p>
<p><em><strong><code>Test on jsfiddle:</code></strong></em></p>
<p><a href="https://jsfiddle.net/faridkiron/bwrg15e9/8/" rel="nofollow noreferrer">Coding sample on <code>jsfiddle</code></a></p>
<p><strong>Note:</strong> There are new annoucement published on <code>25th August</code> please be aware of it. <a href="https://devblogs.microsoft.com/typescript/announcing-typescript-4-8/#unconstrained-generics-no-longer-assignable-to" rel="nofollow noreferrer"><code>Have alook here</code></a></p> |
1,242,758 | What is correct behaviour of UpdateModel in ASP.NET MVC? | <p>I am interested to know what you guys feel should be deemed "correct behaviour" in terms of the <code>UpdateModel</code> method in ASP.NET MVC.</p>
<p>The reason I ask here is perhaps if this functionality is "by design" somebody could clarify as to why it is the way it is, and perhaps a way to call it differently to achieve desired functionality, which I would imagine would be the way 90% of folk would want this to work?</p>
<p>In essence, my gripe lies with the behaviour of the binding process within <code>UpdateModel</code>.</p>
<p>Supposing you wish to update a form via a simple <code>Save</code> action method for which the data fields on the form reflects a model in your database, initially to go about saving the request, we might get the existing model from the DB, and then update relevant fields which which were changed, sent via <code>FormCollection</code> and then updated by <code>UpdateModel</code> to our existing model. This functions, however it appears any of the existing properties on this DB-populated object are being "reset"; and by that I mean, are being set to null or initialisation defaults just as if it was a brand new object, except for obviously those which match those in the <code>FormCollection</code>.</p>
<p>This is a problem because any existing properties which exist on the object, but not necessarily exist on the form, such as any child collections or objects, dates or any non-UI facing fields are empty, leaving you with a half-populated, more or less unusable object which can't be saved to the DB because of all the missing data including probably a stack of ID's now set to 0.</p>
<p>I believe this is not desirable behaviour, and <code>UpdateModel</code> should only update properties where it finds a property match in <code>FormCollection</code>. This would mean all your existing properties would be untouched, but your updates would be set. However, from what has been deduced so far, obviously this is not the case - it appears it instantiates a <em>brand new copy</em> of the object updates the properties from the form, then returns the new object.</p>
<p>Finally, to put it in perspective of how much of a burden this is, the only way really around it to save a half-complex form and keep all your existing object data is to manually marry up <strong>each</strong> property with the corresponding form property to absolutely guarantee only properties that exist in the form are being updated.</p>
<p>I guess,</p>
<ol>
<li>Those who agree this is by design, is my approach of form marrying the best way?</li>
<li>Or, how have you tackled this in this?</li>
</ol>
<p>Please feel free to offer your thoughts on this guys, Thanks.</p>
<p>Here is another instance of somebody suffering from this problem:<br>
<a href="https://stackoverflow.com/questions/1207991/calling-updatemodel-with-a-collection-of-complex-data-types-reset-all-non-bound-v">Calling UpdateModel with a collection of complex data types reset all non-bound values?</a></p> | 1,242,841 | 4 | 2 | null | 2009-08-07 03:35:22.443 UTC | 10 | 2009-08-08 07:22:12.507 UTC | 2017-05-23 11:48:36.187 UTC | null | -1 | null | 41,211 | null | 1 | 17 | asp.net-mvc|updatemodel|formcollection | 4,347 | <p>The behavior you're experiencing with UpdateModel() sounds like you're list binding, in which case UpdateModel() will blow away the contents of the list and repopulate it. See <a href="http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx" rel="noreferrer">Hanselman's blog</a> for a discussion on this. If you're updating a single object, UpdateModel() will update that individual object, leaving properties that don't have a corresponding form value as-is.</p>
<p>Many of these problems boil down to that UpdateModel() is really meant to repopulate view models - not domain models - based on form input. (I'm slightly simplifying things by saying that a view model is just a contract between a controller and the view, while your domain model might be a LINQ2SQL or EF model object.) All of the MVC tutorials and demos show UpdateModel() being used against database objects, which I feel is unfortunate since it's somewhat misleading as to the intended purpose of model binding. Robert's post is more indicative of the actual intent of UpdateModel().</p> |
796,748 | How can I add a custom url handler on Windows. Like iTunes itms:// | <p>I would like telnet://blah to open putty and not the native windows telnet client.</p>
<p>I don't even know what this 'feature' is called under windows so I'm having no luck find any information about it.</p>
<p>Thanks in advance,
Jan</p> | 796,780 | 4 | 2 | null | 2009-04-28 08:04:26.743 UTC | 15 | 2014-12-27 20:47:54.92 UTC | 2009-04-28 13:17:30.643 UTC | null | 44,330 | null | 460,845 | null | 1 | 19 | windows|url|shell|protocol-handler | 22,326 | <p>If it's simple, you can do it via the command line:</p>
<pre><code>ftype telnet # view current binding
ftype telnet=\path\to\putty.exe %1
</code></pre>
<p>Otherwise you'll need to use the registry as previously posted.</p> |
449,627 | Are line breaks in XML attribute values allowed? | <p>I realise that it's not elegant or desired, but is it allowed (in well-formed XML) for an attribute value in an XML element to span multiple lines?</p>
<p>e.g.</p>
<pre><code><some-xml-element value="this value goes over....
multiple lines!" />
</code></pre>
<p>Yeah I realise there's better ways of writing that. I would personally write it like:</p>
<pre><code><some-xml-element>
<value>this value goes over...
multiple lines!</value>
</some-xml-element>
</code></pre>
<p>or:</p>
<pre><code><some-xml-element value="this value goes over....&#13;&#10;" />
</code></pre>
<p>But we have our own XML parser and I'd like to know whether the first example is allowed in well-formed XML.</p> | 449,647 | 4 | 4 | null | 2009-01-16 05:57:13.497 UTC | 11 | 2015-09-12 04:57:23.987 UTC | 2015-09-12 04:56:05.113 UTC | null | 423,105 | Ben Daniel | 26,335 | null | 1 | 103 | xml|xml-parsing | 64,683 | <p><a href="http://www.w3.org/TR/REC-xml/#NT-AttValue" rel="noreferrer">http://www.w3.org/TR/REC-xml/#NT-AttValue</a></p>
<p>Seems to say everything except <code><</code>, <code>&</code>, and your delimiter (<code>'</code> or <code>"</code>) are OK. So newline should be, too.</p> |
23,474,666 | Create DropDownList for an ASP.NET MVC5 Relation | <p>I'm stuck creating a proper create/edit view in ASP.NET MVC5. I've got two models <code>Dog</code> and <code>Human</code>. A dog belongs to one <code>Human</code>. I'm trying to create a dropdown in the <code>create</code> and <code>edit</code> views for <code>Dog</code> that'll allow me to select a <code>Human</code> by name for that particular <code>Dog</code>. Here are my models:</p>
<p>Human:</p>
<pre><code>public class Human
{
public int ID { get; set; }
public string Name { get; set; }
}
</code></pre>
<p>Dog:</p>
<pre><code>public class Dog
{
public int ID { get; set; }
public string Name { get; set; }
public Human Human { get; set; }
}
</code></pre>
<p>My create action:</p>
<pre><code>// GET: /Dog/Create
public ActionResult Create()
{
ViewBag.HumanSelection = db.Humen.Select(h => new SelectListItem
{
Value = h.ID.ToString(),
Text = h.Name
});
return View();
}
</code></pre>
<p>And here is the relevant part of my view:</p>
<pre><code><div class="form-group">
@Html.LabelFor(model => model.Human.Name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Human, ViewBag.HumanSelection);
</div>
</div>
</code></pre>
<p>I get the following error when I run this:</p>
<pre><code>Compiler Error Message: CS1973: 'System.Web.Mvc.HtmlHelper<Test.Models.Dog>' has no applicable method named 'DropDownListFor' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
</code></pre>
<p>I'm new to C# & the Entity framework. What am I doing wrong? Is there a way of doing this without manually querying the database? Something like the collection form helpers in Rails?
I've followed a bunch of tutorials that are either old or too complicated for me to follow.</p> | 23,474,889 | 2 | 2 | null | 2014-05-05 14:12:57.433 UTC | 3 | 2015-07-22 06:17:19.257 UTC | 2014-05-05 14:28:03.23 UTC | null | 555,297 | null | 555,297 | null | 1 | 9 | c#|asp.net|asp.net-mvc | 62,215 | <p>Important to note is that if you use <code>DropDownListFor(x => x.Human)</code>, the returned value of the dropdownlist should be a <code>Human</code> object.</p>
<p>It isn't. In your own code snippet, you set the value of the <code>SelectListItem</code> to <strong>the ID of the Human</strong>. Therefore, when you submit your form, you will receive <strong>the ID that you selected</strong>.</p>
<p>Add the following to your model:</p>
<pre><code>public int HumanId { get; set; }
</code></pre>
<p>Bind your dropdownlist to that int:</p>
<pre><code>@Html.DropDownListFor(model => model.HumanId, (SelectList)ViewBag.HumanSelection);
</code></pre>
<p>Now, when you get back to the controller, use that ID to look up the actual Human you want:</p>
<pre><code>[HttpPost]
public ActionResult Create (CreateModel model)
{
if(model.HumanId > 0)
{
model.Human = GetHumanByID(model.HumanId);
//or however you want to get the Human entoty from your database
}
}
</code></pre>
<p>It's a simplified solution, but I suspect your main confusion stems from the fact that you're expecting to receive a Human from the DropDownList, while it will actually only return an int (the ID).</p>
<p><strong>Edit</strong></p>
<p>I don't have much information on your data model, but if you're using entity framework, odds are that your <code>Dog</code> class will have a foreign key property called <code>HumanId</code>. If that is the case, you don't even need to get the <code>Human</code> entity like I showed you before. If you put the selected ID in the <code>HumanId</code> property, Entity Framework should be able to use that to create the relation between Human/Dog you want.</p>
<p>If this is the case, it would seems best to elaborate on this in your question, as this would otherwise be more guesswork than actual confirmation.</p>
<p><strong>Edit 2</strong> <em>going offtopic here</em></p>
<p>Your code:</p>
<pre><code>db.Humen
</code></pre>
<p>The plural form of <code>man</code> is <code>men</code>, <code>woman</code> is <code>women</code>; but for <code>human</code>, it's <code>humans</code> :) Humen does sounds like an awesome suggestion though ;)</p> |
25,657,541 | Merge two Excel tables Based on matching data in Columns | <p>I've been working on a excel problem, that I need to find an answer for I'll explain it below.</p>
<p>I've Table01 with the Columns :</p>
<ul>
<li>Group No</li>
<li>Name</li>
<li>Price</li>
</ul>
<p>I've Table02 with the columns:</p>
<ul>
<li>Group No</li>
<li>City</li>
<li>Code</li>
</ul>
<p>I've merged two tables of Table01 & Table02 as shown in the Image03 , But without order. </p>
<p><strong>But,as you see Group No Column is similar in both tables.</strong></p>
<p>What I need is to get the matching rows of Table01 & 02 considering 'Group No' Column.</p>
<p>The Final result is to be seen as the final image.</p>
<p>Is there a way to do this with excel functions ?</p>
<p><img src="https://i.stack.imgur.com/QAhrv.jpg" alt="The Image"></p>
<p>Thank You!</p> | 25,657,614 | 2 | 1 | null | 2014-09-04 04:53:57.84 UTC | 10 | 2016-11-06 23:20:10.443 UTC | 2016-11-06 23:20:10.443 UTC | null | 4,370,109 | null | 1,664,967 | null | 1 | 21 | excel|merge | 115,267 | <p>Put the table in the second image on Sheet2, columns D to F.</p>
<p>In Sheet1, cell D2 use the formula</p>
<pre><code>=iferror(vlookup($A2,Sheet2!$D$1:$F$100,column(A1),false),"")
</code></pre>
<p>copy across and down.</p>
<p><strong>Edit</strong>: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need. </p>
<p><img src="https://i.stack.imgur.com/VIzEo.png" alt="enter image description here"></p> |
30,348,833 | Check if file exist in Gulp | <p>I need to check if a file exists in a gulp task, i know i can use some node functions from node, there are two:</p>
<p><code>fs.exists()</code> and <code>fs.existsSync()</code></p>
<p>The problem is that in the node documentation, is saying that these functions will be deprecated</p> | 30,348,965 | 5 | 1 | null | 2015-05-20 11:49:47.5 UTC | 3 | 2019-07-08 14:07:56.81 UTC | null | null | null | null | 2,953,308 | null | 1 | 32 | javascript|node.js|gulp | 22,761 | <p>You can use <a href="https://nodejs.org/api/fs.html#fs_fs_access_path_mode_callback" rel="noreferrer"><code>fs.access</code></a></p>
<pre><code>fs.access('/etc/passwd', (err) => {
if (err) {
// file/path is not visible to the calling process
console.log(err.message);
console.log(err.code);
}
});
</code></pre>
<p>List of available error codes <a href="https://nodejs.org/api/errors.html#errors_error_code" rel="noreferrer">here</a></p>
<hr>
<blockquote>
<p>Using <code>fs.access()</code> to check for the accessibility of a file before calling <code>fs.open(), fs.readFile()</code> or <code>fs.writeFile()</code> is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.</p>
</blockquote> |
39,825,034 | iOS 10 App has crashed because it attempted to access privacy-sensitive data | <p>I'm running my project which was working fine previously but after updating my xcode my app crashes and giving this error:</p>
<blockquote>
<p>This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSCameraUsageDescription key with a string value explaining to the user how the app uses this data</p>
</blockquote> | 39,825,049 | 5 | 1 | null | 2016-10-03 05:23:46.387 UTC | 6 | 2021-02-28 04:02:32.113 UTC | 2016-10-03 07:06:40.503 UTC | null | 2,227,743 | null | 3,275,134 | null | 1 | 33 | ios|cocoa-touch|ios10 | 31,846 | <p><strong>Privacy Settings in iOS 10</strong></p>
<blockquote>
<p>A significant change in iOS 10 is that you must declare ahead of time any access to private data or your App will crash.</p>
<p>Once you link with iOS 10 you must declare access to any user private data types. You do this by adding a usage key to your app’s Info.plist together with a purpose string. The list of frameworks that count as private data is a long one</p>
<p><strong>Contacts, Calendar, Reminders, Photos, Bluetooth Sharing, Microphone, Camera, Location, Health, HomeKit, Media Library, Motion, CallKit, Speech Recognition, SiriKit, TV Provider.</strong></p>
</blockquote>
<p>You need to put the <strong>NSCameraUsageDescription</strong> in your plist.</p>
<p>Like</p>
<pre><code><key> NSCameraUsageDescription </key>
<string>$(PRODUCT_NAME) uses Cameras</string>
</code></pre>
<p>for e.g</p>
<p><a href="https://i.stack.imgur.com/dAbQA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dAbQA.png" alt="enter image description here" /></a></p>
<p>Check all the usage descriptions <a href="http://useyourloaf.com/blog/privacy-settings-in-ios-10/" rel="noreferrer">here</a>.</p> |
39,511,528 | Exposing .NET events to COM? | <p>I've been trying to expose and fire an event to a VBA client. So far on the VBA client side, the event is exposed and I see the method event handling method added to my module class however the VBA event handling method does not fire. For some reason, when debugging the event is null. Modifying my code with synchronously did not help either. </p>
<p>For the record, I've checked other SO questions but they didn't help.</p>
<p>Any good answers will be appreciated.</p>
<pre><code>[ComVisible(true)]
[Guid("56C41646-10CB-4188-979D-23F70E0FFDF5")]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IWebEvents))]
[ProgId("MyAssembly.MyClass")]
public class MyClass : ServicedComponent, IMyClass
{
public string _address { get; private set; }
public string _filename { get; private set; }
[DispId(4)]
public void DownloadFileAsync(string address, string filename)
{
_address = address;
_filename = filename;
System.Net.WebClient wc = new System.Net.WebClient();
Task.Factory.StartNew(() => wc.DownloadFile(_address, _filename))
.ContinueWith((t) =>
{
if (null != this.OnDownloadCompleted)
OnDownloadCompleted();
});
}
public event OnDownloadCompletedEventHandler OnDownloadCompleted;
}
[ComVisible(false)]
public delegate void OnDownloadCompletedEventHandler();
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IWebEvents
{
[DispId(1)]
void OnDownloadCompleted();
}
</code></pre>
<p><strong>This is a good gig for you all bounty hunters, 200 rep points</strong></p> | 39,703,172 | 1 | 1 | null | 2016-09-15 12:52:17.417 UTC | 10 | 2021-10-19 07:19:36.95 UTC | 2016-09-26 08:05:53.473 UTC | null | 863,240 | null | 3,704,475 | null | 1 | 32 | c#|vba|events|com | 7,379 | <p>The key concept in .NET code is to define event(s) as method(s) on a separate interface and connect it to the class via <code>[ComSourceInterfacesAttribute]</code>. In the example this is done with this code <code>[ComSourceInterfaces(typeof(IEvents))]</code> where <code>IEvents</code> interface defines the event(s) which should be handled on COM client.</p>
<p><em>Note to event naming:<br />
Event names defined in c# class and interface method names defined on interface must be the same. In this example <code>IEvents::OnDownloadCompleted</code> corresponds with <code>DemoEvents::OnDownloadCompleted</code></em>.</p>
<p>Then a second interface is defined which represents the public API of the class itself, here it is called <code>IDemoEvents</code>. On this interface methods are defined which are called on COM client.</p>
<blockquote>
<p>C# code (builds to COMVisibleEvents.dll)</p>
</blockquote>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.EnterpriseServices;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace COMVisibleEvents
{
[ComVisible(true)]
[Guid("8403C952-E751-4DE1-BD91-F35DEE19206E")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IEvents
{
[DispId(1)]
void OnDownloadCompleted();
}
[ComVisible(true)]
[Guid("2BF7DA6B-DDB3-42A5-BD65-92EE93ABB473")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IDemoEvents
{
[DispId(1)]
Task DownloadFileAsync(string address, string filename);
}
[ComVisible(true)]
[Guid("56C41646-10CB-4188-979D-23F70E0FFDF5")]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IEvents))]
[ProgId("COMVisibleEvents.DemoEvents")]
public class DemoEvents
: ServicedComponent, IDemoEvents
{
public delegate void OnDownloadCompletedDelegate();
private event OnDownloadCompletedDelegate OnDownloadCompleted;
public string _address { get; private set; }
public string _filename { get; private set; }
private readonly string _downloadToDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
public async Task DownloadFileAsync(string address, string filename)
{
try
{
using (WebClient webClient = new WebClient())
{
webClient.Credentials = new NetworkCredential(
"user", "psw", "domain");
string file = Path.Combine(_downloadToDirectory, filename);
await webClient.DownloadFileTaskAsync(new Uri(address), file)
.ContinueWith(t =>
{
// https://stackoverflow.com/q/872323/
var ev = OnDownloadCompleted;
if (ev != null)
{
ev();
}
}, TaskScheduler.FromCurrentSynchronizationContext());
}
}
catch (Exception ex)
{
// Log exception here ...
}
}
}
}
</code></pre>
<blockquote>
<p>regasm</p>
</blockquote>
<pre class="lang-none prettyprint-override"><code>C:\Windows\Microsoft.NET\Framework\v4.0.30319>regasm C:\Temp\COMVisibleEvents\bin\Debug\COMVisibleEvents.dll /tlb: C:\Temp\COMVisibleEvents\bin\Debug\COMVisibleEvents.tlb
</code></pre>
<blockquote>
<p>VBA client reference to <code>*.tlb</code> file</p>
</blockquote>
<p>Add reference to <code>*tlb</code> which was generated by <code>regasm</code>. Here the name of this <code>tlb</code> file is <code>COMVisibleEvents</code>.</p>
<p><a href="https://i.stack.imgur.com/yIQ5k.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yIQ5k.jpg" alt="enter image description here" /></a></p>
<p>Here Excel User Form was used as VBA client. After the button was clicked, the method <code>DownloadFileAsync</code> was executed and when this method completes the event was caught in handler <code>m_eventSource_OnDownloadCompleted</code>. In this example you can download the source codes of the C# project COMVisibleEvents.dll from my dropbox.</p>
<blockquote>
<p>VBA client code (MS Excel 2007)</p>
</blockquote>
<pre class="lang-vb prettyprint-override"><code>Option Explicit
Private WithEvents m_eventSource As DemoEvents
Private Sub DownloadFileAsyncButton_Click()
m_eventSource.DownloadFileAsync "https://www.dropbox.com/s/0q3dskxopelymac/COMVisibleEvents.zip?dl=0", "COMVisibleEvents.zip"
End Sub
Private Sub m_eventSource_OnDownloadCompleted()
MsgBox "Download completed..."
End Sub
Private Sub UserForm_Initialize()
Set m_eventSource = New COMVisibleEvents.DemoEvents
End Sub
</code></pre>
<blockquote>
<p>Result</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/NUtJ0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NUtJ0.jpg" alt="enter image description here" /></a></p> |
39,336,171 | Executing SQL query on multiple databases | <p>I know my post has a very similar title to other ones in this forum, but I really couldn't find the answer I need.</p>
<p>Here is my problem, I have a SQL Server running on my Windows Server. Inside my SQL Server, I have around 30 databases. All of them have the same tables, and the same stored procedures. </p>
<p>Now, here is the problem, I have this huge script that I need to run in all of these databases. I wish I could do it just once against all my databases.</p>
<p>I tried a couple things like go to "view" >> registered servers >> local server groups >> new server registration. But this solution is for many servers, not many databases.</p>
<p>I know I could do it by typing the database name, but the query is really huge, so it would take too long to run in all databases.</p>
<p>Does anybody have any idea if that is possible?</p> | 46,048,577 | 7 | 3 | null | 2016-09-05 18:47:10.787 UTC | 3 | 2021-03-26 11:54:28.69 UTC | 2016-09-05 19:09:55.033 UTC | null | 13,302 | null | 6,640,681 | null | 1 | 12 | sql|sql-server|database | 54,198 | <p><a href="https://www.apexsql.com/sql_tools_propagate.aspx" rel="noreferrer">ApexSQL Propagate</a> is the tool which can help in this situation. It is used for executing single or multiple scripts on multiple databases, even multiple servers. What you should do is simply select that script, then select all databases against which you want to execute that script:</p>
<p><a href="https://i.stack.imgur.com/izt9f.png" rel="noreferrer"><img src="https://i.stack.imgur.com/izt9f.png" alt="select databases"></a></p>
<p>When you load scripts and databases you should just click the “Execute” button and wait for the results:</p>
<p><a href="https://i.stack.imgur.com/Cb4KT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Cb4KT.png" alt="click the execute button"></a></p> |
26,883,615 | Using `throw;` on a modified exception | <p>I have a function <code>foo</code> that can throw a <code>bar</code> exception.</p>
<p>In another function I call <code>foo</code> but I have the ability to add some more detail to the <code>bar</code> exception if thrown. (I'd rather not pass such information as a parameter to <code>foo</code> as it doesn't really belong there due to the generic nature of that function.)</p>
<p>So I do this in the caller:</p>
<pre><code>try {
foo();
} catch (bar& ex){
ex.addSomeMoreInformation(...);
throw;
}
</code></pre>
<p>Will <code>throw</code> re-throw the modified exception or do I need to use <code>throw ex;</code>? The latter would presumably take a value copy so I'd rather not do that. Would <code>throw</code> take a value copy too? I suspect it wouldn't.</p>
<p>(I'm aware I could verify but I'm concerned about stumbling on an unspecified or undefined construct so would like to know for sure).</p> | 26,883,786 | 5 | 0 | null | 2014-11-12 09:38:01.693 UTC | 2 | 2016-03-18 10:36:28.677 UTC | 2016-03-18 10:36:28.677 UTC | null | 3,647,361 | null | 3,415,258 | null | 1 | 57 | c++|exception|exception-handling|language-lawyer|throw | 3,061 | <p>C++11 §15.1/8:</p>
<blockquote>
<p><strong>”</strong> A <em>throw-expression</em> with no operand rethrows the currently handled exception (15.3). The exception is
reactivated with the existing temporary; no new temporary exception object is created.</p>
</blockquote> |
26,819,675 | Navbar highlight for current page | <p>I was wondering how I would add the ability to add a highlight box the nav bar on the page your currently on. You know so people know what page their on.</p>
<p>Very much like this site with the white box on the active page:<a href="https://woodycraft.net/home/" rel="noreferrer">https://woodycraft.net/home/</a></p>
<p>Here is the CSS for my nav bar:</p>
<pre><code>/*TOP NAV BAR SECTION*/
*{margin: 0px;
padding: 0px;}
#nav_bar {background-color: #a22b2f;
box-shadow: 0px 2px 10px;
height: 45px;
text-align: center;}
#nav_bar > ul > li {display: inline-block;}
#nav_bar ul > li > a {color: white;
display: block;
text-decoration: none;
font-weight: bold;
padding-left: 10px;
padding-right: 10px;
line-height: 45px;}
#nav_bar ul li ul {display: none;
list-style: none;
position: absolute;
background: #e2e2e2;
box-shadow: 0px 2px 10px;
text-align: left;}
#nav_bar ul li a:hover {background: #8e262a;}
#nav_bar a:active {background: white;}
#nav_bar ul li:hover ul {display: block;}
#nav_bar ul li ul li a {color: #252525;
display: block;}
#nav_bar ul li ul li a:hover {background: #4485f5;
color: #fff;}
</code></pre>
<p>Here is the HTML for one of my pages:</p>
<pre><code><!--TOP NAV BAR SECTION-->
<div id="nav_bar">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="status.html">Status</a></li>
<li><a href="info.html">Info</a></li>
<li><a href="#">Gamemodes</a>
<ul>
<li><a href="survival.html">Survival</a></li>
<li><a href="pure-pvp.html">Pure-PVP</a></li>
<li><a href="gamesworld.html">Gamesworld</a></li>
</ul>
</li>
<li><a href="rules.html">Rules</a></li>
<li><a href="vote.html">Vote</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
</code></pre> | 26,819,796 | 4 | 1 | null | 2014-11-08 16:58:38.45 UTC | 6 | 2021-12-07 21:29:26.473 UTC | 2014-11-08 18:41:00.423 UTC | user4171782 | null | user4171782 | null | null | 1 | 12 | html|css | 54,847 | <p>If you have the same navigation bar in each HTML page of your website, then you can do like this:<br>
For example in <strong>index.html</strong> add <strong>class='active-page'</strong> to the first menu item:</p>
<pre><code><div id="nav_bar">
<ul>
<li><a href="index.html" class='active-page'>Home</a></li>
<li><a href="status.html">Status</a></li>
<li><a href="info.html">Info</a></li>
</code></pre>
<p>Then in the <strong>status.html</strong> add <strong>class='active-page'</strong> again but for the second item:</p>
<pre><code><div id="nav_bar">
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="status.html" class='active-page'>Status</a></li>
<li><a href="info.html">Info</a></li>
</code></pre>
<p>And do this for all of your pages. </p>
<p>Finally in your css write a class for <strong>active-page</strong> like this:</p>
<pre><code>#nav_bar ul li a.active-page
{
background-color:blue;
}
</code></pre> |
7,420,109 | What does style.display = '' actually do? | <p>After researching this issue for a couple of hours, I found that one of the most efficient ways to toggle a page element's display (in HTML) is to do something like:</p>
<pre><code>// showing
document.getElementById('element').style.display = '';
// hiding
document.getElementById('element').style.display = 'none';
</code></pre>
<p><strong>Simple question:</strong> What does <code>style.display = ''</code> actually do?</p>
<p>Does it "reset" the original display property?</p>
<p>Or does it remove the display property, thereby using the default style for display?</p>
<p>..........................................</p>
<p><strong>Would be nice to know:</strong> Does anyone know of any links to any kind of documentation about this? </p>
<p>(Yes, I have Google-d this issue, but I'm probably not entering the right search term and keep coming up with completely un-related search results.)</p>
<p>Thanks for any suggestions or links.</p> | 7,420,125 | 4 | 1 | null | 2011-09-14 16:58:21.757 UTC | 26 | 2012-01-04 18:29:03.497 UTC | null | null | null | null | 914,482 | null | 1 | 51 | javascript|css|syntax | 55,453 | <p>Yes, it resets the element's display property to the default by blanking out the inline "display: none", causing the element to fall back on its display property as defined by the page's ranking CSS rules.</p>
<p>For example, here's a <code><div></code> with the ID of "myElement".</p>
<pre><code><div id="myElement"></div>
</code></pre>
<p>A <code><div></code> has a setting of <code>display:block</code> by default. In our style sheet, suppose we specify that your <code><div></code> is to be displayed as <code>table</code>:</p>
<pre><code>div#myElement
{
display:table;
}
</code></pre>
<p>Upon loading your page, the <code><div></code> is displayed as <code>table</code>. If you want to hide this <code><div></code> with scripting, you might do any of these:</p>
<pre><code>// JavaScript:
document.getElementById("myElement").style.display = 'none';
// jQuery:
$("#myElement").toggle(); // if currently visible
$("#myElement").hide();
$("#myElement").css({"display":"none"});
</code></pre>
<p>All of thse have the same effect: adding an inline <code>style</code> property to your <code><div></code>:</p>
<pre><code><div id="myElement" style="display:none"></div>
</code></pre>
<p>If you wish to show the element again, any of these would work:</p>
<pre><code>// JavaScript:
document.getElementById("myElement").style.display = "";
// jQuery:
$("#myElement").toggle(); // if currently hidden
$("#myElement").show();
$("#myElement").css({"display":""});
</code></pre>
<p>These remove the <code>display</code> CSS property from the inline <code>style</code> property:</p>
<pre><code><div style=""></div>
</code></pre>
<p>Since the inline style no longer specifies a <code>display</code>, the <code><div></code> goes back to being displayed as <code>table</code>, since that's what we put in the style sheet. The <code><div></code> does <strong>not</strong> revert to being displayed as <code>block</code> because our CSS overrode that default setting; blanking out the inline <code>display</code> property does not negate the rules in our style sheets.</p>
<hr>
<p>For giggles, here's the Google query I used for verification of my answer: <code>javascript style display empty string default</code></p>
<p>...and a couple of links where this is mentioned:</p>
<p><a href="http://jszen.blogspot.com/2004/07/table-rowsrevealed.html" rel="noreferrer">http://jszen.blogspot.com/2004/07/table-rowsrevealed.html</a></p>
<p><a href="http://www.harrymaugans.com/2007/03/05/how-to-create-a-collapsible-div-with-javascript-and-css/" rel="noreferrer">http://www.harrymaugans.com/2007/03/05/how-to-create-a-collapsible-div-with-javascript-and-css/</a>
(not in the article, but in the comments section)</p> |
67,018,079 | Error in "from keras.utils import to_categorical" | <p>I have probem with this code , why ?</p>
<p>the code :</p>
<pre><code>import cv2
import numpy as np
from PIL import Image
import os
import numpy as np
import cv2
import os
import h5py
import dlib
from imutils import face_utils
from keras.models import load_model
import sys
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D,Dropout
from keras.layers import Dense, Activation, Flatten
from keras.utils import to_categorical
from keras import backend as K
from sklearn.model_selection import train_test_split
from Model import model
from keras import callbacks
# Path for face image database
path = 'dataset'
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml");
def downsample_image(img):
img = Image.fromarray(img.astype('uint8'), 'L')
img = img.resize((32,32), Image.ANTIALIAS)
return np.array(img)
# function to get the images and label data
def getImagesAndLabels(path):
path = 'dataset'
imagePaths = [os.path.join(path,f) for f in os.listdir(path)]
faceSamples=[]
ids = []
for imagePath in imagePaths:
#if there is an error saving any jpegs
try:
PIL_img = Image.open(imagePath).convert('L') # convert it to grayscale
except:
continue
img_numpy = np.array(PIL_img,'uint8')
id = int(os.path.split(imagePath)[-1].split(".")[1])
faceSamples.append(img_numpy)
ids.append(id)
return faceSamples,ids
print ("\n [INFO] Training faces now.")
faces,ids = getImagesAndLabels(path)
K.clear_session()
n_faces = len(set(ids))
model = model((32,32,1),n_faces)
faces = np.asarray(faces)
faces = np.array([downsample_image(ab) for ab in faces])
ids = np.asarray(ids)
faces = faces[:,:,:,np.newaxis]
print("Shape of Data: " + str(faces.shape))
print("Number of unique faces : " + str(n_faces))
ids = to_categorical(ids)
faces = faces.astype('float32')
faces /= 255.
x_train, x_test, y_train, y_test = train_test_split(faces,ids, test_size = 0.2, random_state = 0)
checkpoint = callbacks.ModelCheckpoint('trained_model.h5', monitor='val_acc',
save_best_only=True, save_weights_only=True, verbose=1)
model.fit(x_train, y_train,
batch_size=32,
epochs=10,
validation_data=(x_test, y_test),
shuffle=True,callbacks=[checkpoint])
# Print the numer of faces trained and end program
print("enter code here`\n [INFO] " + str(n_faces) + " faces trained. Exiting Program")
</code></pre>
<hr />
<pre><code>the output:
------------------
File "D:\my hard sam\ماجستير\سنة ثانية\البحث\python\Real-Time-Face-Recognition-Using-CNN-master\Real-Time-Face-Recognition-Using-CNN-master\02_face_training.py", line 16, in <module>
from keras.utils import to_categorical
ImportError: cannot import name 'to_categorical' from 'keras.utils' (C:\Users\omar\PycharmProjects\SnakGame\venv\lib\site-packages\keras\utils\__init__.py)
</code></pre> | 67,018,610 | 4 | 3 | null | 2021-04-09 08:58:22.287 UTC | 4 | 2022-03-03 11:32:17.047 UTC | 2021-04-09 09:01:26.76 UTC | null | 9,215,780 | null | 15,558,831 | null | 1 | 30 | python|keras | 77,845 | <p><strong>Keras</strong> is now fully intregrated into <strong>Tensorflow</strong>. So, importing only <strong>Keras</strong> causes error.</p>
<p>It should be imported as:</p>
<pre><code>from tensorflow.keras.utils import to_categorical
</code></pre>
<br>
<p><strong>Avoid</strong> importing as:</p>
<pre><code>from keras.utils import to_categorical
</code></pre>
<br>
<p>It is safe to use
<code>from tensorflow.keras.</code> instead of <code>from keras.</code> while importing all the necessary modules.</p>
<pre class="lang-py prettyprint-override"><code>from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D,Dropout
from tensorflow.keras.layers import Dense, Activation, Flatten
from tensorflow.keras.utils import to_categorical
from tensorflow.keras import backend as K
from sklearn.model_selection import train_test_split
from tensorflow.keras import callbacks
</code></pre> |
1,474,702 | Link to a file share through an anchor tag | <p>How do I format an HTML anchor tag to link to a shared network folder?</p>
<p>I tried the following and it does not like it.</p>
<pre><code><a href="file:\\myserver\myfolder\myfile.docx">My Shared Folder</a>
</code></pre> | 1,474,735 | 4 | 0 | null | 2009-09-24 23:33:12.513 UTC | 1 | 2014-04-23 17:45:16.34 UTC | 2009-09-24 23:42:51.993 UTC | null | 9,021 | null | 26,327 | null | 1 | 13 | html | 46,667 | <p>Try this URL:</p>
<pre><code><a href="file://///myserver/myfolder/myfile.docx">
</code></pre> |
1,685,389 | Possible to use more than one argument on __getitem__? | <p>I am trying to use</p>
<pre><code>__getitem__(self, x, y):
</code></pre>
<p>on my Matrix class, but it seems to me it doesn't work (I still don't know very well to use python).
I'm calling it like this:</p>
<pre><code>print matrix[0,0]
</code></pre>
<p>Is it possible at all to use more than one argument? Thanks. Maybe I can use only one argument but pass it as a tuple?</p> | 1,685,412 | 4 | 0 | null | 2009-11-06 04:21:49.33 UTC | 3 | 2021-10-31 00:11:53.303 UTC | null | null | null | null | 130,758 | null | 1 | 53 | python | 19,365 | <p><code>__getitem__</code> only accepts one argument (other than <code>self</code>), so you get passed a tuple.</p>
<p>You can do this:</p>
<pre><code>class matrix:
def __getitem__(self, pos):
x,y = pos
return "fetching %s, %s" % (x, y)
m = matrix()
print m[1,2]
</code></pre>
<p>outputs</p>
<pre class="lang-none prettyprint-override"><code>fetching 1, 2
</code></pre>
<p>See the <a href="https://docs.python.org/3/reference/datamodel.html#object.__getitem__" rel="noreferrer">documentation</a> for <code>object.__getitem__</code> for more information.</p> |
2,057,210 | Ruby on rails - Reference the same model twice? | <p>Is it possible to set up a double relationship in <code>activerecord</code> models via the <code>generate scaffold</code> command?</p>
<p>For example, if I had a <code>User</code> model and a <code>PrivateMessage</code> model, the private_messages table would need to keep track of both the <code>sender</code> and <code>recipient</code>.</p>
<p>Obviously, for a single relationship I would just do this:</p>
<pre><code>ruby script/generate scaffold pm title:string content:string user:references
</code></pre>
<p>Is there a similar way to set up two relations?</p>
<p>Also, is there anyway to set up aliases for the relations?</p>
<p>So rather than saying:</p>
<pre><code>@message.user
</code></pre>
<p>You can use something like:</p>
<p><code>@message.sender</code> or <code>@message.recipient</code></p>
<p>Any advice would be greatly appreciated.</p>
<p>Thanks.</p> | 2,057,243 | 4 | 0 | null | 2010-01-13 14:16:15.633 UTC | 35 | 2020-09-04 07:03:43.13 UTC | 2019-10-14 20:47:19.253 UTC | null | 4,880,924 | null | 207,316 | null | 1 | 60 | ruby-on-rails|rails-activerecord|relationship | 28,484 | <p>Add this to your Model</p>
<pre><code>belongs_to :sender, :class_name => "User"
belongs_to :recipient, :class_name => "User"
</code></pre>
<p>And you are able to call <code>@message.sender</code> and <code>@message.recipient</code> and both reference to the User model.</p>
<p>Instead of <code>user:references</code> in your generate command, you'd need <code>sender:references</code> and <code>recipient:references</code></p> |
10,331,817 | SQL Server ISDATE() Function - Can someone explain this? | <p>So I was looking at the documentation for the ISDATE() function in SQL Server and saw this in the examples:</p>
<pre><code>SET DATEFORMAT mdy;
SELECT ISDATE('15/04/2008'); --Returns 0.
SET DATEFORMAT mdy;
SELECT ISDATE('15/2008/04'); --Returns 0.
SET DATEFORMAT mdy;
SELECT ISDATE('2008/15/04'); --Returns 0.
SET DATEFORMAT mdy;
SELECT ISDATE('2008/04/15'); --Returns 1.
</code></pre>
<p>The last example returns 1 (a valid date) but the date format above doesn't match the format in the expression of the function. I thought it was a mistake in the documentation but then curiously tried it out myself and it does actually return 1.</p>
<p>So why is '2008/04/15' a valid date when the date format is mdy?</p>
<p>Documentation here: <a href="http://msdn.microsoft.com/en-us/library/ms187347(SQL.105).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms187347(SQL.105).aspx</a></p> | 10,331,903 | 2 | 2 | null | 2012-04-26 10:44:03.633 UTC | 1 | 2012-04-26 11:21:45.26 UTC | null | null | null | null | 424,084 | null | 1 | 5 | sql-server|function|date-formatting | 45,777 | <p>from <a href="http://msdn.microsoft.com/en-us/library/ms187347%28SQL.105%29.aspx#SessionSettingDependencies" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms187347%28SQL.105%29.aspx#SessionSettingDependencies</a> </p>
<blockquote>
<p>The return value of ISDATE depends on the settings set by SET
DATEFORMAT, SET LANGUAGE and default language option.</p>
</blockquote>
<p>So if the given string not applies to the set dateformat it also cecks the default language option which allows dates in a format like y/m/d</p> |
28,557,719 | How do you full text search an Amazon S3 bucket? | <p>I have a bucket on S3 in which I have large amount of text files.</p>
<p>I want to search for some text within a text file. It contains raw data only.
And each text file has a different name.</p>
<p>For example, I have a bucket name:</p>
<p><strong>abc/myfolder/abac.txt</strong></p>
<p><strong>xyx/myfolder1/axc.txt</strong></p>
<p>& I want to search text like "I am human" in the above text files.</p>
<p>How to achieve this? Is it even possible?</p> | 28,561,175 | 7 | 4 | null | 2015-02-17 08:35:16.903 UTC | 11 | 2022-07-26 05:52:49.663 UTC | 2022-01-04 06:47:34.103 UTC | null | 74,089 | null | 857,500 | null | 1 | 32 | amazon-web-services|amazon-s3 | 17,505 | <p>The only way to do this will be via <a href="http://aws.amazon.com/cloudsearch/faqs/">CloudSearch</a>, which can use S3 as a source. It works using rapid retrieval to build an index. This should work very well but thoroughly check out the pricing model to make sure that this won't be too costly for you. </p>
<p>The alternative is as Jack said - you'd otherwise need to transfer the files out of S3 to an EC2 and build a search application there. </p> |
36,554,322 | Cannot start Emulator in android studio 2.0 | <p>I just upgraded my android studio from 1.5 to 2.0.And now I am facing some weird bug when I try to start Emulator. I use Ubuntu 15.10 OS</p>
<p>Android monitor returns this message</p>
<pre><code>sh: 1: glxinfo: not found
sh: 1: glxinfo: not found
libGL error: unable to load driver: r600_dri.so
libGL error: driver pointer missing
libGL error: failed to load driver: r600
libGL error: unable to load driver: swrast_dri.so
libGL error: failed to load driver: swrast
X Error of failed request: BadValue (integer parameter out of range for operation)
Major opcode of failed request: 155 (GLX)
Minor opcode of failed request: 24 (X_GLXCreateNewContext)
Value in failed request: 0x0
Serial number of failed request: 33
Current serial number in output stream: 34
QObject::~QObject: Timers cannot be stopped from another thread
</code></pre>
<p>When I was using 1.5 version all was going good. Is it a bug in android studio 2.0.</p>
<p>How to remove this error?</p> | 36,568,949 | 14 | 7 | null | 2016-04-11 16:31:16.213 UTC | 35 | 2019-03-30 13:38:34.147 UTC | 2016-04-11 16:44:53.117 UTC | null | 1,235,698 | null | 3,985,848 | null | 1 | 67 | android | 48,225 | <p>Verify that you have installed in your system lib64stdc++6 </p>
<p>With a 32 bits operating system :</p>
<pre><code># apt-get install lib64stdc++6
</code></pre>
<p>With a 64 bits operating system with multiarch enabled :</p>
<pre><code># apt-get install lib64stdc++6:i386
</code></pre>
<p>Then link the new installed libraries to the android sdk tools path</p>
<pre><code>$ cd $ANDROID_HOME/android-sdk-linux_x86/tools/lib64/libstdc++
$ mv libstdc++.so.6 libstdc++.so.6.bak
$ ln -s /usr/lib64/libstdc++.so.6 $ANDROID_HOME/android-sdk-linux_x86/tools/lib64/libstdc++
</code></pre>
<p>EDIT: in <code>15.10 x64</code> with current Sdk (23), the folder is <code>$ANDROID_HOME/Sdk</code></p> |
7,608,714 | Why is my pointer not null after free? | <pre><code>void getFree(void *ptr)
{
if(ptr != NULL)
{
free(ptr);
ptr = NULL;
}
return;
}
int main()
{
char *a;
a=malloc(10);
getFree(a);
if(a==NULL)
printf("it is null");
else
printf("not null");
}
</code></pre>
<p><strong>Why is the output of this program not NULL?</strong></p> | 7,608,781 | 6 | 1 | null | 2011-09-30 09:54:41.78 UTC | 10 | 2019-10-19 02:43:08.697 UTC | 2011-09-30 09:59:41.793 UTC | null | 908,515 | null | 775,964 | null | 1 | 15 | c|free | 20,033 | <p>Because the pointer is copied <em>by value</em> to your function. You are assigning <code>NULL</code> to the local copy of the variable (<code>ptr</code>). This does not assign it to the original copy.</p>
<p>The memory will still be freed, so you can no longer safely access it, but your original pointer will not be <code>NULL</code>.</p>
<p>This the same as if you were passing an <code>int</code> to a function instead. You wouldn't expect the original <code>int</code> to be edited by that function, unless you were passing a pointer to it.</p>
<pre><code>void setInt(int someValue) {
someValue = 5;
}
int main() {
int someOtherValue = 7;
setInt(someOtherValue);
printf("%i\n", someOtherValue); // You'd expect this to print 7, not 5...
return 0;
}
</code></pre>
<p>If you want to null the original pointer, you'll have to pass a pointer-to-pointer:</p>
<pre><code>void getFree(void** ptr) {
/* Note we are dereferencing the outer pointer,
so we're directly editing the original pointer */
if (*ptr != NULL) {
/* The C standard guarantees that free() safely handles NULL,
but I'm leaving the NULL check to make the example more clear.
Remove the "if" check above, in your own code */
free(*ptr);
*ptr = NULL;
}
return;
}
int main() {
char *a;
a = malloc(10);
getFree(&a); /* Pass a pointer-to-pointer */
if (a == NULL) {
printf("it is null");
} else {
printf("not null");
}
return 0;
}
</code></pre> |
7,113,865 | How to copy/clone a hash/object in JQuery? | <p>I have a simple object (or hash) in Javascript:</p>
<pre><code>var settings = {
link: 'http://example.com',
photo: 'http://photos.com/me.jpg'
};
</code></pre>
<p>I need a copy of it. Is there a <code>settings.clone()</code> type method that will give me another object with the same attributes? I'm using jQuery, so happy to use a jQuery utility method if one exists.</p> | 7,113,883 | 6 | 2 | null | 2011-08-18 20:40:01.573 UTC | 5 | 2016-12-16 11:24:28.27 UTC | 2016-12-16 11:24:28.27 UTC | null | 1,320,510 | null | 326,389 | null | 1 | 39 | javascript|jquery|copy|clone|javascript-objects | 33,611 | <p>Yes, <a href="http://api.jquery.com/jQuery.extend/">extend</a> an empty object with the original one; that way, everything will simply be copied:</p>
<pre><code>var clone = $.extend({}, settings);
</code></pre>
<hr>
<p>Extending some filled object with another, e.g.:</p>
<pre><code>$.extend({a:1}, {b:2})
</code></pre>
<p>will return:</p>
<pre><code>{a:1, b:2}
</code></pre>
<hr>
<p>With the same logic:</p>
<pre><code>$.extend({}, {foo:'bar', test:123})
</code></pre>
<p>will return:</p>
<pre><code>{foo:'bar', test:123}
</code></pre>
<p>i.e. effectively a clone.</p> |
7,014,953 | I need to securely store a username and password in Python, what are my options? | <p>I'm writing a small Python script which will periodically pull information from a 3rd party service using a username and password combo. I don't need to create something that is 100% bulletproof (does 100% even exist?), but I would like to involve a good measure of security so at the very least it would take a long time for someone to break it. </p>
<p>This script won't have a GUI and will be run periodically by <code>cron</code>, so entering a password each time it's run to decrypt things won't really work, and I'll have to store the username and password in either an encrypted file or encrypted in a SQLite database, which would be preferable as I'll be using SQLite anyway, and I <em>might</em> need to edit the password at some point. In addition, I'll probably be wrapping the whole program in an EXE, as it's exclusively for Windows at this point. </p>
<p>How can I securely store the username and password combo to be used periodically via a <code>cron</code> job?</p> | 7,015,578 | 8 | 1 | null | 2011-08-10 17:13:04.213 UTC | 69 | 2020-11-06 22:04:16.253 UTC | 2011-08-10 17:22:41.357 UTC | null | 128,967 | null | 128,967 | null | 1 | 124 | python|security|encryption | 128,526 | <p>I recommend a strategy similar to <a href="http://en.wikipedia.org/wiki/Ssh-agent">ssh-agent</a>. If you can't use ssh-agent directly you could implement something like it, so that your password is only kept in RAM. The cron job could have configured credentials to get the actual password from the agent each time it runs, use it once, and de-reference it immediately using the <code>del</code> statement.</p>
<p>The administrator still has to enter the password to start ssh-agent, at boot-time or whatever, but this is a reasonable compromise that avoids having a plain-text password stored anywhere on disk.</p> |
7,178,170 | All IntelliJ run configurations disappeared | <p>After IntelliJ IDEA froze and was killed from the task manager, all the Run/Debug Configurations disappeared. I have tried invalidating caches, reloading files from disk, synchronizing and restarting, but nothing helped.</p> | 7,178,813 | 12 | 9 | null | 2011-08-24 15:33:01.533 UTC | 4 | 2022-08-12 08:19:26.913 UTC | 2022-02-08 22:04:00.24 UTC | null | 266,531 | null | 630,372 | null | 1 | 64 | intellij-idea | 34,263 | <p>You can try to restore your Run configuration using the <strong>Local History</strong> feature of IntelliJ IDEA.</p>
<p>If you are using <code>.idea</code> directory based format, then your configurations will reside in <code>workspace.xml</code> file under <code>.idea</code> directory, invoke <strong>Local History</strong> dialog from the <strong>.idea</strong> directory right click menu in IDEA <strong>Project View</strong>, select the label some time before the crash and revert the old copy of <code>workspace.xml</code>.</p>
<p>In case <code>.ipr</code> file based format is used, your configurations will be stored in the <code><project>.iws</code> file in the project root which you can restore in a similar way.</p>
<p>If the configurations were <strong>Shared</strong>, they are stored in <code>.idea\runConfigurations</code> directory as separate XML files or in the <code><project>.ipr</code> file (if old project format is used).</p>
<p>If the <strong>Local history</strong> is blank and you are in Windows, try <strong>Restore previous versions</strong> right clicking the <code>workspace.xml</code> file or the <code><project>.iws</code> one in <strong>Windows Explorer</strong>.</p> |
13,832,866 | unix- show the second line of the file | <p>this command displays the second line of the file :</p>
<pre><code>cat myfile | head -2 | tail -1
</code></pre>
<p>My file contains the following data : </p>
<pre><code>hello
mark
this is the head line
this is the first line
this is the second line
this is the last line
</code></pre>
<p>the command above prints the data as: <code>mark</code></p>
<p>But i am unable to understand this because, head -2 is used to print the first two lines and tail -1 prints the last line but how come 2nd line is printed!!???</p> | 13,832,897 | 3 | 2 | null | 2012-12-12 04:37:35.62 UTC | 5 | 2012-12-12 04:49:08.98 UTC | 2012-12-12 04:39:11.097 UTC | null | 390,913 | null | 975,234 | null | 1 | 31 | unix | 90,741 | <p>tail displays the last line of the head output and the last line of the head output is the second line of the file.</p>
<p>Output of head (input to tail):</p>
<pre><code>hello
mark
</code></pre>
<p>Output of tail:</p>
<pre><code>mark
</code></pre> |
14,336,450 | JavaScript frameworks to build single page applications | <p>My goal is to migrate an existing web application to a RESTful <a href="http://en.wikipedia.org/wiki/Single-page_application" rel="nofollow noreferrer">single page application</a> (SPA).
Currently, I'm evaluating several Javascript web application frameworks. </p>
<hr>
<p>My requirements are as follow:</p>
<ul>
<li>RESTful data layer (like ember-data)</li>
<li>MV*-structure</li>
<li>Dynamic routes</li>
<li>Testing-support</li>
<li>Coding by convention</li>
<li>SEO-support</li>
<li>Browser-History-Support</li>
<li>Good (API-) documentation</li>
<li>Production-ready</li>
<li>Living community</li>
</ul>
<hr>
<h3><a href="http://backbonejs.org" rel="nofollow noreferrer">Backbone</a></h3>
<p>The current application is using <code>backbone.js</code>. Overall, <code>backbone.js</code> is a nice project, but I'm missing well-defined structures that determine where what has to happen and how things must get implemented. Working in a bigger team with changing developers this leads to some kind of unstructured code, difficult to maintain and difficult to understand. This is why I'm searching now for a framework, that already defines all this stuff.</p>
<h3><a href="http://emberjs.com" rel="nofollow noreferrer">Ember</a></h3>
<p>I looked into <code>ember.js</code> the last days. The approach seems very promising to me. But, unfortunately, the code changes almost daily. So, I won't call it production-ready. And, unfortunately, we can't wait for it to be version 1.0. But I really like the idea behind this framework.</p>
<h3><a href="http://angularjs.org" rel="nofollow noreferrer">Angular</a></h3>
<p><code>Angular.js</code> is a widely spread framework as well, maintained by Google. But I could not get familiar with angular. For me, the structure seems kind of unclear, explanations are missing of the overall responsibilities of each part of the framework, and the implementations feel circuitous.
Just to get this straight: this is just my personal impression and might be based on missing knowledge.</p>
<h3><a href="http://batmanjs.org" rel="nofollow noreferrer">Batman</a> and <a href="http://meteor.com" rel="nofollow noreferrer">Meteor</a></h3>
<p>As I understood, both frameworks need a server part as well. And since we just want a RESTful backend - no matter what language, technic or software, this is not what we want. Further, the backend API does already exist (RoR).</p>
<h3><a href="http://knockoutjs.com" rel="nofollow noreferrer">Knockout</a>, <a href="http://canjs.us" rel="nofollow noreferrer">CanJS</a> and <a href="http://spinejs.com" rel="nofollow noreferrer">Spine</a></h3>
<p>I did not go any deeper into these three candidates. Maybe this will be my next step.</p>
<hr>
<p>So my questions now:</p>
<ul>
<li>Am I missing any good SPA-frameworks?</li>
<li>What framework would you suggest/recommend?</li>
<li>Would you avoid any of the mentioned frameworks?</li>
<li>What is your experience in bigger SP applications?</li>
</ul>
<hr>
<p>PS: I'd would like to recommend a <a href="http://blog.stevensanderson.com/2012/08/01/rich-javascript-applications-the-seven-frameworks-throne-of-js-2012/" rel="nofollow noreferrer">great blogpost</a> from Steven Anderson (core developer from Knockout.js) about the "Throne of JS"-conference (from 2012) and javascript frameworks in general.</p>
<p>PS: Yes, I know there are already some question on SO. But since the development is so rapidly and fast for SPAs, most of them are already out-of-date.</p> | 14,338,436 | 2 | 1 | null | 2013-01-15 11:10:05.29 UTC | 69 | 2018-02-04 15:08:40.937 UTC | 2018-02-04 15:08:40.937 UTC | null | 3,924,118 | null | 842,302 | null | 1 | 101 | javascript|singlepage | 75,935 | <p>I recently had to decide on a JavaScript SPA framework on a project too.</p>
<ul>
<li><p><a href="http://emberjs.com/">Ember</a> </p>
<p>Looked at Ember early on and had similar thoughts as you about it - I really liked it but it felt like it was still too early to use... about half the tutorials I read didn't work with the current version because something had recently changed in how templating works.</p></li>
<li><p><a href="http://backbonejs.org/">Backbone</a></p>
<p>Backbone was the first frameworks we seriously looked at. I'm not sure I understand why you think it doesn't have "well defined structures"? Backbone is pretty clear about how to divide up Model and View code. Maybe you mean there's not some kind of app template? Anyway, Backbone seems really focused on the model/REST-binding part, but doesn't really prescribe anything for view binding. If model binding's important to you and you're using Rails it should be a breeze to do this. Unfortunately, the web services for my app didn't really match up, and I had to write my own <code>.sync</code> and <code>.parse</code> methods for everything. The separation of Model and View code was nice, but since we'd have to write all our bindings from scratch it wasn't worth it.</p></li>
<li><p><a href="http://knockoutjs.com/">Knockout</a></p>
<p>Knockout is like the Yin to Backbone's Yang. Where Backbone is focused on the Model, Knockout is a MVVM framework and is focused on the View. It has <code>observable</code> wrappers for JavaScript object properties and uses a <code>data-bind</code> attribute to bind properties to your HTML. In the end we went with Knockout since view binding was mainly what we needed for our app. (...plus others, as discussed later...) If you like Knockout's view binding and Backbone's model bindings there's also <a href="http://kmalakoff.github.com/knockback/">KnockBack</a> which combines both frameworks.</p></li>
<li><p><a href="http://angularjs.org/">Angular</a></p>
<p>Looked at this after Knockout - unfortunately we all seemed pretty happy with how Knockout did view binding. It seemed a lot more complex and harder to get into than Knockout. And it uses a bunch of custom HTML attributes to do bindings, which I'm not sure I like... I may take another look at Angular later, because since I've come across multiple people who really like the framework - maybe we just looked at it too late for this project.</p></li>
<li><p><a href="http://batmanjs.org/">Batman</a>, <a href="http://meteor.com/">Meteor</a>, <a href="http://canjs.us/">CanJS</a>, <a href="http://spinejs.com/">Spine</a></p>
<p>Didn't really look too closely at any of these. Though I know Spine is a similar framework to Backbone with explicit Controller objects, and is written in CoffeeScript.</p></li>
<li><p>Afterword</p>
<p>As I mentioned, we ended up using Knockout because, for our project, focusing on view binding was more important. We also ended up using <a href="http://requirejs.org/">RequireJS</a> for modularization, <a href="http://millermedeiros.github.com/crossroads.js/">crossroads</a> and <a href="https://github.com/millermedeiros/hasher/">Hasher</a> to handle routing and history, <a href="http://pivotal.github.com/jasmine/">Jasmine</a> for testing, as well as <a href="http://jquery.com/">JQuery</a>, <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a>, and <a href="http://underscorejs.org/">Underscore.js</a> (and probably more libraries I'm forgetting at the moment). </p>
<p>Javascript app development is more like the Java ecosystem than the Rails ecosystem. Rails provides a solid core of stuff you're going to use for every app (Rails framework), and the community provides a lot of customizations on top of that (gems). Java provides... a language. And then you can choose Java EE or Spring or Play or Struts or Tapestry. And choose JDBC or Hibernate or TopLink or Ibatis to talk to the database. And then you can use Ant or Maven or Gradle to build it. And choose Tomcat or Jetty or JBoss or WebLogin to run it in. So there's more emphasis on choosing what you need and what works together than choosing <em>THE</em> framework to use.</p></li>
</ul> |
29,217,209 | Is it ok to use HTTP REST API for Chat application? | <p>We are building a chat application on Android. We are thinking of using HTTP REST API to send outbound messages. Wanted to know if it's a good approach or has any downsides compared to using WebSockets or XMPP (which seems to be more of a defacto standard for transferring chat messages)?</p>
<p>Some of the pros/cons I can think of are:</p>
<ul>
<li>HTTP endpoint is easy to scale horizontally on the server side (This is the main concern)</li>
<li>Learning curve for Websockets is steeper compared to HTTP</li>
</ul>
<ul>
<li>HTTP messages would have a larger payload compared to WebSockets</li>
</ul>
<p>As per this document, it seems even Facebook used AJAX to handle chat messages initially:</p>
<p><a href="https://www.erlang-factory.com/upload/presentations/31/EugeneLetuchy-ErlangatFacebook.pdf" rel="noreferrer">https://www.erlang-factory.com/upload/presentations/31/EugeneLetuchy-ErlangatFacebook.pdf</a></p> | 29,340,059 | 5 | 3 | null | 2015-03-23 18:00:46.863 UTC | 12 | 2021-05-14 09:37:51.63 UTC | 2021-05-14 09:37:51.63 UTC | null | 11,573,842 | null | 507,256 | null | 1 | 32 | android|xmpp|chat | 24,907 | <p>We can use REST API for chat messaging, but IMHO, XMPP is a better alternative. Let's consider what XMPP has to offer.</p>
<p>XMPP beside supporting TCP transport also provides HTTP (via <strong>polling</strong> and <strong>binding</strong>) and <strong>websocket</strong> transports. Read <a href="http://en.wikipedia.org/wiki/XMPP#XMPP_via_HTTP_and_WebSocket_transports" rel="noreferrer">XMPP via HTTP and WebSocket transports</a></p>
<p>It would be interesting to understand pros and cons of each transport from XMPP perspective.</p>
<blockquote>
<p>XMPP could use HTTP in two ways: <strong>polling</strong>[18] and <strong>binding</strong>. </p>
</blockquote>
<p><strong>XMPP over HTTP Polling</strong></p>
<blockquote>
<p>The polling
method, now deprecated, essentially implies messages stored on a
server-side database are being fetched (and posted) regularly by an
XMPP client by way of HTTP 'GET' and 'POST' requests. </p>
</blockquote>
<hr>
<p><strong>XMPP over HTTP Binding (BOSH)</strong></p>
<p><strong>The binding method is considered more efficient</strong> than the regular HTTP 'GET' and 'POST' requests in Polling method because it reduces latency and bandwidth consumption over other HTTP polling techniques</p>
<p>However, this also poses a disadvantage that sockets remain open for an extended length of time, awaiting the client's next request</p>
<blockquote>
<p>The binding method, implemented using Bidirectional-streams Over Synchronous HTTP
(<strong>BOSH</strong>),[19] allows servers to push messages to clients as soon as they
are sent. <strong>This push model of notification is more efficient than
polling, where many of the polls return no new data.</strong> </p>
</blockquote>
<p>It would be good if we understand how <a href="http://xmpp.org/extensions/xep-0124.html#technique" rel="noreferrer">the BOSH technique</a> works. </p>
<blockquote>
<p>The technique employed by BOSH, which is sometimes called "HTTP long
polling", reduces latency and bandwidth consumption over other HTTP
polling techniques. When the client sends a request, the connection
manager does not immediately send a response; instead it holds the
request open until it has data to actually send to the client (or an
agreed-to length of inactivity has elapsed). The client then
immediately sends a new request to the connection manager, continuing
the long polling loop.</p>
<p>If the connection manager does not have any data to send to the client
after some agreed-to length of time [12], it sends a response with an
empty . This serves a similar purpose to whitespace keep-alives
or XMPP Ping (XEP-0199) [13]; it helps keep a socket connection active
which prevents some intermediaries (firewalls, proxies, etc) from
silently dropping it, and helps to detect breaks in a reasonable
amount of time.</p>
</blockquote>
<hr>
<p><strong>XMPP over WebSocket binding</strong></p>
<p>XMPP supports <strong>WebSocket binding which is a more efficient transport</strong></p>
<blockquote>
<p>A perhaps more efficient transport for real-time messaging is
WebSocket, a web technology providing for bi-directional, full-duplex
communications channels over a single TCP connection. XMPP over
WebSocket binding is defined in the IETF proposed standard RFC 7395.</p>
</blockquote>
<p>Speaking of the learning curve, yes, you might be tempted to use the REST API, but now there are several resources to learn about <a href="https://stackoverflow.com/questions/4769020/android-and-xmpp-currently-available-solutions?lq=1">Android and XMPP</a>, and <a href="http://xmpp.org/xmpp-software/servers/" rel="noreferrer">XMPP server softwares</a> that you can use to run your own XMPP service, either over the Internet or on a local area network. It would be worth spending this effort before you decide your architecture.</p> |
9,345,841 | PHP: is there a way to see "invisible" characters like \n | <p>Is there a way to see invisible characters like whitespace, newlines, and other non-printing characters in a manner like print_r() ?</p>
<p>Reason is there is some sort of character in my array that I can't see and breaking things.</p>
<pre><code>Object Object
(
[name] => name
[numbers] => Array
(
[0] => 123
[1] => 456
[2] => 789
)
[action] => nothing
)
</code></pre>
<p>See the weird whitespace between [0] and [1]? When printing out [0] a newline gets printed as well. But no where do I assign a newline to [0] so I'm quite confused. </p>
<p>Is there a built in function in php that's like <code>show_invisible(Object->numbers[0])</code> and it will show <code>123\n</code> or similar?</p> | 9,345,911 | 5 | 1 | null | 2012-02-19 01:33:56 UTC | 8 | 2016-10-13 18:46:31.713 UTC | null | null | null | null | 255,439 | null | 1 | 29 | php | 32,914 | <p>You can use the <a href="http://www.php.net/manual/en/function.addcslashes.php" rel="nofollow">addcslashes</a> function:</p>
<blockquote>
<p>string addcslashes ( string $str, string $charlist )</p>
</blockquote>
<p>which will return a string with backslashes before characters. An example would be:</p>
<blockquote>
<pre><code><?php
echo addcslashes('foo[ ]', 'A..z');
// output: \f\o\o\[ \]
// All upper and lower-case letters will be escaped
// ... but so will the [\]^_`
?>
</code></pre>
</blockquote> |
9,293,721 | AddressFilter mismatch at the EndpointDispatcher - the msg with To | <p>Any ideas how I correct this.. calling a service via js</p>
<blockquote>
<p>The message with To 'http://MySite.svc/GetStateXML' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher. Check that the sender and receiver's EndpointAddresses agree</p>
</blockquote>
<p>thanks</p> | 37,167,950 | 12 | 1 | null | 2012-02-15 12:50:26.363 UTC | 8 | 2020-11-09 11:48:54.817 UTC | 2012-09-25 14:03:59.507 UTC | null | 223,386 | null | 1,211,292 | null | 1 | 51 | wcf | 101,551 | <p>Look at <code><webHttp /></code></p>
<pre><code><services>
<service name="SimpleService.SimpleService" behaviorConfiguration="serviceBehaviour">
<endpoint address="" binding="webHttpBinding" contract="SimpleService.ISimpleService" behaviorConfiguration="web">
</endpoint>
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange">
</endpoint>
</service>
</services>
....
....
<endpointBehaviors>
<behavior name="web">
<webHttp />
</behavior>
</endpointBehaviors>
</code></pre> |
9,089,842 | C++ chrono system time in milliseconds, time operations | <p>I've got a small problem caused by insufficient documentation of C++11.</p>
<p>I'd like to obtain a time since epoch in milliseconds, or nanoseconds or seconds and then I will have to "cast" this value to another resolution.
I can do it using gettimeofday() but it will be to easy, so I tried to achieve it using std::chrono.</p>
<p>I tried:</p>
<pre><code>std::chrono::time_point<std::chrono::system_clock> now =
std::chrono::system_clock::now();
</code></pre>
<p>But I have no idea what is a resolution of obtained in this way time_point, and I don't know how to get this time as a simple unsigned long long, and I haven't any conception how to cast it to another resolution.</p> | 9,089,870 | 1 | 1 | null | 2012-02-01 02:14:39.883 UTC | 27 | 2017-06-23 10:01:41.1 UTC | 2017-01-02 18:03:17.93 UTC | null | 1,033,581 | null | 784,345 | null | 1 | 87 | c++|time|c++11|chrono | 128,606 | <p>You can do <code>now.time_since_epoch()</code> to get a duration representing the time since the epoch, with <a href="https://stackoverflow.com/q/8386128">the clock's resolution</a>. To convert to milliseconds use <a href="http://en.cppreference.com/w/cpp/chrono/duration/duration_cast" rel="noreferrer"><code>duration_cast</code></a>:</p>
<pre><code>auto duration = now.time_since_epoch();
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
</code></pre> |
44,409,105 | Invalid datetime format: 1292 Incorrect datetime value - Laravel 5.2 | <p>I'm getting this error when I insert these value into my database table:</p>
<blockquote>
<pre>
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value:
'24/06/2017' for column 'registration_from' at row 1
(SQL: insert into `campus_registrations` (`campus_major_class_id`,
`registration_from`, `registration_to`, `testing`, `announcement`,
`enrollment_from`, `enrollment_to`, `updated_at`, `created_at`) values (3,
24/06/2017, 27/06/2017, 13/07/2017, 01/08/2017, 05/09/2017, 31/01/2018,
2017-06-07 09:39:31, 2017-06-07 09:39:31))
</pre>
</blockquote>
<p>Do I have to intiate the datetime first or what?</p> | 44,409,398 | 10 | 3 | null | 2017-06-07 09:46:58.17 UTC | 3 | 2022-08-17 08:41:13.537 UTC | 2017-06-07 13:17:47.233 UTC | null | 5,808,894 | null | 3,822,744 | null | 1 | 10 | php|mysql|laravel | 82,040 | <p>The error is here:</p>
<pre><code>Incorrect datetime value: '24/06/2017' for column 'registration_from' at row 1
</code></pre>
<p>the default format for <code>date</code> column in mysql is <code>Y-m-d</code> and for <code>datetime</code> is <code>Y-m-d H:i:s</code>. So change your date to this format and try again.</p> |
32,667,398 | Best tool for text extraction from PDF in Python 3.4 | <p>I am using Python 3.4 and need to extract all the text from a PDF and then use it for text processing.</p>
<p>All the answers I have seen suggest options for Python 2.7.</p>
<p>I need something in Python 3.4.</p>
<p>Bonson</p> | 32,669,303 | 5 | 4 | null | 2015-09-19 11:00:49.343 UTC | 17 | 2020-06-24 09:10:46.593 UTC | null | null | null | null | 1,181,744 | null | 1 | 45 | python-3.x|pdf | 63,359 | <p>You need to install PyPDF2 module to be able to work with PDFs in Python 3.4. PyPDF2 cannot extract images, charts or other media but it can extract text and return it as a Python string. To install it run <code>pip install PyPDF2</code> from the command line. This module name is case-sensitive so make sure to type 'y' in lowercase and all other characters as uppercase.</p>
<pre><code>>>> import PyPDF2
>>> pdfFileObj = open('my_file.pdf','rb') #'rb' for read binary mode
>>> pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
>>> pdfReader.numPages
56
>>> pageObj = pdfReader.getPage(9) #'9' is the page number
>>> pageObj.extractText()
</code></pre>
<p>last statement returns all the text that is available in page-9 of 'my_file.pdf' document.</p> |
35,060,111 | Random Number Order in C++ using <random> | <p>I have the following code, that I wrote to test a part of a larger program :</p>
<pre><code>#include <fstream>
#include <random>
#include <iostream>
using namespace std ;
int main()
{
mt19937_64 Generator(12187) ;
mt19937_64 Generator2(12187) ;
uniform_int_distribution<int> D1(1,6) ;
cout << D1(Generator) << " " ;
cout << D1(Generator) << " " << D1(Generator) << endl ;
cout << D1(Generator2) << " " << D1(Generator2) << " " << D1(Generator2) << endl ;
ofstream g1("g1.dat") ;
g1 << Generator ;
g1.close() ;
ofstream g2("g2.dat") ;
g2 << Generator2 ;
g2.close() ;
}
</code></pre>
<p>The two generators are seeded with the same value, and therefore I expected the second row in the output to be identical to the first one. Instead, the output is</p>
<pre><code>1 1 3
1 3 1
</code></pre>
<p>The state of the two generators as printed in the <code>*.dat</code> files is the same. I was wondering if there might be some hidden multi-threading in the random number generation causing the order mismatch.</p>
<p>I compiled with <code>g++</code> version 5.3.0, on Linux, with the flag <code>-std=c++11</code>.</p>
<p>Thanks in advance for your help.</p> | 35,060,325 | 4 | 5 | null | 2016-01-28 11:21:21.94 UTC | 1 | 2016-01-28 21:57:35.62 UTC | 2016-01-28 11:32:24.393 UTC | null | 2,684,539 | null | 5,204,967 | null | 1 | 39 | c++|c++11|random|operator-precedence | 2,648 | <p><code>x << y</code> is syntactic sugar for a function call to <code>operator<<(x, y)</code>.</p>
<p>You will remember that the c++ standard places no restriction on the order of evaluation of the arguments of a function call.</p>
<p>So the compiler is free to emit code that computes x first or y first.</p>
<p>From the standard: §5 note 2:</p>
<blockquote>
<p>Operators can be overloaded, that is, given meaning when applied to expressions of class type (Clause
9) or enumeration type (7.2). <strong>Uses of overloaded operators are transformed into function calls as described
in 13.5</strong>. Overloaded operators obey the rules for syntax specified in Clause 5, but the requirements of
operand type, value category, <strong>and evaluation order are replaced by the rules for function call</strong>.</p>
</blockquote> |
655,163 | Convert a Static Library to a Shared Library? | <p>I have a third-party library which consists mainly of a large number of static (<code>.a</code>) library files. I can compile this into a single <code>.a</code> library file, but I really need it to be a single <code>.so</code> shared library file.</p>
<p>Is there any way to convert a static <code>.a</code> file into a shared <code>.so</code> file? Or more generally is there a good way to combine a huge number of static <code>.a</code> files with a few <code>.o</code> object files into a single <code>.so</code> file?</p> | 655,175 | 5 | 0 | null | 2009-03-17 17:06:15.2 UTC | 33 | 2019-02-18 15:19:19.827 UTC | 2012-04-06 05:30:24.717 UTC | user166390 | null | Eli Courtwright | 1,694 | null | 1 | 66 | c|linux|shared-libraries|static-libraries | 64,736 | <p>Does this (with appropriate -L's of course)</p>
<pre><code>gcc -shared -o megalib.so foo.o bar.o -la_static_lib -lb_static_lib
</code></pre>
<p>Not do it?</p> |
909,673 | How do I use gems with Ubuntu? | <p>I recently upgraded to Ubuntu 9.04 and I have issues using gems.
I installed Ruby, Rubygems and Rails using apt-get.
The <code>rails</code> command does work.</p>
<p>I then installed capistrano and other gems, such as heroku.
In order to do that, I used the command:</p>
<pre><code>sudo gem install XXX
</code></pre>
<p>When I want to use the <code>cap</code> command it does not work:</p>
<pre><code>bash: cap: command not found
</code></pre>
<p>It is the same with the other gem commands.</p>
<p>Do I have something particular to do so that the gem commands work?</p> | 909,980 | 5 | 2 | null | 2009-05-26 08:55:22.733 UTC | 52 | 2013-04-02 11:36:20.517 UTC | 2012-02-04 00:52:47.733 UTC | null | 128,421 | null | 109,525 | null | 1 | 77 | ruby-on-rails|ruby|ubuntu|rubygems|capistrano | 62,817 | <h2>Where are my Gems?</h2>
<p>You can find where your gems are stored using the <code>gem environment</code> command. For example:</p>
<pre><code>chris@chris-laptop:~$ gem environment
RubyGems Environment:
- RUBYGEMS VERSION: 1.3.2
- RUBY VERSION: 1.8.7 (2008-08-11 patchlevel 72) [i486-linux]
- INSTALLATION DIRECTORY: /usr/lib/ruby/gems/1.8
- RUBY EXECUTABLE: /usr/bin/ruby1.8
- EXECUTABLE DIRECTORY: /usr/bin
- RUBYGEMS PLATFORMS:
- ruby
- x86-linux
- GEM PATHS:
- /usr/lib/ruby/gems/1.8
- /home/chris/.gem/ruby/1.8
- GEM CONFIGURATION:
- :update_sources => true
- :verbose => true
- :benchmark => false
- :backtrace => false
- :bulk_threshold => 1000
- REMOTE SOURCES:
</code></pre>
<p>If you look at the "GEM PATHS:" section you can see that gems can be stored in two places on my laptop: <code>/usr/lib/ruby/gems/1.8</code> or in the <code>.gem</code> directory in my home dir.</p>
<p>You can also see that executables are stored in EXECUTABLE DIRECTORY which in this case is <code>/usr/bin</code>.</p>
<p>Because <code>/usr/bin</code> is in my path this lets me run <code>cap</code>, <code>merb</code>, <code>rails</code> etc.</p>
<h3>Updating your PATH</h3>
<p>If for some reason your EXECUTABLE DIRECTORY isn't on your path (for example if it is /var/lib/gems/1.8/bin) then you need to update your PATH variable.</p>
<p>Assuming that you are using the bash shell. You can do this quickly for the current session by typing the following at the shell prompt; let's pretend that you want to add <code>/var/lib/gems/1.8/bin</code> to the path:</p>
<pre><code>export PATH=$PATH:/var/lib/gems/1.8/bin
</code></pre>
<p>and press return. That appends the new directory to the end of the current path. Note the colon between <code>$PATH</code> and <code>/var/lib/gems/1.8/bin</code></p>
<p>To set the value for all sessions you will need to edit either your <code>.profile</code> or <code>.bashrc</code> file and add the same line to the end of the file. I usually edit my <code>.bashrc</code> file for no reason other than that's what I've always done. When finished, save the file and then refresh your environment by typing:</p>
<pre><code>bash
</code></pre>
<p>at the shell prompt. That will cause the <code>.bashrc</code> to get reread. </p>
<p>At any point you can check the current value of <code>$PATH</code> by typing</p>
<pre><code>echo $PATH
</code></pre>
<p>at the shell prompt. </p>
<p>Here's a sample from one of my own servers, where my username is "chris" and the machine name is "chris-laptop":</p>
<pre><code>chris@chris-laptop:~$
chris@chris-laptop:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
chris@chris-laptop:~$
chris@chris-laptop:~$ export PATH=$PATH:/var/lib/gems/1.8/bin
chris@chris-laptop:~$
chris@chris-laptop:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/var/lib/gems/1.8/bin
chris@chris-laptop:~$
</code></pre>
<h2>My Gem won't load!</h2>
<p>"<a href="https://stackoverflow.com/questions/3792080/ruby-gems-wont-load-even-though-installed/3793059#3793059">Ruby gems won't load even though installed</a>" highlights a common problem using multiple different versions of Ruby; Sometimes the Gem environment and Gem path get out of sync:</p>
<pre><code>rb(main):003:0> Gem.path
=> ["/opt/ruby1.9/lib/ruby1.9/gems/1.9.1"]
irb(main):004:0> exit
</code></pre>
<p>Any Ruby process here is looking only in one place for its Gems. </p>
<pre><code>:~/$ gem env
RubyGems Environment:
- RUBYGEMS VERSION: 1.3.7
- RUBY VERSION: 1.9.1 (2009-05-12 patchlevel 129) [x86_64-linux]
- INSTALLATION DIRECTORY: /opt/ruby1.9/lib/ruby/gems/1.9.1
- RUBY EXECUTABLE: /opt/ruby1.9/bin/ruby1.9
- EXECUTABLE DIRECTORY: /opt/ruby1.9/bin
- RUBYGEMS PLATFORMS:
- ruby
- x86_64-linux
- GEM PATHS:
- /opt/ruby1.9/lib/ruby/gems/1.9.1
- /home/mark/.gem/ruby/1.9.1
- GEM CONFIGURATION:
- :update_sources => true
- :verbose => true
- :benchmark => false
- :backtrace => false
- :bulk_threshold => 1000
- REMOTE SOURCES:
- http://rubygems.org/
</code></pre>
<p>Look carefully at the output of gem environment:</p>
<pre><code> - GEM PATHS:
- /opt/ruby1.9/lib/ruby/gems/1.9.1
</code></pre>
<p>This isn't the same path as returned by Gem.path:</p>
<pre><code>["/opt/ruby1.9/lib/ruby1.9/gems/1.9.1"]
</code></pre>
<p>It's hard to say what exactly caused <code>lib/ruby</code> to change to <code>lib/ruby1.9</code> but most likely the developer was working with multiple Ruby versions. A quick <code>mv</code> or <code>ln</code> will solve the problem.</p>
<p>If you do need to work with multiple Ruby versions then you really should be using <a href="http://rvm.beginrescueend.com/" rel="nofollow noreferrer">rvm</a>.</p> |
445,067 | If vs. Switch Speed | <p>Switch statements are typically faster than equivalent if-else-if statements (as e.g. descibed in this <a href="http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx" rel="noreferrer">article</a>) due to compiler optimizations.</p>
<p>How does this optimization actually work? Does anyone have a good explanation?</p> | 445,076 | 5 | 2 | null | 2009-01-14 23:13:28.29 UTC | 26 | 2019-03-03 07:30:06.59 UTC | null | null | null | divo | 40,347 | null | 1 | 114 | c#|performance|switch-statement|if-statement | 72,518 | <p>The compiler can build jump tables where applicable. For example, when you use the reflector to look at the code produced, you will see that for huge switches on strings, the compiler will actually generate code that uses a hash table to dispatch these. The hash table uses the strings as keys and delegates to the <code>case</code> codes as values.</p>
<p>This has asymptotic better runtime than lots of chained <code>if</code> tests and is actually faster even for relatively few strings.</p> |
514,771 | Equivalent of ctrl c in command to cancel a program | <p>I am running a long linux program in a remote machine, and I want to stop it, but my problem is that if I use the kill command then the program will exit without saving results. Normally what I do to finish the program is use <kbd>Ctrl</kbd>+<kbd>C</kbd> and in that case the program saves the results, but right now I am not in the machine that is running the session so I cannot press <kbd>Ctrl</kbd>+<kbd>C</kbd>.</p>
<p>My question is: is there any way to do in a remote way the equivalent of <kbd>Ctrl</kbd>+<kbd>C</kbd>?</p> | 514,801 | 6 | 0 | null | 2009-02-05 06:14:16.36 UTC | 12 | 2020-01-31 19:24:25.637 UTC | 2020-01-31 19:24:25.637 UTC | Eduardo | 7,487,335 | Eduardo | 39,160 | null | 1 | 79 | linux|command-line|copy-paste | 90,817 | <p>Try:</p>
<pre><code>kill -SIGINT processPIDHere
</code></pre>
<p>Basically <kbd>Ctrl C</kbd> sends the <code>SIGINT</code> (interrupt) signal while kill sends the <code>SIGTERM</code> (termination) signal by default unless you specify the signal to send.</p> |
894,779 | ASP.NET MVC Routing Via Method Attributes | <p>In the <a href="https://blog.stackoverflow.com/2009/05/podcast-54/">StackOverflow Podcast #54</a>, Jeff mentions they register their URL routes in the StackOverflow codebase via an attribute above the method that handles the route. Sounds like a good concept (with the caveat that Phil Haack brought up regarding route priorities).</p>
<p>Could someone provide some sample to make this happen?</p>
<p>Also, any "best practices" for using this style of routing?</p> | 895,176 | 6 | 0 | null | 2009-05-21 19:50:01.02 UTC | 85 | 2012-04-16 06:12:35.153 UTC | 2021-01-18 12:38:11.483 UTC | null | -1 | null | 44,318 | null | 1 | 80 | asp.net-mvc|routing|url-routing|decorator | 25,859 | <p><strong><em>UPDATE</em></strong>: This has been posted on <a href="http://itcloud.codeplex.com" rel="noreferrer">codeplex</a>. The complete source code as well as the pre-compiled assembly are there for download. I haven't had time to post the documentation on the site yet, so this SO post will have to suffice for now.</p>
<p><strong><em>UPDATE</strong>: I added some new attributes to handle 1) route ordering, 2) route parameter constraints, and 3) route parameter default values. The text below reflects this update.</em></p>
<p>I've actually done something like this for my MVC projects (I have no idea how Jeff is doing it with stackoverflow). I defined a set of custom attributes: UrlRoute, UrlRouteParameterConstraint, UrlRouteParameterDefault. They can be attached to MVC controller action methods to cause routes, constraints, and defaults to be bound to them automatically.</p>
<p><strong>Example usage:</strong></p>
<p>(Note this example is somewhat contrived but it demonstrates the feature)</p>
<pre><code>public class UsersController : Controller
{
// Simple path.
// Note you can have multiple UrlRoute attributes affixed to same method.
[UrlRoute(Path = "users")]
public ActionResult Index()
{
return View();
}
// Path with parameter plus constraint on parameter.
// You can have multiple constraints.
[UrlRoute(Path = "users/{userId}")]
[UrlRouteParameterConstraint(Name = "userId", Regex = @"\d+")]
public ActionResult UserProfile(int userId)
{
// ...code omitted
return View();
}
// Path with Order specified, to ensure it is added before the previous
// route. Without this, the "users/admin" URL may match the previous
// route before this route is even evaluated.
[UrlRoute(Path = "users/admin", Order = -10)]
public ActionResult AdminProfile()
{
// ...code omitted
return View();
}
// Path with multiple parameters and default value for the last
// parameter if its not specified.
[UrlRoute(Path = "users/{userId}/posts/{dateRange}")]
[UrlRouteParameterConstraint(Name = "userId", Regex = @"\d+")]
[UrlRouteParameterDefault(Name = "dateRange", Value = "all")]
public ActionResult UserPostsByTag(int userId, string dateRange)
{
// ...code omitted
return View();
}
</code></pre>
<p><strong>Definition of UrlRouteAttribute:</strong></p>
<pre><code>/// <summary>
/// Assigns a URL route to an MVC Controller class method.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class UrlRouteAttribute : Attribute
{
/// <summary>
/// Optional name of the route. If not specified, the route name will
/// be set to [controller name].[action name].
/// </summary>
public string Name { get; set; }
/// <summary>
/// Path of the URL route. This is relative to the root of the web site.
/// Do not append a "/" prefix. Specify empty string for the root page.
/// </summary>
public string Path { get; set; }
/// <summary>
/// Optional order in which to add the route (default is 0). Routes
/// with lower order values will be added before those with higher.
/// Routes that have the same order value will be added in undefined
/// order with respect to each other.
/// </summary>
public int Order { get; set; }
}
</code></pre>
<p><strong>Definition of UrlRouteParameterConstraintAttribute:</strong></p>
<pre><code>/// <summary>
/// Assigns a constraint to a route parameter in a UrlRouteAttribute.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class UrlRouteParameterConstraintAttribute : Attribute
{
/// <summary>
/// Name of the route parameter on which to apply the constraint.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Regular expression constraint to test on the route parameter value
/// in the URL.
/// </summary>
public string Regex { get; set; }
}
</code></pre>
<p><strong>Definition of UrlRouteParameterDefaultAttribute:</strong></p>
<pre><code>/// <summary>
/// Assigns a default value to a route parameter in a UrlRouteAttribute
/// if not specified in the URL.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class UrlRouteParameterDefaultAttribute : Attribute
{
/// <summary>
/// Name of the route parameter for which to supply the default value.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Default value to set on the route parameter if not specified in the URL.
/// </summary>
public object Value { get; set; }
}
</code></pre>
<p><strong>Changes to Global.asax.cs:</strong></p>
<p>Replace calls to MapRoute, with a single call to the RouteUtility.RegisterUrlRoutesFromAttributes function:</p>
<pre><code> public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteUtility.RegisterUrlRoutesFromAttributes(routes);
}
</code></pre>
<p><strong>Definition of RouteUtility.RegisterUrlRoutesFromAttributes:</strong></p>
<p>The full source is up on <a href="http://itcloud.codeplex.com" rel="noreferrer">codeplex</a>. Please go to the site if you have any feedback or bug reports.</p> |
31,063,474 | Nodejs library without nodejs | <p>How can I integrate a nodejs library into my non nodejs project?
I am particularly needing this library:
<a href="https://github.com/greenify/biojs-io-blast">https://github.com/greenify/biojs-io-blast</a></p> | 31,075,281 | 5 | 3 | null | 2015-06-26 01:29:34.21 UTC | null | 2016-11-25 20:46:44.667 UTC | 2015-06-26 15:16:05.31 UTC | null | 1,259,510 | null | 2,058,333 | null | 1 | 29 | javascript|node.js | 3,891 | <p><a href="http://biojs.io/">BioJS</a> uses <a href="https://wzrd.in/">Browserify CDN</a> to automatically generate a single JS file for usage. Either include </p>
<p><code><script src="http://wzrd.in/bundle/biojs-io-blast@latest"></script></code> </p>
<p>in your html or download the JS file via this link. </p>
<p>We also have a live JS Bin example <a href="http://jsbin.com/fufaxezawa/edit?js,console">here</a>.</p> |
35,471,261 | Using CefSharp.Offscreen to retrieve a web page that requires Javascript to render | <p>I have what is hopefully a simple task, but it's going to take someone that's versed in CefSharp to solve it.</p>
<p>I have an url that I want to retrieve the HTML from. The problem is this particular url doesn't actually distribute the page on a GET. Instead, it pushes a mound of Javascript to the browser, which then executes and produces the actual rendered page. This means that the usual approaches involving <code>HttpWebRequest</code> and <code>HttpWebResponse</code> aren't going to work.</p>
<p>I've looked at a number of different "headless" options, and the one that I <em>think</em> best meets my needs for a number of reasons is CefSharp.Offscreen. But I'm at a loss as to how this thing works. I see that there are several events that can be subscribed to, and some configuration options, but I don't need anything like an embedded browser.</p>
<p>All I really need is a way to do something like this (pseudocode):</p>
<pre><code>string html = CefSharp.Get(url);
</code></pre>
<p>I don't have a problem subscribing to events, if that's what's needed to wait for the Javascript to execute and produce the rendered page.</p> | 35,472,369 | 2 | 3 | null | 2016-02-18 01:45:39.767 UTC | 8 | 2019-08-30 12:47:38.977 UTC | 2016-02-18 01:56:19.61 UTC | null | 102,937 | null | 102,937 | null | 1 | 7 | javascript|c#|cefsharp|headless-browser|cefsharp.offscreen | 20,313 | <p>If you can't get a headless version of Chromium to help you, you could try node.js and <a href="https://github.com/tmpvar/jsdom" rel="nofollow noreferrer">jsdom</a>. Easy to install and play with once you have node up and running. You can see simple examples on Github README where they pull down a URL, run all javascript, including any custom javascript code (example: jQuery bits to count some type of elements), and then you have the HTML in memory to do what you want. You can just do $('body').html() and get a string, like in your pseudo code. (This even works for stuff like generating SVG graphics since that is just more XML tree nodes.)</p>
<p>If you need this as part of a larger C# app that you need to distribute, your idea to use CefSharp.Offscreen sounds reasonable. One approach might be to get things working with CefSharp.WinForms or CefSharp.WPF first, where you can literally see things, then try CefSharp.Offscreen later when this all works. You can even get some JavaScript running in the on-screen browser to pull down body.innerHTML and return it as a string to the C# side of things before you go headless. If that works, the rest should be easy.</p>
<p>Perhaps start with <a href="https://github.com/cefsharp/CefSharp.MinimalExample" rel="nofollow noreferrer">CefSharp.MinimalExample</a> and get that compiling, then tweak it for your needs. You need to be able to set webBrowser.Address in your C# code, and you need to know when the page has Loaded, then you need to call webBrowser.EvaluateScriptAsync(".. JS code ..") with your JavaScript code (as a string) which will do something as described (returning bodyElement.innerHTML as a string).</p> |
20,936,486 | Node.js - Maximum call stack size exceeded | <p>When I run my code, Node.js throws a <code>"RangeError: Maximum call stack size exceeded"</code> exception caused by too many recursive calls. I tried to increase Node.js stack size by <code>sudo node --stack-size=16000 app</code>, but Node.js crashes without any error message. When I run this again without sudo, then Node.js prints <code>'Segmentation fault: 11'</code>. Is there a possibility to solve this without removing my recursive calls?</p> | 20,999,077 | 11 | 5 | null | 2014-01-05 17:08:47.61 UTC | 43 | 2022-08-25 10:57:48.823 UTC | 2019-09-29 16:34:17.417 UTC | null | 1,709,587 | null | 1,518,183 | null | 1 | 99 | node.js|recursion|stack-overflow|callstack | 195,248 | <p>You should wrap your recursive function call into a </p>
<ul>
<li><code>setTimeout</code>,</li>
<li><code>setImmediate</code> or </li>
<li><code>process.nextTick</code> </li>
</ul>
<p>function to give node.js the chance to clear the stack. If you don't do that and there are many loops without any <strong>real</strong> async function call or if you do not wait for the callback, your <code>RangeError: Maximum call stack size exceeded</code> will be <em>inevitable</em>.</p>
<p>There are many articles concerning "Potential Async Loop". <a href="https://blog.jcoglan.com/2010/08/30/the-potentially-asynchronous-loop/">Here is one</a>. </p>
<p>Now some more example code:</p>
<pre><code>// ANTI-PATTERN
// THIS WILL CRASH
var condition = false, // potential means "maybe never"
max = 1000000;
function potAsyncLoop( i, resume ) {
if( i < max ) {
if( condition ) {
someAsyncFunc( function( err, result ) {
potAsyncLoop( i+1, callback );
});
} else {
// this will crash after some rounds with
// "stack exceed", because control is never given back
// to the browser
// -> no GC and browser "dead" ... "VERY BAD"
potAsyncLoop( i+1, resume );
}
} else {
resume();
}
}
potAsyncLoop( 0, function() {
// code after the loop
...
});
</code></pre>
<p>This is right:</p>
<pre><code>var condition = false, // potential means "maybe never"
max = 1000000;
function potAsyncLoop( i, resume ) {
if( i < max ) {
if( condition ) {
someAsyncFunc( function( err, result ) {
potAsyncLoop( i+1, callback );
});
} else {
// Now the browser gets the chance to clear the stack
// after every round by getting the control back.
// Afterwards the loop continues
setTimeout( function() {
potAsyncLoop( i+1, resume );
}, 0 );
}
} else {
resume();
}
}
potAsyncLoop( 0, function() {
// code after the loop
...
});
</code></pre>
<p>Now your loop may become too slow, because we loose a little time (one browser roundtrip) per round. But you do not have to call <code>setTimeout</code> in every round. Normally it is o.k. to do it every 1000th time. But this may differ depending on your stack size:</p>
<pre><code>var condition = false, // potential means "maybe never"
max = 1000000;
function potAsyncLoop( i, resume ) {
if( i < max ) {
if( condition ) {
someAsyncFunc( function( err, result ) {
potAsyncLoop( i+1, callback );
});
} else {
if( i % 1000 === 0 ) {
setTimeout( function() {
potAsyncLoop( i+1, resume );
}, 0 );
} else {
potAsyncLoop( i+1, resume );
}
}
} else {
resume();
}
}
potAsyncLoop( 0, function() {
// code after the loop
...
});
</code></pre> |
44,274,982 | Spring Boot Application - what is default timeout for any rest API endpoint or a easy config to control all endpoint timeout | <p>I am using current Spring boot version (1.4.x) and wondering if it has any default timeout for api calls. I have tested it by putting breakpoints but it was keep waiting and didn't time-out.
I was also trying to configure default timeout for all my spring-boot apps by using some annotation or yml settings. </p>
<p>I found couple of alternatives (one of them <a href="https://stackoverflow.com/questions/34852236/spring-boot-rest-api-request-timeout">here</a>) but using callable actually adding extra non-business logic code where setting something in xml bean is out of fashion in latest spring boot applications.</p> | 44,916,759 | 5 | 2 | null | 2017-05-31 03:08:28.337 UTC | 8 | 2021-03-18 07:36:45.19 UTC | null | null | null | null | 3,705,491 | null | 1 | 14 | java|spring|rest|spring-boot|microservices | 88,648 | <p>I agree all above options and tried below option in my spring boot application. It works perfectly fine now. Below is the code sample as a bean. Now just need to <code>@Autowire</code> <code>RestTemplate</code> wherever(<code>java class</code>) I need it. </p>
<pre><code> @Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setConnectTimeout(15000);
((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setReadTimeout(15000);
return restTemplate;
}
</code></pre> |
2,263,186 | In which sequence are queries and sub-queries executed by the SQL engine? | <p>Hello I made a SQL test and dubious/curious about one question:</p>
<p><strong>In which sequence are queries and sub-queries executed by the SQL engine?</strong></p>
<p>the answers was</p>
<ol>
<li>primary query -> sub query -> sub sub query and so on</li>
<li>sub sub query -> sub query -> prime query</li>
<li>the whole query is interpreted at one time</li>
<li>There is no fixed sequence of interpretation, the query parser takes a decision on fly</li>
</ol>
<p>I choosed the last answer (just supposing that it is most reliable w.r.t. others).
Now the curiosity: </p>
<p><strong>where can i read about this and briefly what is the mechanism under all of that?</strong></p>
<p>Thank you.</p> | 2,264,085 | 5 | 0 | null | 2010-02-14 22:52:57.677 UTC | 9 | 2010-02-15 09:37:45.97 UTC | null | null | null | null | 273,141 | null | 1 | 38 | sql|subquery | 47,100 | <p>Option 4 is close.</p>
<p>SQL is <a href="http://en.wikipedia.org/wiki/Declarative_programming" rel="noreferrer">declarative</a>: you tell the query optimiser what you want and it works out the best (subject to time/"cost" etc) way of doing it. This may vary for outwardly identical queries and tables depending on statistics, data distribution, row counts, parallelism and god knows what else.</p>
<p>This means there is no fixed order. But it's not quite "on the fly"</p>
<p>Even with identical servers, schema, queries, and data I've seen execution plans differ</p> |
1,425,912 | Google Protocol Buffers and HTTP | <p>I'm refactoring legacy C++ system to SOA using gSoap. We have some performance issues (very big XMLs) so my lead asked me to take a look at protocol buffers. I did, and it looks very cool (We need C++ and Java support). However protocol buffers are solution just for serialization and now I need to send it to Java front-end. What should I use from C++ and Java perspective to send those serialized stuff over HTTP (just internal network)?</p>
<p>PS. Another guy tries to speed-up our gSoap solution, I'm interested in protocol buffers only.</p> | 1,425,984 | 5 | 4 | null | 2009-09-15 08:38:01.613 UTC | 26 | 2017-09-13 13:26:36.48 UTC | 2016-03-06 15:20:16.163 UTC | null | 3,579 | null | 3,579 | null | 1 | 45 | java|c++|http|protocol-buffers | 68,272 | <p>You can certainly send even a binary payload with an HTTP request, or in an HTTP response. Just write the bytes of the protocol buffer directly into the request/response, and make sure to set the content type to "application/octet-stream". The client, and server, should be able to take care of the rest easily. I don't think you need anything more special than that on either end. </p> |
1,418,015 | How to get Python exception text | <p>I want to embed python in my C++ application. I'm using Boost library - great tool. But i have one problem. </p>
<p>If python function throws an exception, i want to catch it and print error in my application or get some detailed information like line number in python script that caused error.</p>
<p>How can i do it? I can't find any functions to get detailed exception information in Python API or Boost.</p>
<pre><code>try {
module=import("MyModule"); //this line will throw excetion if MyModule contains an error
} catch ( error_already_set const & ) {
//Here i can said that i have error, but i cant determine what caused an error
std::cout << "error!" << std::endl;
}
</code></pre>
<p>PyErr_Print() just prints error text to stderr and clears error so it can't be solution</p> | 1,418,703 | 5 | 0 | null | 2009-09-13 15:36:30.173 UTC | 14 | 2021-09-27 17:07:58.163 UTC | 2009-09-13 18:11:56.193 UTC | null | 157,267 | null | 157,267 | null | 1 | 52 | c++|python|exception|boost-python | 21,715 | <p>Well, I found out how to do it.</p>
<p>Without boost (only error message, because code to extract info from traceback is too heavy to post it here):</p>
<pre><code>PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
//pvalue contains error message
//ptraceback contains stack snapshot and many other information
//(see python traceback structure)
//Get error message
char *pStrErrorMessage = PyString_AsString(pvalue);
</code></pre>
<p>And BOOST version</p>
<pre><code>try{
//some code that throws an error
}catch(error_already_set &){
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
handle<> hType(ptype);
object extype(hType);
handle<> hTraceback(ptraceback);
object traceback(hTraceback);
//Extract error message
string strErrorMessage = extract<string>(pvalue);
//Extract line number (top entry of call stack)
// if you want to extract another levels of call stack
// also process traceback.attr("tb_next") recurently
long lineno = extract<long> (traceback.attr("tb_lineno"));
string filename = extract<string>(traceback.attr("tb_frame").attr("f_code").attr("co_filename"));
string funcname = extract<string>(traceback.attr("tb_frame").attr("f_code").attr("co_name"));
... //cleanup here
</code></pre> |
2,219,714 | SQL Server tables: what is the difference between @, # and ##? | <p>In SQL Server, what is the difference between a @ table, a # table and a ## table?</p> | 2,219,731 | 6 | 0 | null | 2010-02-08 05:13:24.92 UTC | 21 | 2019-06-21 07:49:38.183 UTC | null | null | null | null | 226,235 | null | 1 | 99 | sql-server | 140,270 | <p><code>#table</code> refers to a local (visible to only the user who created it) temporary table.</p>
<p><code>##table</code> refers to a global (visible to all users) temporary table.</p>
<p><code>@variableName</code> refers to a variable which can hold values depending on its type.</p> |
2,158,759 | Case vs If Else If: Which is more efficient? | <blockquote>
<p><strong>Possible Duplicates:</strong><br>
<a href="https://stackoverflow.com/questions/767821/is-else-if-faster-than-switch-case">is “else if” faster than “switch() case” ?</a><br>
<a href="https://stackoverflow.com/questions/2086529/what-is-the-relative-performance-of-if-else-vs-switch-in-java">What is the relative performance of if/else vs. switch in Java?</a> </p>
</blockquote>
<p>Ive been coding-in-the-run again....when the debugger steps through a case statement it jumps to the item that matches the conditions immediately, however when the same logic is specified using if/else it steps through every if statement until it finds the winner. Is the case statement more efficient, or is my debugger just optimizing the step through? (don't worry about the syntax/errors, i typed this in SO, don't know if it will compile, its the principle i'm after, I didn't want to do them as ints cause i vaguely remember something about case using an offset with ints) I use C#, but im interested in a general answer across programming languages.</p>
<pre><code>switch(myObject.GetType()){
case typeof(Car):
//do something
break;
case typeof(Bike):
//do something
break;
case typeof(Unicycle):
//do something
break;
case default:
break;
}
</code></pre>
<p><strong>VS</strong></p>
<pre><code> Type myType = myObject.GetType();
if (myType == typeof(Car)){
//do something
}
else if (myType == typeof(Bike)){
//do something
}
else if (myType == typeof(Unicycle)){
//do something
}
else{
}
</code></pre> | 2,158,792 | 7 | 8 | null | 2010-01-28 23:21:05.817 UTC | 17 | 2010-01-29 00:03:30.647 UTC | 2017-05-23 12:26:00.65 UTC | null | -1 | null | 100,652 | null | 1 | 65 | performance|switch-statement|if-statement | 216,524 | <p>It seems that the compiler is better in optimizing a switch-statement than an if-statement.</p>
<p>The compiler doesn't know if the order of evaluating the if-statements is important to you, and can't perform any optimizations there. You could be calling methods in the if-statements, influencing variables. With the switch-statement it knows that all clauses can be evaluated at the same time and can put them in whatever order is most efficient.</p>
<p>Here's a small comparison:<br>
<a href="http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx" rel="noreferrer">http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx</a></p> |
2,057,994 | Where can I learn about MEF? | <p>I watched the DNR TV episode with Glenn Block and it looks like MEF would be useful for my company. I am trying to find out more information on it's strengths and weaknesses and some sample projects that use it. Are there any good blogs/tutorials on using MEF?</p>
<p>Note: I use C#, so if the examples are in C#, that would be awesome.</p> | 2,058,024 | 7 | 0 | null | 2010-01-13 15:49:28.02 UTC | 44 | 2017-12-12 10:11:45.41 UTC | null | null | null | null | 93,431 | null | 1 | 67 | c#|.net|mef | 22,398 | <p>I haven't found a really comprehensive page, but there are a few:</p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/framework/mef/" rel="nofollow noreferrer">Microsoft Docs</a></p>
<p><a href="http://blogs.msdn.com/brada/archive/2009/07/20/simple-example-using-managed-extensibility-framework-in-silverlight.aspx" rel="nofollow noreferrer">Simple Example from a msdn blog</a></p>
<p><a href="http://www.codeproject.com/KB/library/mefpart1.aspx" rel="nofollow noreferrer">Code Project's Introduction to MEF (part 1)</a></p>
<p><a href="http://geekswithblogs.net/malisancube/archive/2009/05/26/managed-extensibility-framework-101---a.aspx" rel="nofollow noreferrer">MEF 101 part A from Geek with Blogs</a></p>
<p><a href="http://geekswithblogs.net/malisancube/archive/2009/06/09/managed-extensibility-framework-101-b.aspx" rel="nofollow noreferrer">MEF 101 part B</a></p>
<p><a href="http://blogs.msdn.com/kcwalina/archive/2008/04/25/MEF.aspx" rel="nofollow noreferrer">Another MSDN blog, a little more history than tutorial</a></p> |
2,215,458 | Getting started reverse-engineering OS X? | <p>What is a good place to learn reverse engineering, specifically as it applies to Mac OS X? Two apps that I admire in terms of this subject:</p>
<p>Hyperspaces – <a href="https://hyperspacesapp.com" rel="nofollow noreferrer">Link</a></p>
<p>and</p>
<p>Orbit – <a href="http://www.steventroughtonsmith.com/orbit/" rel="nofollow noreferrer">http://www.steventroughtonsmith.com/orbit/</a></p>
<p>Thanks guys.</p> | 2,227,810 | 8 | 7 | null | 2010-02-07 01:05:21.313 UTC | 15 | 2021-10-15 19:42:10.907 UTC | 2021-10-15 19:42:10.907 UTC | null | 4,751,173 | null | 264,843 | null | 1 | 14 | iphone|macos|operating-system|reverse-engineering | 7,080 | <p>Use <a href="http://iphone.freecoder.org/classdump_en.html" rel="nofollow noreferrer">class-dump-x</a>/<a href="http://code.google.com/p/networkpx/wiki/class_dump_z" rel="nofollow noreferrer">-z</a> to get the private Objective-C headers for OS X/iPhone OS system frameworks. There are a lot of classes/methods hidden from the public (some rightly so)</p> |
1,710,809 | When and why should the Strategy Pattern be used? | <p>When would the <a href="http://en.wikipedia.org/wiki/Strategy_pattern" rel="noreferrer">Strategy Pattern</a> be used?</p>
<p>I see client code snippets like this:</p>
<pre>
<code>
class StrategyExample {
public static void main(String[] args) {
Context context;
// Three contexts following different strategies
context = new Context(new ConcreteStrategyAdd());
int resultA = context.executeStrategy(3,4);
context = new Context(new ConcreteStrategySubtract());
int resultB = context.executeStrategy(3,4);
context = new Context(new ConcreteStrategyMultiply());
int resultC = context.executeStrategy(3,4);
}
}
</code>
</pre>
<p>and it looks like you could just refactor it to this:</p>
<pre>
<code>
class StrategyExample {
public static void main(String[] args) {
// Three contexts following different strategies
int resultA =new ConcreteStrategyAdd().execute(3,4);
int resultB =new ConcreteStrategySubtract().execute(3,4);
int resultC =new ConcreteStrategyMultiply().execute(3,4);
}
}
</code>
</pre>
<p>The first section of code was taken directly from the wikipedia page. One big difference is the context goes away, but it wasn't doing anything in the example anyway. Maybe someone has a better example where Strategy makes sense. I usually like design patterns but this one seems to add complexity without adding usefulness.</p> | 1,710,885 | 10 | 1 | null | 2009-11-10 20:04:45.237 UTC | 13 | 2019-09-14 18:22:03.067 UTC | 2009-11-10 20:31:04.05 UTC | null | 572 | null | 125,380 | null | 1 | 34 | design-patterns|strategy-pattern | 26,064 | <p>The problem with toy examples such as this is that it is often easy to miss the point. In this case, the code could indeed be just implemented as you have shown. In a strategy pattern, the main value is in being able to switch out different implementations for different situations.</p>
<p>The example you have is only illustrating the objects in the pattern and the interactions between them. Imagine instead that you had a component that renders graphs for a website depending on whether it was a desktop or a smartphone on the other end you would have some code that would detect the type of browser the create and set the strategy on another component that could use the strategy object in some complex code that would not need to be duplicated and would do the work in both situations leaving the details of the actual drawing of the graph to the appropriate strategy object:</p>
<pre><code>interface GraphStrategy {
Image renderGraph(Data graphData);
}
class BigGraphStrategy implements GraphStrategy {
...
}
class SmallGraphStrategy implements GraphStrategy {
...
}
</code></pre>
<p>Then in some other code:</p>
<pre><code>GraphStrategy graphStrategy;
if (phoneBrowser == true) {
graphStrategy = new SmallGraphStrategy();
} else {
graphStrategy = new BigGraphStrategy();
}
</code></pre>
<p>The rest of your application code can then just use <code>graphStrategy.renderGraph()</code> without having to know whether full or small image rendering is being performed.</p> |
1,896,503 | What are people using JScript.Net for? | <p>I'm interested to know who uses JScript.Net and for what sort of applications.
Whenever I'm reading MSDN .Net documentation, I always notice the JScript samples but in all the years I've been a C# dev I've never actually known anyone to use it.</p>
<p>What sort of applications are people using this for, and how does it measure, in terms of flexibility, power and general usage, to C#?</p>
<p>[<strong>Edit:</strong> Just to clarify - I'm not asking what JScript.Net <em>is</em>, I'm asking what people are actually using it for - i.e. interested to know actual usage scenarios and how people have found it to work with]</p> | 1,899,810 | 12 | 2 | null | 2009-12-13 13:25:10.1 UTC | 16 | 2017-02-15 23:05:01.85 UTC | 2009-12-15 09:49:00.763 UTC | null | 134,754 | null | 134,754 | null | 1 | 42 | .net|asp.net|jscript.net | 13,095 | <p>Rob - I have used JScript.NET in anger in one place in my code, which is essentially to expose the functionality of its eval method. Here is a cut-down version:</p>
<pre><code>static public class Evaluator
{
private const string _jscriptSource =
@"package Evaluator
{
class Evaluator
{
public function Eval(expr : String) : String
{
return eval(expr);
}
}
}";
static private object _evaluator;
static private Type _evaluatorType;
static Evaluator()
{
InstantiateInternalEvaluator();
}
static private void InstantiateInternalEvaluator()
{
JScriptCodeProvider compiler = new JScriptCodeProvider();
CompilerParameters parameters;
parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
CompilerResults results;
results = compiler.CompileAssemblyFromSource(parameters, _jscriptSource);
Assembly assembly = results.CompiledAssembly;
_evaluatorType = assembly.GetType("Evaluator.Evaluator");
_evaluator = Activator.CreateInstance(_evaluatorType);
}
static public object EvaluateToObject(string statement)
{
try
{
return _evaluatorType.InvokeMember(
"Eval",
BindingFlags.InvokeMethod,
null,
_evaluator,
new object[] {statement}
);
}
catch (Exception)
{
InstantiateInternalEvaluator();
return null;
}
}
</code></pre>
<p>You can obviously create overloads for other return types. I can't claim the original idea for this was mine! Uses for this would be, for example, to evaluate a string expression like <code>3 + 4</code> to <code>7</code> without expression parsing.</p> |
18,089,562 | How do I keep the delimiters when splitting a Ruby string? | <p>I have text like:</p>
<pre><code>content = "Do you like to code? How I love to code! I'm always coding."
</code></pre>
<p>I'm trying to split it on either a <code>?</code> or <code>.</code> or <code>!</code>:</p>
<pre><code>content.split(/[?.!]/)
</code></pre>
<p>When I print out the results, the punctuation delimiters are missing. </p>
<blockquote>
<p>Do you like to code</p>
<p>How I love to code</p>
<p>I'm always coding</p>
</blockquote>
<p>How can I keep the punctuation?</p> | 18,089,658 | 5 | 2 | null | 2013-08-06 20:12:28.103 UTC | 11 | 2015-12-20 02:50:41.777 UTC | 2015-12-20 02:50:41.777 UTC | null | 102,401 | null | 1,647,484 | null | 1 | 42 | ruby | 14,393 | <p><strong>Answer</strong></p>
<p>Use a positive lookbehind regular expression (i.e. <code>?<=</code>) inside a parenthesis capture group to keep the delimiter at the end of each string:</p>
<pre><code>content.split(/(?<=[?.!])/)
# Returns an array with:
# ["Do you like to code?", " How I love to code!", " I'm always coding."]
</code></pre>
<p>That leaves a white space at the start of the second and third strings. Add a match for zero or more white spaces (<code>\s*</code>) after the capture group to exclude it:</p>
<pre><code>content.split(/(?<=[?.!])\s*/)
# Returns an array with:
# ["Do you like to code?", "How I love to code!", "I'm always coding."]
</code></pre>
<hr>
<p><strong>Additional Notes</strong></p>
<p>While it doesn't make sense with your example, the delimiter can be shifted to the front of the strings starting with the second one. This is done with a positive lookahead regular expression (i.e. <code>?=</code>). For the sake of anyone looking for that technique, here's how to do that:</p>
<pre><code>content.split(/(?=[?.!])/)
# Returns an array with:
# ["Do you like to code", "? How I love to code", "! I'm always coding", "."]
</code></pre>
<p>A better example to illustrate the behavior is:</p>
<pre><code>content = "- the - quick brown - fox jumps"
content.split(/(?=-)/)
# Returns an array with:
# ["- the ", "- quick brown ", "- fox jumps"]
</code></pre>
<p>Notice that the square bracket capture group wasn't necessary since there is only one delimiter. Also, since the first match happens at the first character it ends up as the first item in the array.</p> |
44,667,434 | How to solve "Missing Marketing Icon. iOS Apps must include a 1024x1024px" | <p>I am uploading app in iTunes from Xcode 9.0...This error is showing on the last step. How to solve this? 1024x1024px icon is present in my icons list</p>
<p><a href="https://i.stack.imgur.com/aJdy7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aJdy7.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/Qniqq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Qniqq.png" alt="enter image description here"></a></p> | 44,691,659 | 9 | 6 | null | 2017-06-21 05:24:56.427 UTC | 8 | 2020-10-08 08:57:43.55 UTC | 2017-06-21 05:27:34.827 UTC | null | 1,025,063 | null | 4,970,453 | null | 1 | 67 | ios|xcode | 29,694 | <p>Now onwards we need to add a new icon in our project with the size 1024X1024. Please see below-attached image. This issue was stared from WWDC 2017.</p>
<p><a href="https://i.stack.imgur.com/ccaOa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ccaOa.png" alt="enter image description here"></a></p>
<p>Note: - Do not upload or use the beta version (mac os or Xcode) for app upload. As per Apple recommendation. I already got mail from Apple about this.</p> |
6,797,350 | ASP.NET MVC Cookie Implementation | <p>I try to implement a basic cookie helper in my application.
Mainly I check in base controller everytime whether or not if cookie is set.
If cookie </p>
<pre><code>public class MyCookie
{
public static string CookieName {get;set;}
public virtual User User { get; set; }
public virtual Application App { get; set; }
public MyCookie(Application app)
{
CookieName = "MyCookie" + app;
App = app;
}
public void SetCookie(User user)
{
HttpCookie myCookie = HttpContext.Current.Request.Cookies[CookieName] ?? new HttpCookie(CookieName);
myCookie.Values["UserId"] = user.UserId.ToString();
myCookie.Values["LastVisit"] = DateTime.Now.ToString();
myCookie.Expires = DateTime.Now.AddDays(365);
HttpContext.Current.Response.Cookies.Add(myCookie);
}
public HttpCookie GetCookie()
{
HttpCookie myCookie = HttpContext.Current.Request.Cookies[CookieName];
if(myCookie != null)
{
int userId = Convert.ToInt32(myCookie.Values["UserId"]);
User user = session.Get<User>(userId);
return user;
}
return null;
}
}
</code></pre>
<p>if session is null I try to get from cookie or if session initialize I set cookie but I never see my cookie in browser. What is wrong?</p>
<p>I always start session but with userId=0
To get cookie and set session from cookie:</p>
<pre><code>if (userId == 0)
{
MyCookie myCookie = new MyCookie(_app);
User user = cookieHelper.GetCookie();
if (user != null)
SessionHelper.SetSession(user);
}
</code></pre> | 6,878,527 | 3 | 3 | null | 2011-07-23 00:10:28.483 UTC | 11 | 2017-07-04 08:33:47.45 UTC | 2012-04-11 11:47:19.963 UTC | null | 568,415 | null | 568,415 | null | 1 | 19 | c#|asp.net|asp.net-mvc|httpcookie | 74,673 | <p>My Working Implementation (Basic Version)</p>
<pre><code>public class CookieHelper
{
public static string CookieName {get;set;}
public virtual Application App { get; set; }
public MyCookie(Application app)
{
CookieName = "MyCookie" + app;
}
public static void SetCookie(User user, Community community, int cookieExpireDate = 30)
{
HttpCookie myCookie= new HttpCookie(CookieName);
myCookie["UserId"] = user.UserId.ToString();
myCookie.Expires = DateTime.Now.AddDays(cookieExpireDate);
HttpContext.Current.Response.Cookies.Add(myCookie);
}
}
</code></pre>
<p>if session/cookie is null (actually userid=0)</p>
<pre><code>if (userId == 0){
CookieHelper myCookie = new Cookie(_app);
if (myCookie != null)
{
userId = Convert.ToInt32(System.Web.HttpContext.Current.Request.Cookies[myCookie.CookieName]["userId"]);
if(userId>0)
{
SessionHelper.SetSession(userId);
}
}
}
</code></pre> |
23,699,809 | Any API or Web UI project to manage a Docker private registry? | <p>I can't find how to manage images in a private registry. I can push or pull an image because i know the id but how to get the list of pushed images ? </p>
<p>Take for example a person who wants to see the available images under the private registry of his organization. How can she do ? </p>
<p>Unless I'm mistaken, I can't find API or Web UI to discover the registry content like the index.docker.io do with the public registry. </p>
<p>Are there any open source projects to manage this ?</p>
<p>thanks.</p> | 23,760,530 | 6 | 2 | null | 2014-05-16 16:03:12.513 UTC | 14 | 2018-01-19 10:04:40.24 UTC | 2015-01-08 01:50:26.95 UTC | null | 308,174 | null | 1,766,008 | null | 1 | 30 | docker|docker-registry | 30,087 | <p>Thanks Thomas !</p>
<p>To allow the use of the search API, you must start the container by specifying the value of the environment variable SEARCH_BACKEND like this :</p>
<pre><code>docker run -d -e SEARCH_BACKEND=sqlalchemy -p 5000:5000 --name registry samalba/docker-registry
</code></pre>
<p>Then i have a result for this query : </p>
<pre><code>GET http://registry_host:5000/v1/search?q=base
Result :
{
"num_results": 1,
"query": "base",
"results": [{"description": "", "name": "test/base-img"}]
}
</code></pre>
<p>To list all images, you can do this :</p>
<pre><code>GET http://registry_host:5000/v1/search
Result :
{
"num_results": 2,
"query": "",
"results": [
{"description": "", "name": "test/base-img"},
{"description": "", "name": "test/base-test"}]
}
</code></pre>
<p>And to know the available versions of an image : </p>
<pre><code>GET http://localhost:5000/v1/repositories/**test/base-img**/tags
Result :
{
"0.1": "04e073e1efd31f50011dcde9b9f4d3148ecc4da94c0b7ba9abfadef5a8522d13",
"0.2": "04e073e1efd31f50011dcde9b9f4d3148ecc4da94c0b7ba9abfadef5a8522d13",
"0.3": "04e073e1efd31f50011dcde9b9f4d3148ecc4da94c0b7ba9abfadef5a8522d13"
}
</code></pre> |
15,644,845 | postgres: localhost not connecting | <p>My <code>postgreSQL.conf</code> looks like</p>
<pre><code># - Connection Settings -
listen_addresses = '*' # what IP address(es) to listen on;
# comma-separated list of addresses;
# defaults to 'localhost', '*' = all
# (change requires restart)
port = 5432 # (change requires restart)
</code></pre>
<p>and I also know that postgres is running</p>
<pre><code>air:data postgres$ ps -aef | grep postgres
504 16474 16473 0 11:34AM ?? 0:00.00 postgres: logger process
504 16476 16473 0 11:34AM ?? 0:00.00 postgres: writer process
504 16477 16473 0 11:34AM ?? 0:00.00 postgres: wal writer process
504 16478 16473 0 11:34AM ?? 0:00.00 postgres: autovacuum launcher process
504 16479 16473 0 11:34AM ?? 0:00.00 postgres: stats collector process
0 16087 16078 0 10:54AM ttys001 0:00.03 su - postgres
504 16473 1 0 11:34AM ttys001 0:00.22 /Library/PostgreSQL/9.1/bin/postgres -D/Library/PostgreSQL/9.1/data
504 16484 16088 0 11:34AM ttys001 0:00.00 grep postgres
</code></pre>
<p>But I am not able to connect</p>
<pre><code> psql -Uuser -W
Password for user user:
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/pgsql_socket/.s.PGSQL.5432"?
</code></pre>
<p>Also, when I run the following</p>
<pre><code> lsof -i tcp:5432
✘ me@air11:37:13 ⮀ ~ ⮀ netstat -a | grep postgres
tcp6 0 0 *.postgres *.* LISTEN
tcp4 0 0 *.postgresql *.* LISTEN
</code></pre>
<p>It says nothing running on <code>port 5432</code>
What am I missing?</p>
<p><strong>UPDATE</strong></p>
<p>My <code>pg_hba.conf</code> looks like</p>
<pre><code># TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all md5
# IPv4 local connections:
host all all 127.0.0.1/32 md5
# IPv6 local connections:
host all all ::1/128 md5
</code></pre> | 15,645,670 | 4 | 2 | null | 2013-03-26 18:36:15.15 UTC | 2 | 2021-05-27 13:56:33.72 UTC | 2013-03-26 18:41:38.18 UTC | null | 379,235 | null | 379,235 | null | 1 | 6 | postgresql|postgresql-9.1 | 39,068 | <p>Not sure why this was happening, but I found <a href="http://postgresapp.com" rel="nofollow">postgresapp.com</a> which is pretty good to use</p>
<p>I am using this with <a href="http://www.pgadmin.org/" rel="nofollow">http://www.pgadmin.org/</a> and I am running it smoothly so far</p> |
15,585,216 | How to randomly generate numbers without repetition in javascript? | <p>I want to generate each number between 0 to 4 randomly using javascript and each number can appear only once. So I wrote the code:</p>
<pre><code>for(var l=0; l<5; l++) {
var randomNumber = Math.floor(Math.random()*5);
alert(randomNumber)
}
</code></pre>
<p>but this code is repeating the values. Please help.</p> | 15,585,372 | 12 | 1 | null | 2013-03-23 09:31:26.057 UTC | 3 | 2021-08-20 15:48:42.317 UTC | 2013-03-23 10:02:58.707 UTC | null | 949,476 | null | 2,149,532 | null | 1 | 10 | javascript|arrays|random|for-loop | 44,583 | <p>Generate a range of numbers:</p>
<pre><code>var numbers = [1, 2, 3, 4];
</code></pre>
<p>And then <a href="https://stackoverflow.com/a/6274381/464744">shuffle</a> it:</p>
<pre><code>function shuffle(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
var random = shuffle(numbers);
</code></pre> |
19,189,274 | Nested defaultdict of defaultdict | <p>Is there a way to make a defaultdict also be the default for the defaultdict? (i.e. infinite-level recursive defaultdict?)</p>
<p>I want to be able to do:</p>
<pre><code>x = defaultdict(...stuff...)
x[0][1][0]
{}
</code></pre>
<p>So, I can do <code>x = defaultdict(defaultdict)</code>, but that's only a second level:</p>
<pre><code>x[0]
{}
x[0][0]
KeyError: 0
</code></pre>
<p>There are recipes that can do this. But can it be done simply just using the normal defaultdict arguments?</p>
<p>Note this is asking how to do an infinite-level recursive defaultdict, so it's distinct to <em><a href="https://stackoverflow.com/questions/5029934">Python: defaultdict of defaultdict?</a></em>, which was how to do a two-level defaultdict.</p>
<p>I'll probably just end up using the <em>bunch</em> pattern, but when I realized I didn't know how to do this, it got me interested.</p> | 19,189,356 | 10 | 2 | null | 2013-10-04 19:28:50.147 UTC | 43 | 2021-12-22 10:07:09.06 UTC | 2019-01-13 20:06:48.427 UTC | null | 202,229 | null | 349,948 | null | 1 | 194 | python|recursion|defaultdict | 73,830 | <p>For an arbitrary number of levels:</p>
<pre><code>def rec_dd():
return defaultdict(rec_dd)
>>> x = rec_dd()
>>> x['a']['b']['c']['d']
defaultdict(<function rec_dd at 0x7f0dcef81500>, {})
>>> print json.dumps(x)
{"a": {"b": {"c": {"d": {}}}}}
</code></pre>
<p>Of course you could also do this with a lambda, but I find lambdas to be less readable. In any case it would look like this:</p>
<pre><code>rec_dd = lambda: defaultdict(rec_dd)
</code></pre> |
35,040,978 | Babel unexpected token import when running mocha tests | <p>The solutions offered in other related questions, such as including the proper presets (es2015) in .babelrc, are already implemented in my project.</p>
<p>I have two projects (lets call them A and B) which both use ES6 module syntax. In Project A, I'm importing Project B which is installed via npm and lives in the node_modules folder. When I run my test suite for Project A, I'm getting the error: </p>
<blockquote>
<p>SyntaxError: Unexpected token import</p>
</blockquote>
<p>Which is preceded by this alleged erroneous line of code from Project B:</p>
<blockquote>
<p>(function (exports, require, module, __filename, __dirname) { import
createBrowserHistory from 'history/lib/createBrowserHistory';</p>
</blockquote>
<p>The iife appears to be something npm or possibly babel related since my source file only contains "import createBrowserHistory from 'history/lib/createBrowserHistory'; The unit tests in Project B's test suite runs fine, and if I remove Project B as a dependency from Project A, my test suite then (still using es6 imports for internal project modules) works just fine.</p>
<p>Full Stack Trace:</p>
<pre><code> SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:374:25)
at Module._extensions..js (module.js:405:10)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:138:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (actionCreators.js:4:17)
at Module._compile (module.js:398:26)
at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapper.js:28:23)
at Module._compile (module.js:398:26)
at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/ProjectA/src/components/core/wrapper/wrapperSpec.js:15:16)
at Module._compile (module.js:398:26)
at loader (/ProjectA/node_modules/babel-register/lib/node.js:130:5)
at Object.require.extensions.(anonymous function) [as .js] (/ProjectA/node_modules/babel-register/lib/node.js:140:7)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at /ProjectA/node_modules/mocha/lib/mocha.js:219:27
at Array.forEach (native)
at Mocha.loadFiles (/ProjectA/node_modules/mocha/lib/mocha.js:216:14)
at Mocha.run (/ProjectA/node_modules/mocha/lib/mocha.js:468:10)
at Object.<anonymous> (/ProjectA/node_modules/mocha/bin/_mocha:403:18)
at Module._compile (module.js:398:26)
at Object.Module._extensions..js (module.js:405:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:430:10)
at startup (node.js:141:18)
at node.js:980:3
</code></pre>
<p>Here is my test command from package.json:</p>
<pre><code>"test": "mocha --compilers js:babel-core/register '+(test|src)/**/*Spec.js'"
</code></pre>
<p>This StackOverflow post is similar but doesn't offer a solution for my use of the command line:
<a href="https://stackoverflow.com/questions/31822593/import-a-module-from-node-modules-with-babel-but-failed">import a module from node_modules with babel but failed</a></p> | 35,045,012 | 17 | 6 | null | 2016-01-27 15:09:28.617 UTC | 17 | 2020-12-29 05:57:09.66 UTC | 2017-07-23 13:41:48.483 UTC | null | 3,885,376 | null | 324,243 | null | 1 | 97 | node.js|npm|syntax-error|mocha.js|babeljs | 83,010 | <p>It seems the only solution is to explicitly include: </p>
<pre><code>require('babel-core/register')({
ignore: /node_modules/(?!ProjectB)/
});
</code></pre>
<p>in a test helper file, and pass that along to mocha in my test command:</p>
<pre><code>mocha --require ./test/testHelper.js...
</code></pre>
<hr>
<p><strong>The final solution:</strong></p>
<p>Add <strong><em>registerBabel.js</em></strong>: a separate file whose job is to require babel-core/register...</p>
<pre><code>require('babel-core/register')({
ignore: /node_modules/(?!ProjectB)/
});
</code></pre>
<p>Add an <strong><em>entry.js</em></strong> if your application also relies on babel-node. This acts as a wrapper for your es6 containing application.</p>
<pre><code>require('./registerBabel');
require('./server'); // this file has some es6 imports
</code></pre>
<p>You would then run your application with <code>node entry</code></p>
<p>For mocha testing, <strong><em>testHelper.js</em></strong> should require registerBabel.js as well to initialize babel support at run time.</p>
<pre><code>require('./registerBabel');
</code></pre>
<p>And run your mocha tests with <code>mocha --require ./testHelper.js '+(test)/**/*Spec.js'</code></p>
<p>This will recursively test any file ending in "Spec.js" within "./test". Substitute the pattern with one matching the specs in your project.</p> |
40,306,280 | How to transpose a dataframe in tidyverse? | <p>Using basic R, I can transpose a dataframe, say <code>mtcars</code>, which has all columns of the same class:</p>
<pre><code>as.data.frame(t(mtcars))
</code></pre>
<p>Or with pipes:</p>
<pre><code>library(magrittr)
mtcars %>% t %>% as.data.frame
</code></pre>
<p>How to accomplish the same within tidyr or tidyverse packages?</p>
<p>My attempt below gives:</p>
<blockquote>
<p>Error: Duplicate identifiers for rows</p>
</blockquote>
<pre><code>library(tidyverse)
mtcars %>% gather(var, value, everything()) %>% spread(var, value)
</code></pre> | 40,307,807 | 2 | 4 | null | 2016-10-28 13:36:45.67 UTC | 12 | 2022-01-12 13:53:28.813 UTC | 2017-09-12 17:42:11.747 UTC | null | 2,204,410 | null | 2,947,090 | null | 1 | 32 | r|dataframe|transpose|tidyr|tidyverse | 49,221 | <p>Try with <code>add_rownames</code></p>
<pre><code>add_rownames(mtcars) %>%
gather(var, value, -rowname) %>%
spread(rowname, value)
</code></pre>
<p>In the newer version, <code>rownames_to_column</code> replaces <code>add_rownames</code></p>
<pre><code>mtcars %>%
rownames_to_column %>%
gather(var, value, -rowname) %>%
spread(rowname, value)
</code></pre>
<p>In the even newer version, <code>pivot_wider</code> replaces <code>spread</code>:</p>
<pre><code>mtcars %>%
tibble::rownames_to_column() %>%
pivot_longer(-rowname) %>%
pivot_wider(names_from=rowname, values_from=value)
</code></pre> |
40,096,470 | Get Webpack not to bundle files | <p>So right now I'm working with a prototype where we're using a combination between webpack (for building .tsx files and copying .html files) and webpack-dev-server for development serving. As you can assume we are also using React and ReactDOM as a couple of library dependencies as well. Our current build output is the following structure:</p>
<pre><code>dist
-favicon.ico
-index.html
-main.js
-main.js.map // for source-mapping between tsx / js files
</code></pre>
<p>This places ALL of the modules (including library dependencies into on big bundled file). I want the end result to look like this:</p>
<pre><code>dist
-favicon.ico
-index.html
-appName.js
-appName.min.js
-react.js
-react.min.js
-reactDOM.js
-reactDOM.min.js
</code></pre>
<p>I have references to each of the libraries in index.html and in import statements in the .tsx files. So my question is this...
How do I go from webpack producing this gigantic bundled .js file to individual .js files (libraries included, without having to specify each individually)? **Bonus: I know how to do prod/dev environment flags, so how do I just minify those individual files (again without bundling them)?</p>
<p>current webpack.config:</p>
<pre><code>var webpack = require("webpack"); // Assigning node package of webpack dependency to var for later utilization
var path = require("path"); // // Assigning node package of path dependency to var for later utilization
module.exports = {
entry: [
"./wwwroot/app/appName.tsx", // Starting point of linking/compiling Typescript and dependencies, will need to add separate entry points in case of not deving SPA
"./wwwroot/index.html", // Starting point of including HTML and dependencies, will need to add separate entry points in case of not deving SPA
"./wwwroot/favicon.ico" // Input location for favicon
],
output: {
path: "./dist/", // Where we want to host files in local file directory structure
publicPath: "/", // Where we want files to appear in hosting (eventual resolution to: https://localhost:4444/)
filename: "appName.js" // What we want end compiled app JS file to be called
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
devServer: {
contentBase: './dist', // Copy and serve files from dist folder
port: 4444, // Host on localhost port 4444
// https: true, // Enable self-signed https/ssl cert debugging
colors: true // Enable color-coding for debugging (VS Code does not currently emit colors, so none will be present there)
},
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [
"",
".ico",
".js",
".ts",
".tsx",
".web.js",
".webpack.js"
]
},
module: {
loaders: [
// This loader copies the index.html file & favicon.ico to the output directory.
{
test: /\.(html|ico)$/,
loader: 'file?name=[name].[ext]'
},
// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
{
test: /\.tsx?$/,
loaders: ["ts-loader"]
}
],
preLoaders: [
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
test: /\.js$/,
loader: "source-map-loader"
}
]
},
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
// externals: {
// "react": "React",
// "react-dom": "ReactDOM",
// "redux": "Redux"
// }
};
</code></pre> | 40,101,789 | 3 | 6 | null | 2016-10-17 22:08:41.92 UTC | 11 | 2019-12-20 09:07:27.81 UTC | 2019-12-20 09:07:03.137 UTC | null | 542,251 | null | 7,004,536 | null | 1 | 48 | javascript|node.js|reactjs|typescript|webpack | 45,866 | <p>Change the <code>output</code> setting to be <em>name driven</em> e.g. </p>
<pre><code> entry: {
dash: 'app/dash.ts',
home: 'app/home.ts',
},
output: {
path: './public',
filename: 'build/[name].js',
sourceMapFilename: 'build/[name].js.map'
},
</code></pre> |
5,063,835 | How can I make a Hashmap in Linux shell? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/1494178/how-to-define-hash-tables-in-bash">How to define hash tables in bash?</a> </p>
</blockquote>
<p>I wish to create a hash map in a Linux shell script which associates string keys with string values. Is there a simple way I can do this?</p> | 5,063,920 | 2 | 1 | null | 2011-02-21 08:43:21.403 UTC | 1 | 2011-02-21 08:52:58.84 UTC | 2017-05-23 11:58:44.017 UTC | null | -1 | null | 190,822 | null | 1 | 13 | linux|shell | 57,829 | <p>I think you shold refer this question:
<a href="https://stackoverflow.com/questions/1494178/how-to-define-hash-tables-in-bash">How to define hash tables in Bash?</a>, which is useful. :-)</p> |
5,158,032 | Define multiple variables at the same time in MATLAB? | <p>I don't know if MATLAB can do this, and I want it purely for aesthetics in my code, but can MATLAB create two variables at the same time?</p>
<p>Example</p>
<pre><code>x = cell(4,8);
y = cell(4,8);
</code></pre>
<p>Is there a way to write the code something similar to: </p>
<pre><code>x&y = cell(4,8);
</code></pre> | 5,158,206 | 2 | 2 | null | 2011-03-01 17:26:45.8 UTC | 5 | 2015-11-28 11:31:12.777 UTC | 2015-11-28 11:31:12.777 UTC | null | 4,370,109 | null | 379,362 | null | 1 | 17 | matlab|variables | 50,976 | <p>Use comma-separated lists to get multiple variables in the left hand side of an expression.</p>
<p>You can use deal() to put multiple assignments one line.</p>
<pre><code>[x,y] = deal(cell(4,8), cell(4,8));
</code></pre>
<p>Call it with a single input and all the outputs get the same value.</p>
<pre><code>[x,y] = deal( cell(4,8) );
>> [a,b,c] = deal( 42 )
a =
42
b =
42
c =
42
</code></pre> |
16,325,035 | How to create an automated dynamic line graph in Excel VBA | <p>I have a work problem. I have a data report with tons of information in it and I need to create 3 line graphs to represent 3 different values over time. The time is also in the report and is the same time for all of the values. I am having trouble finding a solution specific to me in forums elsewhere. </p>
<p>The data report varies in length, rows. What I need to do is to create the 3 line graphs and have them positioned horizontally, a few rows under the end of the report. Two of the graphs have one series each and the third has two series. </p>
<p>This is what the graphs need to include:</p>
<p>Graph 1: RPM over Time<br>
Graph 2: Pressure over Time<br>
Graph 3: Step burn off and Demand burn off over Time</p>
<p>I am just getting into VBA because of a recent position change at work and I know very little about it but I have spent a lot of time figuring out how to write other macros for the same report. Since my verbal representation of the workbook is unclear I have attached a link to a sample of the data report for viewing.</p>
<p><a href="https://dl.dropboxusercontent.com/u/28487159/Work%20Example.xls" rel="nofollow noreferrer">Data Report Workbook Download</a>
<img src="https://i.stack.imgur.com/agCtN.gif" alt="Extract from Download + Added Charts"></p>
<p>Here is what I have so far. It works for the first chart. Now what can I put in the code to name the chart "RPM" and to name the series "RPM"?</p>
<pre><code> Sub Test()
Dim LastRow As Long
Dim Rng1 As Range
Dim ShName As String
With ActiveSheet
LastRow = .Range("B" & .Rows.Count).End(xlUp).Row
Set Rng1 = .Range("B2:B" & LastRow & ", E2:E" & LastRow)
ShName = .Name
End With
Charts.Add
With ActiveChart
.ChartType = xlLine
.SetSourceData Source:=Rng1
.Location Where:=xlLocationAsObject, Name:=ShName
End With
End Sub
</code></pre>
<p>I have figured out how to put the chart name in via VBA. The code now looks like this:</p>
<pre><code>Sub Test()
Dim LastRow As Long
Dim Rng1 As Range
Dim ShName As String
With ActiveSheet
LastRow = .Range("B" & .Rows.Count).End(xlUp).Row
Set Rng1 = .Range("B2:B" & LastRow & ", E2:E" & LastRow)
ShName = .Name
End With
Charts.Add
With ActiveChart
.ChartType = xlLine
.HasTitle = True
.ChartTitle.Text = "RPM"
.SetSourceData Source:=Rng1
.Location Where:=xlLocationAsObject, Name:=ShName
End With
End Sub
</code></pre>
<p>I will next be working on the series title and then on to having the chart place itself under the report data. Suggestions and comments welcome.</p>
<p>The updated code below creates the rpm chart and the pressure chart separately. The last chart needs two series and I am working on that now. </p>
<pre><code>Sub chts()
'RPM chart-------------------------------------
Dim LastRow As Long
Dim Rng1 As Range
Dim ShName As String
With ActiveSheet
LastRow = .Range("B" & .Rows.Count).End(xlUp).Row
Set Rng1 = .Range("B2:B" & LastRow & ", E2:E" & LastRow)
ShName = .Name
End With
Charts.Add
With ActiveChart
.ChartType = xlLine
.HasTitle = True
.ChartTitle.Text = "RPM"
.SetSourceData Source:=Rng1
.Location Where:=xlLocationAsObject, Name:=ShName
End With
With ActiveChart.SeriesCollection(1)
.Name = "RPM"
End With
' Pressure chart --------------------------------
Dim LastRow2 As Long
Dim Rng2 As Range
Dim ShName2 As String
With ActiveSheet
LastRow2 = .Range("B" & .Rows.Count).End(xlUp).Row
Set Rng2 = .Range("B2:B" & LastRow2 & ", G2:G" & LastRow2)
ShName2 = .Name
End With
Charts.Add
With ActiveChart
.ChartType = xlLine
.HasTitle = True
.ChartTitle.Text = "Pressure/psi"
.SetSourceData Source:=Rng2
.Location Where:=xlLocationAsObject, Name:=ShName2
End With
With ActiveChart.SeriesCollection(1)
.Name = "Pressure"
End With
End Sub
</code></pre>
<p>David, I am curious to see how your code works with my worksheet but I'm not sure how to fix the syntax error.</p> | 16,329,765 | 1 | 7 | null | 2013-05-01 19:31:08.367 UTC | 5 | 2015-08-03 12:14:03.93 UTC | 2015-08-03 12:14:03.93 UTC | null | 1,481,116 | null | 2,340,579 | null | 1 | 3 | vba|excel|graph|line | 66,660 | <p>To manipulate the Series title (you only have one series in each of these charts) you could do simply:</p>
<pre><code>With ActiveChart.SeriesCollection(1)
.Name = "RPM"
'## You can further manipulate some series properties, like: '
'.XValues = range_variable '## you can assign a range of categorylabels here'
'.Values = another_range_variable '## you can assign a range of Values here'
End With
</code></pre>
<p>Now, what code you have is <em>adding</em> charts to the sheet. But once they have been created, presumably you don't want to re-add a new chart, you just want to update the existing chart.</p>
<p>Assuming you only will have one series in each of these charts, you could do something like this to <strong>update</strong> the charts.</p>
<p>How it works is by iterating over each chart in the worksheet's chartobjects collection, and then determining what Range to use for the Series Values, based on the chart's title.</p>
<p><strong>REVISED</strong> to account for the third chart which has 2 series.</p>
<p><strong>REVISED #2</strong> To add series to chart if chart does not have series data.</p>
<pre><code>Sub UpdateCharts()
Dim cObj As ChartObject
Dim cht As Chart
Dim shtName As String
Dim chtName As String
Dim xValRange As Range
Dim LastRow As Long
With ActiveSheet
LastRow = .Range("B" & .Rows.Count).End(xlUp).Row
Set xValRange = .Range("B2:B" & LastRow)
shtName = .Name & " "
End With
'## This sets values for Series 1 in each chart ##'
For Each cObj In ActiveSheet.ChartObjects
Set cht = cObj.Chart
chtName = shtName & cht.Name
If cht.SeriesCollection.Count = 0 Then
'## Add a dummy series which will be replaced in the code below ##'
With cht.SeriesCollection.NewSeries
.Values = "{1,2,3}"
.XValues = xValRange
End With
End If
'## Assuming only one series per chart, we just reset the Values & XValues per chart ##'
With cht.SeriesCollection(1)
'## Assign the category/XValues ##'
.XValues = xValRange
'## Here, we set the range to use for Values, based on the chart name: ##'
Select Case Replace(chtName, shtName, vbNullString)
Case "RPM"
.Values = xValRange.Offset(0, 3) '## Column E is 3 offset from the xValRange in column B
Case "Pressure/psi"
.Values = xValRange.Offset(0, 5) '## Column G is 5 offset from the xValRange in column B
Case "Third Chart"
.Values = xValRange.Offset(0, 6) '## Column H is 6 offset from the xValRange in column B
'## Make sure this chart has 2 series, if not, add a dummy series ##'
If cht.SeriesCollection.Count < 2 Then
With cht.SeriesCollection.NewSeries
.XValues = "{1,2,3}"
End With
End If
'## add the data for second series: ##'
cht.SeriesCollection(2).XValues = xValRange
cht.SeriesCollection(2).Values = xValRange.Offset(0, 8) '## Column J is 8 offset from the xValRange in column B
Case "Add as many of these Cases as you need"
End Select
End With
Next
End Sub
</code></pre>
<p><strong>REVISION #3</strong> To allow for creation of charts if they do not already exist in the worksheet, add these lines to the bottom of your <code>DeleteRows_0_Step()</code> subroutine:</p>
<p><code>Run "CreateCharts"</code></p>
<p><code>Run "UpdateCharts"</code></p>
<p>Then, add these subroutines to the same code module:</p>
<pre><code>Private Sub CreateCharts()
Dim chts() As Variant
Dim cObj As Shape
Dim cht As Chart
Dim chtLeft As Double, chtTop As Double, chtWidth As Double, chtHeight As Double
Dim lastRow As Long
Dim c As Long
Dim ws As Worksheet
Set ws = ActiveSheet
lastRow = ws.Range("A1", Range("A2").End(xlDown)).Rows.Count
c = -1
'## Create an array of chart names in this sheet. ##'
For Each cObj In ActiveSheet.Shapes
If cObj.HasChart Then
ReDim Preserve chts(c)
chts(c) = cObj.Name
c = c + 1
End If
Next
'## Check to see if your charts exist on the worksheet ##'
If c = -1 Then
ReDim Preserve chts(0)
chts(0) = ""
End If
If IsError(Application.Match("RPM", chts, False)) Then
'## Add this chart ##'
chtLeft = ws.Cells(lastRow, 1).Left
chtTop = ws.Cells(lastRow, 1).Top + ws.Cells(lastRow, 1).Height
Set cObj = ws.Shapes.AddChart(xlLine, chtLeft, chtTop, 355, 211)
cObj.Name = "RPM"
cObj.Chart.HasTitle = True
Set cht = cObj.Chart
cht.ChartTitle.Characters.Text = "RPM"
clearChart cht
End If
If IsError(Application.Match("Pressure/psi", chts, False)) Then
'## Add this chart ##'
With ws.ChartObjects("RPM")
chtLeft = .Left + .Width + 10
chtTop = .Top
Set cObj = ws.Shapes.AddChart(xlLine, chtLeft, chtTop, 355, 211)
cObj.Name = "Pressure/psi"
cObj.Chart.HasTitle = True
Set cht = cObj.Chart
cht.ChartTitle.Characters.Text = "Pressure/psi"
clearChart cht
End With
End If
If IsError(Application.Match("Third Chart", chts, False)) Then
'## Add this chart ##'
With ws.ChartObjects("Pressure/psi")
chtLeft = .Left + .Width + 10
chtTop = .Top
Set cObj = ws.Shapes.AddChart(xlLine, chtLeft, chtTop, 355, 211)
cObj.Name = "Third Chart"
cObj.Chart.HasTitle = True
Set cht = cObj.Chart
cht.ChartTitle.Characters.Text = "Third Chart"
clearChart cht
End With
End If
End Sub
Private Sub clearChart(cht As Chart)
Dim srs As Series
For Each srs In cht.SeriesCollection
If Not cht.SeriesCollection.Count = 1 Then srs.Delete
Next
End Sub
</code></pre> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.