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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
38,036,680 | Align multiple tables side by side | <p>The following code produces 2 tables on top of each other. How would I set it to have them aligned side by side, e.g. 3 to a row?</p>
<pre><code>---
title: "sample"
output: pdf_document
---
```{r global_options, R.options=knitr::opts_chunk$set(warning=FALSE, message=FALSE)}
```
```{r sample, echo=FALSE, results='asis'}
library(knitr)
t1 <- head(mtcars)[1:3]
t2 <- head(mtcars)[4:6]
print(kable(t1))
print(kable(t2))
```
</code></pre>
<p>Output looks like this:
<a href="https://i.stack.imgur.com/EDi50.png" rel="noreferrer"><img src="https://i.stack.imgur.com/EDi50.png" alt="enter image description here"></a></p> | 38,039,391 | 4 | 2 | null | 2016-06-26 08:37:23.517 UTC | 14 | 2022-07-14 10:22:23.763 UTC | 2016-06-27 09:12:45.743 UTC | null | 1,024,586 | null | 1,024,586 | null | 1 | 31 | r|latex|knitr|r-markdown | 60,194 | <p>Just put two data frames in a list, e.g.</p>
<pre><code>t1 <- head(mtcars)[1:3]
t2 <- head(mtcars)[4:6]
knitr::kable(list(t1, t2))
</code></pre>
<p>Note this requires <strong>knitr</strong> >= 1.13.</p> |
37,069,609 | Show loading screen when navigating between routes in Angular 2 | <p>How do I show a loading screen when I change a route in Angular 2?</p> | 38,620,817 | 5 | 2 | null | 2016-05-06 10:04:43.9 UTC | 87 | 2020-02-10 08:21:05.453 UTC | null | null | null | null | 1,136,709 | null | 1 | 135 | html|css|angular|angular2-routing | 118,578 | <p>The current Angular Router provides Navigation Events. You can subscribe to these and make UI changes accordingly. Remember to count in other Events such as <code>NavigationCancel</code> and <code>NavigationError</code> to stop your spinner in case router transitions fail.</p>
<p><em>app.component.ts</em> - your root component</p>
<pre><code>...
import {
Router,
// import as RouterEvent to avoid confusion with the DOM Event
Event as RouterEvent,
NavigationStart,
NavigationEnd,
NavigationCancel,
NavigationError
} from '@angular/router'
@Component({})
export class AppComponent {
// Sets initial value to true to show loading spinner on first load
loading = true
constructor(private router: Router) {
this.router.events.subscribe((e : RouterEvent) => {
this.navigationInterceptor(e);
})
}
// Shows and hides the loading spinner during RouterEvent changes
navigationInterceptor(event: RouterEvent): void {
if (event instanceof NavigationStart) {
this.loading = true
}
if (event instanceof NavigationEnd) {
this.loading = false
}
// Set loading state to false in both of the below events to hide the spinner in case a request fails
if (event instanceof NavigationCancel) {
this.loading = false
}
if (event instanceof NavigationError) {
this.loading = false
}
}
}
</code></pre>
<p><em>app.component.html</em> - your root view</p>
<pre><code><div class="loading-overlay" *ngIf="loading">
<!-- show something fancy here, here with Angular 2 Material's loading bar or circle -->
<md-progress-bar mode="indeterminate"></md-progress-bar>
</div>
</code></pre>
<p><strong>Performance Improved Answer</strong>: If you care about performance there is a better method, it is slightly more tedious to implement but the performance improvement will be worth the extra work. Instead of using <code>*ngIf</code> to conditionally show the spinner, we could leverage Angular's <code>NgZone</code> and <code>Renderer</code> to switch on / off the spinner which will bypass Angular's change detection when we change the spinner's state. I found this to make the animation smoother compared to using <code>*ngIf</code> or an <code>async</code> pipe.</p>
<p>This is similar to my previous answer with some tweaks:</p>
<p><em>app.component.ts</em> - your root component</p>
<pre><code>...
import {
Router,
// import as RouterEvent to avoid confusion with the DOM Event
Event as RouterEvent,
NavigationStart,
NavigationEnd,
NavigationCancel,
NavigationError
} from '@angular/router'
import {NgZone, Renderer, ElementRef, ViewChild} from '@angular/core'
@Component({})
export class AppComponent {
// Instead of holding a boolean value for whether the spinner
// should show or not, we store a reference to the spinner element,
// see template snippet below this script
@ViewChild('spinnerElement')
spinnerElement: ElementRef
constructor(private router: Router,
private ngZone: NgZone,
private renderer: Renderer) {
router.events.subscribe(this._navigationInterceptor)
}
// Shows and hides the loading spinner during RouterEvent changes
private _navigationInterceptor(event: RouterEvent): void {
if (event instanceof NavigationStart) {
// We wanna run this function outside of Angular's zone to
// bypass change detection
this.ngZone.runOutsideAngular(() => {
// For simplicity we are going to turn opacity on / off
// you could add/remove a class for more advanced styling
// and enter/leave animation of the spinner
this.renderer.setElementStyle(
this.spinnerElement.nativeElement,
'opacity',
'1'
)
})
}
if (event instanceof NavigationEnd) {
this._hideSpinner()
}
// Set loading state to false in both of the below events to
// hide the spinner in case a request fails
if (event instanceof NavigationCancel) {
this._hideSpinner()
}
if (event instanceof NavigationError) {
this._hideSpinner()
}
}
private _hideSpinner(): void {
// We wanna run this function outside of Angular's zone to
// bypass change detection,
this.ngZone.runOutsideAngular(() => {
// For simplicity we are going to turn opacity on / off
// you could add/remove a class for more advanced styling
// and enter/leave animation of the spinner
this.renderer.setElementStyle(
this.spinnerElement.nativeElement,
'opacity',
'0'
)
})
}
}
</code></pre>
<p><em>app.component.html</em> - your root view</p>
<pre><code><div class="loading-overlay" #spinnerElement style="opacity: 0;">
<!-- md-spinner is short for <md-progress-circle mode="indeterminate"></md-progress-circle> -->
<md-spinner></md-spinner>
</div>
</code></pre> |
35,443,812 | How to save string entered in HTML form to text file | <p>I have a very basic PHP file. i want to have two textboxes for user input, and a submit button. The user will enter their first and last name, then i would like to append or create a TXT file with the data entered from field1 and field2.</p>
<p>Possibly i am going about this the wrong way. I will post two of the ways i have been tinkering around with.</p>
<pre><code><html>
<head>
<title>Field1 & 2</title>
</head>
<body>
<form>
What is your name?<br>
<input type="text" name="field1"><br>
<input type="text" name="field2"><br>
<input type="submit" value="Submit">
</form>
<?php
$txt= $_POST['field1'].' - '.$_POST['field2'];
$var_str3 = var_export($txt, true); //is this necessary?
$var3 = "$var_str3"; //is this necessary?
file_put_contents('fields.txt', $var3.PHP_EOL, FILE_APPEND);
?>
</body>
</html>
</code></pre>
<p>I cant figure out how to get the data from field1 and field2 into a string variable. </p>
<p>I have also messed around with using this php instead of the section listed above</p>
<pre><code> <?php
$txt= "data.txt";
if (isset($_POST['field1']) && isset($_POST['field2'])) {
$fh = fopen($txt, 'a');
$txt=$_POST['field1'].' - '.$_POST['field2'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
</code></pre> | 35,444,695 | 2 | 1 | null | 2016-02-16 21:57:59.563 UTC | 2 | 2021-10-07 14:24:23.457 UTC | 2016-02-16 23:08:33.5 UTC | null | 718,526 | null | 2,154,727 | null | 1 | 2 | php|html|string | 39,779 | <p>You should learn about <a href="http://www.w3schools.com/html/html_forms.asp" rel="noreferrer">HTML Forms</a> And PHP <a href="http://www.w3schools.com/php/php_forms.asp" rel="noreferrer">Form Handling</a>.</p>
<p>In your code you have to use a form HTTP method. And the form data must sent for processing to a PHP file.</p>
<p>In this code i use HTTP PSOT method you can also use GET method the result will be same. This two method is used for collecting the form data. And the php file name is <code>"action.php"</code>. </p>
<p>index.html</p>
<pre><code> <html>
<head>
<title>Field 1 & 2</title>
</head>
<body>
<form action="action.php" method="post">
What is your name?<br>
<input type="text" name="field1"><br>
<input type="text" name="field2"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
</code></pre>
<p>action.php</p>
<pre><code><?php
$path = 'data.txt';
if (isset($_POST['field1']) && isset($_POST['field2'])) {
$fh = fopen($path,"a+");
$string = $_POST['field1'].' - '.$_POST['field2'];
fwrite($fh,$string); // Write information to the file
fclose($fh); // Close the file
}
?>
</code></pre> |
47,736,650 | Refused to display..... frame-ancestors https://www.facebook.com | <p>I have included Facebook customer chat plugin on my website. It works fine for the first day. From the second day, it's not working. I have seen an error message in Google Chrome console:</p>
<blockquote>
<p>Refused to display
'https://www.facebook.com/v2.11/plugins/customerchat.php?app_id=214160985792954&channel=https%3A%2F%2Fstaticxx.facebook.com%2Fconnect%2Fxd_arbiter%2Fr%2FlY4eZXm_YWu.js%3Fversion%3D42%23cb%3Df157c0f5ff1898c%26domain%3Dwww.fast-pay.cash%26origin%3Dhttps%253A%252F%252Fwww.fast-pay.cash%252Ff11cff6d515fe88%26relation%3Dparent.parent&container_width=0&locale=en_US&minimized=false&ref=front-page&sdk=joey'
in a frame because an ancestor violates the following Content Security
Policy directive: "frame-ancestors <a href="https://www.facebook.com/%22.%22" rel="nofollow noreferrer">https://www.facebook.com/"."</a></p>
</blockquote>
<p>I googled the solution. Every answer I have seen that this is domain white listing problem.
But I have whitelisted my domain in Facebook page.</p>
<p>Here is the process how I white listed my domain</p>
<ol>
<li><p>First I go to my page settings</p>
</li>
<li><p>Under messenger platform settings I put my domain name for whitelisting</p>
</li>
<li><p>I have put my domain name in several patterns. Here I give you my patterns</p>
</li>
<li><p><code>https://www.example.com/</code></p>
</li>
<li><p><code>https://www.example.com/</code></p>
</li>
<li><p><code>https://example.com/</code></p>
</li>
<li><p><code>http://www.example.com/</code></p>
</li>
<li><p><code>http://example.com/</code></p>
</li>
</ol>
<p>Here is the console error image
<a href="https://i.stack.imgur.com/mX863.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mX863.png" alt="" /></a></p> | 47,852,932 | 10 | 4 | null | 2017-12-10 07:01:59.297 UTC | 8 | 2022-07-11 09:44:14.14 UTC | 2022-07-11 09:44:14.14 UTC | null | 1,145,388 | null | 2,738,927 | null | 1 | 43 | wordpress|facebook|facebook-messenger|facebook-customer-chat | 78,429 | <p>You didn't mention anything about using additional plugins or CMS. Are you using plain PHP or CMS like WordPress? I wonder there might be an issue with your incorrect configuration. Please Re-check your Facebook Page Id. For any additional plugin, make sure to turn it on. </p> |
2,162,173 | Is Google Chrome embeddable? | <p>I've asked myself if one can embed the google chrome browser engine in an own application. I'm using Delphi 2009. There's an IE ActiveX wrapper component delivered with the IDE. Also, there's a Firefox ActiveX component out there, but it's based on very old code.</p>
<p>I'd like to embed the chrome engine. Is there a way to do this?</p>
<p>Thanks in advance,</p>
<p>David</p> | 2,162,202 | 3 | 2 | null | 2010-01-29 13:25:56.71 UTC | 10 | 2017-08-03 01:10:17.287 UTC | 2015-01-15 10:34:08.117 UTC | null | 3,242,070 | null | 247,868 | null | 1 | 30 | google-chrome|browser|activex|chromium-embedded|embedded-browser | 29,033 | <p>Google Chrome is basically WebKit layout engine + nice UI. And WebKit <a href="https://stackoverflow.com/questions/142184/is-there-an-embeddable-webkit-component-for-windows-c-development">can be embedded</a>.</p>
<p>There's also <a href="https://bitbucket.org/chromiumembedded/cef" rel="nofollow noreferrer">chromium embedded framework (CEF)</a>.</p>
<p>And finally, check out <a href="http://www.khrona.com/products/awesomium/" rel="nofollow noreferrer">Awesomium</a>.</p> |
8,442,729 | Is there a way to have printf() properly print out an array (of floats, say)? | <p>I believe I have carefully read the entire <code>printf()</code> documentation but could not find any way to have it print out, say, the elements of a 10-element array of <code>float(s)</code>.</p>
<p>E.g., if I have</p>
<pre><code>float[] foo = {1., 2., 3., ..., 10.};
</code></pre>
<p>Then I'd like to have a single statement such as</p>
<pre><code>printf("what_do_I_put_here\n", foo);
</code></pre>
<p>Which would print out something along the lines of:</p>
<pre><code>1. 2. 3. .... 10.
</code></pre>
<p>Is there a way to do that in vanilla C?</p> | 8,442,794 | 6 | 1 | null | 2011-12-09 08:10:43.457 UTC | 5 | 2021-08-12 04:15:35.52 UTC | 2011-12-09 08:12:13.007 UTC | null | 621,013 | null | 1,428 | null | 1 | 27 | c|printf | 163,153 | <p>you need to iterate through the array's elements</p>
<pre><code>float foo[] = {1, 2, 3, 10};
int i;
for (i=0;i < (sizeof (foo) /sizeof (foo[0]));i++) {
printf("%lf\n",foo[i]);
}
</code></pre>
<p>or create a function that returns stacked sn <code>printf</code> and then prints it with</p>
<pre><code>printf("%s\n",function_that_makes_pretty_output(foo))
</code></pre> |
8,790,515 | How to check directory exist or not in linux.? | <p>Given a file path (e.g. <code>/src/com/mot</code>), how can I check whether <code>mot</code> exists, and create it if it doesn't using Linux or shell scripting??</p> | 8,790,538 | 6 | 1 | null | 2012-01-09 15:09:12.583 UTC | 2 | 2012-01-09 15:26:36.823 UTC | 2012-01-09 15:26:36.823 UTC | null | 444,991 | null | 517,066 | null | 1 | 28 | linux|shell | 59,192 | <p>With bash/sh/ksh, you can do:</p>
<pre><code>if [ ! -d /directory/to/check ]; then
mkdir -p /directory/toc/check
fi
</code></pre>
<p>For files, replace <code>-d</code> with <code>-f</code>, then you can do whatever operations you need on the non-existant file.</p> |
8,475,694 | How to specify in crontab by what user to run script? | <p>I have few crontab jobs that run under root, but that gives me some problems. For example all folders created in process of that cron job are under user root and group root.
How can i make it to run under user www-data and group www-data so when i run scripts from my website i can manipulate those folders and files?</p>
<p>My server runs on Ubuntu.<br>
Current crontab job is: </p>
<pre><code>*/1 * * * * php5 /var/www/web/includes/crontab/queue_process.php >> /var/www/web/includes/crontab/queue.log 2>&1
</code></pre> | 8,476,992 | 5 | 1 | null | 2011-12-12 14:18:13.307 UTC | 47 | 2017-04-25 15:12:19.413 UTC | 2015-10-07 21:43:24.447 UTC | null | 128,421 | null | 386,222 | null | 1 | 186 | ubuntu|cron|crontab | 275,891 | <p>Instead of creating a crontab to run as the root user, create a crontab for the user that you want to run the script. In your case, <code>crontab -u www-data -e</code> will edit the crontab for the www-data user. Just put your full command in there and remove it from the root user's crontab.</p> |
62,252,547 | Value of protocol type 'Encodable' cannot conform to 'Encodable'; only struct/enum/class types can conform to protocols | <p>I have the following Swift code</p>
<pre><code>func doStuff<T: Encodable>(payload: [String: T]) {
let jsonData = try! JSONEncoder().encode(payload)
// Write to file
}
var things: [String: Encodable] = [
"Hello": "World!",
"answer": 42,
]
doStuff(payload: things)
</code></pre>
<p>results in the error</p>
<pre><code>Value of protocol type 'Encodable' cannot conform to 'Encodable'; only struct/enum/class types can conform to protocols
</code></pre>
<p>How to fix? I guess I need to change the type of <code>things</code>, but I don't know what to.</p>
<p>Additional info:</p>
<p>If I change <code>doStuff</code> to not be generic, I simply get the same problem in that function</p>
<pre><code>func doStuff(payload: [String: Encodable]) {
let jsonData = try! JSONEncoder().encode(payload) // Problem is now here
// Write to file
}
</code></pre> | 62,258,820 | 4 | 2 | null | 2020-06-07 22:34:17.127 UTC | 3 | 2021-08-23 07:38:36.667 UTC | 2021-03-07 12:07:24.86 UTC | null | 417,385 | null | 417,385 | null | 1 | 29 | ios|swift|generics | 22,091 | <p><code>Encodable</code> cannot be used as an annotated type. It can be only used as a generic constraint. And <code>JSONEncoder</code> can encode only concrete types.</p>
<p>The function </p>
<pre><code>func doStuff<T: Encodable>(payload: [String: T]) {
</code></pre>
<p>is correct but you cannot call the function with <code>[String: Encodable]</code> because a protocol cannot conform to itself. That's exactly what the error message says.</p>
<hr>
<p>The main problem is that the real type of <code>things</code> is <code>[String:Any]</code> and <code>Any</code> cannot be encoded.</p>
<p>You have to serialize <code>things</code> with <code>JSONSerialization</code> or create a helper struct.</p> |
259,553 | TCP is it possible to achieve higher transfer rate with multiple connections? | <p>Is it possible to achieve better data transfer rate with multiple parallel TCP connections in high-latency environment (public internet with large geographical distance assuming no traffic shaping per connection or stuff like that) or can TCP utilize the whole bandwidth with a single connection?</p>
<hr>
<p>Is TCP sending data as fast as it cans if receiver doesn't report buffer congestion with 0 windows size? So if RTT is for example like 60 seconds it doesn't affect the rate at all? Is there some maximum window size or something else limiting the rate? </p> | 259,944 | 4 | 0 | null | 2008-11-03 18:45:18.33 UTC | 12 | 2022-07-23 14:00:38.437 UTC | 2008-11-03 20:31:23.64 UTC | null | 30,958 | null | 30,958 | null | 1 | 15 | networking|tcp | 14,040 | <p>One advantage multiple concurrent connections <em>may</em> give you (subject to the same caveats mentioned by dove and Brian) is you will be able to better overcome the problem of having too small a TCP receive window.</p>
<p>The principle this relates to is <a href="http://en.wikipedia.org/wiki/Bandwidth-delay_product" rel="nofollow noreferrer">bandwidth delay product</a>. (There's a more detailed explanation <a href="https://www.psc.edu/research/networking/tcp-tune/" rel="nofollow noreferrer">here</a>).</p>
<p>A brief summary: in high-latency, high-bandwidth environments, reliable communications such as TCP are often limited by the amount of data in flight at any given time. Multiple connections are one way around this, as the bandwidth delay product applies to each connection individually.</p>
<p>In more detail, consider the following: you have an end-to-end bandwidth of 10^8 bits per second (10 megabits/second), and a round-trip delay of 100ms (0.1 seconds). Therefore, there can be up to 10^7 bits (10 megabits = ~1.25 megabytes) of data sent before the acknowledgment of the first bit of data has gotten back to the sender.</p>
<p>This will vary depending on the TCP stack of your OS, but a not-uncommon value for TCP receive window size is 64Kbytes. This is obviously far too small to allow you to make full use of the end to end bandwidth; once 64kbytes (512kbits) of data have been sent, your sending process will wait for a window update from the receiver indicating that some data has been consumed before putting any more data on the wire.</p>
<p>Having multiple TCP sessions open gets around this by virtue of the fact that each TCP session will have its own send/receive buffers.</p>
<p>Of course, on the internet it's difficult to determine the true available end-to-end bandwidth, due to TCP window size, contention, etc. If you're able to provide some sample figures, we may be able to assist more.</p>
<p>The other option you should look into is setting a larger receive window when you create your socket, either globally using an OS setting, or on a per socket basis using socket options.</p> |
1,126,239 | Git or Subversion for binary files | <p>We need to store binary files (mostly MS Word documents, ranging from a couple of KB to a couple of MB in size) in a version control repository with over 100 "projects". Currently we use Visual Source Safe but there are some problems, the database is crashing sometimes and the access is slow. </p>
<p>We are considering moving to Git or Subversion and we were wondering which one would be a better option for handling binary files.</p> | 1,127,623 | 4 | 3 | null | 2009-07-14 15:36:50.407 UTC | 13 | 2014-05-14 13:05:15.797 UTC | 2009-07-15 20:18:26.207 UTC | null | 119,365 | null | 20,417 | null | 1 | 26 | svn|git|version-control|binaryfiles | 23,633 | <p>Subversion, definitely. Today (2009), TortoiseSVN provides Explorer-integrated navigation of Subversion repositories, and most particularly it supports <em>diffing</em> of arbitrary Word documents (it defers the diff to Word itself, but the feature works really well).</p>
<p>There's no reason why a TortoiseGit can't have this same feature, but such a thing doesn't quite exist in a stable form today. Fortunately, it's easy to migrate a Subversion repository to Git anytime in the future.</p>
<p><strong>Update</strong>: As of 2011, TortoiseGit apparently has the same document management features as TortoiseSVN. However, Subversion supports advisory locking documents so that other users are notified if they try to edit the document at the same time as someone else. To the best of my knowledge, TortoiseGit cannot support this feature because of Git's distributed nature.</p> |
1,037,249 | How to clear browser cache with php? | <p>How to clear browser cache with php?</p> | 1,037,252 | 4 | 1 | null | 2009-06-24 09:07:47.217 UTC | 22 | 2020-08-22 20:47:39.557 UTC | null | null | null | null | 128,070 | null | 1 | 60 | php|browser|caching | 236,368 | <pre><code>header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Content-Type: application/xml; charset=utf-8");
</code></pre> |
54,418,978 | Remove releases in GitLab | <p>I have a problem with my releases in GitLab.</p>
<p>I created them in my project with tags. Now I want to remove them, so I deleted the associated tags but my releases are always displayed. I searched on Google and Stack Overflow but I can't find any solutions.</p>
<p>How can I remove these releases without their tags?</p> | 55,660,480 | 8 | 1 | null | 2019-01-29 10:30:15.22 UTC | 6 | 2022-09-04 13:51:17.31 UTC | 2019-12-11 01:01:24.363 UTC | null | 1,402,846 | null | 7,709,515 | null | 1 | 43 | gitlab | 19,961 | <p>Currently (GitLab v11.9.8) <strong>you can't</strong>. It's silly, I know, but you can't.</p>
<p>Ivan came up with a workaround if you have only a few releases to delete. His steps are copied below.</p>
<blockquote>
<p>Ivan Kostrubin (@ovitente):</p>
<p>For fixing this issue you have to go through those steps</p>
<ul>
<li>Create tag with the same name and release message that was in release, you will be able to edit this tag. </li>
<li>Open tag's release message for editing</li>
<li>Remove all text </li>
<li>Save it</li>
<li>And release has gone from the release list.</li>
<li>Then you can freely delete tag.</li>
</ul>
<p>Source:
<a href="https://gitlab.com/gitlab-org/gitlab-ce/issues/58549#note_160000873" rel="noreferrer">https://gitlab.com/gitlab-org/gitlab-ce/issues/58549#note_160000873</a></p>
</blockquote>
<p>Check out these GitLab issues:</p>
<ul>
<li><a href="https://gitlab.com/gitlab-org/gitlab-ce/issues/58549" rel="noreferrer">[#58549] Deleting releases with removed TAG in Release API</a></li>
<li><a href="https://gitlab.com/gitlab-org/gitlab/-/issues/26016" rel="noreferrer">[#56026] Make it possible to add/edit/delete a release using the UI</a></li>
</ul> |
16,051,267 | java.lang.ClassNotFoundException: org.dom4j.DocumentException | <p>I made some code to learn hibernate. It is throwing the error below. How do I find out what the problem is and fix it ? dom4j sounds like an XML problem. hibernate.cfg.xml is the problem ?</p>
<pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/DocumentException
at com.examscam.model.User.persist(User.java:45)
at com.examscam.model.User.main(User.java:57)
Caused by: java.lang.ClassNotFoundException: org.dom4j.DocumentException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 2 more
</code></pre>
<p><strong>(why is eclipse not showing this "2more" thing ?)</strong></p>
<p><strong>Code -</strong> </p>
<pre><code>package com.examscam.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
@Entity
public class User {
private Long id;
private String password;
@Id
@GeneratedValue
public Long getId(){
return id;
}
public void setId(Long id){
Class c1 = User.class;
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public static void persist(){
/*
* Contains all the info needed to connect to database, along with
* info from your JPA annotated class, ie this class.
*/
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(User.class);
config.configure();
SchemaExport schemaExport = new SchemaExport(config);
schemaExport.create(true, true);
}
public static void main(String[]args){
persist();
}
}
</code></pre>
<p><strong>XML file -</strong> </p>
<pre><code><?xml version = '1.0' encoding='UTF-8' ?>
<!Doctype hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name = "connection.url">
jdbc:mysql://localhost/examscam
</property>
<property name = "connection.username">
root
</property>
<property name = "connection.password">
password
</property>
<property name = "connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name = "dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name = "transaction.factory_class">
org.hibernate.transaction.JDBCTransactionFactory
</property>
<property name = "current_session_context_class">
thread
</property>
<!-- this will show us all the SQL statements-->
<property name = "hibernate.show_sql">
true
</property>
<!-- We dont use any mapping files as of now-->
</session-factory>
</hibernate-configuration>
</code></pre>
<p><strong>UPDATE</strong></p>
<p><strong>After fixing the above errors, there is a new problem -</strong> </p>
<p>I am making code with eclipse. I added all the possible jars needed for the code and my code is still not working. Why is this error <strong>java.lang.ClassNotFoundException: org.slf4j.impl.StaticLoggerBinder</strong> occurring when i already added sl4fj (
slf4j-api-1.5.8.jar) to build path ?</p>
<p>The error - </p>
<pre><code> SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j
/impl/StaticLoggerBinder
at org.slf4j.LoggerFactory.getSingleton(LoggerFactory.java:223)
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:120)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:111)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:269)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:242)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:255)
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:152)
at com.examscam.model.User.persist(User.java:45)
at com.examscam.model.User.main(User.java:57)
Caused by: java.lang.ClassNotFoundException: org.slf4j.impl.StaticLoggerBinder
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 9 more
</code></pre> | 16,051,334 | 2 | 3 | null | 2013-04-17 04:03:37.473 UTC | null | 2020-12-31 10:50:55.13 UTC | 2013-04-17 04:38:21.507 UTC | null | 1,667,147 | null | 1,667,147 | null | 1 | 2 | java|xml|hibernate | 63,280 | <p>Make sure dom4j.jar is in the classpath.</p>
<p>What you are saying by 2more.</p>
<p>When you see '...2 more', that means that the remaining lines of the 'caused by' exception are identical to the remaining lines from that point on of the parent exception.</p> |
31,663,644 | How do I find the position of substring in PowerShell after position x? | <p>Is there a simple way to do so; I can't find any. Am I obliged to scan character by character?</p>
<p>I don't want a string as return, but a <em>position</em> so do not suggest SubString.</p> | 49,843,643 | 2 | 2 | null | 2015-07-27 21:29:02.26 UTC | 1 | 2022-02-26 07:14:42.01 UTC | 2019-04-23 20:52:16.977 UTC | null | 63,550 | null | 310,291 | null | 1 | 12 | powershell | 89,169 | <p>To compliment <a href="https://stackoverflow.com/questions/31663644/how-do-i-find-the-position-of-substring-in-powershell-after-position-x/31663895#31663895">the answer from Mathias R. Jessen</a>:</p>
<p>The <a href="https://msdn.microsoft.com/library/system.string.indexof(v=vs.110).aspx" rel="nofollow noreferrer">String.IndexOf method</a> is in fact a <a href="https://en.wikipedia.org/wiki/.NET_Framework" rel="nofollow noreferrer">.NET</a> method of the string object. This appears from the fact that it is case-sensitive by default (which is not common for PowerShell):</p>
<pre><code>PS C:\> "WordsWordsWords".IndexOf("words")
-1
</code></pre>
<p>You might overcome this by setting the <a href="https://msdn.microsoft.com/library/system.stringcomparison(v=vs.110).aspx" rel="nofollow noreferrer"><code>StringComparison</code></a> to <code>CurrentCultureIgnoreCase</code>:</p>
<pre><code>PS C:\> "WordsWordsWords".IndexOf("words", [System.StringComparison]::CurrentCultureIgnoreCase)
0
</code></pre>
<p>But you might also consider the <a href="https://docs.microsoft.com/powershell/module/microsoft.powershell.utility/select-string?view=powershell-6" rel="nofollow noreferrer"><code>Select-String</code> <em>cmdlet</em></a> which gives you more possibilities including <a href="https://en.wikipedia.org/wiki/Regular_expression" rel="nofollow noreferrer">regular expressions</a>:</p>
<pre><code>PS C:\> ("Words words words" | Select-String "words").Matches.Index
0
PS C:\> ("Words words words" | Select-String "words" -AllMatches).Matches.Index
0
6
12
PS C:\> ("Words words words" | Select-String "\w+" -AllMatches).Matches.Index
0
6
12
</code></pre> |
59,013,109 | RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same | <p>This:</p>
<pre><code>device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
for data in dataloader:
inputs, labels = data
outputs = model(inputs)
</code></pre>
<p>Gives the error:</p>
<blockquote>
<p>RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same</p>
</blockquote> | 59,013,131 | 7 | 0 | null | 2019-11-23 23:08:32.787 UTC | 27 | 2022-09-02 11:02:03.957 UTC | 2022-08-18 13:56:04.72 UTC | null | 10,908,375 | null | 10,168,730 | null | 1 | 129 | python|python-3.x|machine-learning|deep-learning|pytorch | 169,604 | <p>You get this error because your model is on the GPU, but your data is on the CPU. So, you need to send your input tensors to the GPU.</p>
<pre class="lang-py prettyprint-override"><code>inputs, labels = data # this is what you had
inputs, labels = inputs.cuda(), labels.cuda() # add this line
</code></pre>
<p>Or like this, to stay consistent with the rest of your code:</p>
<pre class="lang-py prettyprint-override"><code>device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
inputs, labels = inputs.to(device), labels.to(device)
</code></pre>
<p>The <strong>same error</strong> will be raised if your input tensors are on the GPU but your model weights aren't. In this case, you need to send your model weights to the GPU.</p>
<pre><code>model = MyModel()
if torch.cuda.is_available():
model.cuda()
</code></pre>
<p>See the documentation for <a href="https://pytorch.org/docs/stable/tensors.html#torch.Tensor.cuda" rel="noreferrer"><code>cuda()</code></a>, and its opposite, <a href="https://pytorch.org/docs/stable/tensors.html#torch.Tensor.cpu" rel="noreferrer"><code>cpu()</code></a>.</p> |
55,709,512 | Why is there a difference in the task/microtask execution order when a button is programmatically clicked vs DOM clicked? | <p>There's a difference in the execution order of the microtask/task queues when a button is clicked in the DOM, vs it being programatically clicked. </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const btn = document.querySelector('#btn');
btn.addEventListener("click", function() {
Promise.resolve().then(function() { console.log('resolved-1'); });
console.log('click-1');
});
btn.addEventListener("click", function() {
Promise.resolve().then(function() { console.log('resolved-2'); });
console.log('click-2');
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id='btn'>Click me !</button></code></pre>
</div>
</div>
</p>
<p>My understanding is that when the callstack is empty, the event loop will take callbacks from the microtask queue to place on the callstack. When both the callstack and microtask queue are empty, the event loop starts taking callbacks from the task queue.</p>
<p>When the button with the id <code>btn</code> is clicked, both "click" event listeners are placed on the task queue in order they are declared in.</p>
<pre><code>// representing the callstack and task queues as arrays
callstack: []
microtask queue: []
task queue: ["click-1", "click-2"]
</code></pre>
<p>The event loop places the <code>"click-1" callback</code> on the callstack. It has a promise that immediately resolves, placing the <code>"resolved-1" callback</code> on the microtask queue.</p>
<pre><code>callstack: ["click-1"]
microtask queue: ["resolved-1"]
task queue: ["click-2"]
</code></pre>
<p>The <code>"click-1" callback</code> executes its console.log, and completes. Now there's something on the microtask queue, so the event loop takes the <code>"resolved-1" callback</code> and places it on the callstack.</p>
<pre><code>callstack: ["resolved-1"]
microtask queue: []
task queue: ["click-2"]
</code></pre>
<p><code>"resolved-1" callback</code> is executed. Now both the callstack and microtask queue and are empty.</p>
<pre><code>callstack: []
microtask queue: []
task queue: ["click-2"]
</code></pre>
<p>The event loop then "looks" at the task queue once again, and the cycle repeats.</p>
<pre><code>// "click-2" is placed on the callstack
callstack: ["click-2"]
microtask queue: []
task queue: []
// Immediately resolved promise puts "resolved-2" in the microtask queue
callstack: ["click-2"]
microtask queue: ["resolved-2"]
task queue: []
// "click-2" completes ...
callstack: []
microtask queue: ["resolved-2"]
task queue: []
// "resolved-2" executes ...
callstack: ["resolved-2"]
microtask queue: []
task queue: []
// and completes
callstack: []
microtask queue: []
task queue: []
</code></pre>
<p>This would explain this output from the code snippet above</p>
<pre><code>"hello click1"
"resolved click1"
"hello click2"
"resolved click2"
</code></pre>
<p>I would expect it to be the same then I programatically click the button with <code>btn.click()</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const btn = document.querySelector('#btn');
btn.addEventListener("click", function() {
Promise.resolve().then(function() { console.log('resolved-1'); });
console.log('click-1');
});
btn.addEventListener("click", function() {
Promise.resolve().then(function() { console.log('resolved-2'); });
console.log('click-2');
});
btn.click()</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id='btn'>Click me!</button></code></pre>
</div>
</div>
</p>
<p>However, the output is different.</p>
<pre><code>"hello click1"
"hello click2"
"resolved click1"
"resolved click2"
</code></pre>
<p>Why is there a difference in the execution order when button is programatically clicked ?</p> | 55,709,979 | 3 | 1 | null | 2019-04-16 13:35:54.797 UTC | 9 | 2019-05-15 15:39:13.817 UTC | 2019-05-15 15:39:13.817 UTC | null | 1,196,459 | null | 1,196,459 | null | 1 | 24 | javascript | 1,244 | <p>Fascinating question.</p>
<p>First, the easy part: When you call <code>click</code>, it's a <strong>synchronous</strong> call triggering all of the event handlers on the button. You can see that if you add logging around the call:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const btn = document.querySelector('#btn');
btn.addEventListener("click", function() {
Promise.resolve().then(function() { console.log('resolved-1'); });
console.log('click-1');
});
btn.addEventListener("click", function() {
Promise.resolve().then(function() { console.log('resolved-2'); });
console.log('click-2');
});
document.getElementById("btn-simulate").addEventListener("click", function() {
console.log("About to call click");
btn.click();
console.log("Done calling click");
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" id="btn" value="Direct Click">
<input type="button" id="btn-simulate" value="Call click()"></code></pre>
</div>
</div>
</p>
<p>Since the handlers are run synchronously, microtasks are processed only after both handlers have finished. Processing them sooner would require breaking JavaScript's run-to-completion semantics.</p>
<p>In contrast, when the event is <a href="https://html.spec.whatwg.org/multipage/webappapis.html#the-event-handler-processing-algorithm" rel="noreferrer">dispatched via the DOM</a>, it's more interesting: Each handler is <a href="https://heycam.github.io/webidl/#invoke-a-callback-function" rel="noreferrer">invoked</a>. Invoking a handler includes <a href="https://html.spec.whatwg.org/multipage/webappapis.html#clean-up-after-running-a-callback" rel="noreferrer">cleaning up after running script</a>, which includes doing a <a href="https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint" rel="noreferrer">microtask checkpoint</a>, running any pending microtasks. So microtasks scheduled by the handler that was invoked get run before the next handler gets run.</p>
<p>That's "why" they're different in one sense: Because the handler callbacks are called synchronously, in order, when you use <code>click()</code>, and so there's no opportunity to process microtasks between them.</p>
<p>Looking at "why" slightly differently: <em>Why</em> are the handlers called synchronously when you use <code>click()</code>? Primarily because of history, that's what early browsers did and so it can't be changed. But they're also synchronous if you use <code>dispatchEvent</code>:</p>
<pre><code>const e = new MouseEvent("click");
btn.dispatchEvent(e);
</code></pre>
<p>In that case, the handlers are still run synchronously, because the code using it might need to look at <code>e</code> to see if the default action was prevented or similar. (It <em>could</em> have been defined differently, providing a callback or some such for when the event was done being dispatched, but it wasn't. I'd <em>guess</em> that it wasn't for either simplicity, compatibility with <code>click</code>, or both.)</p> |
29,763,647 | How to make a program that does not display the console window? | <p>I'm trying to develop a program that uses the sdl2 library. It works perfectly so far, but when I run the program I get two windows - the sdl2 window and the console window.</p>
<p>How can I hide or not create the console window? Maybe there is some sort of <code>WinMain</code>?</p> | 29,764,309 | 4 | 0 | null | 2015-04-21 05:26:56.333 UTC | 12 | 2021-10-16 14:47:29.297 UTC | 2015-04-21 14:20:19.327 UTC | null | 155,423 | null | 2,605,687 | null | 1 | 35 | windows|console|rust | 15,026 | <p><a href="https://blog.rust-lang.org/2017/06/08/Rust-1.18.html" rel="noreferrer">Rust 1.18</a> introduced a Windows Subsystem attribute. Turn off the console with:</p>
<pre><code>#![windows_subsystem = "windows"]
</code></pre>
<hr />
<p>When the Rust binaries are linked with the GCC toolchain, to start a program without spawning a command line window we need to <a href="https://gcc.gnu.org/ml/gcc-help/2004-01/msg00225.html" rel="noreferrer">pass the <code>-mwindows</code> option to the linker</a>.</p>
<p>Cargo <a href="https://github.com/rust-lang/cargo/issues/595" rel="noreferrer">has a <code>cargo rustc</code> mode</a> which can be used to pass extra flags to <code>rustc</code>. Before that was introduced, <a href="https://github.com/rust-lang/cargo/issues/544" rel="noreferrer">there was no known way to pass an option to the compiler with Cargo</a>.</p>
<p>When we can not affect the compilation or linking to the desired effect, one workaround is to hide the window after it has been created:</p>
<pre><code>fn hide_console_window() {
use std::ptr;
use winapi::um::wincon::GetConsoleWindow;
use winapi::um::winuser::{ShowWindow, SW_HIDE};
let window = unsafe {GetConsoleWindow()};
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow
if window != ptr::null_mut() {
unsafe {
ShowWindow(window, SW_HIDE);
}
}
}
</code></pre>
<p>We'll need the following in Cargo.toml to compile the example:</p>
<pre><code>[dependencies]
winapi = {version = "0.3", features = ["wincon", "winuser"]}
</code></pre>
<p>When we are running the program from an existing console or IDE:</p>
<pre><code>fn hide_console_window() {
unsafe { winapi::um::wincon::FreeConsole() };
}
</code></pre>
<p>This second method doesn't work if we're starting the application from a batch file, for the batch still owns the console and keeps its from disappearing.</p> |
4,831,322 | How do streaming resources fit within the RESTful paradigm? | <p>With a RESTful service you can create, read, update, and delete resources. This all works well when you're dealing with something like a database assets - but how does this translate to streaming data? (Or does it?) For instance, in the case of video, it seems silly to treat each frame as resource that I should query one at a time. Rather I would set up a socket connection and stream a series of frames. But does this break the RESTful paradigm? What if I want to be able to rewind or fast forward the stream? Is this possible within the RESTful paradigm? So: <strong>How do streaming resources fit within the RESTful paradigm?</strong></p>
<p>As a matter of implementation, I am getting ready to create such a streaming data service, and I want to make sure I'm doing it the "best way". I'm sure this problem's been solved before. Can someone point me to good material?</p> | 4,833,103 | 1 | 1 | null | 2011-01-28 17:40:32.497 UTC | 43 | 2018-03-15 02:59:17.733 UTC | 2014-03-26 18:28:37.957 UTC | null | 142,162 | null | 348,056 | null | 1 | 108 | rest|streaming|theory | 54,233 | <p>I did not manage to find materials about truly <a href="http://www.google.com/search?q=restful+video+stream" rel="noreferrer">RESTful streaming</a> - it seems that results are mostly about delegating streaming to another service (which is not a bad solution). So I'll do my best to tackle it myself - note that streaming is not my domain, but I'll try to add my 2 cents.</p>
<p>In the aspect of streaming, I think that we need to separate the problem into two independent parts:</p>
<ol>
<li>access to media resources (meta data)</li>
<li>access to the medium/stream itself (binary data)</li>
</ol>
<p><strong>1.) Access to media resources</strong><br />
This is pretty straightforward and can be handled in a clean and RESTful way. As an example, let's say that we will have an XML-based API which allows us to access a list of streams:</p>
<pre><code>GET /media/
<?xml version="1.0" encoding="UTF-8" ?>
<media-list uri="/media">
<media uri="/media/1" />
<media uri="/media/2" />
...
</media-list>
</code></pre>
<p>...and also to individual streams:</p>
<pre><code>GET /media/1
<?xml version="1.0" encoding="UTF-8" ?>
<media uri="/media/1">
<id>1</id>
<title>Some video</title>
<stream>rtsp://example.com/media/1.3gp</stream>
</media>
</code></pre>
<p><strong>2.) Access to the medium/stream itself</strong><br />
This is the more problematic bit. You already pointed out one option in your question, and that is to allow access to frames individually via a RESTful API. Even though this might work, I agree with you that it's not a viable option.</p>
<p>I think that there is a choice to be made between:</p>
<ol>
<li>delegating streaming to a dedicated service via a specialized streaming protocol (e.g. RTSP)</li>
<li>utilizing options available in HTTP</li>
</ol>
<p>I believe the former to be the more efficient choice, although it requires a <strong>dedicated streaming service</strong> (and/or hardware). It might be a bit on the edge of what is considered RESTful, however note that our API is RESTful in all aspects and even though the dedicated streaming service does not adhere to the uniform interface (GET/POST/PUT/DELETE), our API does. Our API allows us proper control over resources and their meta data via GET/POST/PUT/DELETE, and we provide links to the streaming service (thus adhering with connectedness aspect of REST).</p>
<p>The latter option - <strong>streaming via HTTP</strong> - might not be as efficient as the above, but it's definitely possible. Technically, it's not that different than allowing access to any form of binary content via HTTP. In this case our API would provide a link to the binary resource accessible via HTTP, and also advises us about the size of the resource:</p>
<pre><code>GET /media/1
<?xml version="1.0" encoding="UTF-8" ?>
<media uri="/media/1">
<id>1</id>
<title>Some video</title>
<bytes>1048576</bytes>
<stream>/media/1.3gp</stream>
</media>
</code></pre>
<p>The client can access the resource via HTTP by using <code>GET /media/1.3gp</code>. One option is for the client to download the whole resource - <a href="http://en.wikipedia.org/wiki/Progressive_download" rel="noreferrer">HTTP progressive download</a>. A cleaner alternative would be for the client to access the resource in chunks by utilizing HTTP <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.2" rel="noreferrer">Range headers</a>. For fetching the second 256KB chunk of a file that is 1MB large, the client request would then look like this:</p>
<pre><code>GET /media/1.3gp
...
Range: bytes=131072-262143
...
</code></pre>
<p>A server which supports ranges would then respond with the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16" rel="noreferrer">Content-Range header</a>, followed by the partial representation of the resource:</p>
<pre><code>HTTP/1.1 206 Partial content
...
Content-Range: bytes 131072-262143/1048576
Content-Length: 1048576
...
</code></pre>
<p>Note that our API already told the client the exact size of the file in bytes (1MB). In a case where the client would not know the size of the resource, it should first call <code>HEAD /media/1.3gp</code> in order to determine the size, otherwise it's risking a server response with <code>416 Requested Range Not Satisfiable</code>.</p> |
6,351,182 | App pushed to heroku still shows standard index page | <p>I went through the steps to install git and the heroku gem and successfully pushed my app to heroku.
The problem is, it shows a standard "You're Riding Ruby on Rails" page even though the local app I have has routes set up to root to a certain controller/page. I have also deleted the index.html page from /public.</p>
<p>Any idea why this is happening? I suspect I might needed to switch from development to deployment somehow but still, I deleted the index.html, why is it still showing up on heroku?</p>
<p>EDIT: Going to mysite.heroku/login and other pages I've created works fine for some reason, so nevermind on the deployment thing.</p> | 6,351,705 | 2 | 2 | null | 2011-06-14 23:01:50.99 UTC | 11 | 2012-06-06 14:34:28.6 UTC | null | null | null | null | 705,725 | null | 1 | 17 | ruby-on-rails|ruby|git|deployment|heroku | 6,955 | <p>When you're using git and delete a file, that file is not automatically removed from the git repo. So when you <code>git push heroku</code> the file still exists and gets pushed to Heroku.</p>
<p>You can tell if this is the case with <code>git status</code>, which will show something like:</p>
<pre><code># Changes not staged for commit:
# (use "git add/rm <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# deleted: public/index.html
</code></pre>
<p>In order to remove the file, you need to use <a href="http://git-scm.com/docs/git-rm" rel="noreferrer"><code>git rm</code></a>. In this case you need to do something like:</p>
<pre><code>git rm public/index.html
git commit -m "Removed public/index.html"
</code></pre>
<p>which will remove the file from the current branch.</p>
<p>Now when you do</p>
<pre><code>git push heroku
</code></pre>
<p>the file won't be included, and so you'll be routed to the controller as specified in routes.rb.</p> |
7,390,015 | Using Dapper with Oracle stored procedures which return cursors | <p>How would one go about using <a href="http://code.google.com/p/dapper-dot-net" rel="noreferrer">Dapper</a> with Oracle stored procedures which return cursors?</p>
<pre><code>var p = new DynamicParameters();
p.Add("foo", "bar");
p.Add("baz_cursor", dbType: DbType.? , direction: ParameterDirection.Output);
</code></pre>
<p>Here, the DbType is System.Data.DbType which does not have a Cursor member. I've tried using DbType.Object but that does not work with both OracleClient and OracleDataAcess.</p>
<p>What would be a possible way to use OracleType or OracleDbType instead?</p> | 7,395,492 | 4 | 3 | null | 2011-09-12 15:08:18.57 UTC | 13 | 2016-05-03 07:57:48.233 UTC | null | null | null | null | 940,393 | null | 1 | 19 | c#|.net|oracle|dapper | 22,803 | <p>You would have to implement: </p>
<pre><code> public interface IDynamicParameters
{
void AddParameters(IDbCommand command, Identity identity);
}
</code></pre>
<p>Then in the <code>AddParameters</code> callback you would cast the <code>IDbCommand</code> to an <code>OracleCommand</code> and add the DB specific params. </p> |
7,297,937 | Does Java return by reference or by value | <p>I have a HashMap:</p>
<pre><code>private HashMap<String, Integer> cardNumberAndCode_ = new HashMap<String, Integer>();
</code></pre>
<p>And later I do this:</p>
<pre><code>Integer balance = cardNumberBalance_.get(cardNumber);
System.out.println(balance);
balance = 10;
Integer newBalance = cardNumberBalance_.get(cardNumber);
System.out.println(newBalance);
</code></pre>
<p>First it prints <code>1000</code>, and the second time it's printing <code>1000</code>, the value does not change. Why is Java returning the Integer by value and not by reference?</p> | 7,297,944 | 4 | 1 | null | 2011-09-04 07:38:04.393 UTC | 10 | 2020-09-16 14:21:04.79 UTC | 2020-09-16 13:40:19.49 UTC | null | 2,074,869 | null | 334,688 | null | 1 | 20 | java|reference|hashmap | 29,961 | <p>The <code>get</code> method returns a <em>copy</em> of the reference to the stored integer...</p>
<p>Assigning a new value to the variable storing this copy in order to point to the value <code>10</code> will <em>not</em> change the reference in the map.</p>
<p>It would work if you could do <code>balance.setValue(10)</code>, but since <code>Integer</code> is an immutable class, this is not an option.</p>
<p>If you want the changes to take affect in the map, you'll have to wrap the balance in a (mutable) class:</p>
<pre><code>class Balance {
int balance;
...
}
Balance balance = cardNumberBalance_.get(cardNumber);
System.out.println(balance.getBalance());
balance.setBalance(10);
Balance newBalance = cardNumberBalance_.get(cardNumber);
System.out.println(newBalance.getBalance());
</code></pre>
<p>But you would probably want to do something like this instead:</p>
<pre><code>cardNumberBalance_.put(cardNumber, 10);
</code></pre> |
24,372,559 | Reverse Range in Swift | <p>Is there a way to work with reverse ranges in Swift?</p>
<p>For example:</p>
<pre><code>for i in 5...1 {
// do something
}
</code></pre>
<p>is an infinite loop.</p>
<p>In newer versions of Swift that code compiles, but at runtime gives the error: </p>
<blockquote>
<p>Fatal error: Can't form Range with upperBound < lowerBound</p>
</blockquote>
<p>I know I can use <code>1..5</code> instead, calculate <code>j = 6 - i</code> and use <code>j</code> as my index. I was just wondering if there was anything more legible?</p> | 24,372,631 | 7 | 1 | null | 2014-06-23 18:10:31.2 UTC | 19 | 2020-12-08 17:21:50.083 UTC | 2020-05-26 01:12:40.727 UTC | null | 1,265,393 | null | 1,153,435 | null | 1 | 121 | swift | 40,309 | <p><strong>Update For latest Swift 3 (still works in Swift 4)</strong></p>
<p>You can use the <code>reversed()</code> method on a range</p>
<pre><code>for i in (1...5).reversed() { print(i) } // 5 4 3 2 1
</code></pre>
<p>Or <code>stride(from:through:by:)</code> method</p>
<pre><code>for i in stride(from:5,through:1,by:-1) { print(i) } // 5 4 3 2 1
</code></pre>
<p><code>stide(from:to:by:)</code> is similar but excludes the last value</p>
<pre><code>for i in stride(from:5,to:0,by:-1) { print(i) } // 5 4 3 2 1
</code></pre>
<p><strong>Update For latest Swift 2</strong></p>
<p>First of all, protocol extensions change how <code>reverse</code> is used:</p>
<p><code>for i in (1...5).reverse() { print(i) } // 5 4 3 2 1</code></p>
<p>Stride has been reworked in Xcode 7 Beta 6. The new usage is:</p>
<pre><code>for i in 0.stride(to: -8, by: -2) { print(i) } // 0 -2 -4 -6
for i in 0.stride(through: -8, by: -2) { print(i) } // 0 -2 -4 -6 -8
</code></pre>
<p>It also works for <code>Doubles</code>:</p>
<pre><code>for i in 0.5.stride(to:-0.1, by: -0.1) { print(i) }
</code></pre>
<p>Be wary of floating point compares here for the bounds.</p>
<p><strong>Earlier edit for Swift 1.2</strong>: As of Xcode 6 Beta 4, <strong>by</strong> and <strong>ReverseRange</strong> don't exist anymore :[</p>
<p>If you are just looking to reverse a range, the <strong>reverse</strong> function is all you need:</p>
<pre><code>for i in reverse(1...5) { println(i) } // prints 5,4,3,2,1
</code></pre>
<p>As posted by <strong>0x7fffffff</strong> there is a new <strong>stride</strong> construct which can be used to iterate and increment by arbitrary integers. Apple also stated that floating point support is coming.</p>
<p>Sourced from his answer:</p>
<pre><code>for x in stride(from: 0, through: -8, by: -2) {
println(x) // 0, -2, -4, -6, -8
}
for x in stride(from: 6, to: -2, by: -4) {
println(x) // 6, 2
}
</code></pre> |
24,178,930 | Programmatically create sqlite db if it doesn't exist? | <p>I am trying to create an sqlite db programmatically if it doesn't exist. I have written the following code but I am getting an exception at the last line.</p>
<pre><code>if (!System.IO.File.Exists("C:\\Users\\abc\\Desktop\\1\\synccc.sqlite"))
{
Console.WriteLine("Just entered to create Sync DB");
SQLiteConnection.CreateFile("C:\\Users\\abc\\Desktop\\1\\synccc.sqlite");
string sql = "create table highscores (name varchar(20), score int)";
SQLiteCommand command = new SQLiteCommand(sql, sqlite2);
command.ExecuteNonQuery();
}
sqlite2 = new SQLiteConnection("Data Source=C:\\Users\\abc\\Desktop\\1\\synccc.sqlite");
</code></pre>
<p>I get the exception at the line <code>command.ExecuteNonQuery();</code> The exception is <code>Invalid operation exception was unhandled</code>. Is there any other way to add an sqlite file to your project? Can I do it manually? If not then how can I solve the above issue?</p> | 24,179,042 | 1 | 1 | null | 2014-06-12 07:38:31.87 UTC | 1 | 2020-10-23 15:52:15.35 UTC | 2014-06-12 07:42:59.717 UTC | null | 500,452 | null | 2,270,057 | null | 1 | 26 | c#|.net|visual-studio|sqlite | 47,334 | <p>To execute any kind of data definition command on the database you need an open connection to pass the command. In your code you create the connection AFTER the execution of the query.</p>
<p>Of course, after that creation, you need to open the connection</p>
<pre><code>if (!System.IO.File.Exists(@"C:\Users\abc\Desktop\1\synccc.sqlite"))
{
Console.WriteLine("Just entered to create Sync DB");
SQLiteConnection.CreateFile(@"C:\Users\abc\Desktop\1\synccc.sqlite");
using(var sqlite2 = new SQLiteConnection(@"Data Source=C:\Users\abc\Desktop\1\synccc.sqlite"))
{
sqlite2.Open();
string sql = "create table highscores (name varchar(20), score int)";
SQLiteCommand command = new SQLiteCommand(sql, sqlite2);
command.ExecuteNonQuery();
}
}
</code></pre>
<p>However, if you use the version 3 of the provider, you don't have to check for the existence of the file. Just opening the connection will create the file if it doesn't exists.</p> |
48,684,276 | Angular CLI gives me "TypeError: callbacks[i] is not a function" when I "ng serve" | <p>I literally just made a fresh installation of the Angular CLI in order to try it out and I don't have a clue on what's causing the following error on the command line:</p>
<pre><code> PC:cobros Fran$ ng serve
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
95% emitting/Users/Fran/Documents/Workspace/Repos/cobros/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:40
callbacks[i](err, result);
^
TypeError: callbacks[i] is not a function
at Storage.finished (/Users/Fran/Documents/Workspace/Repos/cobros/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:40:15)
at /Users/Fran/Documents/Workspace/Repos/cobros/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:77:9
at /Users/Fran/Documents/Workspace/Repos/cobros/node_modules/graceful-fs/polyfills.js:287:18
at FSReqWrap.oncomplete (fs.js:153:5)
</code></pre>
<p>This is the information I get returned when I try "ng -v" (In case it's useful at all):</p>
<pre><code>Angular CLI: 1.6.8
Node: 8.9.0
OS: darwin x64
Angular: 5.2.4
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router
@angular/cli: 1.6.8
@angular-devkit/build-optimizer: 0.0.42
@angular-devkit/core: 0.0.29
@angular-devkit/schematics: 0.0.52
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.9.8
@schematics/angular: 0.1.17
typescript: 2.5.3
webpack: 3.10.0
</code></pre>
<p>What does the 'enhanced-resolve' module even do?
Did I install angular wrong? I followed the instructions from <a href="https://github.com/angular/angular-cli" rel="noreferrer">https://github.com/angular/angular-cli</a> and made sure I fulfilled the prerequisites.</p> | 48,685,186 | 12 | 9 | null | 2018-02-08 11:20:51.247 UTC | 11 | 2018-03-07 11:41:50.84 UTC | 2018-02-08 14:51:49.203 UTC | null | 5,437,671 | null | 3,819,047 | null | 1 | 44 | javascript|angular|npm|angular-cli | 5,605 | <p>EDIT: The issue is now fixed, so there is no need to use this workaround anymore.</p>
<hr>
<p>Solution (workaround) found <a href="https://github.com/angular/angular-cli/issues/9550#issuecomment-364092554" rel="nofollow noreferrer">here</a> </p>
<p>Add <code>"copy-webpack-plugin": "4.3.0"</code> to your package.json</p>
<p>Thanks @neshkatrapati</p> |
1,430,941 | How to understand an EDI file? | <p>I've seen XML before, but I've never seen anything like <a href="http://en.wikipedia.org/wiki/Electronic_Data_Interchange" rel="noreferrer">EDI</a>.</p>
<p>How do I read this file and get the data that I need? I see things like ~, REF, N1, N2, N4 but have no idea what any of this stuff means.</p>
<p>I am looking for Examples and Documentations.
Where can I find them?</p>
<p>Aslo
EDI guide i found says that it is based on " ANSI ASC X12/ ver. 4010".
Should I search form X12 ? </p>
<p>Kindly help.</p> | 1,431,033 | 4 | 3 | null | 2009-09-16 04:28:29.87 UTC | 24 | 2020-06-22 04:10:52.14 UTC | 2009-09-16 06:38:27.457 UTC | null | 28,169 | null | 155,080 | null | 1 | 35 | parsing|edi | 55,650 | <p>Wow, flashbacks. It's been over sixteen years ...</p>
<p>In principle, each line is a "segment", and the identifiers are the beginning of the line is a segment identifier. Each segment contains "elements" which are essentially positional fields. They are delimited by "element delimiters".</p>
<p>Different segments mean different things, and can indicate looping constructs, repeats, etc.</p>
<p>You need to get a current version of the standard for the basic parsing, and then you need the data dictionary to describe the content of the document you are dealing with, and then you might need an industry profile, implementation guide, or similar to deal with the conventions for the particular document type in your environment.</p>
<p>Examples? Not current, but I'm sure you could find a whole bunch using your search engine of choice. Once you get the basic segment/element parsing done, you're dealing with your application level data, and I don't know how much a general example will help you there.</p> |
1,722,437 | Is there a way to get a web page header/footer printed on every page? | <p>Based on my research, it seems that what I want to do is not possible, but in case something has changed, I wanted to check to see if anyone had come up with a way to do this.</p>
<p>I have a web app that generates reports for print based on user selections in the browser window. I have a custom header and footer that, when the report is printed from the browser, should be repeated on every printed page. It is not the browser header and footer I need, but rather the custom ones that I generate. Also, I don't think this is an issue of CSS and media types, but I am not a CSS expert. I have no issues getting the header and footer to print once, but I can't get them to print on each page. I have read that perhaps if I recreated my report pages using tables, and then used table head tags and CSS, that may work at least to get the header on each page. I have not had success with this yet, but I will try it again if it is the only option. A coworker suggested that I count lines in my php and manually put out the header and footer as required. I guess that is an option, but it just seems like there should be a way to do this that isn't so "brute force"!</p>
<p>The other caveat is that I have to support IE 6, so I suspect some of the CSS things I have tried are just not supported.</p>
<p>If anyone knows any way to do this, that would be great! If there isn't, I will have to rethink my approach.</p>
<p>Thanks in advance!</p>
<p><strong>UPDATE (14 Dec 2011)</strong></p>
<p>I made considerable progress with this issue, and using some of the info from the answers, I did produce reports that were usable, but never as nice or as professional as I wanted. Footers would tend to be not close enough to the bottom of the page, I had to do a lot of guess work and "brittle" calculations about how big text was going to be to decide on inserting page breaks, I could only support a restricted set of page formats, and any changes to the reports resulted in a cascade of code changes and yet more brittle calculations. There was always a scenario that broke some part of some report. We revisted the requirements, <strong>and are now generating reports as PDFs using TCPDF</strong>. The documentation is a bit opaque, and it takes some experimentation, but the results are far superior and now the reports appear as they should. I would say to anyone trying to do HTML reports from the browser, unless they are very simple, save yourself the frustration (as others told me here) and go with PDFs or something similar.</p> | 1,723,078 | 4 | 5 | null | 2009-11-12 14:08:33.17 UTC | 8 | 2018-04-16 11:57:07.787 UTC | 2011-12-14 20:29:19.733 UTC | null | 181,180 | null | 181,180 | null | 1 | 39 | html|css|header|printing|footer | 35,355 | <p>It can be done with tables -- and I know I'm going to risk a downvote by suggesting using tables for layout - but we are talking IE6 here which isn't known for its fantastic CSS support :-)</p>
<p>If you set a CSS style as follows:</p>
<pre><code>thead { display: table-header-group; }
tfoot { display: table-footer-group; }
</code></pre>
<p>Then when you create your HTML, render your body as:</p>
<pre><code><body>
<table>
<thead><tr><td>Your header goes here</td></tr></thead>
<tfoot><tr><td>Your footer goes here</td></tr></tfoot>
<tbody>
<tr><td>
Page body in here -- as long as it needs to be
</td></tr>
</tbody>
</table>
</body>
</code></pre>
<p>Yes it's not good (tables vs CSS), it's not ideal, but (importantly for you) it does work on IE6. I can't comment on Firefox as I've not tested it there, but it should do the job. This will also handle differnt sized pages, differing font sizes, etc. so it should "just work".</p>
<p>If you want the header and footer to appear on printed media only, then use the @media parameters to do the right thing:</p>
<pre><code>@media print {
thead { display: table-header-group; }
tfoot { display: table-footer-group; }
}
@media screen {
thead { display: none; }
tfoot { display: none; }
}
</code></pre>
<p><strong><em>Note</em></strong><br>
<strike>As of July 2015, this will still only work in Firefox and IE. Webkit-based browsers (cf. Chrome, Safari) have long standing bugs in their issue trackers about this if anyone feels strongly enough to vote on them:</strike></p>
<p>The comments below this question tell me this is now resolved in Chrome. I haven't checked myself :-)</p>
<p>The original bugs against Chrome (for reference) are:</p>
<ul>
<li><a href="https://bugs.webkit.org/show_bug.cgi?id=17205" rel="nofollow noreferrer">https://bugs.webkit.org/show_bug.cgi?id=17205</a></li>
<li><a href="https://code.google.com/p/chromium/issues/detail?id=24826" rel="nofollow noreferrer">https://code.google.com/p/chromium/issues/detail?id=24826</a></li>
<li><a href="https://code.google.com/p/chromium/issues/detail?id=99124" rel="nofollow noreferrer">https://code.google.com/p/chromium/issues/detail?id=99124</a></li>
</ul> |
1,476,512 | Changing the current count of an Auto Increment value in MySQL? | <p>Currently every time I add an entry to my database, the auto increment value increments by 1, as it should. However, it is only at a count of 47. So, if I add a new entry, it will be 48, and then another it will be 49 etc.</p>
<p>I want to change what the current Auto Increment counter is at. I.e. I want to change it from 47 to say, 10000, so that the next value entered, will be 10001. How do I do that?</p> | 1,476,535 | 4 | 0 | null | 2009-09-25 10:17:27.787 UTC | 7 | 2019-12-20 15:05:17.787 UTC | null | null | null | null | 146,366 | null | 1 | 63 | mysql | 49,040 | <p>You can use <a href="http://dev.mysql.com/doc/refman/5.1/en/alter-table.html" rel="noreferrer">ALTER TABLE</a> to set the value of an AUTO_INCREMENT column ; quoting that page :</p>
<blockquote>
<p>To change the value of the
<code>AUTO_INCREMENT</code> counter to be used for
new rows, do this:</p>
</blockquote>
<pre><code>ALTER TABLE t2 AUTO_INCREMENT = value;
</code></pre>
<p>There is also a note saying that :</p>
<blockquote>
<p>You cannot reset the counter to a
value less than or equal to any that
have already been used.
<br>For MyISAM, if
the value is less than or equal to the
maximum value currently in the
<code>AUTO_INCREMENT</code> column, the value is
reset to the current maximum plus one.
<br>For InnoDB, if the value is less than
the current maximum value in the
column, no error occurs and the
current sequence value is not changed.</p>
</blockquote>
<p>Hope this helps !</p> |
1,624,782 | Django model fields validation | <p>Where should the validation of <em>model fields</em> go in django?</p>
<p>I could name at least two possible choices: in the overloaded .save() method of the model or in the .to_python() method of the models.Field subclass (obviously for that to work you must write custom fields).</p>
<p>Possible use cases:</p>
<ul>
<li>when it is absolutely neccessary to ensure, that an empty string doesn't get written into the database (blank=False keyword argument doesn't work here, it is for form validation only)</li>
<li>when it is neccessary to ensure, that "choices" keyword argument gets respected on a db-level and not only in admin interface (kind of emulating a enum datatype)</li>
</ul>
<p>There is also a class-level attribute <code>empty_strings_allowed</code> in the models.Field base class definition and derived classes happily override it, however it doesn't seem to produce any effect on the database level, meaning I can still construct a model with empty-string fields and save it to the database. Which I want to avoid (yes, it is neccessary).</p>
<p>Possible implementations are</p>
<p>on the field level:</p>
<pre><code>class CustomField(models.CharField):
__metaclass__ = models.SubfieldBase
def to_python(self, value):
if not value:
raise IntegrityError(_('Empty string not allowed'))
return models.CharField.to_python(self, value)
</code></pre>
<p>on the model level:</p>
<pre><code>class MyModel(models.Model)
FIELD1_CHOICES = ['foo', 'bar', 'baz']
field1 = models.CharField(max_length=255,
choices=[(item,item) for item in FIELD1_CHOICES])
def save(self, force_insert=False, force_update=False):
if self.field1 not in MyModel.FIELD1_CHOICES:
raise IntegrityError(_('Invalid value of field1'))
# this can, of course, be made more generic
models.Model.save(self, force_insert, force_update)
</code></pre>
<p>Perhaps, I am missing something and this can be done easier (and cleaner)?</p> | 1,625,760 | 4 | 0 | null | 2009-10-26 13:27:15.273 UTC | 25 | 2016-03-25 17:21:07.597 UTC | null | null | null | null | 96,282 | null | 1 | 64 | python|django|django-models | 56,136 | <p>Django has a <a href="https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects" rel="noreferrer">model validation</a> system in place since version 1.2.</p>
<p>In comments sebpiq says "Ok, now there is a place to put model validation ... except that it is run only when using a ModelForm! So the question remains, when it is necessary to ensure that validation is respected at the db-level, what should you do? Where to call full_clean?"</p>
<p>It's not possible via Python-level validation to ensure that validation is respected on the db level. The closest is probably to call <code>full_clean</code> in an overridden <code>save</code> method. This isn't done by default, because it means everybody who calls that save method had now better be prepared to catch and handle <code>ValidationError</code>. </p>
<p>But even if you do this, someone can still update model instances in bulk using <code>queryset.update()</code>, which will bypass this validation. There is no way Django could implement a reasonably-efficient <code>queryset.update()</code> that could still perform Python-level validation on every updated object.</p>
<p>The only way to really guarantee db-level integrity is through db-level constraints; any validation you do through the ORM requires the writer of app code to be aware of when validation is enforced (and handle validation failures).</p>
<p>This is why model validation is by default only enforced in <code>ModelForm</code> - because in a ModelForm there is already an obvious way to handle a <code>ValidationError</code>.</p> |
1,562,367 | How do short URLs services work? | <p>How do services like <a href="http://tinyurl.com/" rel="noreferrer">TinyURL</a> or <a href="http://metamark.net/" rel="noreferrer">Metamark</a> work?<br>
Do they simply associate the tiny URL key with a [virtual?] web page which merely provide an "HTTP redirect" to the original URL? or is there more "magic" to it ?</p>
<p>[original wording]
I often use URL shortening services like TinyURL, Metamark, and others, but every time I do, I wonder how these services work. Do they create a new file that will redirect to another page or do they use subdomains?</p> | 1,562,539 | 4 | 4 | null | 2009-10-13 19:20:09.26 UTC | 64 | 2016-10-23 04:33:17.9 UTC | 2012-04-04 17:09:08.537 UTC | null | 111,575 | null | 126,353 | null | 1 | 116 | web-services|url|url-shortener|bit.ly|short-url | 74,656 | <p>No, they don't use files. When you click on a link like that, an HTTP request is send to their server with the full URL, like <a href="http://bit.ly/duSk8wK" rel="noreferrer">http://bit.ly/duSk8wK</a> (links to this question). They read the path part (here <code>duSk8wK</code>), which maps to their database. In the database, they find a description (sometimes), your name (sometimes) and the real URL. Then they issue a redirect, which is a HTTP 302 response and the target URL in the header.</p>
<p>This direct redirect is important. If you were to use files or first load HTML and then redirect, the browser would add TinyUrl to the history, which is not what you want. Also, the site that is redirected to will see the referrer (the site that you originally come from) as being the site the TinyUrl link is on (i.e., twitter.com, your own site, wherever the link is). This is just as important, so that site owners can see where people are coming from. This too, would not work if a page gets loaded that redirects.</p>
<p>PS: there are more types of redirect. HTTP 301 means: redirect permanent. If that would happen, the browser will not request the bit.ly or TinyUrl site anymore and those sites want to count the hits. That's why HTTP 302 is used, which is a temporary redirect. The browser will ask TinyUrl.com or bit.ly each time again, which makes it possible to count the hits for you (some tiny url services offer this).</p> |
10,820,343 | How can I generate new variable names on the fly in a shell script? | <p>I'm trying to generate dynamic var names in a shell script to process a set of files with distinct names in a loop as follows:</p>
<pre><code>#!/bin/bash
SAMPLE1='1-first.with.custom.name'
SAMPLE2='2-second.with.custom.name'
for (( i = 1; i <= 2; i++ ))
do
echo SAMPLE{$i}
done
</code></pre>
<p>I would expect the output:</p>
<pre><code>1-first.with.custom.name
2-second.with.custom.name
</code></pre>
<p>but i got:</p>
<pre><code>SAMPLE{1}
SAMPLE{2}
</code></pre>
<p>Is it possible generate var names in the fly?</p> | 10,820,494 | 6 | 2 | null | 2012-05-30 16:25:53.887 UTC | 22 | 2021-07-20 20:55:53.833 UTC | 2012-05-31 07:10:42.75 UTC | null | 1,301,972 | null | 714,967 | null | 1 | 40 | linux|bash|shell | 56,330 | <p>You need to utilize Variable Indirection:</p>
<pre><code>SAMPLE1='1-first.with.custom.name'
SAMPLE2='2-second.with.custom.name'
for (( i = 1; i <= 2; i++ ))
do
var="SAMPLE$i"
echo ${!var}
done
</code></pre>
<p>From the <a href="https://linux.die.net/man/1/bash" rel="noreferrer">Bash man page</a>, under 'Parameter Expansion':</p>
<blockquote>
<p>"If the first character of parameter is an exclamation point (!), a
level of variable indirection is introduced. Bash uses the value of
the variable formed from the rest of parameter as the name of the
variable; this variable is then expanded and that value is used in the
rest of the substitution, rather than the value of parameter itself.
This is known as indirect expansion."</p>
</blockquote> |
10,432,086 | Remove all spaces from a string in SQL Server | <p>What is the best way to remove all spaces from a string in SQL Server 2008?</p>
<p><code>LTRIM(RTRIM(' a b '))</code> would remove all spaces at the right and left of the string, but I also need to remove the space in the middle.</p> | 10,432,124 | 25 | 2 | null | 2012-05-03 13:09:50.457 UTC | 53 | 2022-09-24 22:25:50.337 UTC | 2022-02-19 09:40:15.383 UTC | null | 792,066 | null | 277,087 | null | 1 | 304 | sql-server | 1,090,501 | <p>Simply replace it;</p>
<pre><code>SELECT REPLACE(fld_or_variable, ' ', '')
</code></pre>
<p><strong>Edit:</strong>
Just to clarify; its a global replace, there is no need to <code>trim()</code> or worry about multiple spaces for either <code>char</code> or <code>varchar</code>:</p>
<pre><code>create table #t (
c char(8),
v varchar(8))
insert #t (c, v) values
('a a' , 'a a' ),
('a a ' , 'a a ' ),
(' a a' , ' a a' ),
(' a a ', ' a a ')
select
'"' + c + '"' [IN], '"' + replace(c, ' ', '') + '"' [OUT]
from #t
union all select
'"' + v + '"', '"' + replace(v, ' ', '') + '"'
from #t
</code></pre>
<p><strong>Result</strong></p>
<pre><code>IN OUT
===================
"a a " "aa"
"a a " "aa"
" a a " "aa"
" a a " "aa"
"a a" "aa"
"a a " "aa"
" a a" "aa"
" a a " "aa"
</code></pre> |
26,412,947 | Reliable way to detect if a column in a data.frame is.POSIXct | <p>R has <code>is.vector</code>, <code>is.list</code>, <code>is.integer</code>, <code>is.double</code>, <code>is.numeric</code>, <code>is.factor</code>, <code>is.character</code>, etc. Why is there no <code>is.POSIXct</code>, <code>is.POSIXlt</code> or <code>is.Date</code>?</p>
<p>I need a reliable way to detect <code>POSIXct</code> object, and <code>class(x)[1] == "POSIXct"</code> seems really... dirty.</p> | 26,413,765 | 3 | 1 | null | 2014-10-16 20:05:35.44 UTC | 2 | 2014-10-16 21:05:28.907 UTC | null | null | null | null | 345,660 | null | 1 | 30 | r|datetime|posixct | 9,524 | <p>I would personally just use <code>inherits</code> as <a href="https://stackoverflow.com/questions/26412947/reliable-way-to-detect-if-a-column-in-a-data-frame-is-posixct#comment41473978_26412947">joran</a> suggested. You could use it to create your own <code>is.POSIXct</code> function.</p>
<pre><code># functions
is.POSIXct <- function(x) inherits(x, "POSIXct")
is.POSIXlt <- function(x) inherits(x, "POSIXlt")
is.POSIXt <- function(x) inherits(x, "POSIXt")
is.Date <- function(x) inherits(x, "Date")
# data
d <- data.frame(pct = Sys.time())
d$plt <- as.POSIXlt(d$pct)
d$date <- Sys.Date()
# checks
sapply(d, is.POSIXct)
# pct plt date
# TRUE FALSE FALSE
sapply(d, is.POSIXlt)
# pct plt date
# FALSE TRUE FALSE
sapply(d, is.POSIXt)
# pct plt date
# TRUE TRUE FALSE
sapply(d, is.Date)
# pct plt date
# FALSE FALSE TRUE
</code></pre> |
25,983,090 | Is sanitizing JSON necessary? | <p>I think it's a well-known best practice on the web to mistrust any input. The sentence</p>
<blockquote>
<p>"All input is evil."</p>
</blockquote>
<p>is probably the most cited quote with respect to input validation. Now, for HTML you can use tools such as <a href="https://github.com/cure53/DOMPurify" rel="noreferrer">DOMPurify</a> to sanitize it.</p>
<p>My question is if I have a Node.js server running Express and <a href="https://github.com/expressjs/body-parser" rel="noreferrer">body-parser</a> middleware to receive and parse JSON, do I need to run any sanitizing as well?</p>
<p>My (maybe naive?) thoughts on this are that JSON is only data, no code, and if somebody sends invalid JSON, body-parser (which uses <code>JSON.parse()</code> internally) will fail anyway, so I know that my app will receive a valid JavaScript object. As long as I don't run eval on that or call a function, I should be fine, shouldn't I?</p>
<p>Am I missing something?</p> | 25,983,468 | 2 | 1 | null | 2014-09-22 21:05:05.083 UTC | 11 | 2021-02-05 10:58:48.543 UTC | 2019-05-31 10:52:02.63 UTC | null | 8,791,568 | null | 1,333,873 | null | 1 | 35 | javascript|node.js|json|sanitization|dompurify | 32,588 | <p>Since <code>JSON.parse()</code> does not run any code in the data to be parsed, it is not vulnerable the way <code>eval()</code> is, but there are still things you should do to protect the integrity of your server and application such as:</p>
<ol>
<li>Apply exception handlers in the appropriate place as <code>JSON.parse()</code> can throw an exception.</li>
<li>Don't make assumptions about what data is there, you must explicitly test for data before using it.</li>
<li>Only process properties you are specifically looking for (avoiding other things that might be in the JSON).</li>
<li>Validate all incoming data as legitimate, acceptable values.</li>
<li>Sanitize the length of data (to prevent DOS issues with overly large data). </li>
<li>Don't put this incoming data into places where it could be further evaluated such as directly into the HTML of the page or injected directly into SQL statements without further sanitization to make sure it is safe for that environment.</li>
</ol>
<p>So, to answer your question directly, "yes" there is more to do than just using body-parser though it is a perfectly fine front line for first processing the data. The next steps for what you do with the data once you get it from body-parser do matter in many cases and can require extra care.</p>
<hr>
<p>As an example, here's a parsing function that expects an object with properties that applies some of these checks and gives you a filtered result that only contains the properties you were expecting:</p>
<pre><code>// pass expected list of properties and optional maxLen
// returns obj or null
function safeJSONParse(str, propArray, maxLen) {
var parsedObj, safeObj = {};
try {
if (maxLen && str.length > maxLen) {
return null;
} else {
parsedObj = JSON.parse(str);
if (typeof parsedObj !== "object" || Array.isArray(parsedObj)) {
safeObj = parseObj;
} else {
// copy only expected properties to the safeObj
propArray.forEach(function(prop) {
if (parsedObj.hasOwnProperty(prop)) {
safeObj[prop] = parseObj[prop];
}
});
}
return safeObj;
}
} catch(e) {
return null;
}
}
</code></pre> |
26,089,802 | In Sublime Text 3, how do you enable Emmet for JSX files? | <p>I had been previously using <a href="https://github.com/allanhortle/JSX">Allan Hortle's JSX package</a> until I ran into an issue with how it handled syntax highlighting. I then noticed that there is an official package, <a href="https://github.com/reactjs/sublime-react">sublime-react</a>.</p>
<p>With Allan Hortle's package, he included a snippet in the <code>Preferences > Key Bindings – User</code> for enabling Emmet functionality that looks like this:</p>
<pre><code>{
"keys": ["tab"],
"command": "expand_abbreviation_by_tab",
"context": [
{
"operand": "source.js.jsx",
"operator": "equal",
"match_all": true,
"key": "selector"
}
]
}
</code></pre>
<p>This snippet doesn't appear to work with the official sublime-react package. It seems to be something to modify with the key bindings but an initial perusal of the Sublime documentation yielded no light on the subject. Help?</p> | 26,619,524 | 6 | 1 | null | 2014-09-28 21:23:16.097 UTC | 21 | 2021-02-08 21:18:43.78 UTC | 2015-08-06 18:53:26.353 UTC | null | 1,048,572 | null | 2,445,937 | null | 1 | 63 | sublimetext3|reactjs|emmet | 26,111 | <p>If you type <code>shift+super+p</code> in a file it will let you see the current selection's context in the bottom left.</p>
<p>The first word is always the base file type. (<code>source.js</code>, <code>text.html</code>) In the case of the <a href="https://github.com/allanhortle/JSX">JSX</a> I chose to change this to <code>source.js.jsx</code>. This is because before it is compiled JSX really isn't javascript, though it does look rather similar. There are plenty of completions and sublime sugar that you'd like to have happen in JSX but not JS. <a href="https://github.com/reactjs/sublime-react">sublime-react</a> on the other hand uses plain old <code>source.js</code>. </p>
<p>So this snippet you have is right you just need to replace <code>source.js.jsx</code> with <code>source.js</code></p> |
36,313,850 | Debug view hierarchy in Xcode 7.3 fails | <p>This function fails with runtime error:</p>
<pre><code>-[UIWindow viewForFirstBaselineLayout]: unrecognized selector sent to instance 0x7fb9dae257d0
</code></pre>
<p>Anybody encountered the same?</p>
<p><strong>UPD:</strong><br>
Fails on simulator iOS 8.1/8.4. 9.3 works fine.</p>
<p><strong>UPD2:</strong>
<code>UIWindow</code> is created like:</p>
<pre><code>window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.rootViewController = RootViewController.rootVC
window?.makeKeyAndVisible()
</code></pre> | 36,926,620 | 3 | 9 | null | 2016-03-30 15:51:24.69 UTC | 12 | 2016-06-15 16:28:15.823 UTC | 2016-03-31 08:45:42.91 UTC | null | 1,469,060 | null | 1,469,060 | null | 1 | 21 | xcode|swift | 5,450 | <p>I got the view debugger working again by placing the following fix in my project:</p>
<pre><code>#ifdef DEBUG
#import <UIKit/UIKit.h>
#import <objc/runtime.h>
@implementation UIView (FixViewDebugging)
+ (void)load
{
Method original = class_getInstanceMethod(self, @selector(viewForBaselineLayout));
class_addMethod(self, @selector(viewForFirstBaselineLayout), method_getImplementation(original), method_getTypeEncoding(original));
class_addMethod(self, @selector(viewForLastBaselineLayout), method_getImplementation(original), method_getTypeEncoding(original));
}
@end
#endif
</code></pre>
<p>When your project loads, the <code>load</code> method will execute, causing <code>viewForFirstBaselineLayout</code> and <code>viewForLastBaselineLayout</code> to use the <code>viewForBaselineLayout</code> implementation if they are not currently implemented, so view debugging gets iOS8 flavor the behavior it was looking for.</p>
<p>To add this to your own project, create a new empty Objective-C file in your project and paste the contents in. You can name it whatever you want. I call mine "UIView+FixViewDebugging". If you are in a pure Swift project you <strong>do not</strong> need to create a bridging header. The file will be compiled into your project and you don't need to reference it.</p>
<p>Note this will only work for debug builds because of the <code>#ifdef DEBUG</code>. You can remove it but then you may accidentally compile this into your release builds (though it should have no ill side effects). If this method isn't working with these lines, check that your target has <code>DEBUG=1</code> in Build Settings > Apple LLVM - Preprocessing > Preprocessor Macros > Debug.</p> |
7,073,785 | Dataframes in a list; adding a new variable with name of dataframe | <p>I have a list of dataframes which I eventually want to merge while maintaining a record of their original dataframe name or list index. This will allow me to subset etc across all the rows. To accomplish this I would like to add a new variable 'id' to every dataframe, which contains the name/index of the dataframe it belongs to.</p>
<p>Edit: "In my real code the dataframe variables are created from reading multiple files using the following code, so I don't have actual names only those in the 'files.to.read' list which I'm unsure if they will align with the dataframe order:</p>
<pre><code>mylist <- llply(files.to.read, read.csv)
</code></pre>
<p>A few methods have been highlighted in several posts:
<a href="https://stackoverflow.com/questions/6399011/working-with-dataframes-in-a-list-drop-variables-add-new-ones">Working-with-dataframes-in-a-list-drop-variables-add-new-ones</a> and
<a href="https://stackoverflow.com/questions/6253159/using-lapply-with-changing-arguments">Using-lapply-with-changing-arguments</a></p>
<p>I have tried two similar methods, the first using the index list:</p>
<pre><code>df1 <- data.frame(x=c(1:5),y=c(11:15))
df2 <- data.frame(x=c(1:5),y=c(11:15))
mylist <- list(df1,df2)
# Adds a new coloumn 'id' with a value of 5 to every row in every dataframe.
# I WANT to change the value based on the list index.
mylist1 <- lapply(mylist,
function(x){
x$id <- 5
return (x)
}
)
#Example of what I WANT, instead of '5'.
#> mylist1
#[[1]]
#x y id
#1 1 11 1
#2 2 12 1
#3 3 13 1
#4 4 14 1
#5 5 15 1
#
#[[2]]
#x y id
#1 1 11 2
#2 2 12 2
#3 3 13 2
#4 4 14 2
#5 5 15 2
</code></pre>
<p>The second attempts to pass the names() of the list.</p>
<pre><code># I WANT it to add a new coloumn 'id' with the name of the respective dataframe
# to every row in every dataframe.
mylist2 <- lapply(names(mylist),
function(x){
portfolio.results[[x]]$id <- "dataframe name here"
return (portfolio.results[[x]])
}
)
#Example of what I WANT, instead of 'dataframe name here'.
# mylist2
#[[1]]
#x y id
#1 1 11 df1
#2 2 12 df1
#3 3 13 df1
#4 4 14 df1
#5 5 15 df1
#
#[[2]]
#x y id
#1 1 11 df2
#2 2 12 df2
#3 3 13 df2
#4 4 14 df2
#5 5 15 df2
</code></pre>
<p>But the names() function doesn't work on a list of dataframes; it returns NULL.
Could I use seq_along(mylist) in the first example.</p>
<p>Any ideas or better way to handle the whole "merge with source id"</p>
<p><strong>Edit - Added Solution below:</strong> I've implemented a solution using Hadleys suggestion and Tommy’s nudge which looks something like this. </p>
<pre><code>files.to.read <- list.files(datafolder, pattern="\\_D.csv$", full.names=FALSE)
mylist <- llply(files.to.read, read.csv)
all <- do.call("rbind", mylist)
all$id <- rep(files.to.read, sapply(mylist, nrow))
</code></pre>
<p>I used the files.to.read vector as the id for each dataframe</p>
<p>I also changed from using merge_recurse() as it was very slow for some reason. </p>
<pre><code> all <- merge_recurse(mylist)
</code></pre>
<p>Thanks everyone.</p> | 7,083,029 | 5 | 0 | null | 2011-08-16 05:01:22.897 UTC | 11 | 2022-05-04 09:32:26.45 UTC | 2017-05-23 11:52:56.527 UTC | null | -1 | null | 821,045 | null | 1 | 15 | list|r|dataframe|names|lapply | 10,561 | <p>Personally, I think it's easier to add the names after collapse:</p>
<pre><code>df1 <- data.frame(x=c(1:5),y=c(11:15))
df2 <- data.frame(x=c(1:5),y=c(11:15))
mylist <- list(df1 = df1, df2 = df2)
all <- do.call("rbind", mylist)
all$id <- rep(names(mylist), sapply(mylist, nrow))
</code></pre> |
7,274,392 | Perform PHP loops until end of array OR reaches certain number of iterations? | <p>I wish to receive one array as input, filter values from it, and output as another array. The function should loop through up to <code>x</code> iterations.</p>
<p>For example, if I wanted to output <strong>all</strong> the values from the input, I would use:</p>
<pre><code><?php
$i=0;
foreach ($array as $data) {
if ($data['type'] != 'some_value') {
$formatted_array[$i] = $data;
$i++;
}
}
return $formatted_array;
</code></pre>
<p>But if <code>$array</code> had a large index, the <code>$formatted_array</code> would be larger than I need. I tried using a <code>for</code> loop with multiple conditions, but it seems to get stuck in an infinite loop.</p>
<p>I'm not a developer by trade, so the logic is difficult to comprehend. I'm not getting errors, so it's hard to understand where exactly I'm going wrong.</p>
<p>How can I perform PHP loops until end of array or until the function reaches certain number of iterations?</p> | 7,274,450 | 6 | 1 | null | 2011-09-01 17:54:33.693 UTC | 5 | 2018-09-03 11:40:54.603 UTC | 2011-09-01 17:58:28.47 UTC | null | 229,044 | null | 566,852 | null | 1 | 12 | php|loops|for-loop|foreach|while-loop | 40,293 | <p>You're on the right track - you can exit the <code>foreach</code> loop when you reach your count. You use a <code>foreach</code> to iterate over the full array and if you never reach your stated maximum count, you will process the whole array. But if you do reach the maximum, jump out of the loop.</p>
<pre><code>$i = 0;
// Don't allow more than 5 if the array is bigger than 5
$maxiterations = 5;
foreach ($array as $data) {
if ($i < $maxiterations) {
if ($data['type'] != 'some_value') {
$formatted_array[$i] = $data;
$i++;
}
}
else { // Jump out of the loop if we hit the maximum
break;
}
}
return $formatted_array;
</code></pre> |
7,358,637 | Reading DOC file in php | <p>I'm trying to read <code>.doc .docx</code> file in php. All is working fine. But at last line I'm getting awful characters. Please help me.
Here is code which is developed by someone.</p>
<pre><code> function parseWord($userDoc)
{
$fileHandle = fopen($userDoc, "r");
$line = @fread($fileHandle, filesize($userDoc));
$lines = explode(chr(0x0D),$line);
$outtext = "";
foreach($lines as $thisline)
{
$pos = strpos($thisline, chr(0x00));
if (($pos !== FALSE)||(strlen($thisline)==0))
{
} else {
$outtext .= $thisline." ";
}
}
$outtext = preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\t@\/\_\(\)]/","",$outtext);
return $outtext;
}
$userDoc = "k.doc";
</code></pre>
<p>Here is screenshot.
<img src="https://i.stack.imgur.com/dTnM9.png" alt="enter image description here"></p> | 7,358,766 | 6 | 2 | null | 2011-09-09 07:53:53.987 UTC | 9 | 2021-07-21 19:42:30.61 UTC | null | null | null | null | 559,744 | null | 1 | 14 | php | 58,517 | <p>DOC files are not <a href="http://en.wikipedia.org/wiki/Plain_text" rel="nofollow noreferrer">plain text</a>.</p>
<p>Try a library such as <a href="https://github.com/PHPOffice/PHPWord" rel="nofollow noreferrer">PHPWord</a> (<a href="http://phpword.codeplex.com/" rel="nofollow noreferrer">old CodePlex site</a>).</p>
<p>nb: This answer has been updated multiple times as PHPWord has changed hosting and functionality.</p> |
7,308,908 | Waiting for dynamically loaded script | <p>In my page body, I need to insert this code as the result of an AJAX call:</p>
<pre><code> <p>Loading jQuery</p>
<script type='text/javascript' src='scripts/jquery/core/jquery-1.4.4.js'></script>
<p>Using jQuery</p>
<script type='text/javascript'>
$.ajax({
...
});
</script>
</code></pre>
<p>I can't use <code>$.load()</code> since the document has already loaded, so the event doesn't fire.</p>
<p>Is this safe? If not, how do I make sure the jquery script has loaded before my custom, generated code is executed.</p> | 7,308,984 | 9 | 1 | null | 2011-09-05 13:38:42.763 UTC | 8 | 2022-04-01 07:05:12.41 UTC | 2017-04-17 23:58:00.143 UTC | null | 652,626 | null | 34,088 | null | 1 | 71 | javascript|jquery|html|load-order | 110,232 | <p>It is pretty safe. Historically, <code><script></code> tags are full blocking, hence the second <code><script></code> tag can't get encountered befored the former has finished parsing/excuting. Only problem might be that "modern" browsers tend to load scripts asynchronously and deferred. So to make sure order is correct, use it like this:</p>
<pre><code><p>Loading jQuery</p>
<script type='text/javascript' async=false defer=false src='scripts/jquery/core/jquery-1.4.4.js'></script>
<p>Using jQuery</p>
<script type='text/javascript'>
$.ajax({
...
});
</script>
</code></pre>
<p>However, it's probably a better idea it use dynamic script tag insertion instead of pushing this as HTML string into the DOM. Would be the same story</p>
<pre><code>var scr = document.createElement('script'),
head = document.head || document.getElementsByTagName('head')[0];
scr.src = 'scripts/jquery/core/jquery-1.4.4.js';
scr.async = false; // optionally
head.insertBefore(scr, head.firstChild);
</code></pre> |
7,105,561 | A generic error occurred in GDI+ | <p>I loaded an image into a Picture Box using:</p>
<pre><code>picturebox1.Image = Image.FromFile()
</code></pre>
<p>and I save it by using:</p>
<pre><code>Bitmap bm = new Bitmap(pictureBox1.Image);
bm.Save(FileName, ImageFormat.Bmp);
</code></pre>
<p>It works perfectly fine when creating a new file, but when I try to replace the existing image, I get thrown the following runtime error: </p>
<blockquote>
<p>A generic error occurred in GDI+</p>
</blockquote>
<p>So what can I do to solve this problem?? </p> | 7,105,595 | 11 | 0 | null | 2011-08-18 09:55:04.863 UTC | 1 | 2019-09-20 14:38:26.323 UTC | 2014-05-21 08:26:47.163 UTC | null | 738,017 | null | 887,147 | null | 1 | 20 | c#|bitmap|gdi+ | 57,573 | <p>That because the image file is used by your <code>picturebox1.Image</code>, try to save it to different file path instead:</p>
<pre><code>picturebox1.Image = Image.FromFile(FileName);
Bitmap bm = new Bitmap(pictureBox1.Image);
bm.Save(@"New File Name", ImageFormat.Bmp);
</code></pre>
<p><strong>Edit:</strong> You could also add a copy from the image at the first place like:</p>
<pre><code>picturebox1.Image = new Bitmap(Image.FromFile(FileName));
Bitmap bm = new Bitmap(pictureBox1.Image);
bm.Save(FileName, ImageFormat.Bmp);//no error will occurs here.
</code></pre> |
7,412,548 | Error "gnu/stubs-32.h: No such file or directory" while compiling Nachos source code | <p>I am trying to install Nachos on my laptop and I have Ubuntu 11.04 on the laptop. </p>
<p>The code is in C and so to build it I assume I will need cross compiler. This is where my problem is. I downloaded the source code of the MIPS cross compiler using the command </p>
<pre><code> wget http://mll.csie.ntu.edu.tw/course/os_f08/assignment/mips-decstation.linux-xgcc.gz
</code></pre>
<p>and I unzipped it using </p>
<pre><code>tar zxvf mips-decstation.linux-xgcc.gz
</code></pre>
<p>This is okay, but when I try to build the source code of the nachos os, using make, I get this error -</p>
<pre><code>/usr/include/gnu/stubs.h:7:27: fatal error: gnu/stubs-32.h: No such file or directory compilation terminated. make: *** [bitmap.o] Error 1
</code></pre>
<p>I am trying to follow the instructions given over here - <a href="http://mll.csie.ntu.edu.tw/course/os_f08/217.htm" rel="noreferrer">http://mll.csie.ntu.edu.tw/course/os_f08/217.htm</a> and everything is working fine except when I try to use make.</p> | 7,412,698 | 12 | 1 | null | 2011-09-14 07:12:58.217 UTC | 60 | 2022-07-19 11:52:51.837 UTC | 2014-04-09 09:32:16.73 UTC | null | 3,052,751 | null | 775,936 | null | 1 | 185 | ubuntu|gcc|mips|cross-compiling|nachos | 235,990 | <p>You're missing the 32 bit libc dev package:</p>
<p>On <strong>Ubuntu</strong> it's called libc6-dev-i386 - do <code>sudo apt-get install libc6-dev-i386</code>. See below for extra instructions for Ubuntu 12.04.</p>
<p>On <strong>Red Hat</strong> distros, the package name is <code>glibc-devel.i686</code> (Thanks to David Gardner's comment).</p>
<p>On <strong>CentOS 5.8</strong>, the package name is <code>glibc-devel.i386</code> (Thanks to JimKleck's comment).</p>
<p>On <strong>CentOS 6 / 7</strong>, the package name is <code>glibc-devel.i686</code>.</p>
<p>On <strong>SLES</strong> it's called glibc-devel-32bit - do <code>zypper in glibc-devel-32bit</code>.</p>
<p>On <strong>Gentoo</strong> it's called <code>sys-libs/glibc</code> - do <code>emerge -1a sys-libs/gcc</code>
[<a href="https://forums.gentoo.org/viewtopic-t-501993.html" rel="noreferrer">source</a>] (Note : One may use <code>equery</code> to confirm this is correct; do <code>equery belongs belongs /usr/include/gnu/stubs-32.h</code>)</p>
<p>On <strong>ArchLinux</strong>, the package name is <code>lib32-glibc</code> - do <code>pacman -S lib32-glibc</code>.</p>
<hr>
<p>Are you using <strong>Ubuntu 12.04</strong>? There is <a href="http://gcc.gnu.org/ml/gcc/2012-02/msg00314.html" rel="noreferrer">a known problem that puts the files in a non standard location</a>. You'll <a href="http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=682678" rel="noreferrer">also</a> need to do:</p>
<pre><code>export LIBRARY_PATH=/usr/lib/$(gcc -print-multiarch)
export C_INCLUDE_PATH=/usr/include/$(gcc -print-multiarch)
export CPLUS_INCLUDE_PATH=/usr/include/$(gcc -print-multiarch)
</code></pre>
<p>somewhere before you build (say in your .bashrc).</p>
<hr>
<p>If you are also compiling C++ code, you will also need the 32 bit stdc++ library. If you see this warning:</p>
<blockquote>
<p>.... /usr/bin/ld: cannot find -lstdc++ ....</p>
</blockquote>
<p>On <strong>Ubuntu</strong> you will need to do <code>sudo apt-get install g++-multilib</code></p>
<p>On <strong>CentOS 5</strong> you will need to do <code>yum install libstdc++-devel.i386</code></p>
<p>On <strong>CentOS 6</strong> you will need to do <code>yum install libstdc++-devel.i686</code></p>
<p>Please feel free to edit in the packages for other systems.</p> |
13,823,367 | Let property of VBA class modules - is it possible to have multiple arguments? | <p>My understanding of using the Let property in a class module so far is that you set it up in the class modules like this:</p>
<pre><code>Dim pName as String
Public Property Let Name(Value As String)
pName = Value
End Property
</code></pre>
<p>And then you after you've created an object of this class you can set this property like so:</p>
<pre><code>MyObject.Name = "Larry"
</code></pre>
<p><br><br>
Question: Is it possible to somehow enter multiple arguments into a class property? For instance:</p>
<pre><code>Dim pFirstName as String, pLastName as String
Public Property Let Name(FirstName As String, LastName As String)
pFirstName = FirstName
pLastName = LastName
End Property
</code></pre>
<p>How would you then go about setting this property outside the class? </p>
<pre><code>MyObject.Name = ??
</code></pre>
<p>Or is this just plain not possible to do?</p> | 13,823,848 | 3 | 6 | null | 2012-12-11 15:44:26.077 UTC | 5 | 2014-10-21 15:33:40.233 UTC | 2014-10-21 14:10:31.62 UTC | user2140173 | null | null | 939,124 | null | 1 | 12 | vba|class|oop|excel|properties | 48,404 | <p>As per your comment if you would prefer to encapsulate this logic then you can use something similar to the below. </p>
<p>Below includes the sub and function. The function returns a Person object:</p>
<pre><code>Public Sub testing()
Dim t As Person
Set t = PersonData("John", "Smith")
End Sub
Public Function PersonData(firstName As String, lastName As String) As Person
Dim p As New Person
p.firstName = firstName
p.lastName = lastName
Set PersonData = p
End Function
</code></pre>
<p>Person Class:</p>
<pre><code>Dim pFirstName As String, pLastName As String
Public Property Let FirstName(FirstName As String)
pFirstName = FirstName
End Property
Public Property Get FirstName() As String
FirstName = pFirstName
End Property
Public Property Let LastName(LastName As String)
pLastName = LastName
End Property
Public Property Get LastName() As String
LastName = pLastName
End Property
</code></pre> |
14,196,581 | Python - smtp requires authentication | <p>I am trying to send an email using python but despite I am using the local SMTP server it seems that it needs authentication. The code I run and the error I get can be seen below. I use port 587, because port 25 cannot be opened on my server. Could you please help me on setting up the local SMTP server using python on port 587?</p>
<pre><code>>>> import smtplib
>>> from email.mime.text import MIMEText
>>> msg = MIMEText('Test body')
>>> me = '[email protected]'
>>> to = '[email protected]'
>>> msg['Subject'] = 'My Subject'
>>> msg['From'] = me
>>> msg['To'] = to
>>> s = smtplib.SMTP('localhost', 587)
>>> s.sendmail(me, [to], msg.as_string())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/smtplib.py", line 722, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
smtplib.SMTPSenderRefused: (530, '5.7.0 Authentication required', '[email protected]')
</code></pre> | 14,196,676 | 1 | 3 | null | 2013-01-07 13:04:25.873 UTC | 7 | 2013-01-07 15:24:28.243 UTC | 2013-01-07 15:24:28.243 UTC | null | 577,598 | null | 577,598 | null | 1 | 12 | python|email|authentication|smtp|smtplib | 43,135 | <p>Then before you attempt to use <code>s.sendmail</code>, you use <code>s.login('user', 'password')</code> - <a href="http://docs.python.org/2/library/smtplib.html#smtplib.SMTP.login" rel="noreferrer">http://docs.python.org/2/library/smtplib.html#smtplib.SMTP.login</a></p>
<p>If you don't have login details - then consult your system admin.</p> |
13,910,749 | Difference between *ptr[10] and (*ptr)[10] | <p>For the following code:</p>
<pre><code> int (*ptr)[10];
int a[10]={99,1,2,3,4,5,6,7,8,9};
ptr=&a;
printf("%d",(*ptr)[1]);
</code></pre>
<p>What should it print? I'm expecting the garbage value here but the output is <code>1</code>.<br>
(for which I'm concluding that initializing this way pointer array i.e <code>ptr[10]</code> would start pointing to elements of <code>a[10]</code> in order).</p>
<p>But what about this code fragment:</p>
<pre><code>int *ptr[10];
int a[10]={0,1,2,3,4,5,6,7,8,9};
*ptr=a;
printf("%d",*ptr[1]);
</code></pre>
<p>It is giving the segmentation fault.</p> | 13,910,762 | 6 | 4 | null | 2012-12-17 08:38:44.5 UTC | 20 | 2019-08-26 06:23:26.32 UTC | 2012-12-17 08:48:17.49 UTC | null | 1,673,391 | null | 897,049 | null | 1 | 17 | c|pointers | 73,500 | <p><code>int *ptr[10];</code></p>
<p>This is an array of 10 <code>int*</code> pointers, not as you would assume, a pointer to an array of 10 <code>int</code>s</p>
<p><code>int (*ptr)[10];</code></p>
<p>This is a pointer to an array of 10 <code>int</code> </p>
<p>It is I believe the same as <code>int *ptr;</code> in that both can point to an array, but the given form can ONLY point to an array of 10 <code>int</code>s</p> |
13,936,051 | Adding ellipses to a principal component analysis (PCA) plot | <p>I am having trouble adding grouping variable ellipses on top of an individual site PCA factor plot which also includes PCA variable factor arrows.</p>
<p>My code:</p>
<pre><code>prin_comp<-rda(data[,2:9], scale=TRUE)
pca_scores<-scores(prin_comp)
#sites=individual site PC1 & PC2 scores, Waterbody=Row Grouping Variable.
#site scores in the PCA plot are stratified by Waterbody type.
plot(pca_scores$sites[,1],
pca_scores$sites[,2],
pch=21,
bg=point_colors[data$Waterbody],
xlim=c(-2,2),
ylim=c(-2,2),
xlab=x_axis_text,
ylab=y_axis_text)
#species=column PCA1 & PCA2 Response variables
arrows(0,0,pca_scores$species[,1],pca_scores$species[,2],lwd=1,length=0.2)
#I want to draw 'Waterbody' Grouping Variable ellipses that encompass completely,
# their appropriate individual site scores (this is to visualise total error/variance).
</code></pre>
<p>I have attempted to use both dataellipse, plotellipses & ellipse functions but to no avail.
Ignorance is winning out on this one. If I have not supplied enough info please let me know.</p>
<p>Data (log10 transformed):</p>
<pre><code>dput(data)
structure(list(Waterbody = structure(c(4L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("Ditch", "Garden Pond",
"Peri-Urban Ponds", "River", "Stream"), class = "factor"), Catchment_Size = c(9.73045926,
9.73045926, 9.73045926, 9.73045926, 9.73045926, 9.73045926, 9.73045926,
9.73045926, 9.73045926, 9.73045926, 9.73045926, 9.73045926, 9.73045926,
9.73045926, 9.73045926, 9.73045926, 9.73045926, 9.73045926, 9.73045926,
9.73045926, 8.602059991, 8.602059991, 8.602059991, 8.602059991,
8.602059991, 8.602059991, 8.602059991, 8.602059991, 8.602059991,
8.602059991, 8.602059991, 8.602059991, 8.602059991, 8.602059991,
8.602059991, 8.602059991, 8.602059991, 8.602059991, 8.602059991,
8.602059991, 5.230525555, 5.271197816, 5.310342762, 5.674064357,
5.745077916, 5.733059168, 5.90789752, 5.969640923, 0, 0, 0.419955748,
0, 0.079181246, 0, 0.274157849, 0, 0.301029996, 1, 0.62838893,
0.243038049, 0, 0, 0, 1.183269844, 0, 1.105510185, 0, 0.698970004,
2, 1.079181246, 2.954242509, 1.84509804, 1.477121255, 2.477121255,
3.662757832, 1.397940009, 1.84509804, 0), pH = c(0.888740961,
0.891537458, 0.890421019, 0.904715545, 0.886490725, 0.88592634,
0.892651034, 0.891537458, 0.895422546, 0.8876173, 0.881384657,
0.888179494, 0.876794976, 0.898725182, 0.894316063, 0.882524538,
0.881384657, 0.916980047, 0.890979597, 0.886490725, 0.88592634,
0.903089987, 0.889301703, 0.897627091, 0.896526217, 0.890979597,
0.927370363, 0.904174368, 0.907948522, 0.890979597, 0.910090546,
0.892094603, 0.896526217, 0.891537458, 0.894869657, 0.894316063,
0.898725182, 0.914343157, 0.923244019, 0.905256049, 0.870988814,
0.868644438, 0.872156273, 0.874481818, 0.88422877, 0.876217841,
0.874481818, 0.8876173, 0.859138297, 0.887054378, 0.856124444,
0.856124444, 0.860936621, 0.903089987, 0.860338007, 0.8876173,
0.860338007, 0.906335042, 0.922206277, 0.851869601, 0.862131379,
0.868056362, 0.869818208, 0.861534411, 0.875061263, 0.852479994,
0.868644438, 0.898725182, 0.870403905, 0.88422877, 0.867467488,
0.905256049, 0.88536122, 0.8876173, 0.876794976, 0.914871818,
0.899820502, 0.946943271), Conductivity = c(2.818885415, 2.824125834,
2.824776462, 2.829303773, 2.824125834, 2.82672252, 2.829303773,
2.82672252, 2.824776462, 2.829946696, 2.846337112, 2.862727528,
2.845718018, 2.848804701, 2.86923172, 2.85308953, 2.867467488,
2.847572659, 2.86569606, 2.849419414, 2.504606771, 2.506775537,
2.691346764, 2.628797486, 2.505963518, 2.48756256, 2.501470072,
2.488973525, 2.457124626, 2.778295991, 2.237040791, 2.429267666,
2.3287872, 2.461198289, 2.384174139, 2.386320574, 2.410608543,
2.404320467, 2.426836454, 2.448397103, 2.768704683, 2.76718556,
2.771602178, 2.775289978, 2.90579588, 2.909020854, 3.007747778,
3.017867719, 2.287129621, 2.099680641, 2.169674434, 1.980457892,
2.741781696, 2.597804842, 2.607669437, 2.419129308, 2.786751422,
2.639884742, 2.19893187, 2.683497318, 2.585235063, 2.393048466,
2.562411833, 2.785329835, 2.726808683, 2.824776462, 2.699056855,
2.585122186, 2.84260924, 2.94792362, 2.877371346, 2.352568386,
2.202760687, 2.819543936, 2.822168079, 2.426348574, 2.495683068,
2.731266349), NO3 = c(1.366236124, 1.366236124, 1.376029182,
1.385606274, 1.376029182, 1.385606274, 1.385606274, 1.385606274,
1.376029182, 1.385606274, 1.458637849, 1.489114369, 1.482158695,
1.496098992, 1.502290528, 1.50174373, 1.500785173, 1.499549626,
1.485721426, 1.490520309, 0.693726949, 0.693726949, 1.246005904,
1.159266331, 0.652246341, 0.652246341, 0.883093359, 0.85672889,
0.828659897, 1.131297797, 0.555094449, 0.85672889, 0.731588765,
0.883093359, 0.731588765, 0.731588765, 0.693726949, 0.693726949,
0.693726949, 0.693726949, 1.278524965, 1.210853365, 1.318480725,
1.308777774, 1.404833717, 1.412796429, 0, 0, 0, 0, 0, 0, 1.204391332,
0, 0, 0, 0.804820679, 0, 0, 0.021189299, 0, 0, 0.012837225, 0,
0, 0, 0, 0.539076099, 0, 0, 1.619406411, 0, 0, 1.380753771, 0,
0, 0, 0.931966115), NH4 = c(0.14, 0.14, 0.18, 0.19, 0.2, 0.2,
0.15, 0.14, 0.11, 0.11, 0.04, 0.06, 0.04, 0.03, 0.07, 0.03, 0.03,
0.04, 0.04, 0.03, 0.01, 0, 0, 0.01, 0.02, 0.02, 0.05, 0.03, 0.04,
0.02, 0.21, 0.19, 0.2, 0.1, 0.05, 0.05, 0.08, 0.11, 0.04, 0.04,
0.15, 2.03, 0.14, 0.09, 0.05, 0.04, 2.82, 3.18, 0.06, 0.12, 2.06,
0.1, 0.14, 0.06, 1.06, 0.03, 0.04, 0.03, 0.03, 1.91, 0.2, 1.35,
0.69, 0.05, 0.17, 3.18, 0.21, 0.1, 0.03, 1.18, 0.01, 0.03, 0.02,
0.09, 0.14, 0.02, 0.07, 0.17), SRP = c(0.213348889, 0.221951667,
0.24776, 0.228833889, 0.232275, 0.249480556, 0.259803889, 0.244318889,
0.249480556, 0.240877778, 0.314861667, 0.292494444, 0.311420556,
0.306258889, 0.285612222, 0.323464444, 0.316582222, 0.34067,
0.285612222, 0.321743889, 0.074328, 0.074328, 0.120783, 0.133171,
0.0820705, 0.080522, 0.0789735, 0.0820705, 0.080522, 0.0913615,
0.136268, 0.1656895, 0.1223315, 0.130074, 0.1192345, 0.1285255,
0.1873685, 0.167238, 0.15485, 0.157947, 0.1378165, 0.1966595,
0.198208, 0.241566, 0.037164, 0.0325185, 0.455259, 0.560557,
0.07987, 0.02119, 0.02119, 0.03912, 0.36349, 0.40098, 0.04401,
0.07172, 0.15322, 0.92421, 0.02282, 0.17604, 0.17767, 0.66667,
0.28688, 0.03586, 0.17278, 0.07661, 0.10432, 1.12959, 0.0170335,
0.0975555, 0.009291, 0.0263245, 0.037164, 0.2214355, 0.0449065,
0.068134, 0.09291, 0.545072), Zn = c(0.802630077, 1.172124009,
0.891565332, 0.600253919, 0.583912562, 0.962473516, 0.99881711,
0.709787074, 1.139860204, 0.953730706, 0.945832806, 0.906270378,
0.81663232, 0.912514323, 0.935073763, 1.032328597, 1.357197063,
1.070662063, 0.51200361, 0.987514325, 1.433709044, 1.380974206,
1.143661074, 0.999774108, 1.449654241, 1.366165106, 1.014239038,
0.891258617, 0.703978825, 1.086487964, 1.503432481, 1.243241499,
0.890504851, 0.291391053, 0, 0.802855789, 0.776316103, 0.927421695,
0.421505212, 0.952099537, 0.688802331, 0.852504392, 0.773545103,
1.006581553, 1.028229538, 0.880619259, 0.833408503, 1.038608242,
1.107084413, 0.973967909, 2.135781222, 1.819197019, 1.629353525,
1.163194184, 1.343286462, 1.273614642, 1.92374902, 1.70523233,
1.377623112, 1.119971423, 1.461175762, 1.691856516, 1.661826878,
1.104531494, 1.449455257, 1.092376721, 1.519029523, 1.553407226,
1.52652924, 1.332876573, 1.293079563, 0.996734891, 1.590475126,
1.525755949, 1.180418366, 0.712624451, 0.6739512, 0.585043155
), Mn = c(0.817367016, 0.799340549, 1.023910606, 1.012921546,
0.821579028, 1.321888278, 1.115077717, 1.02031984, 1.135482491,
1.073645046, 1.016866271, 1.052809328, 0.818423855, 0.836387419,
1.151032582, 0.720490068, 1.03746634, 1.072580733, 1.041590047,
0.979548375, 1.073168262, 1.134336511, 0.916137983, 0.641374945,
1.083753378, 0.84441504, 0.547159121, 0.144262774, 1.084826417,
0.674861141, 0.478566496, 1.211654401, 1.095518042, 0.387033701,
0.647480773, 0.775828814, 0.533899101, 0.854548936, 0.755188586,
0.714497409, 0.851808514, 0.390051496, 0.832508913, 1.222482357,
1.477048866, 1.475147977, 2.127826941, 2.132205239, 1.639576128,
1.155578931, 2.203783274, 1.148448404, 1.644586284, 1.122609024,
1.577319427, 1.633417953, 1.583901241, 1.215478936, 1.135418905,
1.612847407, 1.95593777, 1.783639208, 1.567837703, 2.251767151,
0.992155711, 1.738923187, 0.681964459, 0.852845818, 1.77749932,
2.465019796, 0.887729797, 0.610447221, 1.777760209, 1.034588354,
0.303196057, 1.793371249, 1.677734668, 1.802157753)), .Names = c("Waterbody",
"Catchment_Size", "pH", "Conductivity", "NO3", "NH4", "SRP",
"Zn", "Mn"), class = "data.frame", row.names = c("1_1", "1_2",
"1_3", "1_4", "1_5", "1_6", "1_7", "1_8", "1_9", "1_10", "1_11",
"1_12", "1_13", "1_14", "1_15", "1_16", "1_17", "1_18", "1_19",
"1_20", "2_1", "2_2", "2_3", "2_4", "2_5", "2_6", "2_7", "2_8",
"2_9", "2_10", "2_11", "2_12", "2_13", "2_14", "2_15", "2_16",
"2_17", "2_18", "2_19", "2_20", "3_1", "3_2", "3_3", "3_4", "3_5",
"3_6", "3_7", "3_8", "4_1", "4_2", "4_3", "4_4", "4_5", "4_6",
"4_7", "4_8", "4_9", "4_10", "4_11", "4_12", "4_13", "4_14",
"4_15", "4_16", "4_17", "4_18", "4_19", "4_20", "5_1", "5_2",
"5_3", "5_4", "5_5", "5_6", "5_7", "5_8", "5_9", "5_10"))
</code></pre> | 13,938,639 | 3 | 8 | null | 2012-12-18 15:20:07.003 UTC | 12 | 2020-03-26 16:53:43.777 UTC | 2013-08-10 17:46:03.153 UTC | null | 707,145 | null | 1,913,139 | null | 1 | 22 | r|plot|pca|ggbiplot | 30,102 | <p>Since you do not mention this in your question, I will assume that the package you used is <code>vegan</code>, since it has the function <code>rda()</code> that accepts the <code>scale=TRUE</code> argument.</p>
<p>Your initial <code>plot()</code> call was modified as some of variables are not given.</p>
<pre><code>library(vegan)
prin_comp<-rda(data[,2:9], scale=TRUE)
pca_scores<-scores(prin_comp)
plot(pca_scores$sites[,1],
pca_scores$sites[,2],
pch=21,
bg=as.numeric(data$Waterbody),
xlim=c(-2,2),
ylim=c(-2,2))
arrows(0,0,pca_scores$species[,1],pca_scores$species[,2],lwd=1,length=0.2)
</code></pre>
<p>To make ellipses, function <code>ordiellipse()</code> of package <code>vegan</code> is used. As arguments PCA analysis object and grouping variable must be provided. To control number of points included in ellipse, argument <code>conf=</code> can be used.</p>
<pre><code>ordiellipse(prin_comp,data$Waterbody,conf=0.99)
</code></pre>
<p><img src="https://i.stack.imgur.com/21LVx.jpg" alt="enter image description here"></p> |
14,138,161 | What does (?: do in a regular expression | <p>I have come across a regular expression that I don't fully understand - can somebody help me in deciphering it:</p>
<pre><code>^home(?:\/|\/index\.asp)?(?:\?.+)?$
</code></pre>
<p>It is used in url matching and the above example matches the following urls:</p>
<pre><code>home
home/
home/?a
home/?a=1
home/index.asp
home/index.asp?a
home/index.asp?a=1
</code></pre>
<p>It seems to me that the question marks within the brackets <code>(?:</code> don't do anything. Can somebody enlighten me.</p>
<p>The version of regex being used is the one supplied with Classic ASP and is being run on the server if that helps at all.</p> | 14,138,179 | 4 | 1 | null | 2013-01-03 11:35:53.207 UTC | 10 | 2019-10-18 05:57:09.557 UTC | null | null | null | null | 1,180,438 | null | 1 | 32 | regex|asp-classic | 21,196 | <p><code>(?:)</code> creates a <em>non-capturing group</em>. It groups things together without creating a backreference.</p>
<p>A backreference is a part you can refer to in the expression or a possible replacement (usually by saying <code>\1</code> or <code>$1</code> etc - depending on flavor). You can also usually extract them from a match afterwards when using regex in a programming language. The only reason for using <code>(?:)</code> is to avoid creating a new backreference, which avoids incrementing the group number, and saves (a usually negligible amount of) memory</p> |
14,188,451 | Get multiple request params of the same name | <p>My problem is that with the given code:</p>
<pre><code>from flask import Flask, request
app = Flask(__name__)
@app.route("/")
def hello():
return str(request.values.get("param", "None"))
app.run(debug=True)
</code></pre>
<p>and I visit:</p>
<pre><code>http://localhost:5000/?param=a&param=bbb
</code></pre>
<p>I should expect an output of ['a', 'bbb'] except Flask seems to only accept the first param and ignore the rest.</p>
<p>Is this a limitation of Flask? Or is it by design?</p> | 14,188,496 | 4 | 0 | null | 2013-01-07 00:48:42.47 UTC | 8 | 2021-06-29 20:24:45.51 UTC | 2016-04-08 17:11:17.573 UTC | null | 400,617 | null | 100,758 | null | 1 | 58 | python|flask | 39,473 | <p>You can use <code>getlist</code>, which is similar to Django's <code>getList</code> but for some reason isn't mentioned in the Flask documentation:</p>
<pre><code>return str(request.args.getlist('param'))
</code></pre>
<p>The result is:</p>
<pre><code>[u'a', u'bbb']
</code></pre>
<p>Use <code>request.args</code> if the param is in the query string (as in the question), <code>request.form</code> if the values come from multiple form inputs with the same name. <code>request.values</code> combines both, but should normally be avoided for the more specific collection.</p> |
13,838,405 | Custom sorting in pandas dataframe | <p>I have python pandas dataframe, in which a column contains month name.</p>
<p>How can I do a custom sort using a dictionary, for example:</p>
<pre><code>custom_dict = {'March':0, 'April':1, 'Dec':3}
</code></pre> | 13,839,029 | 5 | 2 | null | 2012-12-12 11:09:42.73 UTC | 53 | 2021-06-03 22:27:45.82 UTC | 2012-12-12 11:54:02.947 UTC | null | 1,240,268 | null | 1,645,853 | null | 1 | 126 | python|pandas | 140,331 | <p>Pandas 0.15 introduced <a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html" rel="noreferrer">Categorical Series</a>, which allows a much clearer way to do this:</p>
<p>First make the month column a categorical and specify the ordering to use.</p>
<pre><code>In [21]: df['m'] = pd.Categorical(df['m'], ["March", "April", "Dec"])
In [22]: df # looks the same!
Out[22]:
a b m
0 1 2 March
1 5 6 Dec
2 3 4 April
</code></pre>
<p>Now, when you sort the month column it will sort with respect to that list:</p>
<pre><code>In [23]: df.sort_values("m")
Out[23]:
a b m
0 1 2 March
2 3 4 April
1 5 6 Dec
</code></pre>
<p><em>Note: if a value is not in the list it will be converted to NaN.</em></p>
<hr>
<p>An older answer for those interested...</p>
<p>You could create an intermediary series, and <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.set_index.html" rel="noreferrer"><code>set_index</code></a> on that:</p>
<pre><code>df = pd.DataFrame([[1, 2, 'March'],[5, 6, 'Dec'],[3, 4, 'April']], columns=['a','b','m'])
s = df['m'].apply(lambda x: {'March':0, 'April':1, 'Dec':3}[x])
s.sort_values()
In [4]: df.set_index(s.index).sort()
Out[4]:
a b m
0 1 2 March
1 3 4 April
2 5 6 Dec
</code></pre>
<hr>
<p>As commented, in newer pandas, Series has a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="noreferrer"><code>replace</code></a> method to do this more elegantly:</p>
<pre><code>s = df['m'].replace({'March':0, 'April':1, 'Dec':3})
</code></pre>
<p><em>The slight difference is that this won't raise if there is a value outside of the dictionary (it'll just stay the same).</em></p> |
13,894,632 | Get time difference between two dates in seconds | <p>I'm trying to get a difference between two dates in seconds. The logic would be like this :</p>
<ul>
<li>set an initial date which would be now;</li>
<li>set a final date which would be the initial date plus some amount of seconds in future ( let's say 15 for instance )</li>
<li>get the difference between those two ( the amount of seconds )</li>
</ul>
<p>The reason why I'm doing it it with dates it's because the final date / time depends on some other variables and it's never the same ( it depends on how fast a user does something ) and I also store the initial date for other things.</p>
<p>I've been trying something like this : </p>
<pre><code>var _initial = new Date(),
_initial = _initial.setDate(_initial.getDate()),
_final = new Date(_initial);
_final = _final.setDate(_final.getDate() + 15 / 1000 * 60);
var dif = Math.round((_final - _initial) / (1000 * 60));
</code></pre>
<p>The thing is that I never get the right difference. I tried dividing by <code>24 * 60</code> which would leave me with the seconds, but I never get it right. So what is it wrong with my logic ? I might be making some stupid mistake as it's quite late, but it bothers me that I cannot get it to work :)</p> | 13,894,670 | 9 | 12 | null | 2012-12-15 17:48:07.187 UTC | 35 | 2022-09-09 06:33:51.193 UTC | null | null | null | null | 1,092,007 | null | 1 | 223 | javascript|date | 351,427 | <h3>The Code</h3>
<pre><code>var startDate = new Date();
// Do your operations
var endDate = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;
</code></pre>
<p>Or even simpler <code>(endDate - startDate) / 1000</code> as pointed out in the comments unless you're using typescript.</p>
<hr/>
<h3>The explanation</h3>
<p>You need to call the <code>getTime()</code> method for the <code>Date</code> objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the <code>getDate()</code> method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the <code>getTime()</code> method, representing the number of milliseconds since <em>January 1st 1970, 00:00</em></p>
<hr/>
<h3>Rant</h3>
<p>Depending on what your date related operations are, you might want to invest in integrating a library such as <a href="http://www.datejs.com/" rel="noreferrer">date.js</a> or <a href="https://momentjs.com/" rel="noreferrer">moment.js</a> which make things <em>so much easier</em> for the developer, but that's just a matter of personal preference.</p>
<p>For example in <a href="https://momentjs.com/" rel="noreferrer">moment.js</a> we would do <code>moment1.diff(moment2, "seconds")</code> which is beautiful.</p>
<hr />
<h3>Useful docs for this answer</h3>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Unix_time" rel="noreferrer">Why 1970?</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ie/cd9w2te4%28v=vs.94%29.aspx" rel="noreferrer">Date object</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ie/7hcawkw2%28v=vs.94%29.aspx" rel="noreferrer">Date's getTime method</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ie/217fw5tk%28v=vs.94%29.aspx" rel="noreferrer">Date's getDate method</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Performance/now" rel="noreferrer">Need more accuracy than just seconds?</a></li>
</ul> |
29,099,292 | Need Sha1 encryption in jquery/javascript | <p>I have sha1 encryption coding in php </p>
<pre><code><?php
echo hash('sha1', 'testing'.'abcdb');
?>
</code></pre>
<p>but, my requirement should have to run the page xyz.html, so the above block is not working.</p>
<p>So, I need to do sha1 encryption in jquery/javascript. Help me by providing coding for sha1 encryption.</p>
<p><strong><em>this is exactly have to be converted to scripts</em></strong></p>
<pre><code>'<?php echo hash('sha1', 'my-secret-key' . $_REQUEST["email"]); ?>'
</code></pre> | 29,099,387 | 2 | 4 | null | 2015-03-17 12:38:26.127 UTC | null | 2018-06-26 09:44:29.793 UTC | 2018-06-26 09:44:29.793 UTC | null | 1,033,581 | null | 3,358,683 | null | 1 | -4 | javascript|jquery|sha1 | 40,849 | <p>There are two ways to go about this, you can either use AJAX to call up your PHP page and retrieve the SHA-1. </p>
<p>Or, you could use one of the JS libraries, such as CryptoJS. </p> |
9,634,281 | How to get the list of active triggers on a database? | <p>My application is based on a sql server db.</p>
<p>All customers has the same db except for customizations.</p>
<p>Some customizations include: new tables, modified tables, custom views, custom triggers...</p>
<p>When I run the software update some scripts are executed. Now I manually disable triggers and reenable after the scripts are done.</p>
<p>Anyway I would like automatically to disable all the triggers (that are enabled, may be some of them could be already disabled) and then reenable them at the end.</p>
<p>Not to reinvent the whell, how to do that?</p>
<p><strong>How to get only the active triggers on the current db?</strong></p>
<p>Once I got this I can programmatically create and run the</p>
<pre><code>DISABLE TRIGGER triggername ON TABLENAME
ENABLE TRIGGER triggername ON TABLENAME
</code></pre> | 9,634,454 | 9 | 1 | null | 2012-03-09 12:46:23.21 UTC | 5 | 2018-12-18 13:19:46.97 UTC | null | null | null | null | 193,655 | null | 1 | 13 | sql-server|triggers|sql-server-2008-r2 | 69,264 | <pre><code>select objectproperty(object_id('TriggerName'), 'ExecIsTriggerDisabled')
</code></pre>
<p>1 means true, 0 means false obviously</p>
<p>Use Jeff O's query and modify it a bit</p>
<pre><code>SELECT
TAB.name as Table_Name
, TRIG.name as Trigger_Name
, TRIG.is_disabled --or objectproperty(object_id('TriggerName'), 'ExecIsTriggerDisabled')
FROM [sys].[triggers] as TRIG
inner join sys.tables as TAB
on TRIG.parent_id = TAB.object_id
</code></pre>
<p>or add it as a where clause.</p>
<pre><code>where TRIG.is_disabled = 0 -- or 1 depends on what you want
</code></pre> |
9,575,914 | Table is 'read only' | <p>When I want to execute an <code>update</code> query on my table I got an error saying:</p>
<blockquote>
<p>1036 - Table <code>data</code> is read only.</p>
</blockquote>
<p>How can I fix that?</p>
<p>Table attributes in <code>/var/db/mysql</code> are set to <code>777</code>.</p>
<p>'Repair Table' function doesnt seems to help.</p>
<p>Is there anything I can do with that?</p> | 9,575,958 | 12 | 1 | null | 2012-03-05 23:50:57.593 UTC | 2 | 2022-06-09 11:34:45.41 UTC | null | null | null | null | 989,749 | null | 1 | 30 | mysql|freebsd|sql-update | 115,251 | <p>who owns /var/db/mysql and what group are they in, should be mysql:mysql. you'll also need to restart mysql for changes to take affect</p>
<p>also check that the currently logged in user had GRANT access to update</p> |
32,837,471 | How to get local/internal IP with JavaScript | <p>How can I get the local client IP using <strong>WebRTC</strong>.</p>
<p>I don't need the <code>REMOTE_ADDR</code> of the client but his local network IP.
I've seen this before on websites like <code>sharedrop.com</code>, it recognizes computer within the same network using WebRTC.</p>
<p>In PHP I do this to get the clients remote IP:</p>
<pre><code><?php
echo $_SERVER["REMOTE_ADDR"]; // which would return 72.72.72.175
?>
</code></pre>
<p>I looked through stackoverflow but every question is answered using the remote addr.</p>
<p>How can I get my local IP (192.168.1.24 for example) with JavaScript instead of the remote addr. </p> | 32,838,936 | 2 | 3 | null | 2015-09-29 06:52:09.88 UTC | 8 | 2022-07-14 23:35:27.257 UTC | null | null | null | null | 1,268,652 | null | 1 | 12 | javascript|network-programming|ip|webrtc | 27,986 | <h2>UPDATE</h2>
<p>Unfortunately the below answer no longer works as browsers have changed this behavior due to security concerns. See <a href="https://stackoverflow.com/questions/56755747/rtcicecandidate-no-longer-returning-ip">this StackOverflow Q&A for more details</a>.</p>
<hr />
<p>where I took code from --> <a href="https://github.com/diafygi/webrtc-ips" rel="nofollow noreferrer">Source</a></p>
<p>You can find a demo at --> <a href="https://diafygi.github.io/webrtc-ips/" rel="nofollow noreferrer">Demo</a></p>
<p>I have modified the source code, reduced the lines, not making any stun requests since you only want Local IP not the Public IP, the below code works in latest Firefox and Chrome:</p>
<pre><code> window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome
var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){};
pc.createDataChannel(""); //create a bogus data channel
pc.createOffer(pc.setLocalDescription.bind(pc), noop); // create offer and set local description
pc.onicecandidate = function(ice){ //listen for candidate events
if(!ice || !ice.candidate || !ice.candidate.candidate) return;
var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];
console.log('my IP: ', myIP);
pc.onicecandidate = noop;
};
</code></pre>
<p>what is happening here is, we are creating a dummy peer connection, and for the remote peer to contact us, we generally exchange ice candidates with each other. And reading the ice candiates we can tell the ip of the user.</p> |
32,677,133 | App installation failed due to application-identifier entitlement | <p>I am unable to install a watchOS 2 WatchKit app due to an application-identifier entitlement. This happened after turning on App Groups in the Capabilities tab.</p>
<p>Full error:</p>
<blockquote>
<p><strong>App installation failed</strong></p>
<p>This application's application-identifier entitlement does not match that of the installed application. These values must match for an upgrade to be allowed.</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/tHqUy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tHqUy.png" alt="Screenshot 1" /></a></p>
<p>This is running the app in debug mode on a physical device. Running just the iOS app works fine.</p>
<p>I have turned App Groups off again and removed the entitlements files that were added, but same error.</p> | 32,788,128 | 36 | 4 | null | 2015-09-20 07:58:37.44 UTC | 54 | 2022-09-20 07:27:59.493 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 883,413 | null | 1 | 332 | ios|watchkit|watchos-2 | 129,280 | <p>I had this problem with an iPhone app, and fixed it using the following steps. </p>
<ul>
<li>With your device connected, and Xcode open, select Window->Devices</li>
<li>In the left tab of the window that pops up, select your problem device</li>
<li>In the detail panel on the right, remove the offending app from the "Installed Apps" list.</li>
</ul>
<p>After I did that, my app rebuilt and launched just fine. Since your app is a watchOS app, I'm not sure that you'll have the same result, but it's worth a try.</p> |
32,709,075 | Docker image error: "/bin/sh: 1: [python,: not found" | <p>I'm building a new Docker image based on the standard Ubuntu 14.04 image. </p>
<p>Here's my <em>Dockerfile</em>:</p>
<pre><code>FROM ubuntu:14.04
RUN apt-get update -y
RUN apt-get install -y nginx git python-setuptools python-dev
RUN easy_install pip
ADD . /code
WORKDIR /code
RUN pip install -r requirements.txt # only 'django' for now
ENV projectname myproject
EXPOSE 80 8000
WORKDIR ${projectname}
CMD ['python', 'manage.py', 'runserver', '0.0.0.0:80']
</code></pre>
<p>When I try to run this image, I get this error...</p>
<blockquote>
<p>/bin/sh: 1: [python,: not found</p>
</blockquote>
<p>But if I open a shell when running the image, running <code>python</code> opens the interactive prompt as expected. </p>
<p>Why can't I invoke <code>python</code> through <code>CMD</code> in the Dockerfile?</p> | 32,709,181 | 5 | 4 | null | 2015-09-22 05:32:36.023 UTC | 5 | 2022-08-16 09:33:22.52 UTC | 2015-09-22 06:12:31.293 UTC | null | 3,156,647 | null | 593,956 | null | 1 | 66 | python|django|ubuntu|docker|dockerfile | 70,804 | <p>Use <code>"</code> instead of <code>'</code> in CMD. <a href="https://docs.docker.com/engine/reference/builder/#cmd" rel="noreferrer">(Documentation)</a></p> |
46,102,963 | The application is in break mode - Unable to determine cause | <p>I'm experiencing that the IDE breaks sometimes when my application terminates.</p>
<p>When this occurs, the call stack is empty, and the thread list shows some threads which don't reveal any information to me.</p>
<p>When I choose "Debugger"-"Step into", the IDE quits / terminally seemingly normally, so I don't see how I could further investigate what causes the breaking.</p>
<p>Clicking "Check for running Tasks" doesn't display any tasks.
Clicking "Continue executing" quits debugging seemingly normally.
Clicking "Show diagnostic tools" shows the event "Stop at Execution: Stopped at Execution", which doesn't tell me any more.</p>
<p>A screenshot is attached.</p>
<p>How can I investigate what's causing this break?</p>
<p><a href="https://i.stack.imgur.com/SQLEC.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/SQLEC.jpg" alt="enter image description here"></a></p>
<p>Edit:
I've tried what one forum member suggested, but that wouldn't result in anything that would help me, I think. This is a screenshot:</p>
<p><a href="https://i.stack.imgur.com/HfGfA.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/HfGfA.jpg" alt="enter image description here"></a></p> | 46,352,548 | 8 | 4 | null | 2017-09-07 18:31:07.59 UTC | 6 | 2021-08-29 04:07:29.787 UTC | 2017-09-12 12:43:06.677 UTC | null | 1,390,192 | null | 1,390,192 | null | 1 | 38 | vb.net|debugging|ide|visual-studio-2017 | 65,237 | <p>I didn't find any way to actually debug the problem.
I solved the problem the bruteforce way:</p>
<p>I removed all assemblies and COM objects one by one until the error was gone.</p>
<p>In my case, I had a public control with a WithEvents in a module.
It seems that VB.NET didn't like that at all.
From now on, I will put the control and its withevent in a form. </p>
<p>The main problem however remains: Visual Studio doesn't offer any help to isolate the problem easily. </p> |
45,272,138 | throws ERROR TypeError: Cannot read property 'emit' of undefined | <p>In <code>MyComponent</code>, I am trying to emit another event from an event handler. (This new event will be used by the parent component to take a few actions). I created an event emitter as a member of <code>MyComponent</code>, but the event handler method is not able to access the event emitter. It throws <code>ERROR TypeError: Cannot read property 'emit' of undefined</code>. I found some related questions on StackOverflow, but could not comprehend much due to being new to <code>Angular2</code>.</p>
<pre><code>import { Component, Input, Output, OnChanges, SimpleChanges, OnInit, EventEmitter } from '@angular/core';
import YouTubePlayer from 'youtube-player';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnChanges, OnInit {
@Input()
videoURL = '';
player : any;
videoId : any;
@Output()
myEmitter: EventEmitter<number> = new EventEmitter();
ngOnInit(): void {
this.player = YouTubePlayer('video-player', {
videoId: this.videoId,
width: "100%"
});
this.registerEvents();
}
private registerEvents() {
this.player.on("stateChange", this.onStateChangeEvent);
}
private onStateChangeEvent(event: any) {
console.log("reached here: " + event);
this.myEmitter.emit(1); //throws `ERROR TypeError: Cannot read property 'emit' of undefined`
}
}
</code></pre>
<p>Could someone help me out? Please note that I have to emit events only from <code>onStateChangeEvent</code>, because later I will have different types of event emitters for different types of events. So I will put a switch-case inside <code>onStateChangeEvent</code> and will use different emitters - one for each type.</p> | 45,272,171 | 2 | 1 | null | 2017-07-24 03:23:22.983 UTC | 3 | 2019-08-30 13:54:36.113 UTC | null | null | null | null | 1,892,348 | null | 1 | 18 | angular|typescript|event-handling|youtube-api|emit | 49,810 | <blockquote>
<p>Cannot read property 'emit' of undefined</p>
</blockquote>
<p>Commonly caused by wrong <code>this</code>. Add the arrow lambda syntax <code>=></code></p>
<p>Fix </p>
<pre><code> private onStateChangeEvent = (event: any) => {
console.log("reached here: " + event);
this.myEmitter.emit(1); // now correct this
}
</code></pre>
<h1>More</h1>
<p><a href="https://basarat.gitbooks.io/typescript/docs/arrow-functions.html" rel="noreferrer">https://basarat.gitbooks.io/typescript/docs/arrow-functions.html</a></p> |
45,259,589 | What's the difference between Red/Black deployment and Blue/Green Deployment? | <p>I've heard both used to describe the idea of deploying an update on new machines while keeping old machines active, ready to rollback if an issue occurs. I've also heard it used to describe sharing load between updated services and old service, again for the purpose of a rollbacks —sometimes terminating inactive older patches and sometimes not.</p>
<p>My understanding also is that it is strictly for cloud services. </p>
<p>Can someone help to demystify these terms?</p> | 47,280,105 | 2 | 1 | null | 2017-07-22 21:57:09.177 UTC | 15 | 2020-09-21 23:34:17.823 UTC | 2020-09-21 23:34:17.823 UTC | null | 4,327,053 | null | 4,327,053 | null | 1 | 80 | design-patterns|deployment|cloud|spinnaker | 32,462 | <p>Both blue/green and red/black deployment represent the same concept.</p>
<p>While the first is the most common term, the latter seems to be used mainly in Netflix and their tools (like <a href="https://www.spinnaker.io/" rel="noreferrer">Spinnaker</a>).</p>
<p>They apply only to cloud, virtualized or containerized services in the sense your infrastructure has to be automatable in order to make sense of this approach.</p> |
71,920 | How to implement a Digg-like algorithm? | <p>How to implement a website with a recommendation system similar to stackoverflow/digg/reddit? I.e., users submit content and the website needs to calculate some sort of "hotness" according to how popular the item is. The flow is as follows:</p>
<ul>
<li>Users submit content</li>
<li>Other users view and vote on the content (assume 90% of the users only views content and 10% actively votes up or down on content)</li>
<li>New content is continuously submitted</li>
</ul>
<p>How do I implement an algorithm that calculates the "hotness" of a submitted item, preferably in real-time? Are there any best-practices or design patterns?</p>
<p>I would assume that the algorithm takes the following into consideration:</p>
<ul>
<li>When an item was submitted</li>
<li>When each vote was cast</li>
<li>When the item was viewed</li>
</ul>
<p>E.g. an item that gets a constant trickle of votes would stay somewhat "hot" constantly while an item that receives a burst of votes when it is first submitted will jump to the top of the "hotness"-list but then fall down as the votes stop coming in.</p>
<p>(I am using a MySQL+PHP but I am interested in general design patterns).</p> | 71,970 | 5 | 1 | null | 2008-09-16 12:59:00.897 UTC | 10 | 2013-12-09 05:10:10.163 UTC | 2013-12-09 05:10:10.163 UTC | cynicalman | 168,868 | Niklas | 103,373 | null | 1 | 10 | sql|algorithm|recommendation-engine|digg | 2,528 | <p>You could use something similar to the <a href="http://redflavor.com/reddit.cf.algorithm.png" rel="noreferrer">Reddit algorithm</a> - the basic principle of which is you compute a value for a post based on the time it was posted and the score. What's neat about the Reddit algorithm is that you only need recompute the value when the score of a post changes. When you want to display your front page, you just get the top n posts from your database based on that score. As time goes on the scores will naturally increase, so you don't have to do any special processing to remove items from the front page.</p> |
1,333,492 | SharePoint : How can I programmatically add items to a custom list instance | <p>I am really looking for either a small code snippet, or a good tutorial on the subject. </p>
<p>I have a C# console app that I will use to somehow add list items to my custom list. I have created a custom content type too. So not sure if I need to create an C# class from this content type too. Perhaps not. </p>
<p>Thanks in advance</p> | 1,333,615 | 5 | 0 | null | 2009-08-26 09:35:22.003 UTC | 8 | 2020-06-08 03:23:14.367 UTC | 2012-04-30 11:27:13.02 UTC | null | 1,234,563 | null | 41,543 | null | 1 | 25 | c#|sharepoint|content-type | 135,811 | <p>I think these both blog post should help you solving your problem.</p>
<p><a href="http://blog.the-dargans.co.uk/2007/04/programmatically-adding-items-to.html" rel="noreferrer">http://blog.the-dargans.co.uk/2007/04/programmatically-adding-items-to.html</a>
<a href="http://asadewa.wordpress.com/2007/11/19/adding-a-custom-content-type-specific-item-on-a-sharepoint-list/" rel="noreferrer">http://asadewa.wordpress.com/2007/11/19/adding-a-custom-content-type-specific-item-on-a-sharepoint-list/</a></p>
<p>Short walk through:</p>
<ol>
<li>Get a instance of the list you want to add the item to.</li>
<li><p>Add a new item to the list: </p>
<pre><code>SPListItem newItem = list.AddItem();
</code></pre></li>
<li><p>To bind you new item to a content type you have to set the content type id for the new item: </p>
<pre><code>newItem["ContentTypeId"] = <Id of the content type>;
</code></pre></li>
<li><p>Set the fields specified within your content type.</p></li>
<li><p>Commit your changes: </p>
<pre><code>newItem.Update();
</code></pre></li>
</ol> |
430,145 | How can I reverse code around an equal sign in Visual Studio? | <p>After writing code to populate textboxes from an object, such as:</p>
<pre><code>txtFirstName.Text = customer.FirstName;
txtLastName.Text = customer.LastName;
txtAddress.Text = customer.Address;
txtCity.Text = customer.City;
</code></pre>
<p>is there way in Visual Studio (or even something like Resharper) to copy and paste this code into a save function and reverse the code around the equal sign, so that it will look like:</p>
<pre><code>customer.FirstName = txtFirstName.Text;
customer.LastName = txtLastName.Text;
customer.Address = txtAddress.Text;
customer.City = txtCity.Text;
</code></pre> | 430,160 | 5 | 1 | null | 2009-01-09 23:38:28.4 UTC | 18 | 2022-02-26 06:42:27.21 UTC | null | null | null | ckal | 10,276 | null | 1 | 30 | c#|visual-studio-2008 | 8,978 | <p>Before VS2012:</p>
<ul>
<li>Copy and paste the original block of code</li>
<li>Select it again in the place you want to switch</li>
<li>Press Ctrl-H to get the "Replace" box up</li>
<li>Under "Find what" put: <code>{[a-zA-Z\.]*} = {[a-zA-Z\.]*};</code></li>
<li>Under "Replace with" put: <code>\2 = \1;</code></li>
<li>Look in: "Selection"</li>
<li>Use: "Regular expressions"</li>
<li>Hit Replace All</li>
</ul>
<p>With VS2012 (and presumably later) which uses .NET regular expressions:</p>
<ul>
<li>Copy and paste the original block of code</li>
<li>Select it again in the place you want to switch</li>
<li>Press Ctrl-H to get the "Replace" box up</li>
<li>Under "Find what" put: <code>([a-zA-Z\.]*) = ([a-zA-Z\.]*);</code></li>
<li>Under "Replace with" put: <code>${2} = ${1};</code></li>
<li>Make sure that the <code>.*</code> (regular expressions) icon is selected (the third one along under the replacement textbox)</li>
<li>Hit Replace All</li>
</ul> |
191,306 | How can I set the current line of execution in the eclipse java debugger? | <p>I want to force the current execution line to a specific line in the same function, possibly skipping intermediate lines. All my old school debuggers had this feature, but I can't find it in eclipse. Is there a way to do it without changing code?</p> | 191,823 | 5 | 3 | null | 2008-10-10 13:37:25.667 UTC | 8 | 2017-03-09 07:44:50.227 UTC | 2017-03-08 14:22:52.773 UTC | null | 895,245 | stu | 12,386 | null | 1 | 34 | eclipse|debugging|execution | 13,297 | <p>The first two answers seem to miss the topic, unless it is me not understanding the question.</p>
<p>My understanding, a feature I searched myself, is that you want to <em>skip</em> a number of lines (when stepping in code) and set the program counter (to take assembly vocabulary) to the given line. It might be interesting to skip some costly object creation, see some error situations, etc. I used to do that in Visual Studio (C or C++ code).</p>
<p>I haven't found that in Eclipse, nor in NetBean. It might be a limitation of JVM, or an enforcement of some policy...</p>
<p>The <em>Run to line</em> command execute, of course, all lines between the current execution position and the designated one.</p> |
39,742 | Does git have anything like `svn propset svn:keywords` or pre-/post-commit hooks? | <p>Browsing through the git documentation, I can't see anything analogous to SVN's commit hooks or the "propset" features that can, say, update a version number or copyright notice within a file whenever it is committed to the repository.</p>
<p>Are git users expected to write external scripts for this sort of functionality (which doesn't seem out of the question) or have I just missed something obvious?</p>
<p><em>Edit</em> : Just to be clear, I'm more interested in, e.g.,</p>
<pre><code>svn propset svn:keywords "Author Date Id Revision" expl3.dtx
</code></pre>
<p>where a string like this:</p>
<pre><code>$Id: expl3.dtx 780 2008-08-30 12:32:34Z morten $
</code></pre>
<p>is kept up-to-date with the relevant info whenever a commit occurs.</p> | 39,947 | 5 | 0 | null | 2008-09-02 15:05:22.15 UTC | 4 | 2017-01-23 21:13:21.413 UTC | 2008-09-02 15:15:35.667 UTC | Will Robertson | 4,161 | Will Robertson | 4,161 | null | 1 | 39 | svn|git|version-control | 21,548 | <p>Quoting from the <a href="https://git.wiki.kernel.org/index.php/GitFaq#Does_git_have_keyword_expansion.3F" rel="noreferrer">Git FAQ</a>:</p>
<blockquote>
<p>Does git have keyword expansion?</p>
<p>Not recommended. Keyword expansion causes all sorts of strange problems and
isn't really useful anyway, especially within the context of an SCM. Outside
git you may perform keyword expansion using a script. The Linux kernel export
script does this to set the EXTRA_VERSION variable in the Makefile.</p>
<p>See gitattributes(5) if you really want to do this. If your translation is not
reversible (eg SCCS keyword expansion) this may be problematic.</p>
</blockquote> |
729,900 | JavaScript Charting library - Google Analytics Style | <p>I'm searching for a Javascript library to create line charts like the ones of Google Analytics. When the mouse is over a point, a box shows you the data.</p>
<p>An example is at <a href="http://wikirank.com/en" rel="noreferrer">http://wikirank.com/en</a></p>
<p>No Flash or Air, only JS and client-side Canvas...</p>
<p>Better if Free...</p> | 729,910 | 6 | 0 | null | 2009-04-08 13:05:34.717 UTC | 10 | 2012-07-12 12:40:23.867 UTC | 2009-04-08 13:14:56.193 UTC | null | 85,067 | null | 85,067 | null | 1 | 7 | javascript|canvas|charts | 9,099 | <p>Edit: If you want a free library, try <a href="http://code.google.com/p/flot/" rel="noreferrer">Flot</a>.</p>
<p><a href="http://www.ejschart.com/" rel="noreferrer">Emprise Charts</a> is a commercial library that I've seen featured on news sites.</p> |
161,510 | 'pass parameter by reference' in Ruby? | <p>In Ruby, is it possible to pass by reference a parameter with value-type semantics (e.g. a Fixnum)?
I'm looking for something similar to C#'s '<strong>ref</strong>' keyword.</p>
<p>Example:</p>
<pre><code>def func(x)
x += 1
end
a = 5
func(a) #this should be something like func(ref a)
puts a #should read '6'
</code></pre>
<p>Btw. I know I could just use:</p>
<pre><code>a = func(a)
</code></pre> | 161,607 | 6 | 0 | null | 2008-10-02 09:33:16.93 UTC | 5 | 2019-05-16 12:08:34.733 UTC | 2014-07-06 14:48:08.587 UTC | CD | 707,111 | CD | 11,545 | null | 1 | 29 | ruby|parameter-passing|pass-by-reference | 24,521 | <p>You can accomplish this by explicitly passing in the current binding:</p>
<pre><code>def func(x, bdg)
eval "#{x} += 1", bdg
end
a = 5
func(:a, binding)
puts a # => 6
</code></pre> |
644,821 | Python: How to run unittest.main() for all source files in a subdirectory? | <p>I am developing a Python module with several source files, each with its own test class derived from <a href="http://docs.python.org/library/unittest.html" rel="noreferrer">unittest</a> right in the source. Consider the directory structure:</p>
<pre><code>dirFoo\
test.py
dirBar\
__init__.py
Foo.py
Bar.py
</code></pre>
<p>To test either Foo.py or Bar.py, I would add this at the end of the Foo.py and Bar.py source files:</p>
<pre><code>if __name__ == "__main__":
unittest.main()
</code></pre>
<p>And run Python on either source, i.e.</p>
<pre><code>$ python Foo.py
...........
----------------------------------------------------------------------
Ran 11 tests in 2.314s
OK
</code></pre>
<p>Ideally, I would have "test.py" automagically search dirBar for any unittest derived classes and make one call to "unittest.main()". What's the best way to do this in practice? </p>
<p>I tried using Python to call <a href="http://docs.python.org/library/functions.html#execfile" rel="noreferrer">execfile</a> for every *.py file in dirBar, which runs once for the first .py file found & exits the calling test.py, plus then I have to duplicate my code by adding unittest.main() in every source file--which violates DRY principles. </p> | 644,844 | 6 | 0 | null | 2009-03-13 22:20:31.05 UTC | 19 | 2020-11-29 07:26:37.197 UTC | 2009-03-16 19:57:44.937 UTC | Pete | 40,785 | Pete | 40,785 | null | 1 | 67 | python|unit-testing | 53,738 | <p>I knew there was an obvious solution:</p>
<pre><code>dirFoo\
__init__.py
test.py
dirBar\
__init__.py
Foo.py
Bar.py
</code></pre>
<p>Contents of dirFoo/test.py</p>
<pre><code>from dirBar import *
import unittest
if __name__ == "__main__":
unittest.main()
</code></pre>
<p>Run the tests:</p>
<pre class="lang-none prettyprint-override"><code>$ python test.py
...........
----------------------------------------------------------------------
Ran 11 tests in 2.305s
OK
</code></pre> |
38,976,955 | setTimeout ReactJS with arrow function es6 | <p>I'd like to know how to use <code>setTimeout()</code> on ReactJS, because I'm doing this: </p>
<pre><code> timerid = setTimeout( () => this.reqMaq( obj['fkmaqid'] ), 2000 )
</code></pre>
<p>and it calls twice the function <code>this.reqMaq()</code>.</p>
<p>How do I prevent the first call? and just keep the call <strong>after</strong> the time?</p>
<p>Here it's the Component:</p>
<pre><code>reqMaq (maqid) {
return fetch(`/scamp/index.php/batchprodpry/${maqid}`, {credentials: 'same-origin'})
.then(req => {
if (req.status >= 400) {
throw new Error("Bad response from server")
}
return req.json()
})
.then(json => this.processMaqReq(json))
.catch(function(error) {
console.log('request failed', error)
})
}
handleChangeMaq (event) {
event.preventDefault()
if (event.target.value.length > 0) {
let obj = this.state.obj
obj['fkmaqid'] = VMasker.toPattern(event.target.value, "99-99-99-99")
// if (timerid) {
// clearTimeout(timerid)
// }
// timerid = setTimeout(() => {
// if (!isRunning) {
// this.reqMaq(obj['fkmaqid'])
// }
// }, 2000)
const fx = () => this.reqMaq( obj['fkmaqid'] )
timerid = setTimeout( fx, 2000 )
this.setState({ obj: obj })
}
}
render() {
return (
<div className="form-group">
<label htmlFor="maquina">M&aacute;quina</label>
<input type="text" className="form-control" id="maquina"
name="maquina"
placeholder="Maquina"
value={this.state.obj['fkmaqid'] || ''}
onChange={this.handleChangeMaq}
ref={node => {
input1 = node
}}
required="required"
/>
</div>
)
}
</code></pre>
<p>Thank you.</p> | 38,977,418 | 3 | 10 | null | 2016-08-16 13:59:41.373 UTC | 7 | 2018-04-25 01:41:02.483 UTC | 2017-07-25 09:20:20.653 UTC | null | 593,963 | null | 4,008,161 | null | 1 | 33 | javascript|reactjs|settimeout | 91,735 | <p>Try this:</p>
<pre><code>if (timerid) {
clearTimeout(timerid);
}
timerid = setTimeout(() => {
this.reqMaq(obj['fkmaqid'])
}, 2000);
</code></pre> |
35,421,000 | Can't install/update heroku toolbelt - heroku-pipelines | <p>I'm having problems updating with heroku toolbelt (on Ubuntu x64).</p>
<p>Whatever heroku command I try to run, heroku toolbelt will try to update itself and the update always fails with this output:</p>
<pre><code>$ heroku
heroku-cli: Installing Toolbelt v4... done
For more information on Toolbelt v4: https://github.com/heroku/heroku-cli
heroku-cli: Adding dependencies... done
heroku-cli: Installing core plugins (retrying)...
▸ Error reading plugin: heroku-pipelines
▸ exit status 1
▸ module.js:327
▸ throw err;
▸ ^
▸
▸ Error: Cannot find module 'heroku-pipelines'
▸ at Function.Module._resolveFilename (module.js:325:15)
▸ at Function.Module._load (module.js:276:25)
▸ at Module.require (module.js:353:17)
▸ at require (internal/module.js:12:17)
▸ at [eval]:2:15
▸ at Object.exports.runInThisContext (vm.js:54:17)
▸ at Object.<anonymous> ([eval]-wrapper:6:22)
▸ at Module._compile (module.js:397:26)
▸ at node.js:611:27
▸ at nextTickCallbackWith0Args (node.js:452:9)
heroku-cli: Installing core plugins (retrying)...
▸ Error reading plugin: heroku-pipelines
▸ exit status 1
▸ module.js:327
▸ throw err;
▸ ^
▸
▸ Error: Cannot find module 'heroku-pipelines'
▸ at Function.Module._resolveFilename (module.js:325:15)
▸ at Function.Module._load (module.js:276:25)
▸ at Module.require (module.js:353:17)
▸ at require (internal/module.js:12:17)
▸ at [eval]:2:15
▸ at Object.exports.runInThisContext (vm.js:54:17)
▸ at Object.<anonymous> ([eval]-wrapper:6:22)
▸ at Module._compile (module.js:397:26)
▸ at node.js:611:27
▸ at nextTickCallbackWith0Args (node.js:452:9)
! error getting commands pid 8898 exit 1
</code></pre>
<p>I've removed my ~/.heroku, I've apt-get remove --purge heroku*, and still it just fails.</p>
<p>I'm not that familiar with node.js to understand what kind of problem this is or if it even is a node.js problem at all.. Does anyone have a clue? Thanks!</p> | 35,421,559 | 1 | 4 | null | 2016-02-15 23:27:25.903 UTC | 11 | 2016-02-16 00:29:39.703 UTC | null | null | null | null | 1,154,529 | null | 1 | 18 | node.js|ubuntu|heroku | 872 | <p>Known Issue: <a href="https://status.heroku.com/incidents/851" rel="nofollow">https://status.heroku.com/incidents/851</a></p>
<p><strong>Issue</strong></p>
<blockquote>
<p>Our engineers are investigating issues with the Heroku CLI. Customers
may be seeing failures referencing "Error reading plugin:
heroku-pipelines".</p>
</blockquote> |
20,953,273 | Install opencv for Python 3.3 | <p>Is OpenCV still not available for Python 3.3 and do I really have to downgrade to Python 2.7 to use it? I didn't find much about it on the internet, only some posts from 2012 that OpenCV wasn't yet ported to be used in Python 3.x. But now it's 2014 and after trying to install the latest OpenCV 2.4.x and copying the <code>cv2.pyd</code> file to <em>C:\Program Files (x86)\Python333\Lib\site-packages</em> this still yields the error in Python IDLE:</p>
<pre><code>>>> import cv2
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import cv2
ImportError: DLL load failed: %1 ist keine zulässige Win32-Anwendung.
</code></pre> | 21,212,023 | 15 | 5 | null | 2014-01-06 15:29:14.287 UTC | 39 | 2021-09-16 15:09:24.36 UTC | null | null | null | null | 701,049 | null | 1 | 62 | python|opencv|python-3.x | 123,441 | <p>EDIT: first try the new pip method: </p>
<p>Windows: <code>pip3 install opencv-python opencv-contrib-python</code></p>
<p>Ubuntu: <code>sudo apt install python3-opencv</code> </p>
<p>or continue below for build instructions</p>
<p>Note: The original question was asking for OpenCV + Python 3.3 + Windows. Since then, Python 3.5 has been released. In addition, I use Ubuntu for most development so this answer will focus on that setup, unfortunately</p>
<p>OpenCV 3.1.0 + Python 3.5.2 + Ubuntu 16.04 is possible! Here's how.</p>
<p>These steps are copied (and slightly modified) from:</p>
<ul>
<li><a href="http://docs.opencv.org/3.1.0/d7/d9f/tutorial_linux_install.html" rel="noreferrer">http://docs.opencv.org/3.1.0/d7/d9f/tutorial_linux_install.html</a></li>
<li><a href="https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_fedora/py_setup_in_fedora.html#install-opencv-python-in-fedora" rel="noreferrer">https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_fedora/py_setup_in_fedora.html#install-opencv-python-in-fedora</a></li>
</ul>
<h1>Prerequisites</h1>
<p>Install the required dependencies and optionally install/update some libraries on your system:</p>
<pre><code># Required dependencies
sudo apt install build-essential cmake git libgtk2.0-dev pkg-config libavcodec-dev libavformat-dev libswscale-dev
# Dependencies for Python bindings
# If you use a non-system copy of Python (eg. with pyenv or virtualenv), then you probably don't need to do this part
sudo apt install python3.5-dev libpython3-dev python3-numpy
# Optional, but installing these will ensure you have the latest versions compiled with OpenCV
sudo apt install libtbb2 libtbb-dev libjpeg-dev libpng-dev libtiff-dev libjasper-dev libdc1394-22-dev
</code></pre>
<h1>Building OpenCV</h1>
<h3>CMake Flags</h3>
<p>There are several flags and options to tweak your build of OpenCV. There might be comprehensive documentation about them, but here are some interesting flags that may be of use. They should be included in the <code>cmake</code> command:</p>
<pre><code># Builds in TBB, a threading library
-D WITH_TBB=ON
# Builds in Eigen, a linear algebra library
-D WITH_EIGEN=ON
</code></pre>
<h3>Using non-system level Python versions</h3>
<p>If you have multiple versions of Python (eg. from using pyenv or virtualenv), then you may want to build against a certain Python version. By default OpenCV will build for the system's version of Python. You can change this by adding these arguments to the <code>cmake</code> command seen later in the script. Actual values will depend on your setup. I use <code>pyenv</code>:</p>
<pre><code>-D PYTHON_DEFAULT_EXECUTABLE=$HOME/.pyenv/versions/3.5.2/bin/python3.5
-D PYTHON_INCLUDE_DIRS=$HOME/.pyenv/versions/3.5.2/include/python3.5m
-D PYTHON_EXECUTABLE=$HOME/.pyenv/versions/3.5.2/bin/python3.5
-D PYTHON_LIBRARY=/usr/lib/x86_64-linux-gnu/libpython3.5m.so.1
</code></pre>
<h3>CMake Python error messages</h3>
<p>The CMakeLists file will try to detect various versions of Python to build for. If you've got different versions here, it might get confused. The above arguments may only "fix" the issue for one version of Python but not the other. If you only care about that specific version, then there's nothing else to worry about.</p>
<p>This is the case for me so unfortunately, I haven't looked into how to resolve the issues with other Python versions.</p>
<h2>Install script</h2>
<pre><code># Clone OpenCV somewhere
# I'll put it into $HOME/code/opencv
OPENCV_DIR="$HOME/code/opencv"
OPENCV_VER="3.1.0"
git clone https://github.com/opencv/opencv "$OPENCV_DIR"
# This'll take a while...
# Now lets checkout the specific version we want
cd "$OPENCV_DIR"
git checkout "$OPENCV_VER"
# First OpenCV will generate the files needed to do the actual build.
# We'll put them in an output directory, in this case "release"
mkdir release
cd release
# Note: This is where you'd add build options, like TBB support or custom Python versions. See above sections.
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local "$OPENCV_DIR"
# At this point, take a look at the console output.
# OpenCV will print a report of modules and features that it can and can't support based on your system and installed libraries.
# The key here is to make sure it's not missing anything you'll need!
# If something's missing, then you'll need to install those dependencies and rerun the cmake command.
# OK, lets actually build this thing!
# Note: You can use the "make -jN" command, which will run N parallel jobs to speed up your build. Set N to whatever your machine can handle (usually <= the number of concurrent threads your CPU can run).
make
# This will also take a while...
# Now install the binaries!
sudo make install
</code></pre>
<p>By default, the <code>install</code> script will put the Python bindings in some system location, even if you've specified a custom version of Python to use. The fix is simple: Put a symlink to the bindings in your local <code>site-packages</code>:</p>
<pre><code>ln -s /usr/local/lib/python3.5/site-packages/cv2.cpython-35m-x86_64-linux-gnu.so $HOME/.pyenv/versions/3.5.2/lib/python3.5/site-packages/
</code></pre>
<p>The first path will depend on the Python version you setup to build. The second depends on where your custom version of Python is located.</p>
<h1>Test it!</h1>
<p>OK lets try it out!</p>
<pre><code>ipython
Python 3.5.2 (default, Sep 24 2016, 13:13:17)
Type "copyright", "credits" or "license" for more information.
IPython 5.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: import cv2
In [2]: img = cv2.imread('derp.png')
i
In [3]: img[0]
Out[3]:
array([[26, 30, 31],
[27, 31, 32],
[27, 31, 32],
...,
[16, 19, 20],
[16, 19, 20],
[16, 19, 20]], dtype=uint8)
</code></pre> |
44,060,582 | Java Selenium Webdriver Connection Refused | <p>I am getting the all too common connection refused error on my selenium webdriver. The same code was executing a few weeks ago.</p>
<p>I have been reading in circles through existing posts and have tried updating geckodriver and FireFox to no avail. I can run the same code on another computer running the same versions of the driver, browser and libraries etc. How can I find the cause specific to this machine? the error is below.</p>
<p>Debug 1
Debug 2
Debug 3</p>
<pre><code>Exception in thread "main" org.openqa.selenium.WebDriverException: org.apache.http.conn.HttpHostConnectException: Connect to localhost:28379 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect Build info: version: 'unknown', revision: 'unknown', time: 'unknown' System info: host: 'LT9LTDRC2', ip: '10.130.3.15', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_131' Driver info: driver.version: Gecko_Driver
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:91)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:637)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:250)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:236)
at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:137)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:191) at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:108) at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:137) at seleniumPrograms.Gecko_Driver.main(Gecko_Driver.java:13)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to localhost:28379 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:159)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:359)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:381)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
at org.openqa.selenium.remote.internal.ApacheHttpClient.fallBackExecute(ApacheHttpClient.java:139)
at org.openqa.selenium.remote.internal.ApacheHttpClient.execute(ApacheHttpClient.java:87)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:343)
at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:159)
at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:142)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82) ... 8 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.http.conn.socket.PlainConnectionSocketFactory.connectSocket(PlainConnectionSocketFactory.java:75)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142) ... 23 more
</code></pre>
<p>And I get this running even the following basic code.</p>
<pre><code>enter code here
package seleniumPrograms;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class Gecko_Driver {
public static void main(String[] args) {
System.out.println("Debug 1");
DesiredCapabilities capabilities=DesiredCapabilities.firefox();
System.out.println("Debug 2");
capabilities.setCapability("marionette", true);
System.out.println("Debug 3");
WebDriver driver = new FirefoxDriver(capabilities);
System.out.println("Debug 4");
driver.get("http://www.google.com");
driver.manage().window().maximize();
driver.quit();
}
}
</code></pre>
<p>Example with chrome.</p>
<pre><code>@Test
public void testGoogleSearch() throws InterruptedException {
// Optional, if not specified, WebDriver will search your path for chromedriver.
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com/xhtml");
Thread.sleep(5000); // Let the user actually see something!
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("ChromeDriver");
searchBox.submit();
Thread.sleep(5000); // Let the user actually see something!
driver.quit();
}
</code></pre>
<p>Failure trace:</p>
<blockquote>
<p>org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'LT9LTDRC2', ip: '192.168.1.6', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_131'
Driver info: driver.version: Gecko_Driver
at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:193)
at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:181)
at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:78)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:637)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:250)
at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:236)
at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:137)
at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:184)
at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:171)
at org.openqa.selenium.chrome.ChromeDriver.(ChromeDriver.java:124)
at seleniumPrograms.Gecko_Driver.testGoogleSearch(Gecko_Driver.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [<a href="http://localhost:31675/status]" rel="noreferrer">http://localhost:31675/status]</a> to be available after 20002 ms
at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:107)
at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:190)
... 33 more
Caused by: com.google.common.util.concurrent.UncheckedTimeoutException: java.util.concurrent.TimeoutException
at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:140)
at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:80)
... 34 more
Caused by: java.util.concurrent.TimeoutException
at java.util.concurrent.FutureTask.get(Unknown Source)
at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:128)
... 35 more</p>
</blockquote> | 44,147,384 | 3 | 1 | null | 2017-05-19 02:42:39.91 UTC | 1 | 2020-08-01 16:18:39.497 UTC | 2018-04-26 17:35:11.71 UTC | null | 2,387,977 | null | 4,794,382 | null | 1 | 5 | java|selenium|selenium-webdriver|geckodriver|connection-refused | 64,840 | <p>Our security dept introduced a policy which blocked access to the execution of the geckodriver.exe. This was identified by attempting to run from cmd. Not sure why I didn't get the meaningful error in the IDE (blocked by group policy) for gecko, I did get this error for chrome and IE. In order to use the driver it needed to be saved in Program files though this may be specific to my situation. If you get this error for Geckodriver i would suggest trying to execute it from cmd to see if there is a policy issue.</p> |
44,342,455 | More than one file was found with OS independent path 'META-INF/LICENSE' | <p>When I build my app, I get the following error:</p>
<blockquote>
<p>Error: Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.
More than one file was found with OS independent path 'META-INF/LICENSE'</p>
</blockquote>
<p>This is my build.gradle file:</p>
<pre><code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "cn.sz.cyrus.kotlintest"
minSdkVersion 14
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
javaCompileOptions{
annotationProcessorOptions{
includeCompileClasspath = true
}
}
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
/* exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'*/
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
compile 'com.android.support:appcompat-v7:25.3.1'
testCompile 'junit:junit:4.12'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
compile 'com.github.GrenderG:Toasty:1.2.5'
compile 'com.orhanobut:logger:1.15'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.umeng.analytics:analytics:latest.integration'
compile 'ai.api:libai:1.4.8'
compile 'ai.api:sdk:2.0.5@aar'
// api.ai SDK dependencies
compile 'com.google.code.gson:gson:2.8.0'
compile 'commons-io:commons-io:2.4'
compile 'com.android.support:multidex:1.0.1'
}
</code></pre>
<p>When I add this code to my build.gradle file, </p>
<pre><code> packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
</code></pre>
<p>This error would be solved, but another problem will happen. Like this:</p>
<pre><code>java.lang.NoClassDefFoundError: com.squareup.leakcanary.internal.HeapAnalyzerService
at com.squareup.leakcanary.LeakCanary.isInAnalyzerProcess(LeakCanary.java:145)
at cn.sz.cyrus.wemz.TestApplication.onCreate(TestApplication.kt:32)
</code></pre>
<p>Who has ideas how to solve this?</p> | 47,509,465 | 32 | 2 | null | 2017-06-03 09:31:07.937 UTC | 65 | 2022-08-09 12:23:03.54 UTC | 2020-02-14 13:29:05.26 UTC | null | 8,555,403 | null | 6,892,311 | null | 1 | 547 | android|gradle|build.gradle | 442,087 | <p>You can add this in <code>yourProject/app/build.gradle</code> inside <code>android{}</code>. The <a href="https://developer.android.com/reference/tools/gradle-api/7.1/com/android/build/api/dsl/ResourcesPackagingOptions" rel="noreferrer">exclude</a> function adds the named resource to the list of resources that are not packaged in the APK.</p>
<pre><code>android {
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/notice.txt'
exclude 'META-INF/ASL2.0'
exclude("META-INF/*.kotlin_module")
}
}
</code></pre>
<p>The <code>exclude</code> function is deprecated in 7.0.2 and you should use something similar to this:</p>
<pre><code>android {
...
packagingOptions {
resources.excludes.add("META-INF/*")
}
}
</code></pre> |
47,518,333 | Create programmatically a variable product and two new attributes in WooCommerce | <p>I would like to programmatically create a variable product ("parent" product) with two new variante attributes - all that from a WordPress plugin (so no HTTP Request to an API).</p>
<p>These two variante attributes should also be created on the fly.</p>
<p>How can this be done ?</p>
<p>(with WooCommerce version 3)</p>
<hr>
<p>Update : I have written more lines of codes on this that I wished, and tried many things to solve it, using wooCommerce objects, and added missing data about terms, termmeta, the relationship from term with post, in the database using the WordPress database object - but nothing has sufficed to make it work. And I couldn't pin-point where I went wrong - that is why I couldn't provide a narrower problem - things for which stackoverflow is more made for.</p> | 47,844,054 | 3 | 10 | null | 2017-11-27 19:21:56.87 UTC | 14 | 2020-11-14 03:21:36.307 UTC | 2019-04-13 18:09:23.407 UTC | null | 771,496 | null | 278,739 | null | 1 | 18 | php|wordpress|woocommerce | 30,406 | <blockquote>
<p><strong>After:</strong> <a href="https://stackoverflow.com/questions/47518280/create-programmatically-a-woocommerce-product-variation-with-new-attribute-value/47766413#47766413">Create programmatically a WooCommerce product variation with new attribute values</a></p>
</blockquote>
<p>Here you get the way to create a new variable product with new product attributes + values:</p>
<pre><code>/**
* Save a new product attribute from his name (slug).
*
* @since 3.0.0
* @param string $name | The product attribute name (slug).
* @param string $label | The product attribute label (name).
*/
function save_product_attribute_from_name( $name, $label='', $set=true ){
if( ! function_exists ('get_attribute_id_from_name') ) return;
global $wpdb;
$label = $label == '' ? ucfirst($name) : $label;
$attribute_id = get_attribute_id_from_name( $name );
if( empty($attribute_id) ){
$attribute_id = NULL;
} else {
$set = false;
}
$args = array(
'attribute_id' => $attribute_id,
'attribute_name' => $name,
'attribute_label' => $label,
'attribute_type' => 'select',
'attribute_orderby' => 'menu_order',
'attribute_public' => 0,
);
if( empty($attribute_id) ) {
$wpdb->insert( "{$wpdb->prefix}woocommerce_attribute_taxonomies", $args );
set_transient( 'wc_attribute_taxonomies', false );
}
if( $set ){
$attributes = wc_get_attribute_taxonomies();
$args['attribute_id'] = get_attribute_id_from_name( $name );
$attributes[] = (object) $args;
//print_r($attributes);
set_transient( 'wc_attribute_taxonomies', $attributes );
} else {
return;
}
}
/**
* Get the product attribute ID from the name.
*
* @since 3.0.0
* @param string $name | The name (slug).
*/
function get_attribute_id_from_name( $name ){
global $wpdb;
$attribute_id = $wpdb->get_col("SELECT attribute_id
FROM {$wpdb->prefix}woocommerce_attribute_taxonomies
WHERE attribute_name LIKE '$name'");
return reset($attribute_id);
}
/**
* Create a new variable product (with new attributes if they are).
* (Needed functions:
*
* @since 3.0.0
* @param array $data | The data to insert in the product.
*/
function create_product_variation( $data ){
if( ! function_exists ('save_product_attribute_from_name') ) return;
$postname = sanitize_title( $data['title'] );
$author = empty( $data['author'] ) ? '1' : $data['author'];
$post_data = array(
'post_author' => $author,
'post_name' => $postname,
'post_title' => $data['title'],
'post_content' => $data['content'],
'post_excerpt' => $data['excerpt'],
'post_status' => 'publish',
'ping_status' => 'closed',
'post_type' => 'product',
'guid' => home_url( '/product/'.$postname.'/' ),
);
// Creating the product (post data)
$product_id = wp_insert_post( $post_data );
// Get an instance of the WC_Product_Variable object and save it
$product = new WC_Product_Variable( $product_id );
$product->save();
## ---------------------- Other optional data ---------------------- ##
## (see WC_Product and WC_Product_Variable setters methods)
// THE PRICES (No prices yet as we need to create product variations)
// IMAGES GALLERY
if( ! empty( $data['gallery_ids'] ) && count( $data['gallery_ids'] ) > 0 )
$product->set_gallery_image_ids( $data['gallery_ids'] );
// SKU
if( ! empty( $data['sku'] ) )
$product->set_sku( $data['sku'] );
// STOCK (stock will be managed in variations)
$product->set_stock_quantity( $data['stock'] ); // Set a minimal stock quantity
$product->set_manage_stock(true);
$product->set_stock_status('');
// Tax class
if( empty( $data['tax_class'] ) )
$product->set_tax_class( $data['tax_class'] );
// WEIGHT
if( ! empty($data['weight']) )
$product->set_weight(''); // weight (reseting)
else
$product->set_weight($data['weight']);
$product->validate_props(); // Check validation
## ---------------------- VARIATION ATTRIBUTES ---------------------- ##
$product_attributes = array();
foreach( $data['attributes'] as $key => $terms ){
$taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
$attr_label = ucfirst($key); // attribute label name
$attr_name = ( wc_sanitize_taxonomy_name($key)); // attribute slug
// NEW Attributes: Register and save them
if( ! taxonomy_exists( $taxonomy ) )
save_product_attribute_from_name( $attr_name, $attr_label );
$product_attributes[$taxonomy] = array (
'name' => $taxonomy,
'value' => '',
'position' => '',
'is_visible' => 0,
'is_variation' => 1,
'is_taxonomy' => 1
);
foreach( $terms as $value ){
$term_name = ucfirst($value);
$term_slug = sanitize_title($value);
// Check if the Term name exist and if not we create it.
if( ! term_exists( $value, $taxonomy ) )
wp_insert_term( $term_name, $taxonomy, array('slug' => $term_slug ) ); // Create the term
// Set attribute values
wp_set_post_terms( $product_id, $term_name, $taxonomy, true );
}
}
update_post_meta( $product_id, '_product_attributes', $product_attributes );
$product->save(); // Save the data
}
</code></pre>
<p><em>Code goes in function.php file of your active child theme (or active theme).</em> Tested and works.</p>
<hr>
<p><strong>USAGE</strong> (example with 2 new attributes + values):</p>
<pre><code>create_product_variation( array(
'author' => '', // optional
'title' => 'Woo special one',
'content' => '<p>This is the product content <br>A very nice product, soft and clear…<p>',
'excerpt' => 'The product short description…',
'regular_price' => '16', // product regular price
'sale_price' => '', // product sale price (optional)
'stock' => '10', // Set a minimal stock quantity
'image_id' => '', // optional
'gallery_ids' => array(), // optional
'sku' => '', // optional
'tax_class' => '', // optional
'weight' => '', // optional
// For NEW attributes/values use NAMES (not slugs)
'attributes' => array(
'Attribute 1' => array( 'Value 1', 'Value 2' ),
'Attribute 2' => array( 'Value 1', 'Value 2', 'Value 3' ),
),
) );
</code></pre>
<p>Tested and works.</p>
<hr>
<p>Related: </p>
<ul>
<li><a href="https://stackoverflow.com/questions/29549525/create-new-product-attribute-programmatically-in-woocommerce/51994543#51994543">Create new product attribute programmatically in Woocommerce</a></li>
<li><a href="https://stackoverflow.com/questions/47518280/create-programmatically-a-woocommerce-product-variation-with-new-attribute-value/47766413#47766413">Create programmatically a WooCommerce product variation with new attribute values</a></li>
<li><a href="https://stackoverflow.com/questions/52937409/create-programmatically-a-product-using-crud-methods-in-woocommerce-3/52941994#52941994">Create programmatically a product using CRUD methods in Woocommerce 3</a></li>
</ul> |
21,022,779 | How to stop C# from replacing const variable with their values? | <p>We have a project that's compiled into a DLL called consts.dll that contains something like:</p>
<pre><code>public static class Consts
{
public const string a = "a";
public const string b = "b";
public const string c = "c";
}
</code></pre>
<p>We have multiple projects of this sort, each compiled into a DLL of the same name (consts.dll) and we replace them according to need.
We have another class that uses these consts:</p>
<pre><code>public class ConstsUser
{
string f() { return Consts.a; }
}
</code></pre>
<p>Unfortunately, <code>Consts.a</code> is optimized to "a" , so even if we replace Consts.dll implementation, we still get "a" instead of the correct value and we need to recompile <code>ConstsUser</code>. Is there anyway to stop the optimizer from replacing const variables with their values?</p> | 21,022,798 | 2 | 8 | null | 2014-01-09 14:21:08.75 UTC | 7 | 2014-01-16 13:17:53.57 UTC | null | null | null | null | 787,366 | null | 1 | 63 | c#|optimization | 4,353 | <p>I think usage of <code>static readonly</code> modifiers fits your needs:</p>
<pre><code>public static class Consts
{
public static readonly string a = "a";
public static readonly string b = "b";
public static readonly string c = "c";
}
</code></pre>
<p>Constants are hard-coded on the call-site, so that is your problem. Static readonly variable can be modified only in variable declaration or static constructor of <code>Consts</code> class, and it will not be inlined on the call-site.</p> |
20,945,049 | Is a Java string really immutable? | <p>We all know that <code>String</code> is immutable in Java, but check the following code:</p>
<pre><code>String s1 = "Hello World";
String s2 = "Hello World";
String s3 = s1.substring(6);
System.out.println(s1); // Hello World
System.out.println(s2); // Hello World
System.out.println(s3); // World
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
char[] value = (char[])field.get(s1);
value[6] = 'J';
value[7] = 'a';
value[8] = 'v';
value[9] = 'a';
value[10] = '!';
System.out.println(s1); // Hello Java!
System.out.println(s2); // Hello Java!
System.out.println(s3); // World
</code></pre>
<p>Why does this program operate like this? And why is the value of <code>s1</code> and <code>s2</code> changed, but not <code>s3</code>?</p> | 20,945,113 | 16 | 14 | null | 2014-01-06 07:26:51.617 UTC | 168 | 2021-03-09 20:37:38.163 UTC | 2014-01-23 00:32:49.577 UTC | null | 63,550 | null | 3,131,537 | null | 1 | 409 | java|string|reflection|immutability | 57,678 | <p><code>String</code> is immutable* but this only means you cannot change it using its public API. </p>
<p>What you are doing here is circumventing the normal API, using reflection. The same way, you can change the values of enums, change the lookup table used in Integer autoboxing etc.</p>
<p>Now, the reason <code>s1</code> and <code>s2</code> change value, is that they both refer to the same interned string. The compiler does this (as mentioned by other answers). </p>
<p>The reason <code>s3</code> does <em>not</em> was actually a bit surprising to me, as I thought it would share the <code>value</code> array (<a href="http://java-performance.info/changes-to-string-java-1-7-0_06/">it did in earlier version of Java</a>, before Java 7u6). However, looking at the source code of <code>String</code>, we can see that the <code>value</code> character array for a substring is actually copied (using <code>Arrays.copyOfRange(..)</code>). This is why it goes unchanged.</p>
<p>You can install a <code>SecurityManager</code>, to avoid malicious code to do such things. But keep in mind that some libraries depend on using these kind of reflection tricks (typically ORM tools, AOP libraries etc).</p>
<p>*) I initially wrote that <code>String</code>s aren't really immutable, just "effective immutable". This might be misleading in the current implementation of <code>String</code>, where the <code>value</code> array is indeed marked <code>private final</code>. It's still worth noting, though, that there is no way to declare an array in Java as immutable, so care must be taken not to expose it outside its class, even with the proper access modifiers.</p>
<hr>
<p>As this topic seems overwhelmingly popular, here's some suggested further reading: <a href="http://www.javaspecialists.eu/talks/oslo09/ReflectionMadness.pdf">Heinz Kabutz's Reflection Madness talk</a> from JavaZone 2009, which covers a lot of the issues in the OP, along with other reflection... well... madness. </p>
<p>It covers why this is sometimes useful. And why, most of the time, you should avoid it. :-)</p> |
23,088,408 | IF Statement on Range Of Cells | <p>I have a range of cells that I would like to look at with this if statement. I basically want this formula to look at the "Customer" and then look at a list of Customers that provide their own routing, if that "Customer" is on that list (in that range of cells) then i would need for the formula to return a "Y" for yes and if they are not on that list then i just need an "N" for no. I've included a picture. Then range of cells that it needs to look at is G10:G28.<img src="https://i.stack.imgur.com/HrOk8.jpg" alt="example"></p> | 23,088,500 | 2 | 2 | null | 2014-04-15 15:39:32.257 UTC | null | 2014-04-15 16:14:49.347 UTC | null | null | null | null | 3,067,028 | null | 1 | 0 | excel|if-statement|excel-formula | 51,302 | <p>A VLOOKUP can tell if an item is in the first column of a specified set of cells. You could wrap it in an if in order to give you the Y/N value</p>
<p>The basic syntax would be like this.</p>
<p>=IF(ISNA(VLOOKUP(F2, $G$10:$G$28, 1, false)), "N", "Y")</p>
<p>Additionally, if you had a specific value that you wanted to display when a match was found, you could have that value in column H and use a slightly different formula. You'll want to further investigate the VLOOKUP function if you are not familiar with how it works.
Something like
=IFERROR(VLOOKUP(F2, $G$10:$H$28, 2, false), "N")</p> |
23,330,781 | Collect values in order, each containing a map | <p>When iterating through the returned map in the code, returned by the topic function, the keys are not appearing in order.</p>
<p>How can I get the keys to be in order / sort the map so that the keys are in order and the values correspond?</p>
<p>Here is <a href="http://play.golang.org/p/5mhXcu7LFu" rel="nofollow noreferrer">the code</a>.</p> | 23,332,089 | 7 | 2 | null | 2014-04-28 00:34:31.233 UTC | 34 | 2022-05-13 10:00:43.837 UTC | 2021-05-14 14:20:09.287 UTC | null | 115,363 | null | 3,533,791 | null | 1 | 107 | go|hashmap | 146,652 | <p>The <a href="http://blog.golang.org/go-maps-in-action#TOC_7." rel="noreferrer">Go blog: Go maps in action</a> has an excellent explanation.</p>
<blockquote>
<p>When iterating over a map with a range loop, the iteration order is
not specified and is not guaranteed to be the same from one iteration
to the next. Since Go 1 the runtime randomizes map iteration order, as
programmers relied on the stable iteration order of the previous
implementation. If you require a stable iteration order you must
maintain a separate data structure that specifies that order.</p>
</blockquote>
<p>Here's my modified version of example code:
<a href="http://play.golang.org/p/dvqcGPYy3-" rel="noreferrer">http://play.golang.org/p/dvqcGPYy3-</a></p>
<pre><code>package main
import (
"fmt"
"sort"
)
func main() {
// To create a map as input
m := make(map[int]string)
m[1] = "a"
m[2] = "c"
m[0] = "b"
// To store the keys in slice in sorted order
keys := make([]int, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
sort.Ints(keys)
// To perform the opertion you want
for _, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}
}
</code></pre>
<p>Output:</p>
<pre><code>Key: 0 Value: b
Key: 1 Value: a
Key: 2 Value: c
</code></pre> |
1,436,761 | Turn Off Apache Common Logging | <p>I am using Apache Common Logging library in my standalone application. After searching through the web, I try to turn off the logging by using</p>
<pre><code>package javaapplication1;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author yccheok
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
log.info("You do not want to see me");
}
private static final Log log = LogFactory.getLog(Main.class);
}
</code></pre>
<p>However, I still can see the log message being printed. May I know what had I missed out?</p>
<p>I can turn off the logging by putting</p>
<pre><code># Sample ResourceBundle properties file
org.apache.commons.logging.Log=org.apache.commons.logging.impl.NoOpLog
</code></pre>
<p>in commons-logging.properties.</p>
<p>However, during my development time, my Netbeans doesn't know where to get commons-logging.properties, and sometimes I need to turn off logging during development time.</p> | 1,437,999 | 5 | 0 | null | 2009-09-17 04:50:45.307 UTC | 13 | 2022-05-01 08:12:15.297 UTC | null | null | null | null | 72,437 | null | 1 | 35 | java | 30,803 | <p>As others have pointed out, this is happening because you create the Log object <strong>before</strong> you set the property.</p>
<p>One way around this would be to set the property in your <code>Main</code> class' static initialiser block - this will be run when the class is first loaded, and before the static final Log is created:</p>
<pre><code>public class Main {
static {
System.setProperty("org.apache.commons.logging.Log",
"org.apache.commons.logging.impl.NoOpLog");
}
// Rest of class as before
}
</code></pre> |
1,403,493 | What is the point of Lookup<TKey, TElement>? | <p>The MSDN explains Lookup like this:</p>
<blockquote>
<p>A <a href="http://msdn.microsoft.com/en-us/library/bb460184%28v=vs.90%29.aspx" rel="noreferrer"><code>Lookup<TKey, TElement></code></a>
resembles a <a href="http://msdn.microsoft.com/en-us/library/xfhwa508.aspx" rel="noreferrer"><code>Dictionary<TKey,
TValue></code></a>. The difference is that a
<strong>Dictionary<TKey, TValue></strong> maps keys to single values, whereas a
<strong>Lookup<TKey, TElement></strong> maps keys to collections of values.</p>
</blockquote>
<p>I don't find that explanation particularly helpful. What is Lookup used for?</p> | 1,403,499 | 5 | 0 | null | 2009-09-10 05:20:31.863 UTC | 50 | 2019-01-02 19:46:21.117 UTC | 2013-03-31 14:40:09.667 UTC | null | 200,449 | null | 60,620 | null | 1 | 178 | c#|.net|linq|lookup | 101,899 | <p>It's a cross between an <code>IGrouping</code> and a dictionary. It lets you group items together by a key, but then access them via that key in an efficient manner (rather than just iterating over them all, which is what <code>GroupBy</code> lets you do).</p>
<p>For example, you could take a load of .NET types and build a lookup by namespace... then get to all the types in a particular namespace very easily:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
public class Test
{
static void Main()
{
// Just types covering some different assemblies
Type[] sampleTypes = new[] { typeof(List<>), typeof(string),
typeof(Enumerable), typeof(XmlReader) };
// All the types in those assemblies
IEnumerable<Type> allTypes = sampleTypes.Select(t => t.Assembly)
.SelectMany(a => a.GetTypes());
// Grouped by namespace, but indexable
ILookup<string, Type> lookup = allTypes.ToLookup(t => t.Namespace);
foreach (Type type in lookup["System"])
{
Console.WriteLine("{0}: {1}",
type.FullName, type.Assembly.GetName().Name);
}
}
}
</code></pre>
<p>(I'd normally use <code>var</code> for most of these declarations, in normal code.)</p> |
1,527,670 | Summing Duplicates in Excel | <p>I have a long list of names of products and numbers of those products, I want to combine all the duplicate entries and add their numbers. So if I have 2 entries for Widget X, and each entry has 3 products, then I want to combine this to one entry for Widget X with 6 products.</p>
<p>I've sorted the list out and summed them for each product but I just used a sum function, I felt there must be a formula that uses an IF statement to detect entries that equal each other and then sum their respective quantity lines but I can't figure it out.</p>
<p>What i'm trying to get is IF (any field in column A = 3792 , then sum all its associated quantity fields in column C)</p>
<p>Does anyone have any ideas? </p>
<pre><code>3792 Widget A 1
3792 Widget A 1
3792 Widget A 1
3792 Widget A 1
3792 Widget A 1
3792 Widget A 2
3792 Widget A 1
3805 Widget B 1
3805 Widget B 1
3806 Widget C 8
3823 Widget D 895
3823 Widget D 1
3823 Widget D 20
3892 Widget E 2
3892 Widget E 1
3892 Widget E 1
</code></pre> | 1,527,698 | 6 | 1 | null | 2009-10-06 19:41:40.363 UTC | 1 | 2019-01-23 13:26:29.5 UTC | 2009-10-06 21:25:24.107 UTC | null | 146,003 | null | 99,520 | null | 1 | 4 | excel | 83,735 | <p>Excel's <a href="http://www.techonthenet.com/excel/formulas/sumif.php" rel="nofollow noreferrer">SUMIF()</a>-Formula might help you accomplish this.</p>
<p>as described, the syntax is</p>
<pre><code>SUMIF(range, criteria, sum_range)
</code></pre>
<p>Searches fields within <code>range</code> that match <code>criteria</code> and sums up the values in <code>sum_range</code> (at the same index where the criteria has been found in range, respectively).</p>
<p>you might want to create a matrix for each number/search criteria to sum up and compare...</p>
<p><strong>Another approach</strong>:</p>
<p>For a certain Column (let's take C) make a temporary column and add a 1 as value to each line.</p>
<p>For example, in Column "Sum A:" type the formula:</p>
<pre><code>=IF($A2=D$1,1,0)
</code></pre>
<p>Whereas D1 is the cell containing the number 3792 (in top) and the 2 in C2 is the current line the formula stands in.</p>
<p>You would just be able to drag it to the right and to the bottom.</p>
<p>This would be the result:</p>
<pre><code>A B C D E F G
3792 3805 3806 3823 3892
3792 Widget A 1
3792 Widget A 1
3792 Widget A 1
3792 Widget A 1
3792 Widget A 1
3792 Widget A 1
3792 Widget A 1
3805 Widget B 1
3805 Widget B 1
3806 Widget C 1
3823 Widget D 1
3823 Widget D 1
3823 Widget D 1
3892 Widget E 1
3892 Widget E 1
3892 Widget E 1
SUM: 7 2 1 3 3
</code></pre>
<p>You just simply sum up at the end and you got your results. If another number should be added than <code>1</code>, simply add another column containing the appropriate value, you then replace it in the <code>IF</code>-formula. </p>
<p>you might want to automate this even more using a <code>HLOOKUP()</code> for the widget number's at the top.</p>
<p>regards</p> |
1,547,466 | Check if a parameter is a Python module? | <p>How can I (pythonically) check if a parameter is a Python module? There's no type like module or package.</p>
<pre><code>>>> os
<module 'os' from '/usr/lib/python2.6/os.pyc'>
>>> isinstance(os, module)
Traceback (most recent call last):
File "/usr/lib/gedit-2/plugins/pythonconsole/console.py", line 290, in __run
r = eval(command, self.namespace, self.namespace)
File "<string>", line 1, in <module>
NameError: name 'module' is not defined
</code></pre>
<p>I can do this:</p>
<pre><code>>>> type(os)
<type 'module'>
</code></pre>
<p>But what do I compare it to? :(</p>
<p>I've made a simple module to quickly find methods in modules and get help texts for them. I supply a module var and a string to my method:</p>
<pre><code>def gethelp(module, sstring):
# here i need to check if module is a module.
for func in listseek(dir(module), sstring):
help(module.__dict__[func])
</code></pre>
<p>Of course, this will work even if module = 'abc': then dir('abc') will give me the list of methods for string object, but I don't need that.</p> | 1,547,475 | 6 | 4 | null | 2009-10-10 09:18:38.057 UTC | 6 | 2019-10-29 09:35:21.743 UTC | null | null | null | null | 171,278 | null | 1 | 53 | python|types | 20,593 | <pre><code>from types import ModuleType
isinstance(obj, ModuleType)
</code></pre> |
1,380,156 | Java properties: .properties files vs xml? | <p>I'm a newbie when it comes to properties, and I read that XML is the preferred way to store these. I noticed however, that writing a regular .properties file in the style of</p>
<pre><code>foo=bar
fu=baz
</code></pre>
<p>also works. This would mean a lot less typing (and maybe easier to read and more efficient as well). So what are the benefits of using an XML file?</p> | 1,380,204 | 7 | 0 | null | 2009-09-04 16:04:09.517 UTC | 9 | 2017-10-05 23:29:50.903 UTC | 2017-10-05 23:29:50.903 UTC | null | 6,862,601 | null | 147,262 | null | 1 | 23 | java|xml|properties | 28,742 | <p>In XML you can store more complex (e.g. hierarchical) data than in a properties file. So it depends on your usecase. If you just want to store a small number of direct properties a properties file is easier to handle (though the Java properties class can read XML based properties, too).</p>
<p>It would make sense to keep your configuration interface as generic as possible anyway, so you have no problem to switch to another representation ( e.g. by using <a href="http://commons.apache.org/configuration/" rel="noreferrer">Apache Commons Configuration</a> ) if you need to.</p> |
2,043,726 | Best way to copy a database (SQL Server 2008) | <p>Dumb question - what's the best way to copy instances in an environment where I want to refresh a development server with instances from a production server? </p>
<p>I've done backup-restore, but I've heard detach-copy-attach and one guy even told me he would just copy the datafiles between the filesystems....</p>
<p>Are these the three (or two, the last one sounds kind of suspect) accepted methods? </p>
<p>My understanding is that the second method is faster but requires downtime on the source because of the detach aspect.</p>
<p>Also, in this situation (wanting an exact copy of production on a dev server) what's the accepted practice for transferring logins,etc.? Should I just backup and restore the user databases + master + msdb?</p> | 2,043,970 | 8 | 0 | null | 2010-01-11 17:57:18.1 UTC | 34 | 2016-06-01 05:47:49.997 UTC | 2010-01-11 18:03:19.787 UTC | null | 109,687 | null | 248,260 | null | 1 | 72 | sql-server|sql-server-2008 | 103,901 | <p>The fastest way to copy a database is to detach-copy-attach method, but the production users will not have database access while the prod db is detached. You can do something like this if your production DB is for example a Point of Sale system that nobody uses during the night.</p>
<p>If you cannot detach the production db you should use backup and restore.</p>
<p>You will have to create the logins if they are not in the new instance. I do not recommend you to copy the system databases.</p>
<p>You can use the SQL Server Management Studio to create the scripts that create the logins you need. Right click on the login you need to create and select Script Login As / Create.</p>
<p>This will lists the orphaned users:</p>
<pre><code>EXEC sp_change_users_login 'Report'
</code></pre>
<p>If you already have a login id and password for this user, fix it by doing:</p>
<pre><code>EXEC sp_change_users_login 'Auto_Fix', 'user'
</code></pre>
<p>If you want to create a new login id and password for this user, fix it by doing:</p>
<pre><code>EXEC sp_change_users_login 'Auto_Fix', 'user', 'login', 'password'
</code></pre> |
1,964,731 | The need for volatile modifier in double checked locking in .NET | <p>Multiple texts say that when implementing double-checked locking in .NET the field you are locking on should have volatile modifier applied. But why exactly? Considering the following example:</p>
<pre><code>public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
</code></pre>
<p>why doesn't "lock (syncRoot)" accomplish the necessary memory consistency? Isn't it true that after "lock" statement both read and write would be volatile and so the necessary consistency would be accomplished?</p> | 1,964,832 | 8 | 6 | null | 2009-12-27 00:13:56.297 UTC | 39 | 2019-12-09 20:53:56.023 UTC | null | null | null | null | 101,685 | null | 1 | 90 | c#|singleton|volatile | 27,172 | <p>Volatile is unnecessary. Well, sort of**</p>
<p><code>volatile</code> is used to create a memory barrier* between reads and writes on the variable.<br>
<code>lock</code>, when used, causes memory barriers to be created around the block inside the <code>lock</code>, in addition to limiting access to the block to one thread.<br>
Memory barriers make it so each thread reads the most current value of the variable (not a local value cached in some register) and that the compiler doesn't reorder statements. Using <code>volatile</code> is unnecessary** because you've already got a lock. </p>
<p><a href="http://www.albahari.com/threading/part4.aspx#%5FNonBlockingSynch" rel="nofollow noreferrer">Joseph Albahari</a> explains this stuff way better than I ever could.</p>
<p>And be sure to check out Jon Skeet's <a href="https://csharpindepth.com/articles/singleton" rel="nofollow noreferrer">guide to implementing the singleton</a> in C# </p>
<p><br>
<b>update</b>:<br>
*<code>volatile</code> causes reads of the variable to be <code>VolatileRead</code>s and writes to be <code>VolatileWrite</code>s, which on x86 and x64 on CLR, are implemented with a <code>MemoryBarrier</code>. They may be finer grained on other systems.</p>
<p>**my answer is only correct if you are using the CLR on x86 and x64 processors. It <em>might</em> be true in other memory models, like on Mono (and other implementations), Itanium64 and future hardware. This is what Jon is referring to in his article in the "gotchas" for double checked locking. </p>
<p>Doing one of {marking the variable as <code>volatile</code>, reading it with <code>Thread.VolatileRead</code>, or inserting a call to <code>Thread.MemoryBarrier</code>} might be necessary for the code to work properly in a weak memory model situation.</p>
<p>From what I understand, on the CLR (even on IA64), writes are never reordered (writes always have release semantics). However, on IA64, reads may be reordered to come before writes, unless they are marked volatile. Unfortuantely, I do not have access to IA64 hardware to play with, so anything I say about it would be speculation.</p>
<p>i've also found these articles helpful:<br>
<a href="http://www.codeproject.com/KB/tips/MemoryBarrier.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/tips/MemoryBarrier.aspx</a><br>
<a href="http://msdn.microsoft.com/en-us/magazine/cc163715.aspx" rel="nofollow noreferrer">vance morrison's article</a> (everything links to this, it talks about double checked locking)<br>
<a href="http://blogs.msdn.com/cbrumme/archive/2003/05/17/51445.aspx" rel="nofollow noreferrer">chris brumme's article</a> (everything links to this)<br>
<a href="http://joeduffyblog.com/2006/01/26/broken-variants-on-doublechecked-locking/" rel="nofollow noreferrer">Joe Duffy: Broken Variants of Double Checked Locking</a> </p>
<p>luis abreu's series on multithreading give a nice overview of the concepts too<br>
<a href="http://msmvps.com/blogs/luisabreu/archive/2009/06/29/multithreading-load-and-store-reordering.aspx" rel="nofollow noreferrer">http://msmvps.com/blogs/luisabreu/archive/2009/06/29/multithreading-load-and-store-reordering.aspx</a><br>
<a href="http://msmvps.com/blogs/luisabreu/archive/2009/07/03/multithreading-introducing-memory-fences.aspx" rel="nofollow noreferrer">http://msmvps.com/blogs/luisabreu/archive/2009/07/03/multithreading-introducing-memory-fences.aspx</a> </p> |
1,725,923 | how bad is it to use dynamic datastuctures on an embedded system? | <p>So in an embedded systems unit, that i'm taking at uni next year, we will learn that dynamic data structures are a bad thing to have in an embedded system program.
but the lecture notes don't go into why.</p>
<p>Now i'm working on a moderate scale, embedded systems\ 'LURC' controller, mostly just takes advantages of the peripheral of the "Butterfly" demo board for the AVR169MEGA.
produced 4 PWM signals to contol servo's and ESC. and also to provide an 9 seg LCD screen.</p>
<p>Now I can't think of anybetter way to store instructions as they are recieved vial USART serial, than a queue.
esp for things where I'll need to wait until an unknown amount of data has been recieved: eg a string to display on the LCD screen.</p>
<p>so why don't you uses dynamic data structures on a microcontroller in a embedded systems?
Is it just that you're on a heavily memory restricted enviroment, and have to be sure your mallocs are succeeding?</p> | 1,726,006 | 9 | 1 | null | 2009-11-12 22:40:08.563 UTC | 9 | 2021-03-06 13:45:09.443 UTC | 2017-08-17 03:44:59.263 UTC | null | 179,081 | null | 179,081 | null | 1 | 20 | list|stack|queue|avr | 16,378 | <p>There are a number of reasons not to use malloc (or equivalent) in an embedded system.</p>
<ul>
<li>As you mentioned, it is important that you do not suddenly find yourself out of memory.</li>
<li>Fragmentation - embedded systems can run for years which can cause a severe waste of memory due to fragmentation.</li>
<li>Not really required. Dynamic memory allocation allows you to reuse the same memory to do different things at different times. Embedded systems tend to do the same thing all the time (except at startup).</li>
<li>Speed. Dynamic memory allocation is either relatively slow (and gets slower as the memory gets fragmented) or is fairly wasteful (e.g. buddy system).</li>
<li>If you are going to use the same dynamic memory for different threads and interrupts then allocation/freeing routines need to perform locking which can cause problems servicing interrupts fast enough.</li>
<li>Dynamic memory allocation makes it very difficult to debug, especially with some of the limited/primitive debug tools available on embedded system. If you statically allocate stuff then you know where stuff is all the time which means it is much easier to inspect the state of something.</li>
</ul>
<p>Best of all - if you do not dynamically allocate memory then you can't get memory leaks.</p> |
1,893,424 | Count table rows | <p>What is the MySQL command to retrieve the count of records in a table?</p> | 1,893,431 | 12 | 0 | null | 2009-12-12 13:31:02.2 UTC | 23 | 2021-01-02 02:02:42.85 UTC | 2015-06-23 22:20:04.83 UTC | null | 568,371 | null | 200,960 | null | 1 | 182 | mysql | 303,525 | <pre><code>SELECT COUNT(*) FROM fooTable;
</code></pre>
<p>will count the number of rows in the table.</p>
<p>See the <a href="http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html" rel="noreferrer">reference manual</a>.</p> |
1,726,073 | Is it sometimes bad to use <BR />? | <p>Is it sometimes bad to use <code><BR/></code> tags?</p>
<p>I ask because some of the first advice my development team gave me was this: Don't use <code><BR/></code> ; instead, use styles. But why? Are there negative outcomes when using <code><BR/></code> tags?</p> | 1,726,103 | 15 | 3 | null | 2009-11-12 23:15:18.477 UTC | 33 | 2021-07-08 17:47:29.293 UTC | 2012-06-16 19:43:11.807 UTC | null | 109,618 | null | 136,141 | null | 1 | 186 | html|tags|styles | 99,873 | <p>The main reason for not using <code><br></code> is that it's not <a href="http://en.wikipedia.org/wiki/Semantic_Web">semantic</a>. If you want two items in different visual blocks, you probably want them in different logical blocks.</p>
<p>In most cases this means just using different elements, for example <code><p>Stuff</p><p>Other stuff</p></code>, and then using CSS to space the blocks out properly.</p>
<p>There are cases where <code><br></code> is semantically valid, i.e. cases where the line break is <em>part</em> of the data you're sending. This is really only limited to 2 use cases - poetry and mailing addresses.</p> |
1,783,822 | Technical reasons behind formatting when incrementing by 1 in a 'for' loop? | <p>All over the web, code samples have <code>for</code> loops which look like this:</p>
<pre><code>for(int i = 0; i < 5; i++)
</code></pre>
<p>while I used the following format:</p>
<pre><code>for(int i = 0; i != 5; ++i)
</code></pre>
<p>I do this because I believe it to be more efficient, but does this really matter in most cases?</p> | 8,914,410 | 31 | 28 | 2013-05-29 01:40:28.633 UTC | 2009-11-23 15:24:58.103 UTC | 13 | 2018-08-01 06:43:33.567 UTC | 2015-07-22 10:20:02.7 UTC | null | 2,436,175 | null | 202,241 | null | 1 | 53 | java|c#|c++|c|for-loop | 6,504 | <p>I have decided to list the most informative answers as this question is getting a little crowded. </p>
<p><a href="https://stackoverflow.com/questions/1783822/format-of-for-loops/8896521#8896521">DenverCoder8</a>'s bench marking clearly deserves some recognition as well as the compiled versions of the loops by <a href="https://stackoverflow.com/questions/1783822/format-of-for-loops/1784000#1784000">Lucas</a>. <a href="https://stackoverflow.com/questions/1783822/format-of-for-loops/8857037#8857037">Tim Gee</a> has shown the differences between pre & post increment while <a href="https://stackoverflow.com/questions/1783822/format-of-for-loops/8838920#8838920">User377178</a> has highlighted some of the pros and cons of < and !=. <a href="https://stackoverflow.com/questions/1783822/format-of-for-loops/8888046#8888046">Tenacious Techhunter</a> has written about loop optimizations in general and is worth a mention. </p>
<p>There you have my top 5 answers. </p>
<ol>
<li><a href="https://stackoverflow.com/questions/1783822/format-of-for-loops/8896521#8896521">DenverCoder8</a></li>
<li><a href="https://stackoverflow.com/questions/1783822/format-of-for-loops/1784000#1784000">Lucas</a></li>
<li><a href="https://stackoverflow.com/questions/1783822/format-of-for-loops/8857037#8857037">Tim Gee</a></li>
<li><a href="https://stackoverflow.com/questions/1783822/format-of-for-loops/8838920#8838920">User377178</a></li>
<li><a href="https://stackoverflow.com/questions/1783822/format-of-for-loops/8888046#8888046">Tenacious Techhunter</a></li>
</ol> |
8,754,111 | How to read the data in a wav file to an array | <p>I need to get all the samples of a wav file into an array (or two if you need to do that to keep the stereo) so that I can apply some modifications to them. I was wondering if this is easily done (preferably without external libraries). I have no experience with reading in sound files, so I don't know much about the subject.</p> | 8,754,162 | 7 | 2 | null | 2012-01-06 06:13:17.207 UTC | 16 | 2022-09-09 22:59:50.89 UTC | null | null | null | null | 1,063,111 | null | 1 | 34 | c#|file-io|audio | 90,481 | <p>WAV files (at least, uncompressed ones) are fairly straightforward. There's a header, then the data follows it.</p>
<p>Here's a great reference: <strike>https://ccrma.stanford.edu/courses/422/projects/WaveFormat/</strike> (<a href="http://soundfile.sapp.org/doc/WaveFormat/" rel="nofollow noreferrer">mirror</a>)</p> |
8,516,825 | Is deprecated word the only difference between fill_parent and match_parent | <p>I found that both <code>fill_parent</code> and <code>match_parent</code> means the same thing</p>
<ul>
<li><strong>fill_parent</strong> means that the view wants to be as big as its parent, minus the parent's padding, if any.</li>
<li><strong>match_parent</strong> means that the view wants to be as big as its parent, minus the parent's padding, if any.</li>
</ul>
<p><strong>The only difference that I found is that <code>fill_parent</code> is deprecated starting from API Level 8 and is replaced by <code>match_parent</code></strong> </p>
<p>However, I didn't notice any difference between these two. If both are the same then, why is <code>fill_parent</code> deprecated. Can anyone explain any differences between these two except for the fact that one is deprecated and the other isn't?</p>
<p>I have gone through <a href="http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html" rel="noreferrer">http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html</a></p> | 8,516,882 | 4 | 2 | null | 2011-12-15 07:57:12.117 UTC | 4 | 2017-08-11 17:03:01.723 UTC | 2017-08-11 17:03:01.723 UTC | null | -1 | null | 111,988 | null | 1 | 73 | android | 34,053 | <p>As you said they are exact the same. As Romain Guy said, they have changed the name because <code>"fill_parent"</code> was confusing for developers. As matter of the fact, <code>"fill_parent"</code> does not fill the remaining space (for that you use the weight attribute) but it takes as much space as its layout parent. That's why the new name is <code>"match_parent"</code>.</p> |
17,866,311 | How to cast datetime to datetimeoffset? | <p>How can i convert an SQL Server <code>datetime</code> value to a <code>datetimeoffset</code> value?</p>
<hr />
<p>For example, an existing table contains <code>datetime</code> values that are all in <em>"local"</em> server time.</p>
<pre><code>SELECT TOP 5 ChangeDate FROM AuditLog
ChangeDate
=========================
2013-07-25 04:00:03.060
2013-07-24 04:00:03.073
2013-07-23 04:00:03.273
2013-07-20 04:00:02.870
2013-07-19 04:00:03.780
</code></pre>
<p>My server (<em>happens</em>) to be (right now, today) four hours behind UTC (right now, in the U.S. Eastern timezone, with Daylight Savings active):</p>
<pre><code>SELECT SYSDATETIMEOFFSET()
2013-07-25 14:42:41.6450840 -04:00
</code></pre>
<p>i want to convert the stored <code>datetime</code> values into <code>datetimeoffset</code> values; using the server's current timezone offset information.</p>
<p>The values i <strong>desire</strong> are:</p>
<pre><code>ChangeDate ChangeDateOffset
======================= ==================================
2013-07-25 04:00:03.060 2013-07-25 04:00:03.0600000 -04:00
2013-07-24 04:00:03.073 2013-07-24 04:00:03.0730000 -04:00
2013-07-23 04:00:03.273 2013-07-23 04:00:03.2730000 -04:00
2013-07-20 04:00:02.870 2013-07-20 04:00:02.8700000 -04:00
2013-07-19 04:00:03.780 2013-07-19 04:00:03.7800000 -04:00
</code></pre>
<p>You can see the desirable characteristics:</p>
<pre><code>2013-07-19 04:00:03.7800000 -04:00
\_________________________/ \____/
| |
a "local" datetime the offset from UTC
</code></pre>
<p>But instead the actual values are:</p>
<pre><code>SELECT TOP 5
ChangeDate,
CAST(ChangeDate AS datetimeoffset) AS ChangeDateOffset
FROM AuditLog
ChangeDate ChangeDateOffset
======================= ==================================
2013-07-25 04:00:03.060 2013-07-25 04:00:03.0600000 +00:00
2013-07-24 04:00:03.073 2013-07-24 04:00:03.0730000 +00:00
2013-07-23 04:00:03.273 2013-07-23 04:00:03.2730000 +00:00
2013-07-20 04:00:02.870 2013-07-20 04:00:02.8700000 +00:00
2013-07-19 04:00:03.780 2013-07-19 04:00:03.7800000 +00:00
</code></pre>
<p>With the invalid characteristics:</p>
<pre><code>2013-07-19 04:00:03.7800000 +00:00
\_________________________/ \____/
^
|
No offset from UTC present
</code></pre>
<p>So i try other things randomly:</p>
<pre><code>SELECT TOP 5
ChangeDate,
CAST(ChangeDate AS datetimeoffset) AS ChangeDateOffset,
DATEADD(minute, DATEDIFF(minute, GETDATE(), GETUTCDATE()), ChangeDate) AS ChangeDateUTC,
CAST(DATEADD(minute, DATEDIFF(minute, GETDATE(), GETUTCDATE()), ChangeDate) AS datetimeoffset) AS ChangeDateUTCOffset,
SWITCHOFFSET(CAST(ChangeDate AS datetimeoffset), DATEDIFF(minute, GETUTCDATE(), GETDATE())) AS ChangeDateSwitchedOffset
FROM AuditLog
ORDER BY ChangeDate DESC
</code></pre>
<p>With results:</p>
<pre><code>ChangeDate ChangeDateOffset ChangeDateUTC ChangeDateUTCOffset ChangeDateSwitchedOffset
======================= ================================== ======================= ================================== ==================================
2013-07-25 04:00:03.060 2013-07-25 04:00:03.0600000 +00:00 2013-07-25 08:00:03.060 2013-07-25 08:00:03.0600000 +00:00 2013-07-25 00:00:03.0600000 -04:00
2013-07-24 04:00:03.073 2013-07-24 04:00:03.0730000 +00:00 2013-07-24 08:00:03.073 2013-07-24 08:00:03.0730000 +00:00 2013-07-24 00:00:03.0730000 -04:00
2013-07-23 04:00:03.273 2013-07-23 04:00:03.2730000 +00:00 2013-07-23 08:00:03.273 2013-07-23 08:00:03.2730000 +00:00 2013-07-23 00:00:03.2730000 -04:00
2013-07-20 04:00:02.870 2013-07-20 04:00:02.8700000 +00:00 2013-07-20 08:00:02.870 2013-07-20 08:00:02.8700000 +00:00 2013-07-20 00:00:02.8700000 -04:00
2013-07-19 04:00:03.780 2013-07-19 04:00:03.7800000 +00:00 2013-07-19 08:00:03.780 2013-07-19 08:00:03.7800000 +00:00 2013-07-19 00:00:03.7800000 -04:00
---------------------------------- ---------------------------------- ----------------------------------
No UTC offset Time in UTC No UTC offset Time all wrong
</code></pre>
<p>None of them return the desired values.</p>
<p>Can anyone suggest something that returns what i intuitively want?</p> | 17,867,687 | 4 | 3 | null | 2013-07-25 18:46:29.953 UTC | 17 | 2021-10-04 01:18:27 UTC | 2021-02-16 00:46:18.603 UTC | null | 12,597 | null | 12,597 | null | 1 | 52 | sql-server|internationalization|sql-server-2008-r2 | 56,495 | <h2><strong>Edit</strong>: Updated better answer for SQL Server 2016</h2>
<pre><code>SELECT
ChangeDate, --original datetime value
ChangeDate AT TIME ZONE 'Eastern Standard Time' AS ChangeDateOffset
FROM AuditLog
</code></pre>
<p>The <code>AT TIME ZONE</code> takes into account whether daylight savings was in effect <em>at the time</em> of the date being converted. And even though it says <em>"Standard"</em> in <em>"Eastern Standard Time"</em>, it will give you daylight times as well:</p>
<pre><code>ChangeDate ChangeDateOffset
----------------------- ------------------------------
2019-01-21 09:00:00.000 2019-01-21 09:00:00.000 -05:00
2019-02-21 09:00:00.000 2019-02-21 09:00:00.000 -05:00
2019-03-21 09:00:00.000 2019-03-21 09:00:00.000 -04:00 <-- savings time
2019-04-21 09:00:00.000 2019-04-21 09:00:00.000 -04:00 <-- savings time
2019-05-21 09:00:00.000 2019-05-21 09:00:00.000 -04:00 <-- savings time
2019-06-21 09:00:00.000 2019-06-21 09:00:00.000 -04:00 <-- savings time
2019-07-21 09:00:00.000 2019-07-21 09:00:00.000 -04:00 <-- savings time
2019-08-21 09:00:00.000 2019-08-21 09:00:00.000 -04:00 <-- savings time
2019-09-21 09:00:00.000 2019-09-21 09:00:00.000 -04:00 <-- savings time
2019-10-21 09:00:00.000 2019-10-21 09:00:00.000 -04:00 <-- savings time
2019-11-21 09:00:00.000 2019-11-21 09:00:00.000 -05:00
2019-12-21 09:00:00.000 2019-12-21 09:00:00.000 -05:00
</code></pre>
<p>As for how do you avoid hard-coding the string <code>Eastern Standard Time</code>, and use the current timezone of the server? <a href="https://dba.stackexchange.com/questions/148428/how-to-get-the-timezone-in-sql-server">You're SOL.</a></p>
<h2>Original pre-SQL Server 2016 answer</h2>
<p>i figured it out. The trick is that there is a built-in SQL Server function <a href="http://msdn.microsoft.com/en-us/library/bb630335.aspx" rel="noreferrer"><code>ToDateTimeOffset</code></a>, which <strong>attaches</strong> arbitrary offset information to any supplied <code>datetime</code>.</p>
<p>For example, the identical queries:</p>
<pre><code>SELECT ToDateTimeOffset('2013-07-25 15:35:27', -240) -- -240 minutes
SELECT ToDateTimeOffset('2013-07-25 15:35:27', '-04:00') -- -4 hours
</code></pre>
<p>both return:</p>
<pre><code>2013-07-25 15:35:27.0000000 -04:00
</code></pre>
<p><strong>Note</strong>: The offset parameter to <code>ToDateTimeOffset</code> can either be:</p>
<ul>
<li>an <code>integer</code>, representing a number of minutes</li>
<li>a <code>string</code>, representing a hours and minutes (in <code>{+|-}TZH:THM</code> format)</li>
</ul>
<h2>We need the server's current UTC offset</h2>
<p>Next we need the server's current offset from UTC. There are two ways i can have SQL Server return the the <code>integer</code> number of minutes we are from UTC:</p>
<pre><code>DATEPART(TZOFFSET, SYSDATETIMEOFFSET())
DATEDIFF(minute, GETUTCDATE(), GETDATE())
</code></pre>
<p>both return</p>
<pre><code>-240
</code></pre>
<p>Plugging this into the <code>TODATETIMEOFFSET</code> function:</p>
<pre><code>SELECT ToDateTimeOffset(
'2013-07-25 15:35:27',
DATEPART(TZOFFSET, SYSDATETIMEOFFSET()) --e.g. -240
)
</code></pre>
<p>returns the <code>datetimeoffset</code> value i want:</p>
<pre><code>2013-07-25 15:35:27.0000000 -04:00
</code></pre>
<h1>Putting it altogether</h1>
<p>Now we can have a better function to convert a datetime into a datetimeoffset:</p>
<pre><code>CREATE FUNCTION dbo.ToDateTimeOffset(@value datetime2)
RETURNS datetimeoffset AS
BEGIN
/*
Converts a date/time without any timezone offset into a datetimeoffset value,
using the server's current offset from UTC.
For this we use the built-in ToDateTimeOffset function;
which attaches timezone offset information with a datetimeoffset value.
The trick is to use DATEDIFF(minutes) between local server time and UTC
to get the offset parameter.
For example:
DATEPART(TZOFFSET, SYSDATETIMEOFFSET())
returns the integer
-240
for people in EDT (Eastern Daylight Time), which is 4 hours (240 minutes) behind UTC.
Pass that value to the SQL Server function:
TODATETIMEOFFSET(@value, -240)
*/
RETURN TODATETIMEOFFSET(@value, DATEPART(TZOFFSET, SYSDATETIMEOFFSET()))
END;
</code></pre>
<h2>Sample usage</h2>
<pre><code>SELECT TOP 5
ChangeDate,
dbo.ToDateTimeOffset(ChangeDate) AS ChangeDateOffset
FROM AuditLog
</code></pre>
<p>returns the desired:</p>
<pre><code>ChangeDate ChangeDateOffset
======================= ==================================
2013-07-25 04:00:03.060 2013-07-25 04:00:03.0600000 -04:00
2013-07-24 04:00:03.073 2013-07-24 04:00:03.0730000 -04:00
2013-07-23 04:00:03.273 2013-07-23 04:00:03.2730000 -04:00
2013-07-20 04:00:02.870 2013-07-20 04:00:02.8700000 -04:00
2013-07-19 04:00:03.780 2013-07-19 04:00:03.7800000 -04:00
</code></pre>
<p>It would have been <em>ideal</em> if the built-in function would have just did this:</p>
<pre><code>TODATETIMEOFFSET(value)
</code></pre>
<p>rather than having to create an <em>"overload"</em>:</p>
<pre><code>dbo.ToDateTimeOffset(value)
</code></pre>
<blockquote>
<p><strong>Note</strong>: Any code is released into the public domain. No attribution required.</p>
</blockquote> |
17,891,669 | Docker command fails during build, but succeeds while executed within running container | <p>the command : </p>
<pre><code>docker build -t nginx-ubuntu .
</code></pre>
<p>whith the Dockerfile below : </p>
<pre>
FROM ubuntu:12.10
RUN apt-get update
RUN apt-get -y install libpcre3 libssl-dev
RUN apt-get -y install libpcre3-dev
RUN apt-get -y install wget zip gcc
RUN wget http://nginx.org/download/nginx-1.4.1.tar.gz
RUN gunzip nginx-1.4.1.tar.gz
RUN tar -xf nginx-1.4.1.tar
RUN wget --no-check-certificate https://github.com/max-l/nginx_accept_language_module/archive/master.zip
RUN unzip master
RUN cd nginx-1.4.1
RUN ./configure --add-module=../nginx_accept_language_module-master --with-http_ssl_module --with-pcre=/lib/x86_64-linux-gnu --with-openssl=/usr/lib/x86_64-linux-gnu
</pre>
<p>Fails at the last line (./configure ...)</p>
<p>If I remove the last line and run a bash in the container, and
execute the last line manually, it works.</p>
<p>I would expect that whatever command runs successfully within a container should work
when the command is appended in the Dockerfile (prefixed by RUN) </p>
<p>am I missing something ? </p> | 17,891,972 | 4 | 0 | null | 2013-07-26 21:57:08.253 UTC | 8 | 2022-09-16 19:01:09.743 UTC | null | null | null | null | 535,782 | null | 1 | 27 | docker | 20,926 | <p>The pwd is not persistent across RUN commands. You need to cd and configure within the same RUN.</p>
<p>This Dockerfile works fine:</p>
<pre><code>FROM ubuntu:12.10
RUN apt-get update
RUN apt-get -y install libpcre3 libssl-dev
RUN apt-get -y install libpcre3-dev
RUN apt-get -y install wget zip gcc
RUN wget http://nginx.org/download/nginx-1.4.1.tar.gz
RUN gunzip nginx-1.4.1.tar.gz
RUN tar -xf nginx-1.4.1.tar
RUN wget --no-check-certificate https://github.com/max-l/nginx_accept_language_module/archive/master.zip
RUN unzip master
RUN cd nginx-1.4.1 && ./configure --add-module=../nginx_accept_language_module-master --with-http_ssl_module --with-pcre=/lib/x86_64-linux-gnu --with-openssl=/usr/lib/x86_64-linux-gnu
</code></pre> |
18,164,893 | this command is not available unless the connection is created with admin-commands enabled | <p>When trying to run the following in Redis using booksleeve. </p>
<pre><code>using (var conn = new RedisConnection(server, port, -1, password))
{
var result = conn.Server.FlushDb(0);
result.Wait();
}
</code></pre>
<p>I get an error saying:</p>
<blockquote>
<p>This command is not available unless the connection is created with
admin-commands enabled"</p>
</blockquote>
<p>I am not sure how do i execute commands as admin? Do I need to create an a/c in db with admin access and login with that?</p> | 18,165,520 | 4 | 0 | null | 2013-08-10 18:09:55.113 UTC | 4 | 2021-12-03 11:57:16.52 UTC | 2015-12-18 11:23:59.393 UTC | null | 270,901 | null | 931,842 | null | 1 | 36 | redis|booksleeve | 14,590 | <p>Basically, the dangerous commands that you don't need in routine operations, but which can cause lots of problems if used inappropriately (i.e. the equivalent of <code>drop database</code> in tsql, since your example is <code>FlushDb</code>) are protected by a "yes, I meant to do that..." flag:</p>
<pre><code>using (var conn = new RedisConnection(server, port, -1, password,
allowAdmin: true)) <==== here
</code></pre>
<p>I will improve the error message to make this very clear and explicit.</p> |
17,873,384 | How to deep copy a list? | <p>After <code>E0_copy = list(E0)</code>, I guess <code>E0_copy</code> is a deep copy of <code>E0</code> since <code>id(E0)</code> is not equal to <code>id(E0_copy)</code>. Then I modify <code>E0_copy</code> in the loop, but why is <code>E0</code> not the same after?</p>
<pre><code>E0 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for k in range(3):
E0_copy = list(E0)
E0_copy[k][k] = 0
#print(E0_copy)
print E0 # -> [[0, 2, 3], [4, 0, 6], [7, 8, 0]]
</code></pre> | 17,873,397 | 10 | 1 | null | 2013-07-26 05:12:19.67 UTC | 58 | 2022-09-20 10:06:14.163 UTC | 2021-12-17 20:13:53.72 UTC | null | 4,518,341 | null | 1,224,572 | null | 1 | 237 | python|list|copy|deep-copy | 367,995 | <p><code>E0_copy</code> is not a deep copy. You don't make a deep copy using <code>list()</code>. (Both <code>list(...)</code> and <code>testList[:]</code> are shallow copies.)</p>
<p>You use <a href="http://docs.python.org/2/library/copy.html#copy.deepcopy" rel="noreferrer"><code>copy.deepcopy(...)</code></a> for deep copying a list.</p>
<pre><code>deepcopy(x, memo=None, _nil=[])
Deep copy operation on arbitrary Python objects.
</code></pre>
<p>See the following snippet -</p>
<pre><code>>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = list(a)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b
[[1, 2, 3], [4, 5, 6]]
>>> a[0][1] = 10
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b # b changes too -> Not a deepcopy.
[[1, 10, 3], [4, 5, 6]]
</code></pre>
<p>Now see the <code>deepcopy</code> operation</p>
<pre><code>>>> import copy
>>> b = copy.deepcopy(a)
>>> a
[[1, 10, 3], [4, 5, 6]]
>>> b
[[1, 10, 3], [4, 5, 6]]
>>> a[0][1] = 9
>>> a
[[1, 9, 3], [4, 5, 6]]
>>> b # b doesn't change -> Deep Copy
[[1, 10, 3], [4, 5, 6]]
</code></pre>
<p>To explain, <code>list(...)</code> does not recursively make copies of the inner objects. It only makes a copy of the outermost list, while still referencing the same inner lists, hence, when you mutate the inner lists, the change is reflected in both the original list and the shallow copy. You can see that shallow copying references the inner lists by checking that <code>id(a[0]) == id(b[0])</code> where <code>b = list(a)</code>.</p> |
17,927,895 | Automate Extended Validation (EV) code signing | <p>We recently purchased a DigiCert EV code signing certificate. We are able to sign .exe files using signtool.exe. However, every time we sign a file, it prompts for the SafeNet eToken password. </p>
<p>How can we automate this process, without user intervention, by storing/caching the password somewhere?</p> | 54,439,759 | 13 | 5 | null | 2013-07-29 15:21:39.253 UTC | 63 | 2022-09-20 12:10:42.093 UTC | 2015-08-24 17:33:42.043 UTC | null | 25,507 | null | 12,082 | null | 1 | 110 | passwords|code-signing|authenticode|code-signing-certificate | 37,440 | <p>Expanding on answers already in this thread, it is possible to provide the token password using the standard signtool program from microsoft.</p>
<p><strong>0. Open SafeNet Client in Advanced View</strong></p>
<p>Install paths may vary, but for me the SafeNet client is installed to: <code>C:\Program Files\SafeNet\Authentication\SAC\x64\SACTools.exe</code></p>
<p>Click the gear icon in the upper right to open "advanced view".
<a href="https://i.stack.imgur.com/Sassj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Sassj.png" alt="SafeNet Advanced View"></a></p>
<p><strong>1. Export your public certificate to a file from the SafeNet Client</strong>
<a href="https://i.stack.imgur.com/em68v.png" rel="noreferrer"><img src="https://i.stack.imgur.com/em68v.png" alt="Exporting the Certificate to a File"></a></p>
<p><strong>2. Find your private key container name</strong><br>
<a href="https://i.stack.imgur.com/ybbwc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ybbwc.png" alt="Private Key Container Name"></a></p>
<p><strong>3. Find your reader name</strong>
<a href="https://i.stack.imgur.com/OPua2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/OPua2.png" alt="Reader Name"></a></p>
<p><strong>4. Format it all together</strong></p>
<p>The eToken CSP has hidden (or at least not widely advertised) functionality to parse the token password out of the container name.</p>
<p>The format is one of the following</p>
<pre><code>[]=name
[reader]=name
[{{password}}]=name
[reader{{password}}]=name
</code></pre>
<p>Where:</p>
<ul>
<li><code>reader</code> is the "Reader name" from the SafeNet Client UI</li>
<li><code>password</code> is your token password</li>
<li><code>name</code> is the "Container name" from the SafeNet Client UI</li>
</ul>
<p>Presumably you must specify the reader name if you have more than one reader connected - as I only have one reader I cannot confirm this.</p>
<p><strong>5. Pass the information to signtool</strong></p>
<ul>
<li><code>/f certfile.cer</code></li>
<li><code>/csp "eToken Base Cryptographic Provider"</code></li>
<li><code>/k "<value from step 4>"</code></li>
<li>any other signtool flags you require</li>
</ul>
<p>Example signtool command as follows</p>
<pre><code>signtool sign /f mycert.cer /csp "eToken Base Cryptographic Provider" /k "[{{TokenPasswordHere}}]=KeyContainerNameHere" myfile.exe
</code></pre>
<p>Some Images taken from this answer: <a href="https://stackoverflow.com/a/47894907/5420193">https://stackoverflow.com/a/47894907/5420193</a></p> |
6,427,186 | How to make a button stretch across the width of a column | <p>I'm trying to make a button span the width of a column.</p>
<p>e.g. here: <a href="http://davidnhutch.com" rel="noreferrer">http://davidnhutch.com</a>. Notice how the light grey buttons are only as large as the text they contain? I'd like each button to span the width of that column, but can't for the life of me figure out how to do it. I've done quite a bit of looking around but am still kinda new to this.</p>
<p>Any ideas? </p> | 6,427,251 | 3 | 0 | null | 2011-06-21 14:43:16.42 UTC | 1 | 2014-10-07 16:17:32.91 UTC | 2014-10-07 16:17:32.91 UTC | null | 759,866 | null | 633,546 | null | 1 | 7 | css|html|button | 43,105 | <p>You will have to make them block elements to be able to set a width:</p>
<pre><code>.button {
display: block;
width: 100%;
}
</code></pre> |
6,788,749 | Google Chrome background-gradient | <p>Really amateur question here - body background-gradient isn't working in chrome, very strange, I've tried:</p>
<pre><code>background: -webkit-gradient(linear, 0 0, 0 bottom, from(#FFF), to(#000));
</code></pre>
<p>And</p>
<pre><code>background: -webkit-gradient(linear, 0%, 0%, 0%, 100%, from(#fff), to(#000));
</code></pre>
<p>And </p>
<pre><code>background: -webkit-gradient(linear, center top, center bottom, from(#fff), to(#000));
</code></pre>
<p>All to no avail! Works in every other browser...</p> | 6,788,820 | 4 | 1 | null | 2011-07-22 10:34:36.663 UTC | 1 | 2021-09-06 07:48:38.487 UTC | 2015-11-25 10:36:01.287 UTC | null | 504,299 | null | 504,299 | null | 1 | 13 | css|google-chrome|linear-gradients | 44,786 | <p>Have you tried:</p>
<pre><code>background: -webkit-linear-gradient(#917c4d, #ffffff);
</code></pre>
<p>WebKit updated to match the spec syntax, so you should <a href="http://jsfiddle.net/robertc/bxTXd/" rel="noreferrer">have this to get maximum browser support</a>:</p>
<pre><code>background: -webkit-gradient(linear, center top, center bottom, from(#917c4d), to(#ffffff));
background: -webkit-linear-gradient(#917c4d, #ffffff);
background: -moz-linear-gradient(#917c4d, #ffffff);
background: -o-linear-gradient(#917c4d, #ffffff);
background: -ms-linear-gradient(#917c4d, #ffffff);
background: linear-gradient(#917c4d, #ffffff);
</code></pre> |
19,048,507 | how to check for datatype in node js- specifically for integer | <p>I tried the following to check for the datatype (specifically for integer), but not working.</p>
<pre><code>var i = "5";
if(Number(i) = 'NaN')
{
console.log('This is not number'));
}
</code></pre> | 19,049,127 | 9 | 2 | null | 2013-09-27 10:27:46.023 UTC | 3 | 2022-09-06 21:20:04.917 UTC | 2013-09-27 11:15:12.923 UTC | null | 580,951 | null | 484,243 | null | 1 | 30 | javascript|node.js | 122,837 | <p>I think of two ways to test for the type of a value:</p>
<p><strong>Method 1:</strong></p>
<p>You can use the <code>isNaN</code> javascript method, which determines if a value is <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN?redirectlocale=en-US&redirectslug=JavaScript/Reference/Global_Objects/NaN" rel="noreferrer">NaN</a> or not. But because in your case you are testing a numerical value converted to string, Javascript is trying to guess the type of the value and converts it to the number 5 which is not <code>NaN</code>. That's why if you <code>console.log</code> out the result, you will be surprised that the code:</p>
<pre><code>if (isNaN(i)) {
console.log('This is not number');
}
</code></pre>
<p>will not return anything. For this reason a better alternative would be the method 2.</p>
<p><strong>Method 2:</strong></p>
<p>You may use javascript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof" rel="noreferrer">typeof</a> method to test the type of a variable or value</p>
<pre><code>if (typeof i != "number") {
console.log('This is not number');
}
</code></pre>
<p>Notice that i'm using double equal operator, because in this case the type of the value is a string but Javascript internally will convert to Number.</p>
<p>A more robust method to force the value to numerical type is to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN?redirectlocale=en-US&redirectslug=JavaScript/Reference/Global_Objects/Number/isNaN#Browser_compatibility" rel="noreferrer">Number.isNaN</a> which is part of new Ecmascript 6 (Harmony) proposal, hence not widespread and fully supported by different vendors.</p> |
34,048,740 | Is this technically an O(1) algorithm for "Hello World"? | <p>Would this be classified as an O(1) algorithm for "Hello, World!" ??</p>
<pre><code>public class Hello1
{
public static void Main()
{
DateTime TwentyYearsLater = new DateTime(2035,01,01);
while ( DateTime.Now < TwentyYearsLater )
{
System.Console.WriteLine("It's still not time to print the hello ...");
}
System.Console.WriteLine("Hello, World!");
}
}
</code></pre>
<p>I'm thinking of using the </p>
<pre><code>DateTime TwentyYearsLater = new DateTime(2035,01,01);
while ( DateTime.Now < TwentyYearsLater )
{
// ...
}
</code></pre>
<p>snippet of code as a busy loop to put in as a joke whenever someone asks for an algorithm of a certain complexity. Would this be correct?</p> | 34,048,908 | 15 | 26 | null | 2015-12-02 17:06:54.65 UTC | 18 | 2015-12-14 02:05:46.017 UTC | 2015-12-02 17:10:04.25 UTC | null | 5,587,809 | null | 5,587,809 | null | 1 | 116 | c#|.net|algorithm|big-o | 18,176 | <p>Big O notation in this context is being used to describe a relationship between the size of the input of a function and the number of operations that need to be performed to compute the result for that input.</p>
<p>Your operation has no input that the output can be related to, so using Big O notation is nonsensical. The time that the operation takes is <em>independent</em> of the inputs of the operation (which is...none). Since there <em>is</em> no relationship between the input and the number of operations performed, you can't use Big O to describe that non-existent relationship</p> |
27,547,091 | Primary shard is not active or isn't assigned is a known node ? | <p>I am running an elastic search version 4.1 on windows 8. I tried to index a document through java. When running a JUNIT test the error appears as below. </p>
<pre><code>org.elasticsearch.action.UnavailableShardsException: [wms][3] Primary shard is not active or isn't assigned is a known node. Timeout: [1m], request: index {[wms][video][AUpdb-bMQ3rfSDgdctGY], source[{
"fleetNumber": "45",
"timestamp": "1245657888",
"geoTag": "73.0012312,-123.00909",
"videoName": "timestamp.mjpeg",
"content": "ASD123124NMMM"
}]}
at org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction$AsyncShardOperationAction.retryBecauseUnavailable(TransportShardReplicationOperationAction.java:784)
at org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction$AsyncShardOperationAction.doStart(TransportShardReplicationOperationAction.java:402)
at org.elasticsearch.action.support.replication.TransportShardReplicationOperationAction$AsyncShardOperationAction$3.onTimeout(TransportShardReplicationOperationAction.java:500)
at org.elasticsearch.cluster.ClusterStateObserver$ObserverClusterStateListener.onTimeout(ClusterStateObserver.java:239)
at org.elasticsearch.cluster.service.InternalClusterService$NotifyTimeout.run(InternalClusterService.java:497)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
</code></pre>
<p>I can not figure out, why causes this error to happen. When a delete data or index it works fine.
What might be the possible cause of it. </p> | 28,025,994 | 4 | 2 | null | 2014-12-18 12:55:08.087 UTC | 5 | 2020-05-04 14:26:07.423 UTC | null | null | null | null | 1,089,149 | null | 1 | 19 | java|indexing|elasticsearch|sharding | 48,571 | <p>you should look at that link:
<a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/index-modules-allocation.html">http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/index-modules-allocation.html</a></p>
<p>and that part in particular:</p>
<blockquote>
<p>cluster.routing.allocation.disk.watermark.low controls the low
watermark for disk usage. It defaults to 85%, meaning ES will not
allocate new shards to nodes once they have more than 85% disk used.
It can also be set to an absolute byte value (like 500mb) to prevent
ES from allocating shards if less than the configured amount of space
is available.</p>
<p>cluster.routing.allocation.disk.watermark.high controls the high
watermark. It defaults to 90%, meaning ES will attempt to relocate
shards to another node if the node disk usage rises above 90%. It can
also be set to an absolute byte value (similar to the low watermark)
to relocate shards once less than the configured amount of space is
available on the node.</p>
</blockquote> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.