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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7,167,604 | How accurately should I store latitude and longitude? | <p>I was reading this question here:</p>
<p><a href="https://stackoverflow.com/questions/1196415/what-datatype-to-use-when-storing-latitude-and-longitude-data-in-sql-databases">What datatype to use when storing latitude and longitude data in SQL databases?</a></p>
<p>And it seems the general consensus is that using Decimal(9,6) is the way to go. The question for me is, how accurate do I really need this?</p>
<p>For instance, Google's API returns a result like:</p>
<pre><code>"lat": 37.4219720,
"lng": -122.0841430
</code></pre>
<p>Out of -122.0841430, how many digits do I need? I've read several guides but I can't make enough sense out of them to figure this out.</p>
<p>To be more precise in my question: If I want to be accurate within 50 feet of the exact location, how many decimal points do I need to store?</p>
<p>Perhaps a better question would actually be a non-programming question, but it would be: how much more accurate does each decimal point give you?</p>
<p>Is it this simple?</p>
<ol>
<li>List item</li>
<li>x00 = 6000 miles</li>
<li>xx0 = 600 miles</li>
<li>xxx = 60 miles</li>
<li>xxx.x = 6 miles</li>
<li>xxx.xx = .6 miles</li>
<li>etc?</li>
</ol> | 13,571,357 | 7 | 3 | null | 2011-08-23 21:12:06.903 UTC | 52 | 2019-08-22 10:36:17.07 UTC | 2017-05-23 12:10:48.753 UTC | null | -1 | null | 175,250 | null | 1 | 119 | mysql|geolocation | 74,028 | <p>Accuracy versus decimal places at the equator</p>
<pre><code>decimal degrees distance
places
-------------------------------
0 1.0 111 km
1 0.1 11.1 km
2 0.01 1.11 km
3 0.001 111 m
4 0.0001 11.1 m
5 0.00001 1.11 m
6 0.000001 0.111 m
7 0.0000001 1.11 cm
8 0.00000001 1.11 mm
</code></pre>
<p>ref : <a href="https://en.wikipedia.org/wiki/Decimal_degrees#Precision" rel="noreferrer">https://en.wikipedia.org/wiki/Decimal_degrees#Precision</a></p> |
7,523,497 | Should Copy-Item create the destination directory structure? | <p>I'm trying to copy a file to a new location, maintaining directory structure.</p>
<pre><code>$source = "c:\some\path\to\a\file.txt"
destination = "c:\a\more\different\path\to\the\file.txt"
Copy-Item $source $destination -Force -Recurse
</code></pre>
<p>But I get a <code>DirectoryNotFoundException</code>:</p>
<pre><code>Copy-Item : Could not find a part of the path 'c:\a\more\different\path\to\the\file.txt'
</code></pre> | 7,523,632 | 8 | 0 | null | 2011-09-23 01:58:26.577 UTC | 8 | 2021-12-06 17:18:36.383 UTC | 2013-02-14 16:48:54.427 UTC | null | 274,535 | null | 93,733 | null | 1 | 71 | powershell | 108,689 | <p>The <code>-recurse</code> option only creates a destination folder structure if the source is a directory. When the source is a file, Copy-Item expects the destination to be a file or directory that already exists. Here are a couple ways you can work around that.</p>
<p><strong>Option 1:</strong> Copy directories instead of files</p>
<pre><code>$source = "c:\some\path\to\a\dir"; $destination = "c:\a\different\dir"
# No -force is required here, -recurse alone will do
Copy-Item $source $destination -Recurse
</code></pre>
<p><strong>Option 2:</strong> 'Touch' the file first and then overwrite it</p>
<pre><code>$source = "c:\some\path\to\a\file.txt"; $destination = "c:\a\different\file.txt"
# Create the folder structure and empty destination file, similar to
# the Unix 'touch' command
New-Item -ItemType File -Path $destination -Force
Copy-Item $source $destination -Force
</code></pre> |
13,820,477 | <input> tag validation for URL | <p>I am trying to validate an URL using JavaScript, but for some reason it's not working. When someone has not entered any URL, it shows message like:</p>
<blockquote>
<p>Please enter valid URL.(i.e. http://)</p>
</blockquote>
<p>I am trying to fix it, but can't make it working.</p>
<p>Is there any trick in HTML5 that allows to validate an URL?</p>
<pre><code>$(document).ready(function() {
$("#contactInfos").validate(
{ onfocusout: false, rules: {
phone: { number:true },
zipcode: { number:true },
website: { url:true }
},
messages: { phone: { number:"please enter digit only" },
zipcode: { number:"Plese enter digit only" },
website: { url: "Please enter valid URL.(i.e. http://)" }
}
});
</code></pre>
<p>Validate method for an URL:</p>
<pre><code>url: function(value, element) {
values=value.split(',');
for (x in values)
{
temp=values[x].trim();
temp1=this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(temp);
if(temp1!=true)
{
return false;
}
}
return true;
},
</code></pre> | 13,821,385 | 2 | 6 | null | 2012-12-11 12:29:43.997 UTC | 4 | 2019-04-09 21:33:16.8 UTC | 2019-04-09 21:33:16.8 UTC | null | 3,345,644 | null | 1,087,998 | null | 1 | 10 | javascript|html|validation | 40,243 | <p>In html5 you can use the tag input type="url":</p>
<pre><code><input type="url" />
</code></pre>
<p>you can use your own pattern too:</p>
<pre><code><input type="url" pattern="https?://.+" required />
</code></pre>
<p>In the paper Uniform Resource Identifier (URI): Generic Syntax [RFC3986] <a href="http://www.ietf.org/rfc/rfc3986.txt" rel="noreferrer">http://www.ietf.org/rfc/rfc3986.txt</a> the regular expression for a URI is:</p>
<pre><code>^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
</code></pre>
<blockquote>
<p>For example, matching the above expression to</p>
<pre><code> http://www.ics.uci.edu/pub/ietf/uri/#Related
</code></pre>
<p>results in the following subexpression matches:</p>
<pre><code> $1 = http:
$2 = http
$3 = //www.ics.uci.edu
$4 = www.ics.uci.edu
$5 = /pub/ietf/uri/
$6 = <undefined>
$7 = <undefined>
$8 = #Related
$9 = Related
</code></pre>
</blockquote> |
14,122,363 | iphone app allow background music to continue to play | <p>When I launch my iPhone game as soon as a sound plays the background music or podcast that is playing stops. I noticed other games allow background audio to continue to play.</p>
<p>How is this possible? Do I need to override a method in my App Delegate?</p> | 14,122,449 | 1 | 1 | null | 2013-01-02 12:49:54.483 UTC | 12 | 2019-06-12 08:56:11.247 UTC | null | null | null | null | 5,653 | null | 1 | 25 | iphone|objective-c|ios | 20,323 | <p>Place this line in your <code>application:didFinishLaunchingWithOptions:</code> method of your <code>AppDelegate</code> or in general before using the audio player.</p>
<pre><code> [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
</code></pre>
<p>According to the documentation, the <code>AVAudioSessionCategoryAmbient</code> category is</p>
<blockquote>
<p>for an app in which sound playback is nonprimary—that is, your app can be used successfully with the sound turned off.</p>
<p>This category is also appropriate for “play along” style apps, such as a virtual piano that a user plays over iPod audio. <strong>When you use this category, audio from other apps mixes with your audio.</strong> Your audio is silenced by screen locking and by the Silent switch (called the Ring/Silent switch on iPhone).</p>
</blockquote>
<p>If you want also to ensure that no error occurred you have to check the return value</p>
<pre><code>NSError *error;
BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error];
if (!success) {
//Handle error
NSLog(@"%@", [error localizedDescription]);
} else {
// Yay! It worked!
}
</code></pre>
<p>As a final remark, don't forget to link the <code>AVFoundation</code> framework to your project and import it.</p>
<pre><code>#import <AVFoundation/AVFoundation.h>
</code></pre> |
29,128,178 | How to use dimens.xml in Android? | <p>When I design a layout, I centralize all dimensions in dimens.xml because of topics of maintainability. My question is if this is correct or not. What would it be the best good practice? There is very little information about this, nothing. I know it's good idea to centralize all strings of a layout on strings.xml, colors on colors.xml. But about dimensions?</p>
<p>For example:</p>
<pre><code><TableLayout
android:id="@+id/history_detail_rows_submitted"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/cebroker_history_detail_rows_border"
android:collapseColumns="*">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/history_detail_rows_margin_vertical"
android:background="@color/cebroker_history_detail_rows_background"
android:gravity="center"
android:paddingBottom="@dimen/history_detail_rows_padding_vertical"
android:paddingLeft="@dimen/history_detail_rows_padding_horizontal"
android:paddingRight="@dimen/history_detail_rows_padding_horizontal"
android:paddingTop="@dimen/history_detail_rows_padding_vertical">
<TextView
android:layout_width="match_parent"
android:drawableLeft="@mipmap/ic_history_detail_submitted_by"
android:drawablePadding="@dimen/history_detail_rows_textviews_padding_drawable"
android:gravity="left|center"
android:paddingRight="@dimen/history_detail_rows_textviews_padding"
android:text="@string/history_detail_textview_submitted_by"
android:textColor="@color/cebroker_history_detail_rows_textviews"
android:textSize="@dimen/history_detail_rows_textviews_text_size" />
</code></pre> | 47,321,385 | 6 | 3 | null | 2015-03-18 16:58:56.613 UTC | 18 | 2021-05-19 01:14:33.083 UTC | 2017-11-16 04:04:19.773 UTC | null | 3,681,880 | null | 2,212,414 | null | 1 | 63 | android|android-layout | 120,498 | <h2>How to use <code>dimens.xml</code></h2>
<ol>
<li><p>Create a new <code>dimens.xml</code> file by right clicking the <code>values</code> folder and choosing <strong>New > Values resource file</strong>. Write <code>dimens</code> for the name. (You could also call it <code>dimen</code> or <code>dimensions</code>. The name doesn't really matter, only the <code>dimen</code> resource type that it will include.)</p>
</li>
<li><p>Add a <code>dimen</code> name and value.</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="my_value">16dp</dimen>
</resources>
</code></pre>
<p>Values can be in <code>dp</code>, <code>px</code>, or <code>sp</code>.</p>
</li>
<li><p>Use the value in xml</p>
<pre><code> <TextView
android:padding="@dimen/my_value"
... />
</code></pre>
<p>or in code</p>
<pre><code> float sizeInPixels = getResources().getDimension(R.dimen.my_value);
</code></pre>
</li>
</ol>
<h2>When to use <code>dimens.xml</code></h2>
<p><em>Thanks to <a href="https://stackoverflow.com/a/7508587/3681880">this answer</a> for more ideas.</em></p>
<ol>
<li><p><strong>Reusing values</strong> - If you need to use the same dimension multiple places throughout your app (for example, Activity layout padding or a TextView <code>textSize</code>), then using a single <code>dimen</code> value will make it much easier to adjust later. This is the same idea as using styles and themes.</p>
</li>
<li><p><strong>Supporting Multiple Screens</strong> - A padding of <code>8dp</code> might look fine on a phone but terrible on a 10" tablet. You can create multiple <code>dimens.xml</code> to be used with different screens. That way you could do something like set <code>8dp</code> for the phone and <code>64dp</code> for the tablet. To create another <code>dimens.xml</code> file, right click your <code>res</code> folder and choose <strong>New > Value resource file</strong>. (see <a href="https://stackoverflow.com/a/47320767/3681880">this answer</a> for details)</p>
</li>
<li><p><strong>Convenient <code>dp</code> to <code>px</code> code conversion</strong> - In code you usually need to work with pixel values. However you still have to think about the device density and the <a href="https://stackoverflow.com/a/42108115/3681880">conversion</a> is annoying to do programmatically. If you have a constant <code>dp</code> value, you can get it in pixels easy like this for <code>float</code>:</p>
<pre><code> float sizeInPixels = getResources().getDimension(R.dimen.my_value);
</code></pre>
<p>or this for <code>int</code> :</p>
<pre><code> int sizeInPixels = getResources().getDimensionPixelSize(R.dimen.my_value);
</code></pre>
</li>
</ol>
<p>I give many more details of how to do these things in <a href="https://stackoverflow.com/a/47320767/3681880">my fuller answer</a>.</p>
<h2>When not to use <code>dimens.xml</code></h2>
<ul>
<li><p>Don't put your values in <code>dimens.xml</code> if it is going to make them more difficult to maintain. Generally that will be whenever it doesn't fall into the categories I listed above. Using <code>dimens.xml</code> makes the code harder to read because you have to flip back and forth between two files to see what the actual values are. It's not worth it (in my opinion) for individual Views.</p>
</li>
<li><p>Strings are different. All strings should go in a resource file like <code>strings.xml</code> because almost all strings need to be translated when internationalizing your app. Most dimension values, on the other hand, do not need to change for a different locality. Android Studio seems to support this reasoning. Defining a string directly in the layout xml will give a warning but defining a <code>dp</code> value won't.</p>
</li>
</ul> |
9,181,594 | Reading text from file and storing each word from every line into separate variables | <p>I have a .txt file with the following content:</p>
<pre><code>1 1111 47
2 2222 92
3 3333 81
</code></pre>
<p>I would like to read line-by-line and store each word into different variables.</p>
<p>For example: When I read the first line "1 1111 47", I would like store the first word "1" into <code>var_1</code>, "1111" into <code>var_2</code>, and "47" into <code>var_3</code>. Then, when it goes to the next line, the values should be stored into the same <code>var_1</code>, <code>var_2</code> and <code>var_3</code> variables respectively. </p>
<p>My initial approach is as follows:</p>
<pre><code>import java.io.*;
class ReadFromFile
{
public static void main(String[] args) throws IOException
{
int i;
FileInputStream fin;
try
{
fin = new FileInputStream(args[0]);
}
catch(FileNotFoundException fex)
{
System.out.println("File not found");
return;
}
do
{
i = fin.read();
if(i != -1)
System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
</code></pre>
<p>Kindly give me your suggestions. Thank You</p> | 9,181,778 | 4 | 1 | null | 2012-02-07 18:17:37.44 UTC | 3 | 2018-10-25 08:21:29.037 UTC | 2018-10-25 08:21:29.037 UTC | null | 3,136,280 | null | 421,730 | null | 1 | 3 | java|file-io | 48,263 | <pre><code>public static void main(String[] args) throws IOException {
File file = new File("/path/to/InputFile");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while( (line = br.readLine())!= null ){
// \\s+ means any number of whitespaces between tokens
String [] tokens = line.split("\\s+");
String var_1 = tokens[0];
String var_2 = tokens[1];
String var_3 = tokens[2];
}
}
</code></pre> |
58,866,847 | In VS Code, I'm getting this error, 'Failed to load module. Attempted to load prettier from package.json' | <p>When I'm using VS Code and open up a project, I get this notification in the bottom right corner: </p>
<p><code>Failed to load module. If you have prettier or plugins referenced in package.json, ensure you have run</code>npm install<code>Attempted to load prettier from package.json.</code></p>
<p><code>Source: Prettier Code Format (Extension)</code></p>
<p>Running npm install doesn't resolve this. Anyone have any idea why that is or what I can do to fix it?</p> | 58,934,707 | 9 | 6 | null | 2019-11-14 21:32:47.893 UTC | 10 | 2022-03-14 09:13:51.697 UTC | 2019-11-19 19:53:25.773 UTC | null | 11,319,591 | null | 11,319,591 | null | 1 | 39 | visual-studio-code|package.json|prettier | 27,996 | <p>This is a solution that worked for me</p>
<p><strong>1.</strong> Install Prettier Globally via npm if you have never installed it globally </p>
<pre class="lang-sh prettyprint-override"><code>npm i prettier -g
</code></pre>
<p><strong>2.</strong> Search & Use the <code>Prettier Path</code> Extension Settings in your VS Code Settings </p>
<p><a href="https://i.stack.imgur.com/89Nan.png" rel="noreferrer"><img src="https://i.stack.imgur.com/89Nan.png" alt="enter image description here"></a></p>
<p>// You can navigate to VS Code <code>Settings > Extensions > Prettier</code> for all Prettier Extension Settings</p>
<p><strong>3.</strong> Update the <code>Prettier Path</code> to your globally installed Prettier. </p>
<p><strong>For Example</strong></p>
<p><code>/usr/local/lib/node_modules/prettier</code> (Mac OS)</p>
<p><code>\AppData\Roaming\npm\node_modules\prettier</code> (Windows)</p> |
19,603,542 | How can I update a property of an object that is contained in an array of a parent object using mongodb? | <p>I'm using MongoDB to be my database. i have a data:</p>
<pre class="lang-js prettyprint-override"><code> {
_id : '123'
friends: [
{name: 'allen', emails: [{email: '11111', using: 'true'}]}
]
}
</code></pre>
<p>now, i wanna to modify user's friends' emails ' email, whose _id is '123'
i write like this:</p>
<pre class="lang-js prettyprint-override"><code>db.users.update ({_id: '123'}, {$set: {"friends.0.emails.$.email" : '2222'} })
</code></pre>
<p>it's easy, but , it's wrong , when the emails array has two or more data.
so, my question is:
how can i modify the data in a nested filed --- just have two or more nested array? Thanks.</p> | 19,607,157 | 5 | 2 | null | 2013-10-26 06:10:45.007 UTC | 17 | 2022-07-22 10:22:43.067 UTC | 2022-07-22 10:22:43.067 UTC | null | 9,951,284 | null | 2,922,289 | null | 1 | 91 | mongodb|nested | 110,641 | <p>You need to use the <a href="http://docs.mongodb.org/manual/core/document/#dot-notation">Dot Notation</a> for the arrays.</p>
<p>That is, you should replace the <code>$</code> with the zero-based index of the element you're trying to update.</p>
<p>For example:</p>
<pre><code>db.users.update ({_id: '123'}, { '$set': {"friends.0.emails.0.email" : '2222'} });
</code></pre>
<p>will update the first email of the first friend, and</p>
<pre><code>db.users.update ({_id: '123'}, { '$set': {"friends.0.emails.1.email" : '2222'} })
</code></pre>
<p>will update the second email of the first friend.</p> |
19,462,912 | How to get number of days between two calendar instance? | <p>I want to find the difference between two <code>Calendar</code> objects in number of days if there is date change like If clock ticked from 23:59-0:00 there should be a day difference.</p>
<p>i wrote this </p>
<pre><code>public static int daysBetween(Calendar startDate, Calendar endDate) {
return Math.abs(startDate.get(Calendar.DAY_OF_MONTH)-endDate.get(Calendar.DAY_OF_MONTH));
}
</code></pre>
<p>but its not working as it only gives difference between days if there is month difference its worthless.</p> | 41,265,055 | 12 | 2 | null | 2013-10-19 05:58:22.243 UTC | 12 | 2022-02-22 02:29:50.483 UTC | 2013-10-24 14:27:50.36 UTC | null | 932,225 | null | 932,225 | null | 1 | 41 | java|android|date|calendar | 62,403 | <p>In Java 8 and later, we could simply use the <a href="http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html" rel="noreferrer">java.time</a> classes.</p>
<pre><code>hoursBetween = ChronoUnit.HOURS.between(calendarObj.toInstant(), calendarObj.toInstant());
daysBetween = ChronoUnit.DAYS.between(calendarObj.toInstant(), calendarObj.toInstant());
</code></pre> |
19,631,017 | Simple way to prevent a Divide By Zero error in SQL | <p>I have a SQL query which used to cause a </p>
<blockquote>
<p>Divide By Zero exception</p>
</blockquote>
<p>I've wrapped it in a <code>CASE</code> statement to stop this from happening. Is there a simpler way of doing this?</p>
<p><strong>Here's my code:</strong></p>
<pre><code>Percentage = CASE WHEN AttTotal <> 0 THEN (ClubTotal/AttTotal) * 100 ELSE 0 END
</code></pre> | 19,631,071 | 5 | 3 | null | 2013-10-28 09:22:23.043 UTC | 5 | 2018-03-28 06:38:27.843 UTC | 2018-03-28 06:38:27.843 UTC | null | 3,876,565 | null | 923,095 | null | 1 | 14 | sql|sql-server-2008|tsql|sql-server-2005 | 102,922 | <p>A nicer way of doing this is to use <a href="http://technet.microsoft.com/en-us/library/ms177562.aspx">NULLIF</a> like this:</p>
<pre><code>Percentage = 100 * ClubTotal / NULLIF(AttTotal, 0)
</code></pre> |
52,076,242 | Kill vscode from the command line | <p>I tried to kill the vscode from command line:</p>
<pre><code>$ killall vscode
No matching processes belonging to you were found
$ killall "Visual Studio Code"
No matching processes belonging to you were found
</code></pre>
<p>It does not work?</p>
<p>How could I terminate vscode from command line?</p> | 60,805,243 | 2 | 6 | null | 2018-08-29 11:20:34.427 UTC | 5 | 2022-03-25 23:59:45.257 UTC | 2018-08-29 12:50:19.007 UTC | null | 7,301,792 | null | 7,301,792 | null | 1 | 33 | macos|visual-studio-code | 29,218 | <p>Use </p>
<pre><code>killall code
</code></pre>
<p>It will terminate all running instances of Visual Studio Code.</p> |
352,837 | How to add file extensions based on file type on Linux/Unix? | <p>This is a question regarding Unix shell scripting (any shell), but any other "standard" scripting language solution would also be appreciated:</p>
<p>I have a directory full of files where the filenames are hash values like this:</p>
<pre><code>fd73d0cf8ee68073dce270cf7e770b97
fec8047a9186fdcc98fdbfc0ea6075ee
</code></pre>
<p>These files have different original file types such as png, zip, doc, pdf etc.</p>
<p>Can anybody provide a script that would rename the files so they get their appropriate file extension, probably based on the output of the <code>file</code> command?</p>
<h2>Answer:</h2>
<p><a href="https://stackoverflow.com/questions/352837/how-to-add-file-extensions-based-on-file-type-on-linuxunix#352973">J.F. Sebastian's</a> script will work for both ouput of the filenames as well as the actual renaming.</p> | 352,973 | 5 | 2 | null | 2008-12-09 14:10:18.957 UTC | 10 | 2015-07-28 11:22:40.577 UTC | 2020-06-20 09:12:55.06 UTC | Palmin | -1 | Palmin | 5,949 | null | 1 | 15 | python|linux|bash|unix|shell | 13,706 | <p>Here's mimetypes' version:</p>
<pre><code>#!/usr/bin/env python
"""It is a `filename -> filename.ext` filter.
`ext` is mime-based.
"""
import fileinput
import mimetypes
import os
import sys
from subprocess import Popen, PIPE
if len(sys.argv) > 1 and sys.argv[1] == '--rename':
do_rename = True
del sys.argv[1]
else:
do_rename = False
for filename in (line.rstrip() for line in fileinput.input()):
output, _ = Popen(['file', '-bi', filename], stdout=PIPE).communicate()
mime = output.split(';', 1)[0].lower().strip()
ext = mimetypes.guess_extension(mime, strict=False)
if ext is None:
ext = os.path.extsep + 'undefined'
filename_ext = filename + ext
print filename_ext
if do_rename:
os.rename(filename, filename_ext)
</code></pre>
<p>Example:</p>
<pre>
$ ls *.file? | python add-ext.py --rename
avi.file.avi
djvu.file.undefined
doc.file.dot
gif.file.gif
html.file.html
ico.file.obj
jpg.file.jpe
m3u.file.ksh
mp3.file.mp3
mpg.file.m1v
pdf.file.pdf
pdf.file2.pdf
pdf.file3.pdf
png.file.png
tar.bz2.file.undefined
</pre>
<hr>
<p>Following @Phil H's response that follows @csl' response:</p>
<pre><code>#!/usr/bin/env python
"""It is a `filename -> filename.ext` filter.
`ext` is mime-based.
"""
# Mapping of mime-types to extensions is taken form here:
# http://as3corelib.googlecode.com/svn/trunk/src/com/adobe/net/MimeTypeMap.as
mime2exts_list = [
["application/andrew-inset","ez"],
["application/atom+xml","atom"],
["application/mac-binhex40","hqx"],
["application/mac-compactpro","cpt"],
["application/mathml+xml","mathml"],
["application/msword","doc"],
["application/octet-stream","bin","dms","lha","lzh","exe","class","so","dll","dmg"],
["application/oda","oda"],
["application/ogg","ogg"],
["application/pdf","pdf"],
["application/postscript","ai","eps","ps"],
["application/rdf+xml","rdf"],
["application/smil","smi","smil"],
["application/srgs","gram"],
["application/srgs+xml","grxml"],
["application/vnd.adobe.apollo-application-installer-package+zip","air"],
["application/vnd.mif","mif"],
["application/vnd.mozilla.xul+xml","xul"],
["application/vnd.ms-excel","xls"],
["application/vnd.ms-powerpoint","ppt"],
["application/vnd.rn-realmedia","rm"],
["application/vnd.wap.wbxml","wbxml"],
["application/vnd.wap.wmlc","wmlc"],
["application/vnd.wap.wmlscriptc","wmlsc"],
["application/voicexml+xml","vxml"],
["application/x-bcpio","bcpio"],
["application/x-cdlink","vcd"],
["application/x-chess-pgn","pgn"],
["application/x-cpio","cpio"],
["application/x-csh","csh"],
["application/x-director","dcr","dir","dxr"],
["application/x-dvi","dvi"],
["application/x-futuresplash","spl"],
["application/x-gtar","gtar"],
["application/x-hdf","hdf"],
["application/x-javascript","js"],
["application/x-koan","skp","skd","skt","skm"],
["application/x-latex","latex"],
["application/x-netcdf","nc","cdf"],
["application/x-sh","sh"],
["application/x-shar","shar"],
["application/x-shockwave-flash","swf"],
["application/x-stuffit","sit"],
["application/x-sv4cpio","sv4cpio"],
["application/x-sv4crc","sv4crc"],
["application/x-tar","tar"],
["application/x-tcl","tcl"],
["application/x-tex","tex"],
["application/x-texinfo","texinfo","texi"],
["application/x-troff","t","tr","roff"],
["application/x-troff-man","man"],
["application/x-troff-me","me"],
["application/x-troff-ms","ms"],
["application/x-ustar","ustar"],
["application/x-wais-source","src"],
["application/xhtml+xml","xhtml","xht"],
["application/xml","xml","xsl"],
["application/xml-dtd","dtd"],
["application/xslt+xml","xslt"],
["application/zip","zip"],
["audio/basic","au","snd"],
["audio/midi","mid","midi","kar"],
["audio/mpeg","mp3","mpga","mp2"],
["audio/x-aiff","aif","aiff","aifc"],
["audio/x-mpegurl","m3u"],
["audio/x-pn-realaudio","ram","ra"],
["audio/x-wav","wav"],
["chemical/x-pdb","pdb"],
["chemical/x-xyz","xyz"],
["image/bmp","bmp"],
["image/cgm","cgm"],
["image/gif","gif"],
["image/ief","ief"],
["image/jpeg","jpg","jpeg","jpe"],
["image/png","png"],
["image/svg+xml","svg"],
["image/tiff","tiff","tif"],
["image/vnd.djvu","djvu","djv"],
["image/vnd.wap.wbmp","wbmp"],
["image/x-cmu-raster","ras"],
["image/x-icon","ico"],
["image/x-portable-anymap","pnm"],
["image/x-portable-bitmap","pbm"],
["image/x-portable-graymap","pgm"],
["image/x-portable-pixmap","ppm"],
["image/x-rgb","rgb"],
["image/x-xbitmap","xbm"],
["image/x-xpixmap","xpm"],
["image/x-xwindowdump","xwd"],
["model/iges","igs","iges"],
["model/mesh","msh","mesh","silo"],
["model/vrml","wrl","vrml"],
["text/calendar","ics","ifb"],
["text/css","css"],
["text/html","html","htm"],
["text/plain","txt","asc"],
["text/richtext","rtx"],
["text/rtf","rtf"],
["text/sgml","sgml","sgm"],
["text/tab-separated-values","tsv"],
["text/vnd.wap.wml","wml"],
["text/vnd.wap.wmlscript","wmls"],
["text/x-setext","etx"],
["video/mpeg","mpg","mpeg","mpe"],
["video/quicktime","mov","qt"],
["video/vnd.mpegurl","m4u","mxu"],
["video/x-flv","flv"],
["video/x-msvideo","avi"],
["video/x-sgi-movie","movie"],
["x-conference/x-cooltalk","ice"]]
#NOTE: take only the first extension
mime2ext = dict(x[:2] for x in mime2exts_list)
if __name__ == '__main__':
import fileinput, os.path
from subprocess import Popen, PIPE
for filename in (line.rstrip() for line in fileinput.input()):
output, _ = Popen(['file', '-bi', filename], stdout=PIPE).communicate()
mime = output.split(';', 1)[0].lower().strip()
print filename + os.path.extsep + mime2ext.get(mime, 'undefined')
</code></pre>
<hr>
<p>Here's a snippet for old python's versions (not tested):</p>
<pre><code>#NOTE: take only the first extension
mime2ext = {}
for x in mime2exts_list:
mime2ext[x[0]] = x[1]
if __name__ == '__main__':
import os
import sys
# this version supports only stdin (part of fileinput.input() functionality)
lines = sys.stdin.read().split('\n')
for line in lines:
filename = line.rstrip()
output = os.popen('file -bi ' + filename).read()
mime = output.split(';')[0].lower().strip()
try: ext = mime2ext[mime]
except KeyError:
ext = 'undefined'
print filename + '.' + ext
</code></pre>
<p>It should work on Python 2.3.5 (I guess).</p> |
986,592 | Any Emacs command like paste-mode in vim? | <p>When i'm trying to paste some code from browser to Emacs, it will indent code automatically, is there any way to stop Emacs from indenting temporarily like <em>:set paste</em> in vim?</p> | 32,048,737 | 5 | 5 | null | 2009-06-12 13:17:17.323 UTC | 6 | 2017-09-18 09:20:29.06 UTC | 2014-04-02 17:49:46.46 UTC | null | 881,229 | null | 111,896 | null | 1 | 29 | vim|emacs|copy-paste | 8,601 | <p>The easiest way with emacs24 is:</p>
<pre><code>M-x electric-indent-mode RET
</code></pre>
<p><em>That disables auto indentation.</em></p>
<p>Paste your thing.</p>
<p><em>renable</em></p>
<pre><code>M-x electric-indent-mode RET
</code></pre>
<p>Or just <code>M-x UP-Arrow</code> ;-)</p> |
323,325 | IIS 6.0 wildcard mapping benchmarks? | <p>I'm quickly falling in love with ASP.NET MVC beta, and one of the things I've decided I won't sacrifice in deploying to my IIS 6 hosting environment is the extensionless URL. Therefore, I'm weighing the consideration of adding a wildcard mapping, but everything I read suggests a potential performance hit when using this method. However, I can't find any actual benchmarks! </p>
<p>The first part of this question is, do you know where I might find such benchmarks, or is it just an untested assumption?</p>
<p>The second part of the question is in regards to the 2 load tests I ran using jMeter on our dev server over a 100Mbs connection. </p>
<p><strong>Background Info</strong></p>
<p>Our hosting provider has a 4Gbs burstable internet pipe with a 1Gbs backbone for our VLAN, so anything I can produce over the office lan should translate well to the hosting environment. </p>
<p>The test scenario was to load several images / css files, since the supposed performance hit comes when requesting files that are now being passed through the ASP.NET ISAPI filter that would not normally pass through it. Each test contained 50 threads (simulated users) running the request script for 1000 iterations each. The results for each test are posted below.</p>
<p><strong>Test Results</strong></p>
<p>Without wildcard mapping:</p>
<pre>
Samples: 50,000
Average response time: 428ms
Number of errors: 0
Requests per second: 110.1
Kilobytes per second: 11,543
</pre>
<p>With wildcard mapping:</p>
<pre>
Samples: 50,000
Average response time: 429ms
Number of errors: 0
Requests per second: 109.9
Kilobytes per second: 11,534
</pre>
<p>Both tests were run warm (everything was in memory, no initial load bias), and from my perspective, performance was about even. CPU usage was approximately 60% for the duration of both tests, memory was fine, and network utilization held steady around 90-95%.</p>
<p>Is this sufficient proof that wildcard mappings that pass through the ASP.NET filter for ALL content don't <em>really</em> affect performance, or am I missing something?</p>
<p>Edit: 11 hours and not a single comment? I was hoping for more.. lol</p> | 626,806 | 5 | 2 | null | 2008-11-27 09:38:36.577 UTC | 11 | 2011-04-10 06:55:23.237 UTC | 2008-11-27 20:55:04.997 UTC | Chris | 34,942 | Chris | 34,942 | null | 1 | 35 | asp.net|asp.net-mvc|iis-6 | 2,247 | <p>Chris, very handy post.</p>
<p>Many who suggest a performance disadvantage infer that the code processed in a web application is some how different/inferior to code processed in the standard workflow. The base code type maybe different, and sure you'll be needing the MSIL interpreter, but MS has shown in many cases you'll actually see a performance increase in a .NET runtime over a native one.</p>
<p>It's also wise to consider how IIS has to be a "jack of all trades" - allowing all sorts of configuration and overrides <strong>even on static files</strong>. Some of those are designed for performance increase (caching, compression) and - indeed - will be lost unless you reimplement them in your code, but many of them are for other purposes and may not ever be used. If you build for your needs (only) you can ignore those other pieces and should be realising some kind of performance advantage, even though there's a potential ASP.NET disadvantage.</p>
<p>In my (non-.NET) MVC testing I'm seeing considerable (10x or more) performance benefits over webforms. Even if there was a small hit on the static content - that wouldn't be a tough pill to swallow.</p>
<p>I'm not surprised the difference is almost negligible in your tests, but I'm happy to see it backed up.</p>
<p>NOTE: You can disable wildcard mapping from static directories (I keep all static files in /static/(pics|styles|...)) in IIS. Switch the folder to an application, remove the wildcard mapping, and switch it back from an application and - voilà - static files are handled by IIS without pestering your ASP.NET.</p> |
359,436 | C# equivalent to Java's continue <label>? | <p>Should be simple and quick: I want a C# equivalent to the following Java code:</p>
<pre><code>orig: for(String a : foo) {
for (String b : bar) {
if (b.equals("buzz")) {
continue orig;
}
}
// other code comes here...
}
</code></pre>
<hr>
<p><strong><em>Edit</em></strong>:
OK it seems there is no such equivalent (hey - Jon Skeet himself said there isn't, that settles it ;)). So the "solution" for me (in its Java equivalent) is:</p>
<pre><code>for(String a : foo) {
bool foundBuzz = false;
for (String b : bar) {
if (b.equals("buzz")) {
foundBuzz = true;
break;
}
}
if (foundBuzz) {
continue;
}
// other code comes here...
}
</code></pre> | 359,449 | 5 | 2 | null | 2008-12-11 14:01:54.73 UTC | 7 | 2011-02-15 16:43:17.22 UTC | 2008-12-11 14:45:48.2 UTC | Epaga | 6,583 | Epaga | 6,583 | null | 1 | 35 | c#|java | 18,071 | <p>I don't believe there's an equivalent, I'm afraid. You'll have to either use a boolean, or just "goto" the end of the inside of the outer loop. It's even messier than it sounds, as a label has to be applied to a statement - but we don't want to do anything here. However, I think this does what you want it to:</p>
<pre><code>using System;
public class Test
{
static void Main()
{
for (int i=0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
Console.WriteLine("i={0} j={1}", i, j);
if (j == i + 2)
{
goto end_of_loop;
}
}
Console.WriteLine("After inner loop");
end_of_loop: {}
}
}
}
</code></pre>
<p>I would <em>strongly</em> recommend a different way of expressing this, however. I can't think that there are many times where there isn't a more readable way of coding it.</p> |
447,821 | How do I unsubscribe all handlers from an event for a particular class in C#? | <p>Basic premise:</p>
<p>I have a Room which publishes an event when an Avatar "enters" to all Avatars within the Room. When an Avatar leaves the Room I want it to remove all subscriptions for that room.</p>
<p>How can I best unsubscribe the Avatar from all events in the room before I add the Avatar to a new Room and subscribe to the new Room's events?</p>
<p>The code goes something like this:</p>
<pre><code>class Room
{
public event EventHandler<EnterRoomEventArgs> AvatarEntersRoom;
public event EvnetHandler<LeaveRoomEventArgs> AvatarLeavesRoom;
public event EventHandler<AnotherOfManyEventArgs> AnotherOfManayAvatarEvents;
public void AddPlayer(Avatar theAvatar)
{
AvatarEntersRoom(this, new EnterRoomEventArgs());
AvatarEntersRoom += new EventHandler<EnterRoomEventArgs>(theAvatar.HandleAvatarEntersRoom);
AvatarLeavesRoom += new EventHandler<EnterRoomEventArgs>(theAvatar.HandleAvatarEntersRoom);
AnotherOfManayAvatarEvents += new EventHandler<EnterRoomEventArgs>(theAvatar.HandleAvatarEntersRoom);
}
}
class Avatar
{
public void HandleAvatarEntersRoom(object sender, EnterRoomEventArgs e)
{
Log.Write("avatar has entered the room");
}
public void HandleAvatarLeaveRoom(object sender, LeaveRoomEventArgs e)
{
Log.Write("avatar has left room");
}
public void HandleAnotherOfManayAvatarEvents(object sender, AnotherOfManyEventArgs e)
{
Log.Write("another avatar event has occurred");
}
}
</code></pre> | 447,960 | 5 | 2 | null | 2009-01-15 18:03:57.527 UTC | 10 | 2019-08-25 11:00:30.673 UTC | 2009-01-15 18:31:36.8 UTC | Nathan Smith | 4,998 | Nathan Smith | 4,998 | null | 1 | 39 | c#|.net|events | 44,811 | <p>Each delegate has a method named <code>GetInvocationList()</code> that returns all the actual delegates that have been registered. So, assuming the delegate Type (or event) is named say <code>MyDelegate</code>, and the handler instance variable is named <code>myDlgHandler</code>, you can write:</p>
<pre><code>Delegate[] clientList = myDlgHandler.GetInvocationList();
foreach (var d in clientList)
myDlgHandler -= (d as MyDelegate);
</code></pre>
<p>to cover the case where it might be null, </p>
<pre><code> if(myDlgHandler != null)
foreach (var d in myDlgHandler.GetInvocationList())
myDlgHandler -= (d as MyDelegate);
</code></pre> |
628,796 | What does glLoadIdentity() do in OpenGL? | <p>I'm new to OpenGL and I'm a little overwhelmed with all of the random functions that I have in my code. They work and I know when to use them, but I don't know why I need them or what they actually do.</p>
<p>I know that <code>glLoadIdentity()</code> replaces the current matrix with the identity matrix, but what exactly does that do? If every program requires it, why isn't the identity matrix by default unless otherwise specified? I don't like to have functions in my code unless I know what they do. I should note that I am using OpenGL exclusively for rich 2D clients so excuse my ignorance if this is something very obvious for 3D.</p>
<p>Also a little confused about <code>glMatrixMode(GL_PROJECTION)</code> VS <code>glMatrixMode(GL_MODELVIEW)</code>.</p> | 631,500 | 6 | 0 | null | 2009-03-10 03:04:35.877 UTC | 48 | 2019-12-13 10:33:14.063 UTC | 2019-07-17 10:36:59.29 UTC | Serge | 10,488,923 | Alexander | 180,470 | null | 1 | 144 | opengl|graphics | 92,725 | <p>The identity matrix, in terms of the projection and modelview matrices, essentially resets the matrix back to its default state.</p>
<p>As you hopefully know, <code>glTranslate</code> and <code>glRotate</code> are always relative to the matrix's current state. So for instance, if you call <code>glTranslate</code>, you are translating from the matrix's current 'position', not from the origin. But if you want to start over at the origin, that's when you call <code>glLoadIdentity()</code>, and then you can <code>glTranslate</code> from the matrix which is now located at the origin, or <code>glRotate</code> from the matrix which is now oriented in the default direction.</p>
<p>I think Boon's answer, that it is the equivalent of 1, is not exactly correct. The matrix actually looks like this:</p>
<pre><code>1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
</code></pre>
<p>That is the identity matrix. Boon is correct, mathematically, that any matrix multiplied with that matrix (or a matrix that looks like that; diagonal ones, all else 0s) will result in the original matrix, but I don't believe he explained why this is important.</p>
<p>The reason why this is important is because OpenGL multiplies all positions and rotations through each matrix; so when for instance you draw a polygon (<code>glBegin(GL_FACE)</code>, some points, <code>glEnd()</code>), it translates it to "world space" by multiplying it with the MODELVIEW, and then translates it from 3D to 2D by multiplying it with the PROJECT matrix, and that gives it the 2D points on screen, along with the depth (from the screen 'camera'), which it uses to draw pixels. But when one of these matrices are the identity matrix, the points are multiplied with the identity matrix and therefore are not changed, so the matrix has no effect; it does not translate the points, it does not rotate them, it leaves them as-is.</p>
<p>I hope this clarifies a bit more!</p> |
788,225 | Table row and column number in jQuery | <p>How do I get the row and column number of the clicked table cell using jQuery, i.e., </p>
<pre><code>$("td").onClick(function(event){
var row = ...
var col = ...
});
</code></pre> | 788,292 | 6 | 0 | null | 2009-04-25 04:25:13.787 UTC | 42 | 2014-05-08 15:13:18.1 UTC | null | null | null | null | 24,946 | null | 1 | 145 | jquery | 246,522 | <p>You can use the <a href="http://docs.jquery.com/Core/index" rel="noreferrer">Core/index</a> function in a given context, for example you can check the index of the TD in it's parent TR to get the column number, and you can check the TR index on the Table, to get the row number:</p>
<pre><code>$('td').click(function(){
var col = $(this).parent().children().index($(this));
var row = $(this).parent().parent().children().index($(this).parent());
alert('Row: ' + row + ', Column: ' + col);
});
</code></pre>
<p>Check a running example <a href="http://jsbin.com/eyeyu/edit" rel="noreferrer">here</a>.</p> |
32,435,796 | When to use `std::hypot(x,y)` over `std::sqrt(x*x + y*y)` | <p>The <a href="http://en.cppreference.com/w/cpp/numeric/math/hypot">documentation of <code>std::hypot</code></a> says that:</p>
<blockquote>
<p>Computes the square root of the sum of the squares of x and y, without undue overflow or underflow at intermediate stages of the computation.</p>
</blockquote>
<p>I struggle to conceive a test case where <code>std::hypot</code> should be used over the trivial <code>sqrt(x*x + y*y)</code>.</p>
<p>The following test shows that <code>std::hypot</code> is roughly 20x slower than the naive calculation.</p>
<pre><code>#include <iostream>
#include <chrono>
#include <random>
#include <algorithm>
int main(int, char**) {
std::mt19937_64 mt;
const auto samples = 10000000;
std::vector<double> values(2 * samples);
std::uniform_real_distribution<double> urd(-100.0, 100.0);
std::generate_n(values.begin(), 2 * samples, [&]() {return urd(mt); });
std::cout.precision(15);
{
double sum = 0;
auto s = std::chrono::steady_clock::now();
for (auto i = 0; i < 2 * samples; i += 2) {
sum += std::hypot(values[i], values[i + 1]);
}
auto e = std::chrono::steady_clock::now();
std::cout << std::fixed <<std::chrono::duration_cast<std::chrono::microseconds>(e - s).count() << "us --- s:" << sum << std::endl;
}
{
double sum = 0;
auto s = std::chrono::steady_clock::now();
for (auto i = 0; i < 2 * samples; i += 2) {
sum += std::sqrt(values[i]* values[i] + values[i + 1]* values[i + 1]);
}
auto e = std::chrono::steady_clock::now();
std::cout << std::fixed << std::chrono::duration_cast<std::chrono::microseconds>(e - s).count() << "us --- s:" << sum << std::endl;
}
}
</code></pre>
<p>So I'm asking for guidance, when must I use <code>std::hypot(x,y)</code> to obtain correct results over the much faster <code>std::sqrt(x*x + y*y)</code>.</p>
<p><strong>Clarification:</strong> I'm looking for answers that apply when <code>x</code> and <code>y</code> are floating point numbers. I.e. compare:</p>
<pre><code>double h = std::hypot(static_cast<double>(x),static_cast<double>(y));
</code></pre>
<p>to:</p>
<pre><code>double xx = static_cast<double>(x);
double yy = static_cast<double>(y);
double h = std::sqrt(xx*xx + yy*yy);
</code></pre> | 32,436,148 | 1 | 5 | null | 2015-09-07 09:55:42.947 UTC | 7 | 2015-09-07 14:20:40.06 UTC | 2015-09-07 12:47:05.41 UTC | null | 2,498,188 | null | 2,498,188 | null | 1 | 38 | c++|c++11|floating-accuracy | 9,840 | <p>The answer is in the documentation you quoted</p>
<blockquote>
<p>Computes the square root of the sum of the squares of x and y, <strong>without undue overflow or underflow at intermediate stages of the computation</strong>.</p>
</blockquote>
<p>If <code>x*x + y*y</code> overflows, then if you carry out the calculation manually, you'll get the wrong answer. If you use <code>std::hypot</code>, however, it guarantees that the intermediate calculations will not overflow.</p>
<p>You can see an example of this disparity <a href="http://coliru.stacked-crooked.com/a/0c36801163209d24" rel="noreferrer">here</a>.</p>
<p>If you are working with numbers which you know will not overflow the relevant representation for your platform, you can happily use the naive version.</p> |
32,301,336 | Swift: Recursively cycle through all subviews to find a specific class and append to an array | <p>Having a devil of a time trying to figure this out. I asked a similar question here: <a href="https://stackoverflow.com/questions/32151637/swift-get-all-subviews-of-a-specific-type-and-add-to-an-array">Swift: Get all subviews of a specific type and add to an array</a></p>
<p>While this works, I realized there are many subviews and sub-sub views, and so I need a function that starts at the main UIView, cycles through all the subviews (and their subviews until there aren't any left) and adds it to an array for a custom button class which I have named CheckCircle.</p>
<p>Essentially I'd like to end up with an array of CheckCircles which constitute all the CheckCircles added to that view programmatically.</p>
<p>Any ideas? Here's what I've been working on. It doesn't seem to be appending any Checkcircles to the array:</p>
<pre><code> func getSubviewsOfView(v:UIView) -> [CheckCircle] {
var circleArray = [CheckCircle]()
// Get the subviews of the view
var subviews = v.subviews
if subviews.count == 0 {
return circleArray
}
for subview : AnyObject in subviews{
if let viewToAppend = subview as? CheckCircle {
circleArray.append(viewToAppend as CheckCircle)
}
getSubviewsOfView(subview as! UIView)
}
return circleArray
}
</code></pre> | 32,301,491 | 6 | 6 | null | 2015-08-30 21:29:48.643 UTC | 5 | 2019-08-16 04:05:32.513 UTC | 2017-05-23 11:53:31.703 UTC | null | -1 | null | 204,355 | null | 1 | 32 | arrays|swift|recursion|uiview | 21,424 | <p>Your main problem is that when you call <code>getSubviewsOfView(subview as! UIView)</code> (recursively, within the function), you aren't doing anything with the result.</p>
<p>You also can delete the <code>count == 0</code> check, since in that case the <code>for…in</code> loop will just be skipped. You also have a bunch of unnecessary casts</p>
<p>Assuming your desire is to get a flat array of <code>CheckCircle</code> instances, I think this adaptation of your code should work:</p>
<pre><code>func getSubviewsOfView(v:UIView) -> [CheckCircle] {
var circleArray = [CheckCircle]()
for subview in v.subviews as! [UIView] {
circleArray += getSubviewsOfView(subview)
if subview is CheckCircle {
circleArray.append(subview as! CheckCircle)
}
}
return circleArray
}
</code></pre> |
32,556,664 | Getting byte array through input type = file | <p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var profileImage = fileInputInByteArray;
$.ajax({
url: 'abc.com/',
type: 'POST',
dataType: 'json',
data: {
// Other data
ProfileImage: profileimage
// Other data
},
success: {
}
})
// Code in WebAPI
[HttpPost]
public HttpResponseMessage UpdateProfile([FromUri]UpdateProfileModel response) {
//...
return response;
}
public class UpdateProfileModel {
// ...
public byte[] ProfileImage {get ;set; }
// ...
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="file" id="inputFile" /></code></pre>
</div>
</div>
</p>
<p>I am using ajax call to post byte[] value of a input type = file input to web api which receives in byte[] format. However, I am experiencing difficulty of getting byte array. I am expecting that we can get the byte array through File API.</p>
<p>Note: I need to store the byte array in a variable first before passing through ajax call</p> | 32,556,944 | 7 | 6 | null | 2015-09-14 02:54:25.837 UTC | 11 | 2021-11-29 14:59:10.727 UTC | 2015-09-14 03:06:09.91 UTC | null | 5,309,192 | null | 5,309,192 | null | 1 | 39 | javascript|html|fileapi | 191,225 | <h2><strong>[Edit]</strong></h2>
<p>As noted in comments above, while still on some UA implementations, <code>readAsBinaryString</code> method didn't made its way to the specs and should not be used in production.
Instead, use <code>readAsArrayBuffer</code> and loop through it's <code>buffer</code> to get back the binary string : </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>document.querySelector('input').addEventListener('change', function() {
var reader = new FileReader();
reader.onload = function() {
var arrayBuffer = this.result,
array = new Uint8Array(arrayBuffer),
binaryString = String.fromCharCode.apply(null, array);
console.log(binaryString);
}
reader.readAsArrayBuffer(this.files[0]);
}, false);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="file" />
<div id="result"></div></code></pre>
</div>
</div>
</p>
<p>For a more robust way to convert your arrayBuffer in binary string, you can refer to <a href="https://stackoverflow.com/a/16365505/3702797">this answer</a>.</p>
<hr>
<h2>[old answer] <sub>(modified)</sub></h2>
<p>Yes, the file API does provide a way to convert your File, in the <code><input type="file"/></code> to a binary string, thanks to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader" rel="noreferrer">FileReader</a> Object and its method <a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsBinaryString" rel="noreferrer"><code>readAsBinaryString</code></a>.<br>
[<strong>But don't use it in production !</strong>]</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.querySelector('input').addEventListener('change', function(){
var reader = new FileReader();
reader.onload = function(){
var binaryString = this.result;
document.querySelector('#result').innerHTML = binaryString;
}
reader.readAsBinaryString(this.files[0]);
}, false);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="file"/>
<div id="result"></div></code></pre>
</div>
</div>
</p>
<p>If you want an array buffer, then you can use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsArrayBuffer" rel="noreferrer"><code>readAsArrayBuffer()</code></a> method :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.querySelector('input').addEventListener('change', function(){
var reader = new FileReader();
reader.onload = function(){
var arrayBuffer = this.result;
console.log(arrayBuffer);
document.querySelector('#result').innerHTML = arrayBuffer + ' '+arrayBuffer.byteLength;
}
reader.readAsArrayBuffer(this.files[0]);
}, false);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="file"/>
<div id="result"></div></code></pre>
</div>
</div>
</p> |
17,927,525 | Accessing values of object properties in PowerShell | <p>I'm going through an array of objects and I can display the objects fine.</p>
<pre><code>$obj
</code></pre>
<p>displays each object in my foreach loop fine.
I'm trying to access the object fields and their values.
This code also works fine:</p>
<pre><code>$obj.psobject.properties
</code></pre>
<p>To just see the names of each object's fields, I do this:</p>
<pre><code>$obj.psobject.properties | % {$_.name}
</code></pre>
<p>which also works fine.</p>
<p>When I try to access the values of those field by doing this:</p>
<pre><code>$obj.psobject.properties | % {$obj.$_.name}
</code></pre>
<p>nothing is returned or displayed. </p>
<p>This is done for diagnostic purposes to see whether I can access the values of the fields.
The main dilemma is that I cannot access a specific field's value. I.e. </p>
<pre><code>$obj."some field"
</code></pre>
<p>does not return a value even though I have confirmed that "some field" has a value.</p>
<p>This has baffled me. Does anyone know what I'm doing wrong?</p> | 17,927,658 | 3 | 0 | null | 2013-07-29 15:04:45.41 UTC | 4 | 2021-09-12 09:27:47.147 UTC | 2013-07-29 15:16:56.113 UTC | null | 780,392 | null | 780,392 | null | 1 | 18 | object|powershell | 51,313 | <p>Once you iterate over the properties inside the foreach, they become available via <code>$_</code> (current object symbol). Just like you printed the names of the properties with <code>$_.Name</code>, using <code>$_.Value</code> will print their values:</p>
<pre><code>$obj.psobject.properties | % {$_.Value}
</code></pre> |
18,055,189 | Why is my URI not hierarchical? | <p>I have files in resource folder. For example if I need to get file from resource folder, I do like that:</p>
<pre><code>File myFile= new File(MyClass.class.getResource(/myFile.jpg).toURI());
System.out.println(MyClass.class.getResource(/myFile.jpg).getPath());
</code></pre>
<p>I've <strong>tested</strong> and everything <strong>works</strong>!</p>
<p>The path is</p>
<p>/D:/java/projects/.../classes/X/Y/Z/myFile.jpg</p>
<p><strong>But</strong>, If I create jar file, using , <strong>Maven</strong>:</p>
<pre><code>mvn package
</code></pre>
<p>...and then start my app:</p>
<pre><code>java -jar MyJar.jar
</code></pre>
<p>I have that following error:</p>
<pre><code>Exception in thread "Thread-4" java.lang.RuntimeException: ხელმოწერის განხორციელება შეუძლებელია
Caused by: java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.<init>(File.java:363)
</code></pre>
<p>...<strong>and path of file is</strong>:</p>
<pre><code>file:/D:/java/projects/.../target/MyJar.jar!/X/Y/Z/myFile.jpg
</code></pre>
<p>This exception happens when I try to get file from resource folder. At this line. Why? Why have that problem in JAR file? What do you think?</p>
<p>Is there another way, to get the resource folder path?</p> | 18,055,478 | 3 | 1 | null | 2013-08-05 09:51:10.71 UTC | 12 | 2018-08-24 07:27:41.187 UTC | 2017-11-20 14:00:04.453 UTC | null | 452,775 | null | 2,590,960 | null | 1 | 66 | java|maven|jar|java-7|executable-jar | 110,325 | <p>You should be using</p>
<pre><code>getResourceAsStream(...);
</code></pre>
<p>when the resource is bundled as a jar/war or any other single file package for that matter.</p>
<p>See the thing is, a jar is a single file (kind of like a zip file) holding lots of files together. From Os's pov, its a single file and if you want to access a <code>part of the file</code>(your image file) you must use it as a stream.</p>
<p><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResourceAsStream%28java.lang.String%29" rel="noreferrer">Documentation</a></p> |
46,854,330 | ModuleNotFoundError: No module named 'cv2' | <p>I have been working on this error for a long time now. I have Python 3.6 and Python 2.7. I have tried to install opencv 2 and 3 in Python 2.7 and Python 3.6 respectively. I know the python interpreter I am using and I can interchange between them when I want. </p>
<p>When I run Python interpreter and write <code>import cv2</code> it does import it. When I run the code from command prompt it says <em>ModuleNotFoundError: No module named 'cv2'</em>.
The module is installed. The cv2.pyd file is in <code>C:\Python27\Lib\site-packages</code> I have attached a screen shot which shows the modules in Python27</p>
<p><a href="https://i.stack.imgur.com/4srYG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4srYG.png" alt="enter image description here"></a> </p>
<p>I have used <code>pip install opencv-python</code>. I have downloaded the module from different sites and manually copy pasted it in the correct folder. Nothing works and I am seriously short of ideas now.</p>
<p><strong>EDIT:</strong> I am on windows 10 with python 3.6 installed through anaconda and python 2.7 installed directly. Both have their variables set in the path</p> | 49,328,226 | 3 | 6 | null | 2017-10-20 17:27:49.847 UTC | 0 | 2022-07-25 20:24:38.08 UTC | 2022-07-25 20:24:38.08 UTC | null | 6,885,902 | null | 2,609,743 | null | 1 | 9 | python|python-3.x|python-2.7|opencv | 67,571 | <p>Faced with the same issue on Windows 10 I downloaded the open cv binary from the <a href="https://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow noreferrer">Unofficial Windows Binaries for Python Extension Packages</a>.</p>
<p>Search the page for <em>opencv</em> and for and download the correct .whl for your system. Then pip install it. By example, on my system, after opening a <strong>cmd</strong> window I typed the following.</p>
<pre><code>pip install opencv_python-3.4.1-cp36-cp36m-win_amd64.whl
</code></pre>
<p>I then opened python and the following worked</p>
<pre><code>import cv2
print(cv2.__version__)
</code></pre>
<p>More info is available in this <a href="https://youtu.be/PyjBd7IDYZs?list=PLX-LrBk6h3wSGvuTnxB2Kj358XfctL4BM&t=202" rel="nofollow noreferrer">Mark Jay video</a>.</p>
<p>:D</p> |
33,205,146 | How to remove email icon from Android Studio emulation | <p>How do I get rid of the email icon on the bottom of the phone? It is on all of them and it shouldn't be there.<a href="https://i.stack.imgur.com/UoLIf.png"><img src="https://i.stack.imgur.com/UoLIf.png" alt="enter image description here"></a></p> | 33,286,804 | 5 | 2 | null | 2015-10-19 01:13:36.833 UTC | 6 | 2016-04-13 01:37:38.39 UTC | null | null | null | null | 3,577,756 | null | 1 | 32 | android|android-studio | 37,370 | <p>Go to activity_main.xml and delete this portion:</p>
<pre><code><android.support.design.widget.FloatingActionButton android:id="@+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
</code></pre>
<p>And then go to MainActivity.java and delete this portion</p>
<pre><code>FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
</code></pre>
<p>That's it. You should now see that the icon disappeared.</p> |
2,008,806 | How to detect if the user clicked the "back" button | <p>When the user goes history-back-1...how do I detect that? And then, alert "the user clicked back!"</p>
<p>Using binds (and jQuery preferably)</p> | 2,008,831 | 5 | 2 | null | 2010-01-05 20:21:14.16 UTC | 7 | 2022-09-23 14:11:35.89 UTC | 2019-08-25 17:25:02 UTC | null | 4,370,109 | null | 179,736 | null | 1 | 19 | javascript|jquery|back-button|jquery-events | 74,124 | <p>You generally can't (browser security restriction). You can tell if the user navigates away from the page (onbeforeunload, onunload fire) but you can't tell where they went unless you've set up your page to allow it.</p>
<p>HTML5 introduces the HTML5 History API; in conforming browsers, the <a href="http://msdn.microsoft.com/en-us/library/ie/hh771875%28v=vs.85%29.aspx" rel="noreferrer">onpopstate</a> event will fire if the user navigates back to an earlier "page" on your site.</p> |
1,735,870 | Simple statistics - Java packages for calculating mean, standard deviation, etc | <p>Could you please suggest any simple Java statistics packages?</p>
<p>I don't necessarily need any of the advanced stuff. I was quite surprised that there does not appear to be a function to calculate the Mean in the <code>java.lang.Math</code> package...</p>
<p>What are you guys using for this?</p>
<hr>
<p><strong>EDIT</strong></p>
<p>Regarding:</p>
<blockquote>
<p>How hard is it to write a simple class
that calculates means and standard
deviations?</p>
</blockquote>
<p>Well, not hard. I only asked this question after having hand-coded these. But it only added to my Java frustration not to have these simplest functions available at hand when I needed them. I don't remember the formula for calculating stdev by heart :)</p> | 1,735,876 | 5 | 1 | null | 2009-11-14 22:43:42.303 UTC | 16 | 2017-07-06 15:28:26.33 UTC | 2009-11-15 10:40:02.267 UTC | null | 81,520 | null | 81,520 | null | 1 | 70 | java|math|statistics|package | 78,564 | <p><a href="http://commons.apache.org/math/" rel="noreferrer">Apache Commons Math</a>, specifically <a href="http://commons.apache.org/proper/commons-math/javadocs/api-3.2/org/apache/commons/math3/stat/descriptive/DescriptiveStatistics.html" rel="noreferrer">DescriptiveStatistics</a> and <a href="http://commons.apache.org/proper/commons-math/javadocs/api-3.2/org/apache/commons/math3/stat/descriptive/SummaryStatistics.html" rel="noreferrer">SummaryStatistics</a>.</p> |
1,397,251 | Event detect when css property changed using Jquery | <p>Is there a way to detect if the "display" css property of an element is changed (to whether none or block or inline-block...)? if not, any plugin? Thanks</p> | 1,397,500 | 5 | 0 | null | 2009-09-09 02:17:48.57 UTC | 31 | 2018-07-02 19:13:52.643 UTC | null | null | null | null | 149,367 | null | 1 | 93 | javascript|jquery|html | 122,185 | <blockquote>
<h3>Note</h3>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events" rel="noreferrer">Mutation events</a> have been deprecated since this post was written, and may not be supported by all browsers. Instead, use a <a href="https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver" rel="noreferrer">mutation observer</a>.</p>
</blockquote>
<p>Yes you can. DOM L2 Events module defines <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mutationevents" rel="noreferrer">mutation events</a>; one of them - <strong>DOMAttrModified</strong> is the one you need. Granted, these are not widely implemented, but are supported in at least Gecko and Opera browsers.</p>
<p>Try something along these lines:</p>
<pre><code>document.documentElement.addEventListener('DOMAttrModified', function(e){
if (e.attrName === 'style') {
console.log('prevValue: ' + e.prevValue, 'newValue: ' + e.newValue);
}
}, false);
document.documentElement.style.display = 'block';
</code></pre>
<p>You can also try utilizing <a href="http://msdn.microsoft.com/en-us/library/ms536956%28VS.85%29.aspx" rel="noreferrer">IE's "propertychange" event</a> as a replacement to <code>DOMAttrModified</code>. It should allow to detect <code>style</code> changes reliably.</p> |
1,571,427 | Returning first x items from array | <p>I want to return first 5 items from array. How can I do this?</p> | 1,571,444 | 5 | 0 | null | 2009-10-15 10:08:08.877 UTC | 13 | 2018-06-15 13:24:34.417 UTC | 2009-10-15 10:14:15.433 UTC | null | 12,855 | null | 190,494 | null | 1 | 148 | php|arrays | 120,877 | <p><a href="http://php.net/array_slice" rel="noreferrer"><code>array_slice</code></a> returns a slice of an array</p>
<pre><code>$sliced_array = array_slice($array, 0, 5)
</code></pre>
<p>is the code you want in your case to return the first five elements</p> |
1,406,037 | Custom Animation for Pushing a UIViewController | <p>I want to show a custom animation when pushing a view controller: I would like to achieve something like an "expand" animation, that means the new view expands from a given rectangle, lets say [100,100 220,380] during the animation to full screen.</p>
<p>Any suggestions where to start, respectively any documents, tutorials, links? :)</p>
<hr>
<p>Alright. I could make the expand animation with the following code:</p>
<pre><code>if ([coming.view superview] == nil)
[self.view addSubview:coming.view];
coming.view.frame = CGRectMake(160,160,0,0);
[UIView beginAnimations:@"frame" context:nil];
[UIView setAnimationDuration:4];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[coming viewWillAppear:YES];
[going viewWillAppear:YES];
coming.view.frame = CGRectMake(0, 0, 320, 480);
[going viewDidDisappear:YES];
[coming viewDidAppear:YES];
[UIView commitAnimations];
</code></pre>
<p>My View is properly displayed, but unfortunately the navigation bar is not updated. Is there a way to do that manually?</p>
<hr>
<p>In the sample code, a function is called all 0.03 seconds that updates the transformation of the view.
Unfortunately, when pushing a <code>UIViewController</code>, I am not able to resize the frame of the view ... am I ?</p> | 1,795,480 | 6 | 0 | null | 2009-09-10 15:36:09.527 UTC | 62 | 2015-12-30 15:13:49.6 UTC | 2015-12-17 05:49:17.75 UTC | null | 437,146 | null | 164,165 | null | 1 | 55 | iphone|animation|uikit|uiviewcontroller|uinavigationcontroller | 71,038 | <p>What you could do is push the next view controller but don't animate it, like so:</p>
<pre><code>[self.navigationController pushViewController:nextController animated:NO];
</code></pre>
<p>...and then, in the view controller that is getting pushed in, you could do a custom animation of it's view using CoreAnimation. This might be best done in the <code>viewDidAppear:(BOOL)animated</code> method.</p>
<p>Check out the <a href="http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/CoreAnimation_guide/Articles/AnimatingLayers.html#//apple_ref/doc/uid/TP40006085-SW1" rel="nofollow noreferrer">Core Animation Guide</a> on how to actually do the animation. Look particularly at the implicit animation.</p>
<p><strong>EDIT:</strong> <a href="https://developer.apple.com/library/mac/documentation/cocoa/Conceptual/CoreAnimation_guide/CoreAnimationBasics/CoreAnimationBasics.html" rel="nofollow noreferrer">updated link</a></p> |
2,094,429 | Running Jetty 7 as Windows Service | <p>Did Jetty 7 drop support to run as a service using Java Service Wrapper?
What options do I have now?</p> | 6,594,142 | 7 | 0 | null | 2010-01-19 15:08:57.233 UTC | 11 | 2014-09-03 18:34:46.883 UTC | null | null | null | null | 54,623 | null | 1 | 24 | windows|service|jetty | 33,133 | <p>@glb, thanks for pointing out apache commons-daemon Procrun.<br />
Its working great for me on Windows 7 64 Bit, here's how I set it up.</p>
<p>For more info see</p>
<ul>
<li><a href="http://commons.apache.org/daemon/procrun.html" rel="noreferrer">procrun</a> page as per link from @glb</li>
<li>jetty help screen > java -jar start.jar --help</li>
</ul>
<hr />
<pre><code>REM 1. Open command prompt as Administrator
mkdir C:\java\apache-commons-daemon
REM 2. Download commons-daemon binaries for windows to directory above from
REM http://www.apache.org/dist/commons/daemon/binaries/windows/commons-daemon-1.0.15-bin-windows.zip
REM 3. unzip which will create C:\java\apache-commons-daemon\commons-daemon-1.0.5-bin-windows
mkdir C:\java\jetty
REM 4. Download jetty to directory above from
REM http://download.eclipse.org/jetty/7.4.2.v20110526/dist/jetty-distribution-7.4.2.v20110526.zip
REM 5. install / unzip which will create C:\java\jetty\jetty-distribution-7.4.2.v20110526
REM 6. Verify that jetty can be started
cd C:\java\jetty\jetty-distribution-7.4.2.v20110526
java -jar start.jar
REM Look for any obvious errors on the console
REM Open a browser at http://localhost:8080/
REM You should be presented with the Jetty Start Page,
REM and be able to execute the Hello World Servlet
REM OK, that's enough,
REM come back to the command prompt and ctrl-C to stop the jetty server
REM 7. Copy and rename commons-daemon binaries into the JETTY_HOME directory structure
REM Note that the GUI manager is copied to JETTY_HOME,
REM and the service exe is copied to JETTY_HOME\bin
REM Note that both binaries get the same target name,
REM but are placed in different directories
REM This is just makes it easier to launch the GUI manager
REM by not having to provide command line arguments
REM Note that I have selected the amd64\prunsrv.exe as the service exe,
REM I am running on Windows 7 64 bit Intel i7 Xeon
cd C:\java\jetty\jetty-distribution-7.4.2.v20110526
copy \java\apache-commons-daemon\commons-daemon-1.0.5-bin-windows\prunmgr.exe .\JettyService.exe
copy \java\apache-commons-daemon\commons-daemon-1.0.5-bin-windows\amd64\prunsrv.exe .\bin\JettyService.exe
REM 8. Time to install the service
bin\JettyService //IS//JettyService --DisplayName="Jetty Service" --Install=C:\java\jetty\jetty-distribution-7.4.2.v20110526\bin\JettyService.exe --LogPath=C:\java\jetty\jetty-distribution-7.4.2.v20110526\logs --LogLevel=Debug --StdOutput=auto --StdError=auto --StartMode=Java --StopMode=Java --Jvm=auto ++JvmOptions=-Djetty.home=C:\java\jetty\jetty-distribution-7.4.2.v20110526 ++JvmOptions=-DSTOP.PORT=8087 ++JvmOptions=-DSTOP.KEY=downB0y ++JvmOptions=-Djetty.logs=C:\java\jetty\jetty-distribution-7.4.2.v20110526\logs ++JvmOptions=-Dorg.eclipse.jetty.util.log.SOURCE=true ++JvmOptions=-XX:MaxPermSize=128M ++JvmOptions=-XX:+CMSClassUnloadingEnabled ++JvmOptions=-XX:+CMSPermGenSweepingEnabled --Classpath=C:\java\jetty\jetty-distribution-7.4.2.v20110526\start.jar --StartClass=org.eclipse.jetty.start.Main ++StartParams=OPTIONS=All ++StartParams=C:\java\jetty\jetty-distribution-7.4.2.v20110526\etc\jetty.xml ++StartParams=C:\java\jetty\jetty-distribution-7.4.2.v20110526\etc\jetty-deploy.xml ++StartParams=C:\java\jetty\jetty-distribution-7.4.2.v20110526\etc\jetty-webapps.xml ++StartParams=C:\java\jetty\jetty-distribution-7.4.2.v20110526\etc\jetty-contexts.xml ++StartParams=C:\java\jetty\jetty-distribution-7.4.2.v20110526\etc\jetty-testrealm.xml --StopClass=org.eclipse.jetty.start.Main ++StopParams=--stop
REM 9. Test that the service starts at the command prompt
bin\JettyService //TS
REM 10. To delete the service uncomment the line below
REM bin\JettyService //DS
REM 11. Now launch the GUI manager to check the parameter settings
JettyService.exe
REM You can use the GUI to start and stop the service, and to change the settings
REM If you want the GUI exe to have a different name to the service exe,
REM then close the GUI and uncomment and run the line below
REM ren JettyService.exe JettyServiceMgr.exe
REM To launch the renamed GUI uncomment and run the line below
REM JettyServiceMgr.exe //ES//JettyService
</code></pre>
<hr />
<p>done!</p> |
1,711,840 | How do I specify "close existing connections" in sql script | <p>I'm doing active development on my schema in SQL Server 2008 and frequently want to rerun my drop/create database script. When I run </p>
<pre><code>USE [master]
GO
IF EXISTS (SELECT name FROM sys.databases WHERE name = N'MyDatabase')
DROP DATABASE [MyDatabase]
GO
</code></pre>
<p>I often get this error</p>
<pre><code>Msg 3702, Level 16, State 4, Line 3
Cannot drop database "MyDatabase" because it is currently in use.
</code></pre>
<p>If you right click on the database in the object explorer pane and select the Delete task from the context menu, there is a checkbox which to "close existing connections"</p>
<p>Is there a way to specify this option in my script?</p> | 1,711,852 | 8 | 0 | null | 2009-11-10 22:56:12.72 UTC | 24 | 2021-12-27 05:01:26.723 UTC | null | null | null | null | 10,884 | null | 1 | 175 | sql|sql-server | 122,304 | <p>You can disconnect everyone and roll back their transactions with:</p>
<pre><code>alter database [MyDatbase] set single_user with rollback immediate
</code></pre>
<p>After that, you can safely drop the database :)</p> |
1,522,252 | How to resize/maximize Firefox window during launching Selenium Remote Control? | <p>I am using <a href="http://en.wikipedia.org/wiki/Selenium_%28software%29#Selenium_Remote_Control" rel="noreferrer">Selenium Remote Control</a> . During executing the tests the actual Firefox window is so small. I want it full screen so I can see what is happening. How can I maximize the browser screen?</p> | 1,524,348 | 9 | 2 | null | 2009-10-05 20:35:08 UTC | 7 | 2015-05-04 20:54:23.897 UTC | 2013-05-20 09:45:42.77 UTC | null | 617,450 | null | 130,015 | null | 1 | 24 | firefox|selenium|selenium-rc|automated-tests | 51,267 | <p>Try the windowMaximize command:</p>
<pre><code>selenium.windowMaximize();
</code></pre>
<p>You can also set a specific width and height using the following command:</p>
<pre><code>selenium.getEval("window.resizeTo(X, Y); window.moveTo(0,0);")
</code></pre>
<p>Where X is the width and Y is the height.</p> |
1,888,647 | UIScrollView - showing the scroll bar | <p>Possibly a simple one!</p>
<p>Does anyone know how to get the scroll bar of a UIScrollView to constantly show?</p>
<p>It displays when the user is scrolling, so they can see what position of the scroll view they are in. </p>
<p>BUT I would like it to constantly show because it is not immediately obvious to the user that scrolling is available</p>
<p>Any advice would be highly appreciated.</p> | 1,888,679 | 11 | 1 | null | 2009-12-11 15:02:04.367 UTC | 5 | 2022-04-18 16:22:43.36 UTC | 2011-12-22 17:33:49.227 UTC | null | 544,714 | null | 150,449 | null | 1 | 56 | iphone|objective-c|uiscrollview|scrollbar | 44,905 | <p>No, you can't make them always show, but you can make them temporarily flash.</p>
<pre><code>[myScrollView flashScrollIndicators];
</code></pre>
<p>They are scroll indicators, not scroll bars. You can't use them to scroll.</p> |
1,943,273 | Convert all first letter to upper case, rest lower for each word | <p>I have a string of text (about 5-6 words mostly) that I need to convert.</p>
<p>Currently the text looks like:</p>
<pre><code>THIS IS MY TEXT RIGHT NOW
</code></pre>
<p>I want to convert it to:</p>
<pre><code>This Is My Text Right Now
</code></pre>
<p>I can loop through my collection of strings, but I am not sure how to go about performing this text modification.</p> | 1,943,293 | 11 | 1 | null | 2009-12-21 23:21:26.557 UTC | 23 | 2021-07-12 02:04:45.47 UTC | 2021-07-12 01:41:52.05 UTC | null | 63,550 | null | 68,183 | null | 1 | 111 | c#|asp.net|regex | 137,990 | <pre><code>string s = "THIS IS MY TEXT RIGHT NOW";
s = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
</code></pre> |
1,381,725 | How to make --no-ri --no-rdoc the default for gem install? | <p>I don't use the RI or RDoc output from the gems I install in my machine or in the servers I handle (I use other means of documentation).</p>
<p>Every gem I install installs RI and RDoc documentation by default, because I forget to set <code>--no-ri --no-rdoc</code>.</p>
<p>Is there a way to make those two flags the default?</p> | 1,386,014 | 12 | 3 | null | 2009-09-04 21:48:59.303 UTC | 277 | 2021-11-05 08:55:59.26 UTC | 2014-12-09 02:45:13.44 UTC | null | 128,421 | null | 19,224 | null | 1 | 1,080 | ruby|rubygems | 271,278 | <p>You just add the following line to your local <code>~/.gemrc</code> file (it is in your <em>home</em> folder):</p>
<pre><code>gem: --no-document
</code></pre>
<p>by</p>
<pre><code>echo 'gem: --no-document' >> ~/.gemrc
</code></pre>
<p>or you can add this line to the global <code>gemrc</code> config file.</p>
<p>Here is how to find it (in Linux):</p>
<pre><code>strace gem source 2>&1 | grep gemrc
</code></pre>
<p>The <code>--no-document</code> option is documented in <a href="https://guides.rubygems.org/command-reference/#installupdate-options" rel="noreferrer">the RubyGems CLI Reference</a>.</p> |
1,374,990 | How to customize tableView separator in iPhone | <p>By default there is a single line separator in uitableview.</p>
<p>But I want to put my customized line as a separator.</p>
<p>Is it possible? How?</p> | 1,375,081 | 12 | 0 | null | 2009-09-03 18:02:10.127 UTC | 29 | 2019-10-04 10:15:31.18 UTC | 2014-09-21 11:26:05.077 UTC | null | 759,866 | null | 140,765 | null | 1 | 67 | iphone|uitableview | 101,466 | <p>If you want to do more than change the color of the separator using the <a href="http://developer.apple.com/iphone/library/documentation/uikit/reference/UITableView_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006943-CH3-SW3" rel="nofollow noreferrer">separatorColor</a> property of the <a href="http://developer.apple.com/iphone/library/documentation/uikit/reference/UITableView_Class/Reference/Reference.html" rel="nofollow noreferrer">UITableView</a> then you could set the <a href="http://developer.apple.com/iphone/library/documentation/uikit/reference/UITableView_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006943-CH3-SW31" rel="nofollow noreferrer">separatorStyle</a> property to <a href="http://developer.apple.com/iphone/library/documentation/uikit/reference/UITableViewCell_Class/Reference/Reference.html#//apple_ref/doc/c_ref/UITableViewCellSeparatorStyleNone" rel="nofollow noreferrer">UITableViewCellSeparatorStyleNone</a> and then either:</p>
<ul>
<li>create custom <a href="http://developer.apple.com/iphone/library/documentation/uikit/reference/UITableViewCell_Class/Reference/Reference.html" rel="nofollow noreferrer">UITableViewCell</a>s that include your custom seperator within them </li>
<li>create alternate [UITableViewCell][6]s that include your custom separator</li>
</ul>
<p>For example, if your table currently displays 5 rows you could update it to display 9 rows and the rows at index 1, 3, 5, 7 would be separator cells.</p> |
8,587,555 | Code to check when page has finished loading | <p>How can I check whether the page has finished loading? When it has, how can I execute a method already created in the C# code behind for that page?</p>
<p>I would like to orchestrate the following sequence of events</p>
<ol>
<li>Finish Loading the page</li>
<li>Download a gridview as an Excel file in the page</li>
<li>Call this method <code>download()</code></li>
<li>Close the browser</li>
</ol>
<p>How can I accomplish this?</p> | 8,587,602 | 3 | 2 | null | 2011-12-21 09:26:44.587 UTC | 1 | 2016-08-17 15:42:31.63 UTC | 2014-10-07 17:16:23.407 UTC | null | 299,327 | user1083756 | null | null | 1 | 7 | c#|asp.net|window|pageload | 61,248 | <p>Does this <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.page.loadcomplete.aspx" rel="noreferrer">link</a> answer your question?</p>
<p>Example usage (in your C# code)</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
Page.LoadComplete +=new EventHandler(Page_LoadComplete);
}
void Page_LoadComplete(object sender, EventArgs e)
{
// call your download function
}
</code></pre> |
8,820,748 | When to use the CQRS design pattern? | <p>My team and I have been discussing using the CQRS (Command Query Responsibility Segregation) design pattern and we are still trying to asses the pros and cons of using it. According to: <a href="http://martinfowler.com/bliki/CQRS.html" rel="noreferrer">http://martinfowler.com/bliki/CQRS.html</a> </p>
<blockquote>
<p>we haven't seen enough uses of CQRS in the field yet to be confident
that we understand its pros and cons</p>
</blockquote>
<p>So what do you guys think, when does a problem call for using CQRS? </p> | 8,823,383 | 11 | 2 | null | 2012-01-11 14:14:52.36 UTC | 24 | 2021-11-12 07:54:48.677 UTC | null | null | null | null | 587,959 | null | 1 | 71 | design-patterns|architecture|cqrs | 44,474 | <p>CQRS is not a pattern that encompasses the whole application.</p>
<p>It is a concept that builds on Domain Driven Design (DDD). And an important strategic concept of DDD is the so-called <strong>Bounded Context</strong>. </p>
<p>In a typical application there are multiple bounded contexts, any of which can be implemented the way it makes sense. For instance</p>
<ul>
<li>User Management -> CRUD</li>
<li>Invoicing -> CRUD</li>
<li>Insurance Policy Management (the Core Domain) -> CQRS</li>
<li>...</li>
</ul>
<p>This probably doesn't answer your question but it might give a little more insight into the topic. To be honest, I don't think it can be answered at all without considering a project's specifics, and even then there is rarely something like a definite <em>best practice</em>.</p> |
8,389,636 | creating over 20 unique legend colors using matplotlib | <p>I am plotting 20 different lines on a single plot using matplotlib. I use a for loop for plotting and label every line with its key and then use the legend function</p>
<pre><code>for key in dict.keys():
plot(x,dict[key], label = key)
graph.legend()
</code></pre>
<p>But using this way, the graph repeats a lot of colors in the legend. Is there any way to ensure a unique color is assigned to each line using matplotlib and over 20 lines?</p>
<p>thanks</p> | 8,391,452 | 4 | 2 | null | 2011-12-05 17:54:02.467 UTC | 49 | 2021-06-01 17:17:09.233 UTC | 2017-07-06 06:41:23.247 UTC | null | 4,794 | null | 1,066,479 | null | 1 | 78 | python|matplotlib|legend | 116,409 | <p>The answer to your question is related to two other SO questions.</p>
<p>The answer to <a href="https://stackoverflow.com/q/4971269/717357">How to pick a new color for each plotted line within a figure in matplotlib?</a> explains how to define the default list of colors that is cycled through to pick the next color to plot. This is done with the <code>Axes.set_color_cycle</code> <a href="https://matplotlib.sourceforge.net/api/axes_api.html?highlight=set_color_cycle#matplotlib.axes.Axes.set_color_cycle" rel="noreferrer">method</a>. </p>
<p>You want to get the correct list of colors though, and this is most easily done using a color map, as is explained in the answer to this question: <a href="https://stackoverflow.com/q/3016283/717357">Create a color generator from given colormap in matplotlib</a>. There a color map takes a value from 0 to 1 and returns a color. </p>
<p>So for your 20 lines, you want to cycle from 0 to 1 in steps of 1/20. Specifically you want to cycle form 0 to 19/20, because 1 maps back to 0. </p>
<p>This is done in this example:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
NUM_COLORS = 20
cm = plt.get_cmap('gist_rainbow')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_color_cycle([cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS)])
for i in range(NUM_COLORS):
ax.plot(np.arange(10)*(i+1))
fig.savefig('moreColors.png')
plt.show()
</code></pre>
<p>This is the resulting figure:</p>
<p><img src="https://i.stack.imgur.com/XJtJ6.png" alt="Yosemitebear Mountain Giant Double Rainbow 1-8-10"></p>
<p><strong>Alternative, better (debatable) solution</strong></p>
<p>There is an alternative way that uses a <code>ScalarMappable</code> object to convert a range of values to colors. The advantage of this method is that you can use a non-linear <code>Normalization</code> to convert from line index to actual color. The following code produces the same exact result:</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib.cm as mplcm
import matplotlib.colors as colors
import numpy as np
NUM_COLORS = 20
cm = plt.get_cmap('gist_rainbow')
cNorm = colors.Normalize(vmin=0, vmax=NUM_COLORS-1)
scalarMap = mplcm.ScalarMappable(norm=cNorm, cmap=cm)
fig = plt.figure()
ax = fig.add_subplot(111)
# old way:
#ax.set_color_cycle([cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS)])
# new way:
ax.set_color_cycle([scalarMap.to_rgba(i) for i in range(NUM_COLORS)])
for i in range(NUM_COLORS):
ax.plot(np.arange(10)*(i+1))
fig.savefig('moreColors.png')
plt.show()
</code></pre>
<hr>
<p><strong>Deprecation Note</strong><br>
In more recent versions of mplib (1.5+), the <code>set_color_cycle</code> function has been deprecated in favour of <code>ax.set_prop_cycle(color=[...])</code>.</p> |
17,836,273 | Export javascript data to CSV file without server interaction | <p>If we were on a nodeJS server, we could write a header, set a mime type, and send it:</p>
<pre><code>res.header("Content-Disposition", "attachment;filename="+name+".csv");
res.type("text/csv");
res.send(200, csvString);
</code></pre>
<p>and because of the headers, the browser will create a download for the named csv file.</p>
<p>When useful data is generated in a browser, one solution to getting it in a CSV file is to use ajax, upload it to the server, (perhaps optionally save it there) and get the server to send it back with these headers to become a csv download back at the browser.</p>
<p>However, I would like a 100% browser solution that does not involve ping-pong with the server.</p>
<p>So it occurred to me that one could open a new window and try to set the header with a META tag equivalent. </p>
<p>But this doesn't work for me in recent Chrome. </p>
<p>I do get a new window, and it contains the csvString, but does not act as a download.</p>
<p>I guess I expected to get either a download in a bottom tab or a blank new window with a download in a bottom tab. </p>
<p>I'm wondering if the meta tags are correct or if other tags are also needed.</p>
<p>Is there a way to make this work without punting it to the server?</p>
<p><a href="http://jsfiddle.net/7SDXv/8/" rel="noreferrer">JsFiddle for Creating a CSV in the Browser (not working - outputs window but no download)</a></p>
<pre><code>var A = [['n','sqrt(n)']]; // initialize array of rows with header row as 1st item
for(var j=1;j<10;++j){ A.push([j, Math.sqrt(j)]) }
var csvRows = [];
for(var i=0,l=A.length; i<l; ++i){
csvRows.push(A[i].join(',')); // unquoted CSV row
}
var csvString = csvRows.join("\n");
console.log(csvString);
var csvWin = window.open("","","");
csvWin.document.write('<meta name="content-type" content="text/csv">');
csvWin.document.write('<meta name="content-disposition" content="attachment; filename=data.csv"> ');
csvWin.document.write(csvString);
</code></pre> | 17,836,529 | 6 | 3 | null | 2013-07-24 14:02:07.383 UTC | 47 | 2018-10-15 11:59:19.023 UTC | 2013-07-24 15:10:36.463 UTC | null | 103,081 | null | 103,081 | null | 1 | 79 | javascript|export-to-csv | 140,937 | <p>There's always the HTML5 <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attr-download" rel="noreferrer"><code>download</code></a> attribute :</p>
<blockquote>
<p>This attribute, if present, indicates that the author intends the
hyperlink to be used for downloading a resource so that when the user
clicks on the link they will be prompted to save it as a local file.</p>
<p>If the attribute has a value, the value will be used as the pre-filled
file name in the Save prompt that opens when the user clicks on the
link. </p>
</blockquote>
<pre><code>var A = [['n','sqrt(n)']];
for(var j=1; j<10; ++j){
A.push([j, Math.sqrt(j)]);
}
var csvRows = [];
for(var i=0, l=A.length; i<l; ++i){
csvRows.push(A[i].join(','));
}
var csvString = csvRows.join("%0A");
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + encodeURIComponent(csvString);
a.target = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
a.click();
</code></pre>
<p><a href="http://jsfiddle.net/nkm2b/222/" rel="noreferrer"><strong>FIDDLE</strong></a></p>
<p>Tested in Chrome and Firefox, works fine in the newest versions <em>(as of July 2013)</em>.<br>
Works in Opera as well, but does not set the filename <em>(as of July 2013)</em>.<br>
Does not seem to work in IE9 (big suprise) <em>(as of July 2013)</em>.</p>
<p>An overview over what browsers support the download attribute can be found <a href="http://caniuse.com/download" rel="noreferrer"><strong>Here</strong></a><br>
For non-supporting browsers, one has to set the appropriate headers on the serverside.</p>
<hr>
<p>Apparently there is <a href="https://msdn.microsoft.com/library/hh779016.aspx" rel="noreferrer">a hack for IE10 and IE11</a>, which doesn't support the <code>download</code> attribute <em>(Edge does however)</em>. </p>
<pre><code>var A = [['n','sqrt(n)']];
for(var j=1; j<10; ++j){
A.push([j, Math.sqrt(j)]);
}
var csvRows = [];
for(var i=0, l=A.length; i<l; ++i){
csvRows.push(A[i].join(','));
}
var csvString = csvRows.join("%0A");
if (window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([csvString]);
window.navigator.msSaveOrOpenBlob(blob, 'myFile.csv');
} else {
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + encodeURIComponent(csvString);
a.target = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
a.click();
}
</code></pre> |
18,146,614 | How to send string from one activity to another? | <p>I have a string in activity2</p>
<pre><code>String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s", lat, lng);
</code></pre>
<p>I want to insert this string into text field in activity1. How can I do that?</p> | 18,146,745 | 10 | 4 | null | 2013-08-09 12:24:46.533 UTC | 14 | 2021-06-05 07:07:19.817 UTC | 2020-04-18 09:32:46.06 UTC | null | 5,446,749 | null | 2,389,512 | null | 1 | 36 | android|android-activity | 151,413 | <p>You can use intents, which are messages sent between activities. In a intent you can put all sort of data, String, int, etc.</p>
<p>In your case, in <code>activity2</code>, before going to <code>activity1</code>, you will store a String message this way :</p>
<pre><code>Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("message", message);
startActivity(intent);
</code></pre>
<p>In <code>activity1</code>, in <code>onCreate()</code>, you can get the <code>String</code> message by retrieving a <code>Bundle</code> (which contains all the messages sent by the calling activity) and call <code>getString()</code> on it :</p>
<pre><code>Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
</code></pre>
<p>Then you can set the text in the <code>TextView</code>:</p>
<pre><code>TextView txtView = (TextView) findViewById(R.id.your_resource_textview);
txtView.setText(message);
</code></pre>
<p>Hope this helps !</p> |
44,741,054 | Python class methods: when is self not needed | <p>I'm trying to rewrite some code using classes. At some point what I want is assign a member function a particular definition using a parameter value for each instance of an object.</p>
<p>Coming from other languages (JavaScript, C++, Haskell, Fortran, ...) I am struggling to <em>understand</em> a few things on Python. One thing is the following distinction of <em>self</em> in class methods.</p>
<p>For instance, the following code obviously won't work:</p>
<pre><code>class fdf:
def f(x):
return 666
class gdg(fdf):
def sq():
return 7*7
hg = gdg()
hf = fdf()
print(hf.f(),hg.f(),hg.sq())
</code></pre>
<p>which gives the error that "<em>sq() takes 0 positional arguments but 1 was given</em>". </p>
<p>The reason, as I understand it, is that at <em>execution time</em> the function is passed a reference to the calling object (the instance calling sq) as first argument before any other parameter/argument we may have defined/called sq with. So the solution is simple: change the code of sq to <code>def sq(self):</code>. Indeed, the <a href="https://docs.python.org/3/tutorial/classes.html#method-objects" rel="noreferrer">Python tutorial <a href="https://docs.python.org/3/tutorial/classes.html#method-objects" rel="noreferrer">1</a></a> <em>seems</em> to suggest that object methods should always be defined with <code>self</code> as first parameter. Doing so we get as expected <code>666 666 49</code>. So far so good.</p>
<p><strong>However</strong>, when I try to implement my class like this:</p>
<pre><code>class Activation:
def nonLinearBipolarStep(self,x,string=None):
if not string: return (-1 if x<0 else 1 )
else: return ('-' if x<0 else '1')
default='bipolar'
activationFunctions = {
'bipolar': nonLinearBipolarStep ,
}
def _getActivation(self,func=default):
return self.activationFunctions.get(func,self.activationFunctions.get(self.default))
def __init__(self,func=None):
if func == None: func=self.default
self.run = self._getActivation(func)
ag = Activation()
print(ag.run(4))
</code></pre>
<p>I get the error</p>
<pre><code>nonLinearBipolarStep() missing 1 required positional argument: 'x'
</code></pre>
<p>Yet, a workaround ( solution??) is defining the the step function without the parameter <code>self</code> (!) as</p>
<pre><code>def nonLinearBipolarStep(x,string=None):
</code></pre>
<p>Then I get the expected behavior (at least for this trivial test) of <code>1</code>. So, not only is <code>self</code> not needed here, <em>but it even is incorrect an use here!</em></p>
<p><strong>But according to the tutorial mentioned above, or to the answers in threads like <a href="https://stackoverflow.com/questions/1984104/how-to-avoid-explicit-self-in-python?rq=1">this <a href="https://stackoverflow.com/questions/1984104/how-to-avoid-explicit-self-in-python?rq=1">2</a></a> or <a href="https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self?rq=1">this <a href="https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self?rq=1">3</a></a>, it seems to me this code shouldn't work...or should have some unexpected consequences at some point(?).</strong> Indeed, if I remove all references to <code>self</code> in the definition of <code>_getActivation</code> I get the error message <code>_getActivation() takes from 0 to 1 positional arguments but 2 were given</code> which I can understand according to that rule.</p>
<p><strong>The thread <a href="https://stackoverflow.com/questions/39803950/why-is-self-not-used-in-this-method">"Why is self not used in this method" <a href="https://stackoverflow.com/questions/39803950/why-is-self-not-used-in-this-method">4</a></a> does not provide a clear answer to me: What syntax detail of the code above tells me that <code>self</code> is not needed?</strong> For instance, how is that code different from this tutorial example</p>
<pre><code>class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
</code></pre>
<p>? Instantiating this class works as expected, but it complains about missing parameter (I know it could be any label) if defined with none. </p>
<p>This makes me question whether my code is not hiding a time bomb somehow: is <code>self</code> passed as the value for <code>x</code>? It works as expected so I'd say no, but then I'm facing this conundrum. </p>
<p>I guess I'm missing some key ideas of the language. I admit I also struggle with the question the OP of reference <a href="https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self?rq=1">3</a> is asking^.</p>
<p>[^]: In JS one just uses <code>this</code> in the function body, and the function itself is defined either as member of the object's prototype or as an instance member which then gets assigned correctly using...<code>this</code>. </p>
<p><strong>EDIT:</strong>
The thread is long. For those browsing for some help, if you are new to Python, then you may want to check the selected solution and its comments. However, if you already know about bound/unbound methods in Python, you just want to check directly the use of descriptor as described in Blckknght's answer. I finally opted for this way in my code using <code>__get__</code> in the assignment to run. </p> | 44,741,389 | 4 | 13 | null | 2017-06-24 21:16:44.693 UTC | 10 | 2022-09-05 18:44:35.58 UTC | 2017-06-26 01:21:51.603 UTC | null | 5,025,261 | null | 5,025,261 | null | 1 | 12 | python | 27,459 | <h2>What is <code>self</code>?</h2>
<p>In Python, every <em>normal</em> method is forced to accept a parameter commonly named <code>self</code>. This is an instance of class - an object. This is how Python methods interact with a class's state.</p>
<p>You are allowed to rename this parameter whatever you please. but it will always have the same value:</p>
<pre><code>>>> class Class:
def method(foo): #
print(foo)
>>> cls = Class()
>>> cls.method()
<__main__.F object at 0x03E41D90>
>>>
</code></pre>
<h2>But then why does my example work?</h2>
<p>However, what you are probably confused about is how this code works differently:</p>
<pre><code>>>> class Class:
def method(foo):
print(foo)
methods = {'method': method}
def __init__(self):
self.run = self.methods['method']
>>> cls = Class()
>>> cls.run(3)
3
>>>
</code></pre>
<p>This is because of the distinction between <strong>bound</strong>, and <strong>unbound</strong> methods in Python.</p>
<p>When we do this in <code>__init__()</code>:</p>
<pre><code>self.run = self.methods['method']
</code></pre>
<p>We are referring to the <em><strong>unbound</strong></em> method <code>method</code>. That means that our reference to <code>method</code> is not bound to any <em>specific</em> instance of <code>Class</code>, and thus, Python will not force <code>method</code> to accept an object instance. because it does not have one to give.</p>
<p>The above code would be the same as doing this:</p>
<pre><code>>>> class Class:
def method(foo):
print(foo)
>>> Class.method(3)
3
>>>
</code></pre>
<p>In both examples, we are calling the method <code>method</code> of the class object <code>Class</code> , and <em>not</em> an <em>instance</em> of the <code>Class</code> object.</p>
<p>We can further see this distinction by examining the <code>repr</code> for a bound and unbound method:</p>
<pre><code>>>> class Class:
def method(foo):
print(foo)
>>> Class.method
<function Class.method at 0x03E43D68>
>>> cls = Class()
>>> cls.method
<bound method Class.method of <__main__.Class object at 0x03BD2FB0>>
>>>
</code></pre>
<p>As you can see, in the first example when we do <code>Class.method</code>, Python shows:
<code><function Class.method at 0x03E43D68></code>. I've lied to you a little bit. When we have an unbound method of a class, Python treats them as plain functions. So <code>method</code> is simply a function that is not bound to any instance of `Class.</p>
<p>However in the second example, when we create an instance of <code>Class</code>, and then access the <code>method</code> object of it, we see printed: <code><bound method Class.method of <__main__.Class object at 0x03BD2FB0>></code>.</p>
<p>The key part to notice is <code>bound method Class.method</code>. That means <code>method</code> is <em>**bound</em>** to <code>cls</code> - a specfic an instance of <code>Class</code>.</p>
<h2>General remarks</h2>
<p>As @jonshapre mentioned, writing code like in your example leads to confusion (as proof by this question), and bugs. It would be a better idea if you simply defined <code>nonLinearBipolarStep()</code> <em>outside</em> of <code>Activation</code>, and reference that from inside of <code>Activation.activation_functions</code>:</p>
<pre><code>def nonLinearBipolarStep(self,x,string=None):
if not string: return (-1 if x<0 else 1 )
else: return ('-' if x<0 else '1')
class Activation:
activation_functions = {
'bipolar': nonLinearBipolarStep,
}
...
</code></pre>
<blockquote>
<p>I guess a more specific question would be: what should I pay attention to on that code in order to become evident that <code>ag.run(x)</code> would be a call to an unbound function?</p>
</blockquote>
<p>If you'd still like to let <code>nonLinearBipolarStep</code> be unbound, then I recommend simply being carefully. If you think your method would make for the cleanest code then go for it, but make sure you know what you are doing and the behavior your code will have.</p>
<p>If you still wanted to make is clear to users of your class that <code>ag.run()</code> would be static, you <em>could</em> document it in a docstring somewhere, but that is something the user really shouldn't even have to be concerned with at all.</p> |
6,559,472 | SQL sum of 3 columns | <p>I know this question might seem a little basic stuff but I want to make sure I get the right syntax because this line of code will run often:</p>
<p>I want to <strong>sum columns A, B and C of table "alphabet" for all rows which have an id included in my IN clause</strong>.</p>
<p>This is how I would do it but I'd like a confirmation if possible:</p>
<pre><code>SELECT SUM(A + B + C) as "subtotal" FROM alphabet WHERE id IN ('1','5','378');
</code></pre> | 6,559,501 | 3 | 3 | null | 2011-07-02 20:35:41.063 UTC | null | 2014-06-30 10:30:58.667 UTC | null | null | null | null | 774,018 | null | 1 | 2 | sql | 53,433 | <p>If <code>id</code> is not a string, you shouldn't quote those values.</p>
<pre><code>SELECT SUM(A + B + C) as "subtotal" FROM alphabet WHERE id IN (1,5,378);
</code></pre>
<p>This should work, but may may have one non-obvious consequence. If any row has <code>A</code> not null and one of the others null, that row will drop out of the summation because a null plus anything else is null, and nulls are ignored by the <code>SUM</code> operator. Thus it may be safer to write:</p>
<pre><code>SELECT SUM(A) + SUM(B) + SUM(C) as "subtotal" FROM alphabet WHERE id IN (1,5,378);
</code></pre>
<p>This suffers from the same potential problem, but it is less likely to happen because an entire column would have to be null. There are various dialect specific ways to defend against that problem if you are still concerned. The most portable is the painfully verbose:</p>
<pre><code>SELECT SUM(
CASE
WHEN A IS NULL
THEN 0
ELSE A
END
+
CASE
WHEN B IS NULL
THEN 0
ELSE B
END
+
CASE
WHEN c IS NULL
THEN 0
ELSE C
END
) as "subtotal"
FROM alphabet
WHERE id IN (1,5,378);
</code></pre> |
6,360,207 | Android: Sending a byte[] array via Http POST | <p>I am able to do a POST of a parameters string. I use the following code:</p>
<pre><code>String parameters = "firstname=john&lastname=doe";
URL url = new URL("http://www.mywebsite.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(parameters);
out.flush();
out.close();
connection.disconnect();
</code></pre>
<p>However, I need to do a POST of binary data (which is in form of byte[]). </p>
<p>Not sure how to change the above code to implement it.<br>
Could anyone please help me with this?</p> | 6,362,260 | 3 | 0 | null | 2011-06-15 15:27:04.32 UTC | 6 | 2013-07-09 21:22:14.207 UTC | null | null | null | null | 289,918 | null | 1 | 11 | android|http-post | 42,857 | <p>These links might be helpful:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/4896949/android-httpclient-file-upload-data-corruption-and-timeout-issues/4896988#4896988">Android httpclient file upload data corruption and timeout issues</a></li>
<li><a href="http://getablogger.blogspot.com/2008/01/android-how-to-post-file-to-php-server.html" rel="nofollow noreferrer">http://getablogger.blogspot.com/2008/01/android-how-to-post-file-to-php-server.html</a></li>
<li><a href="http://forum.springsource.org/showthread.php?108546-How-do-I-post-a-byte-array" rel="nofollow noreferrer">http://forum.springsource.org/showthread.php?108546-How-do-I-post-a-byte-array</a></li>
</ul> |
6,590,185 | Order a column based on another column | <p>I want to order Column A based on the values of Column B.</p>
<p>In Google Sheets that is simply: <code>=SORT(A1:A100,B1:B100,TRUE)</code></p>
<p>How to do that in <strong>Excel</strong>?</p> | 6,590,480 | 4 | 0 | null | 2011-07-05 23:56:40.177 UTC | 3 | 2020-11-04 16:27:40.9 UTC | 2019-06-23 13:54:36.883 UTC | null | 7,882,470 | null | 556,641 | null | 1 | 9 | excel | 68,670 | <p>To do it manually, you can highlight all the columns you want sorted, then click "Custom Sort..." under "Sort & Filter" in the "Home" tab. This brings up a dialog where you can tell it what column to sort by, add multiple sort levels, etc.</p>
<p>If you know how to do something manually in Excel and want to find out how to do it programmatically using VBA, you can simply record a macro of yourself doing it manually and then look at the source code it generates. I did this to sort columns A and B based on column B and pulled the relevant code from what was generated:</p>
<pre><code>ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("B1:B6"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A1:B6")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
</code></pre>
<p>Note that the automatically generated code almost always has unnecessary bloat though. But, it's a nice way to figure out what functions you might need to use or research more. In this case, you could trim it down to something like this:</p>
<pre><code>Range("A1:B6").Sort Key1:=Range("B1:B6"), Order1:=xlAscending
</code></pre>
<p>If you only want to reorder the contents of column A without touching column B (even though you're using it as the sort key), you probably need to make a temporary copy, sort it, and copy back only column A. This is because Excel's Sort function requires the sort key to be in the range being sorted. So, it might look like this:</p>
<pre><code>Application.ScreenUpdating = False
Range("A1:B6").Copy Destination:=Range("G1:H6")
Range("G1:H6").Sort Key1:=Range("H1:H6"), Order1:=xlAscending
Range("G1:G6").Copy Destination:=Range("A1:A6")
Range("G1:H6").Clear
Application.ScreenUpdating = True
</code></pre> |
6,865,436 | Get all E-Mail addresses from contacts (iOS) | <p>I know it is possible to pull up a contact and see information based on one contact. But is there any way to get all the emails from the contacts you have entered email addresses for and then store that in a NSArray?
This is my first time working with contacts so I don't know much about it.</p> | 6,865,877 | 4 | 3 | null | 2011-07-28 20:45:13.287 UTC | 9 | 2016-09-20 12:03:06.91 UTC | 2012-11-27 06:59:44.9 UTC | null | 147,019 | null | 394,736 | null | 1 | 10 | objective-c|ios|contacts | 14,598 | <p>Yes, you can do this. It seems suspicious that you would want to do this (why do you need this information?), but it isn't difficult to do.</p>
<p>You can use <code>ABAddressBookCopyArrayOfAllPeople</code> to get an CFArrayRef with all of the people, and then you can query <code>kABPersonEmailProperty</code> of each using <code>ABRecordCopyValue</code>. The code would look something like this (untested):</p>
<pre><code>ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
NSMutableArray *allEmails = [[NSMutableArray alloc] initWithCapacity:CFArrayGetCount(people)];
for (CFIndex i = 0; i < CFArrayGetCount(people); i++) {
ABRecordRef person = CFArrayGetValueAtIndex(people, i);
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
for (CFIndex j=0; j < ABMultiValueGetCount(emails); j++) {
NSString* email = (NSString*)ABMultiValueCopyValueAtIndex(emails, j);
[allEmails addObject:email];
[email release];
}
CFRelease(emails);
}
CFRelease(addressBook);
CFRelease(people);
</code></pre>
<p>(Memory allocation may be a little off; it's been a while since I've developed Cocoa/Core Foundation code.)</p>
<p>But seriously, question why you are doing this. There's a good chance that there's a better solution by just using the Apple-provided APIs to present a contact picker at appropriate times.</p> |
18,894,103 | onClickListener does not work in fragment | <p>I've got some problems with the onClicklistener in the fragment. If I click on the button nothing happens at all. I get neither a message from the onClicklistener in Logcat nor does a Toast appear on the screen, but I can't find the error in the code. Any ideas?</p>
<p>I'd appreciate any help! Thanks a lot! And sorry for my bad english</p>
<pre><code>import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;
import android.util.Log;
public class InputFragment extends Fragment
{
EditText input_text;
String text;
Button translate_button;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View InputFragmentView = inflater.inflate(R.layout.input_fgmt, container, false);
input_text = (EditText) InputFragmentView.findViewById(R.id.input_field);
translate_button = (Button) InputFragmentView.findViewById(R.id.translate);
translate_button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View view)
{
Log.d("Test", "onClickListener ist gestartet");
Toast.makeText(getActivity().getApplicationContext(), "Test", Toast.LENGTH_LONG).show();
saveInString();
}
});
return inflater.inflate(R.layout.input_fgmt, container, false);
}
public void saveInString()
{
if(text.equals(null))
{
Toast.makeText(getActivity().getApplicationContext(), "Das Feld ist leer!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Speichern...", Toast.LENGTH_LONG).show();
text = input_text.getText().toString();
Toast.makeText(getActivity().getApplicationContext(), "Fertig", Toast.LENGTH_SHORT).show();
}
}
}
</code></pre> | 18,894,294 | 5 | 2 | null | 2013-09-19 12:02:30.237 UTC | 6 | 2019-05-10 13:55:04.34 UTC | null | null | null | null | 2,795,262 | null | 1 | 11 | android|android-fragments|onclicklistener | 42,642 | <p>I think problem is here in your code</p>
<pre><code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
.....
....
//problem is here below line
return inflater.inflate(R.layout.input_fgmt, container, false);
}
</code></pre>
<p>return your already inflated view </p>
<pre><code> public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View inputFragmentView = inflater.inflate(R.layout.input_fgmt, container, false);
.....
....
return inputFragmentView;
}
</code></pre> |
27,807,232 | Finding enum value with Java 8 Stream API | <p>Suppose there is a simple enum called Type defined like this:</p>
<pre><code>enum Type{
X("S1"),
Y("S2");
private String s;
private Type(String s) {
this.s = s;
}
}
</code></pre>
<p>Finding the correct enum for given <code>s</code> is trivially done with static method with for-loop (assume the method is defined inside enum), e.g.:</p>
<pre><code>private static Type find(String val) {
for (Type e : Type.values()) {
if (e.s.equals(val))
return e;
}
throw new IllegalStateException(String.format("Unsupported type %s.", val));
}
</code></pre>
<p>I think the functional equivalent of this expressed with Stream API would be something like this:</p>
<pre><code>private static Type find(String val) {
return Arrays.stream(Type.values())
.filter(e -> e.s.equals(val))
.reduce((t1, t2) -> t1)
.orElseThrow(() -> {throw new IllegalStateException(String.format("Unsupported type %s.", val));});
}
</code></pre>
<p>How could we write this better and simpler? This code feels coerced and not very clear. The <code>reduce()</code> especially seems clunky and abused as it doesn't accumulate anything, performs no calculation and always simply returns <code>t1</code> (provided the filter returns one value - if it doesn't that's clearly a disaster), not to mention <code>t2</code> is there superfluous and confusing. Yet I couldn't find anything in Stream API that simply somehow returns directly a <code>T</code> from a <code>Stream<T></code>.</p>
<p>Is there a better way?</p> | 27,807,324 | 9 | 3 | null | 2015-01-06 21:10:48.427 UTC | 19 | 2019-04-18 13:23:36.773 UTC | 2015-02-14 00:07:26.117 UTC | null | 1,441,122 | null | 271,149 | null | 1 | 44 | java|enums|functional-programming|java-8|java-stream | 91,263 | <p>I would use <code>findFirst</code> instead:</p>
<pre><code>return Arrays.stream(Type.values())
.filter(e -> e.s.equals(val))
.findFirst()
.orElseThrow(() -> new IllegalStateException(String.format("Unsupported type %s.", val)));
</code></pre>
<p><hr/>
Though a <code>Map</code> could be better in this case:</p>
<pre><code>enum Type{
X("S1"),
Y("S2");
private static class Holder {
static Map<String, Type> MAP = new HashMap<>();
}
private Type(String s) {
Holder.MAP.put(s, this);
}
public static Type find(String val) {
Type t = Holder.MAP.get(val);
if(t == null) {
throw new IllegalStateException(String.format("Unsupported type %s.", val));
}
return t;
}
}
</code></pre>
<p>I learnt this trick from this <a href="https://stackoverflow.com/questions/27703119/convert-from-string-to-a-java-enum-with-large-amount-of-values/27703839#27703839">answer</a>. Basically the class loader initializes the static classes before the enum class, which allows you to fill the <code>Map</code> in the enum constructor itself. Very handy !</p>
<p>Hope it helps ! :)</p> |
5,356,948 | Scraping Javascript driven web pages with PyQt4 - how to access pages that need authentication? | <p>I have to scrape a very, very simple page on our company's intranet in order to automate one of our internal processes (returning a function's output as successful or not).</p>
<p>I found the following example:</p>
<pre><code>import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
class Render(QWebPage):
def __init__(self, url):
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.mainFrame().load(QUrl(url))
self.app.exec_()
def _loadFinished(self, result):
self.frame = self.mainFrame()
self.app.quit()
url = 'http://sitescraper.net'
r = Render(url)
html = r.frame.toHtml()
</code></pre>
<p>From <a href="http://blog.sitescraper.net/2010/06/scraping-javascript-webpages-in-python.html" rel="nofollow noreferrer">http://blog.sitescraper.net/2010/06/scraping-javascript-webpages-in-python.html</a> and it's almost perfect. I just need to be able to provide authentication to view the page. </p>
<p>I've been looking through the documentation for PyQt4 and I'll admit a lot of it is over my head. If anyone could help, I'd appreciate it.</p>
<p><strong>Edit:</strong>
Unfortunately gruszczy's method didn't work for me. When I had done something similar through urllib2, I used the following code and it worked...</p>
<pre><code>username = 'user'
password = 'pass'
req = urllib2.Request(url)
base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
authheader = "Basic %s" % base64string
req.add_header("Authorization", authheader)
handle = urllib2.urlopen(req)
</code></pre> | 5,357,712 | 2 | 0 | null | 2011-03-18 19:32:38.227 UTC | 10 | 2016-12-23 19:46:05.827 UTC | 2016-12-23 19:46:05.827 UTC | null | 769,871 | null | 666,612 | null | 1 | 9 | python|ssl|web-scraping|pyqt|pyqt5 | 7,137 | <p>I figured it out. Here's what I ended up with in case it can help someone else.</p>
<pre><code>#!/usr/bin/python
# -*- coding: latin-1 -*-
import sys
import base64
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
from PyQt4 import QtNetwork
class Render(QWebPage):
def __init__(self, url):
self.app = QApplication(sys.argv)
username = 'username'
password = 'password'
base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
authheader = "Basic %s" % base64string
headerKey = QByteArray("Authorization")
headerValue = QByteArray(authheader)
url = QUrl(url)
req = QtNetwork.QNetworkRequest()
req.setRawHeader(headerKey, headerValue)
req.setUrl(url)
QWebPage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.mainFrame().load(req)
self.app.exec_()
def _loadFinished(self, result):
self.frame = self.mainFrame()
self.app.quit()
def main():
url = 'http://www.google.com'
r = Render(url)
html = r.frame.toHtml()
</code></pre> |
5,374,255 | How to write data to existing process's STDIN from external process? | <p>I'm seeking for ways to write data to the existing process's <code>STDIN</code> from external processes, and found similar question <a href="https://stackoverflow.com/questions/3792054/how-do-you-stream-data-into-the-stdin-of-a-program-from-different-local-remote-pr">How do you stream data into the STDIN of a program from different local/remote processes in Python?</a> in stackoverlow.</p>
<p>In that thread, @Michael says that we can get file descriptors of existing process in path like below, and permitted to write data into them on Linux.</p>
<pre><code>/proc/$PID/fd/
</code></pre>
<p>So, I've created a simple script listed below to test writing data to the script's <code>STDIN</code> (and <code>TTY</code>) from external process.</p>
<pre><code>#!/usr/bin/env python
import os, sys
def get_ttyname():
for f in sys.stdin, sys.stdout, sys.stderr:
if f.isatty():
return os.ttyname(f.fileno())
return None
if __name__ == "__main__":
print("Try commands below")
print("$ echo 'foobar' > {0}".format(get_ttyname()))
print("$ echo 'foobar' > /proc/{0}/fd/0".format(os.getpid()))
print("read :: [" + sys.stdin.readline() + "]")
</code></pre>
<p>This test script shows paths of <code>STDIN</code> and <code>TTY</code> and then, wait for one to write it's <code>STDIN</code>.</p>
<p>I launched this script and got messages below.</p>
<pre><code>Try commands below
$ echo 'foobar' > /dev/pts/6
$ echo 'foobar' > /proc/3308/fd/0
</code></pre>
<p>So, I executed the command <code>echo 'foobar' > /dev/pts/6</code> and <code>echo 'foobar' > /proc/3308/fd/0</code> from other terminal. After execution of both commands, message <code>foobar</code> is displayed twice on the terminal the test script is running on, but that's all. The line <code>print("read :: [" + sys.stdin.readline() + "]")</code> was not executed.</p>
<p>Are there any ways to write data from external processes to the existing process's <code>STDIN</code> (or other file descriptors), i.e. invoke execution of the line<code>print("read :: [" + sys.stdin.readline() + "]")</code> from other processes?</p> | 5,380,763 | 2 | 2 | null | 2011-03-21 05:46:57.557 UTC | 13 | 2017-06-16 13:25:15.3 UTC | 2017-05-23 12:10:26.89 UTC | null | -1 | null | 641,359 | null | 1 | 31 | linux|process|stdin|file-descriptor|tty | 33,809 | <p>Your code will not work.<br>
<code>/proc/pid/fd/0</code> is a link to the <code>/dev/pts/6</code> file.</p>
<blockquote>
<p>$ echo 'foobar' > /dev/pts/6<br>
$ echo 'foobar' > /proc/pid/fd/0</p>
</blockquote>
<p>Since both the commands write to the terminal. This input goes to terminal and not to the process.</p>
<p>It will work if stdin intially is a pipe.<br>
For example, <code>test.py</code> is :</p>
<pre><code>#!/usr/bin/python
import os, sys
if __name__ == "__main__":
print("Try commands below")
print("$ echo 'foobar' > /proc/{0}/fd/0".format(os.getpid()))
while True:
print("read :: [" + sys.stdin.readline() + "]")
pass
</code></pre>
<p>Run this as:</p>
<pre><code>$ (while [ 1 ]; do sleep 1; done) | python test.py
</code></pre>
<p>Now from another terminal write something to <code>/proc/pid/fd/0</code> and it will come to <code>test.py</code></p> |
16,407,502 | How to declare session variable in C#? | <p>I want to make a new session, where whatever is typed in a textbox is saved in that session. Then on another aspx page, I would like to display that session in a label. </p>
<p>I'm just unsure on how to start this, and where to put everything.</p>
<p>I know that I'm going to need:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if (Session["newSession"] != null)
{
//Something here
}
}
</code></pre>
<p>But I'm still unsure where to put everything.</p> | 16,407,628 | 1 | 2 | null | 2013-05-06 21:22:26.45 UTC | 2 | 2018-08-02 13:57:40.277 UTC | null | null | null | null | 2,353,452 | null | 1 | 10 | c#|session|declare | 66,131 | <p><code>newSession</code> is a poor name for a <code>Session</code> variable. However, you just have to use the indexer as you've already done. If you want to improve readability you could use a property instead which can even be static. Then you can access it on the first page from the second page without an instance of it.</p>
<p>page 1 (or wherever you like):</p>
<pre><code>public static string TestSessionValue
{
get
{
object value = HttpContext.Current.Session["TestSessionValue"];
return value == null ? "" : (string)value;
}
set
{
HttpContext.Current.Session["TestSessionValue"] = value;
}
}
</code></pre>
<p>Now you can get/set it from everywhere, for example on the first page in the <code>TextChanged</code>-handler:</p>
<pre><code>protected void TextBox1_TextChanged(Object sender, EventArgs e)
{
TestSessionValue = ((TextBox)sender).Text;
}
</code></pre>
<p>and read it on the second page:</p>
<pre><code>protected void Page_Load(Object sender, EventArgs e)
{
this.Label1.Text = Page1.TestSessionValue; // assuming first page is Page1
}
</code></pre> |
158,189 | How to trunc a date to seconds in Oracle | <p><a href="http://www.techonthenet.com/oracle/functions/trunc_date.php]" rel="noreferrer">This page</a> mentions how to trunc a timestamp to minutes/hours/etc. in Oracle.</p>
<p>How would you trunc a timestamp to seconds in the same manner?</p> | 158,252 | 7 | 0 | null | 2008-10-01 15:23:35.77 UTC | 2 | 2019-12-27 19:39:33.327 UTC | 2019-12-27 19:39:33.327 UTC | Zizzencs | 10,012,519 | Zizzencs | 686 | null | 1 | 15 | sql|oracle | 61,294 | <p>Since the precision of <code>DATE</code> is to the second (and no fractions of seconds), there is no need to <code>TRUNC</code> at all.</p>
<p>The data type <code>TIMESTAMP</code> allows for fractions of seconds. If you convert it to a <code>DATE</code> the fractional seconds will be removed - e.g.</p>
<pre><code>select cast(systimestamp as date)
from dual;
</code></pre> |
640,885 | Best Cocoa/Objective-C Wrapper Library for SQLite on iPhone | <p>I'm developing for the iPhone and am looking for a good Cocoa/Objective-C library for working with SQLite. I don't want to use the standard procedural SQLite C API. I see options at <a href="http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers" rel="noreferrer">sqlite.org</a> under the Objective-C section, but am not sure which is the best in terms of library API design, stability, and functionality. I'd like to use something that's actively being developed and hopefully will be around for a while. Anyone have suggestions based on experience using one?</p>
<p>Thanks</p> | 640,943 | 7 | 2 | null | 2009-03-12 23:30:22.077 UTC | 29 | 2017-01-16 00:15:20.093 UTC | 2009-06-03 22:20:47.36 UTC | null | 30,461 | methym | 29,148 | null | 1 | 53 | iphone|objective-c|cocoa-touch|sqlite | 38,271 | <p>I personally use <a href="https://github.com/ccgus/fmdb" rel="noreferrer">FMDB</a>, and the last update to it was yesterday.</p> |
862,051 | What is the difference between ImageMagick and GraphicsMagick? | <p>I've found myself evaluating both of these libs. Apart from what the GraphicsMagick comparison says, I see that ImageMagick still got updates and it seems that the two are almost identical.</p>
<p>I'm just looking to do basic image manipulation in C++ (i.e. image load, filters, display); are there any differences I should be aware of when choosing between these libraries?</p> | 908,186 | 7 | 0 | null | 2009-05-14 07:44:36.74 UTC | 23 | 2019-11-08 06:56:05.75 UTC | 2019-03-02 14:16:38.587 UTC | null | 2,660,408 | null | 60,373 | null | 1 | 74 | c++|image|imagemagick|comparison|graphicsmagick | 33,973 | <p>From what I have read GraphicsMagick is more stable and is faster.
I did a couple of unscientific tests and found gm to be twice as fast as im (doing a resize).</p> |
389,169 | Best practices for API versioning? | <p>Are there any known how-tos or best practices for web service REST API versioning?</p>
<p>I have noticed that <a href="http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/APIUsage.html" rel="noreferrer">AWS does versioning by the URL of the endpoint</a>. Is this the only way or are there other ways to accomplish the same goal? If there are multiple ways, what are the merits of each way? </p> | 398,564 | 7 | 0 | null | 2008-12-23 15:32:42.387 UTC | 1,271 | 2014-09-03 08:05:59.273 UTC | 2014-06-30 13:51:58.993 UTC | null | 7,432 | Swaroop C H | 4,869 | null | 1 | 877 | rest|versioning | 599,698 | <p>This is a good and a tricky question. The topic of <strong>URI design is</strong> at the same time <strong>the most prominent part of a REST API and</strong>, therefore, a potentially <strong>long-term commitment towards the users of that API</strong>.</p>
<p>Since evolution of an application and, to a lesser extent, its API is a fact of life and that it's even similar to the evolution of a seemingly complex product like a programming language, the <strong>URI design</strong> should have less <strong>natural constraints</strong> and it <strong>should be preserved over time</strong>. The longer the application's and API's lifespan, the greater the commitment to the users of the application and API.</p>
<p>On the other hand, another fact of life is that it is hard to foresee all the resources and their aspects that would be consumed through the API. Luckily, it is not necessary to design the entire API which will be used until <a href="http://en.wikipedia.org/wiki/Apocalypse" rel="noreferrer">Apocalypse</a>. It is sufficient to correctly define all the resource end-points and the addressing scheme of every resource and resource instance.</p>
<p>Over time you may need to add new resources and new attributes to each particular resource, but the method that API users follow to access a particular resources should not change once a resource addressing scheme becomes public and therefore final.</p>
<p>This method applies to HTTP verb semantics (e.g. PUT should always update/replace) and HTTP status codes that are supported in earlier API versions (they should continue to work so that API clients that have worked without human intervention should be able to continue to work like that).</p>
<p>Furthermore, since embedding of API version into the URI would disrupt the concept of <a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5" rel="noreferrer">hypermedia as the engine of application state</a> (stated in Roy T. Fieldings PhD dissertation) by having a resource address/URI that would change over time, I would conclude that <strong>API versions should not be kept in resource URIs for a long time</strong> meaning that <strong>resource URIs that API users can depend on should be permalinks</strong>.</p>
<p>Sure, <strong>it is possible to embed API version in base URI</strong> but <strong>only for reasonable and restricted uses like debugging a API client</strong> that works with the the new API version. Such versioned APIs should be time-limited and available to limited groups of API users (like during closed betas) only. Otherwise, you commit yourself where you shouldn't.</p>
<p>A couple of thoughts regarding maintenance of API versions that have expiration date on them. All programming platforms/languages commonly used to implement web services (Java, .NET, PHP, Perl, Rails, etc.) allow easy binding of web service end-point(s) to a base URI. This way it's easy to <strong>gather and keep</strong> a collection of files/classes/methods <strong>separate across different API versions</strong>. </p>
<p>From the API users POV, it's also easier to work with and bind to a particular API version when it's this obvious but only for limited time, i.e. during development.</p>
<p>From the API maintainer's POV, it's easier to maintain different API versions in parallel by using source control systems that predominantly work on files as the smallest unit of (source code) versioning.</p>
<p>However, with API versions clearly visible in URI there's a caveat: one might also object this approach since <strong>API history becomes visible/aparent in the URI design</strong> <strong>and therefore is prone to changes over time</strong> which goes against the guidelines of REST. I agree!</p>
<p>The way to go around this reasonable objection, is to implement the latest API version under versionless API base URI. In this case, API client developers can choose to either:</p>
<ul>
<li><p>develop against the latest one (committing themselves to maintain the application protecting it from eventual API changes that might break their <strong>badly designed API client</strong>).</p></li>
<li><p>bind to a specific version of the API (which becomes apparent) but only for a limited time</p></li>
</ul>
<p>For example, if API v3.0 is the latest API version, the following two should be aliases (i.e. behave identically to all API requests):</p>
<pre>
<b>http://shonzilla/api/customers/1234</b>
http://shonzilla/api<b>/v3.0</b>/customers/1234
http://shonzilla/api<b>/v3</b>/customers/1234
</pre>
<p>In addition, API clients that still try to point to the <em>old</em> API should be informed to use the latest previous API version, <strong>if the API version they're using is obsolete or not supported anymore</strong>. So accessing any of the obsolete URIs like these:</p>
<pre>
http://shonzilla/api<b>/v2.2</b>/customers/1234
http://shonzilla/api<b>/v2.0</b>/customers/1234
http://shonzilla/api<b>/v2</b>/customers/1234
http://shonzilla/api<b>/v1.1</b>/customers/1234
http://shonzilla/api<b>/v1</b>/customers/1234
</pre>
<p>should return any of the <strong>30x HTTP status codes that indicate redirection</strong> that are used in conjunction with <code>Location</code> HTTP header that redirects to the appropriate version of resource URI which remain to be this one:</p>
<pre>
<b>http://shonzilla/api/customers/1234</b>
</pre>
<p>There are at least two redirection HTTP status codes that are appropriate for API versioning scenarios:</p>
<ul>
<li><p><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2" rel="noreferrer">301 Moved permanently</a> indicating that the resource with a requested URI is moved permanently to another URI (which should be a resource instance permalink that does not contain API version info). This status code can be used to indicate an obsolete/unsupported API version, informing API client that a <strong>versioned resource URI been replaced by a resource permalink</strong>.</p></li>
<li><p><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3" rel="noreferrer">302 Found</a> indicating that the requested resource temporarily is located at another location, while requested URI may still supported. This status code may be useful when the version-less URIs are temporarily unavailable and that a request should be repeated using the redirection address (e.g. pointing to the URI with APi version embedded) and we want to tell clients to keep using it (i.e. the permalinks).</p></li>
<li><p>other scenarios can be found in <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3" rel="noreferrer">Redirection 3xx chapter of HTTP 1.1 specification</a></p></li>
</ul> |
941,104 | How to make a property protected AND internal in C#? | <p>Here is my shortened abstract class:</p>
<pre><code>abstract class Report {
protected internal abstract string[] Headers { get; protected set; }
}
</code></pre>
<p>Here is a derived class:</p>
<pre><code>class OnlineStatusReport : Report {
static string[] headers = new string[] {
"Time",
"Message"
}
protected internal override string[] Headers {
get { return headers; }
protected set { headers = value; }
}
internal OnlineStatusReport() {
Headers = headers;
}
}
</code></pre>
<p>The idea is, I want to be able to call <code>Report.Headers</code> from anywhere in the assembly, but only allow it to be set by derived classes. I tried making <code>Headers</code> just internal, but protected does not count as more restrictive than internal. Is there a way to make Headers internal and its set accessor protected AND internal?</p>
<p>I feel like I'm grossly misusing access modifiers, so any design help would be greatly appreciate.</p> | 941,592 | 8 | 9 | null | 2009-06-02 18:22:49.137 UTC | 3 | 2022-08-23 00:12:34.943 UTC | 2018-07-18 10:16:06.07 UTC | null | 5,893,316 | null | 88,739 | null | 1 | 31 | c#|access-modifiers | 10,622 | <p>What's wrong with making the getter public? If you declare the property as</p>
<pre><code>public string[] Headers { get; protected set; }
</code></pre>
<p>it meets all of the criteria you want: all members of the assembly can get the property, and only derived classes can set it. Sure, classes outside the assembly can get the property too. So?</p>
<p>If you genuinely need to expose the property within your assembly but not publicly, another way to do it is to create a different property:</p>
<pre><code>protected string[] Headers { get; set; }
internal string[] I_Headers { get { return Headers; } }
</code></pre>
<p>Sure, it's ugly decorating the name with that <code>I_</code> prefix. But it's kind of a weird design. Doing some kind of name mangling on the internal property is a way of reminding yourself (or other developers) that the property they're using is unorthodox. Also, if you later decide that mixing accessibility like this is not really the right solution to your problem, you'll know which properties to fix.</p> |
474,497 | How/why do functional languages (specifically Erlang) scale well? | <p>I have been watching the growing visibility of functional programming languages and features for a while. I looked into them and didn't see the reason for the appeal. </p>
<p>Then, recently I attended Kevin Smith's "Basics of Erlang" presentation at <a href="http://codemash.org/default.aspx" rel="noreferrer">Codemash</a>. </p>
<p>I enjoyed the presentation and learned that a lot of the attributes of functional programming make it much easier to avoid threading/concurrency issues. I understand the lack of state and mutability makes it impossible for multiple threads to alter the same data, but Kevin said (if I understood correctly) all communication takes place through messages and the mesages are processed synchronously (again avoiding concurrency issues). </p>
<p>But I have read that Erlang is used in highly scalable applications (the whole reason Ericsson created it in the first place). How can it be efficient handling thousands of requests per second if everything is handled as a synchronously processed message? Isn't that why we started moving towards asynchronous processing - so we can take advantage of running multiple threads of operation at the same time and achieve scalability? It seems like this architecture, while safer, is a step backwards in terms of scalability. What am I missing?</p>
<p>I understand the creators of Erlang intentionally avoided supporting threading to avoid concurrency problems, but I thought multi-threading was necessary to achieve scalability. </p>
<p><strong>How can functional programming languages be inherently thread-safe, yet still scale?</strong></p> | 474,530 | 8 | 2 | null | 2009-01-23 20:59:28.983 UTC | 55 | 2020-04-03 14:18:35.02 UTC | 2009-01-23 21:31:27.42 UTC | David Locke | 1,447 | Jim Anderson | 42,439 | null | 1 | 92 | concurrency|functional-programming|erlang|scalability | 14,468 | <p>A functional language doesn't (in general) rely on <a href="https://en.wikipedia.org/wiki/Immutable_object" rel="nofollow noreferrer">mutating</a> a variable. Because of this, we don't have to protect the "shared state" of a variable, because the value is fixed. This in turn avoids the majority of the hoop jumping that traditional languages have to go through to implement an algorithm across processors or machines.</p>
<p>Erlang takes it further than traditional functional languages by baking in a message passing system that allows everything to operate on an event based system where a piece of code only worries about receiving messages and sending messages, not worrying about a bigger picture. </p>
<p>What this means is that the programmer is (nominally) unconcerned that the message will be handled on another processor or machine: simply sending the message is good enough for it to continue. If it cares about a response, it will wait for it as <em>another message</em>. </p>
<p>The end result of this is that each snippet is independent of every other snippet. No shared code, no shared state and all interactions coming from a a message system that can be distributed among many pieces of hardware (or not).</p>
<p>Contrast this with a traditional system: we have to place mutexes and semaphores around "protected" variables and code execution. We have tight binding in a function call via the stack (waiting for the return to occur). All of this creates bottlenecks that are less of a problem in a shared nothing system like Erlang.</p>
<p>EDIT: I should also point out that Erlang is asynchronous. You send your message and maybe/someday another message arrives back. Or not. </p>
<p>Spencer's point about out of order execution is also important and well answered.</p> |
398,468 | Ordering SQL query by specific field values | <p>I've got a sql query (using Firebird as the RDBMS) in which I need to order the results by a field, EDITION. I need to order by the contents of the field, however. i.e. "NE" goes first, "OE" goes second, "OP" goes third, and blanks go last. Unfortunately, I don't have a clue how this could be accomplished. All I've ever done is ORDER BY [FIELD] ASC/DESC and nothing else. </p>
<p>Any suggestions? </p>
<p>Edit: I really should clarify: I was just hoping to learn more here. I have it now that I just have multiple select statements defining which to show first. The query is rather large and I was really hoping to learn possibly a more effecient way of doing this:
example: </p>
<pre><code>SELECT * FROM RETAIL WHERE MTITLE LIKE 'somethi%' AND EDITION='NE'
UNION
SELECT * FROM RETAIL WHERE MTITLE LIKE 'somethi%' AND EDITION='OE'
UNION
SELECT * FROM RETAIL WHERE MTITLE LIKE 'somethi%' AND EDITION='OP'
UNION (etc...)
</code></pre> | 398,490 | 9 | 3 | null | 2008-12-29 19:41:22.317 UTC | 1 | 2019-06-06 03:57:39.547 UTC | 2009-10-20 02:39:55.147 UTC | null | 135,152 | null | 48,957 | null | 1 | 22 | sql|firebird | 39,902 | <pre><code>Order By Case Edition
When 'NE' Then 1
When 'OE' Then 2
When 'OP' Then 3
Else 4 End
</code></pre> |
1,093,598 | pyserial - How to read the last line sent from a serial device | <p>I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms. </p>
<p>I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.</p>
<p>How do you do this in Pyserial?</p>
<p>Here's the code I tried which does't work. It reads the lines sequentially.</p>
<pre><code>import serial
import time
ser = serial.Serial('com4',9600,timeout=1)
while 1:
time.sleep(10)
print ser.readline() #How do I get the most recent line sent from the device?
</code></pre> | 1,093,662 | 10 | 0 | null | 2009-07-07 17:16:43.703 UTC | 26 | 2019-04-23 20:52:17.17 UTC | 2015-03-15 15:52:08.97 UTC | null | 1,079,075 | null | 13,009 | null | 1 | 22 | python|serial-port|arduino|pyserial | 103,052 | <p>Perhaps I'm misunderstanding your question, but as it's a serial line, you'll have to read everything sent from the Arduino sequentially - it'll be buffered up in the Arduino until you read it.</p>
<p>If you want to have a status display which shows the latest thing sent - use a thread which incorporates the code in your question (minus the sleep), and keep the last complete line read as the latest line from the Arduino.</p>
<p><strong>Update:</strong> <code>mtasic</code>'s example code is quite good, but if the Arduino has sent a partial line when <code>inWaiting()</code> is called, you'll get a truncated line. Instead, what you want to do is to put the last <em>complete</em> line into <code>last_received</code>, and keep the partial line in <code>buffer</code> so that it can be appended to the next time round the loop. Something like this:</p>
<pre><code>def receiving(ser):
global last_received
buffer_string = ''
while True:
buffer_string = buffer_string + ser.read(ser.inWaiting())
if '\n' in buffer_string:
lines = buffer_string.split('\n') # Guaranteed to have at least 2 entries
last_received = lines[-2]
#If the Arduino sends lots of empty lines, you'll lose the
#last filled line, so you could make the above statement conditional
#like so: if lines[-2]: last_received = lines[-2]
buffer_string = lines[-1]
</code></pre>
<p>Regarding use of <code>readline()</code>: Here's what the Pyserial documentation has to say (slightly edited for clarity and with a mention to readlines()):</p>
<blockquote>
<p>Be careful when using "readline". Do
specify a timeout when opening the
serial port, otherwise it could block
forever if no newline character is
received. Also note that "readlines()"
only works with a timeout. It
depends on having a timeout and
interprets that as EOF (end of file).</p>
</blockquote>
<p>which seems quite reasonable to me!</p> |
296,967 | Animation End Callback for CALayer? | <p>I'm wondering where the callbacks are (or if there are anything) for animations in a CALayer. Specifically, for implied animations like altering the frame, position, etc. In a UIView, you could do something like this:</p>
<pre><code>[UIView beginAnimations:@"SlideOut" context:nil];
[UIView setAnimationDuration:.3];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animateOut:finished:context:)];
CGRect frame = self.frame;
frame.origin.y = 480;
self.frame = frame;
[UIView commitAnimations];
</code></pre>
<p>Specifically, the <code>setAnimationDidStopSelector</code> is what I want for an animation in a CALayer. Is there anything like that?</p>
<p>TIA.</p> | 297,045 | 11 | 1 | null | 2008-11-17 21:17:15.89 UTC | 20 | 2021-04-15 20:43:02.603 UTC | 2008-11-17 23:05:51.787 UTC | Chris Hanson | 714 | Jeffrey Forbes | 28,019 | null | 1 | 75 | iphone|core-animation | 58,162 | <p>I answered my own question. You have to add an animation using <code>CABasicAnimation</code> like so:</p>
<pre><code>CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"frame"];
anim.fromValue = [NSValue valueWithCGRect:layer.frame];
anim.toValue = [NSValue valueWithCGRect:frame];
anim.delegate = self;
[layer addAnimation:anim forKey:@"frame"];
</code></pre>
<p>And implement the delegate method <code>animationDidStop:finished:</code> and you should be good to go. Thank goodness this functionality exists! :D</p> |
509,711 | Why does overflow:hidden not work in a <td>? | <p>I've got a table cell that I would always like to be a particular width. However, it doesn't work with large strings of unspaced text. Here's a test case:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>td {
border: solid green 1px;
width: 200px;
overflow: hidden;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tbody>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
</tbody>
</table></code></pre>
</div>
</div>
</p>
<p>How do I get the text to be cut off at the edge of the box, rather than having the box expand?</p> | 509,825 | 11 | 0 | null | 2009-02-04 01:06:05.827 UTC | 28 | 2019-12-22 20:06:33.763 UTC | 2015-10-14 23:01:52.237 UTC | null | 2,930,477 | Mike | 91,385 | null | 1 | 157 | html|css | 160,630 | <p>Here is the <a href="https://stackoverflow.com/questions/480722/how-can-i-set-a-td-width-to-visually-truncate-its-displayed-contents">same problem</a>.</p>
<p>You need to set <code>table-layout:fixed</code> <em>and</em> a suitable width on the table element, as well as <code>overflow:hidden</code> and <code>white-space: nowrap</code> on the table cells.</p>
<hr />
<h2>Examples</h2>
<h3>Fixed width columns</h3>
<p>The width of the table has to be the same (or smaller) than the fixed width cell(s).</p>
<p><strong>With one fixed width column:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
box-sizing: border-box;
}
table {
table-layout: fixed;
border-collapse: collapse;
width: 100%;
max-width: 100px;
}
td {
background: #F00;
padding: 20px;
overflow: hidden;
white-space: nowrap;
width: 100px;
border: solid 1px #000;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tbody>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
</tbody>
</table></code></pre>
</div>
</div>
</p>
<p><strong>With multiple fixed width columns:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
box-sizing: border-box;
}
table {
table-layout: fixed;
border-collapse: collapse;
width: 100%;
max-width: 200px;
}
td {
background: #F00;
padding: 20px;
overflow: hidden;
white-space: nowrap;
width: 100px;
border: solid 1px #000;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tbody>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
</tbody>
</table></code></pre>
</div>
</div>
</p>
<h3>Fixed and fluid width columns</h3>
<p>A width for the table <strong>must be set</strong>, but any extra width is simply taken by the fluid cell(s).</p>
<p><strong>With multiple columns, fixed width and fluid width:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
box-sizing: border-box;
}
table {
table-layout: fixed;
border-collapse: collapse;
width: 100%;
}
td {
background: #F00;
padding: 20px;
border: solid 1px #000;
}
tr td:first-child {
overflow: hidden;
white-space: nowrap;
width: 100px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
<tbody>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
<tr>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
<td>
This_is_a_terrible_example_of_thinking_outside_the_box.
</td>
</tr>
</tbody>
</table></code></pre>
</div>
</div>
</p> |
1,014,292 | Concatenate integers in C# | <p>Is there an <em>inexpensive</em> way to concatenate integers in csharp?</p>
<p>Example: 1039 & 7056 = 10397056</p> | 1,014,307 | 12 | 7 | null | 2009-06-18 18:11:11.107 UTC | 8 | 2017-10-16 09:22:51.633 UTC | null | null | null | null | 2,636,656 | null | 1 | 42 | c# | 76,277 | <p>If you can find a situation where this is expensive enough to cause any concern, I'll be very impressed:</p>
<pre><code>int a = 1039;
int b = 7056;
int newNumber = int.Parse(a.ToString() + b.ToString())
</code></pre>
<p>Or, if you want it to be a little more ".NET-ish":</p>
<pre><code>int newNumber = Convert.ToInt32(string.Format("{0}{1}", a, b));
</code></pre>
<p>int.Parse is <em>not</em> an expensive operation. Spend your time worrying about network I/O and O^N regexes.</p>
<p>Other notes: the overhead of instantiating StringBuilder means there's no point if you're only doing a few concatenations. And very importantly - if you <em>are</em> planning to turn this back into an integer, keep in mind it's limited to ~2,000,000,000. Concatenating numbers gets very large very quickly, and possibly well beyond the capacity of a 32-bit int. (signed of course).</p> |
930,877 | apc vs eaccelerator vs xcache | <p>Im doing research on which one of these to use and I can't really find one that stands out. <a href="http://eaccelerator.net/" rel="noreferrer">Eaccelerator</a> is faster than <a href="http://pecl.php.net/apc" rel="noreferrer">APC</a>, but APC is better maintained. <a href="http://xcache.lighttpd.net/" rel="noreferrer">Xcache</a> is faster but the others have easier syntax.</p>
<p>Anyone have recommendations on which to use and why?</p> | 930,942 | 12 | 3 | null | 2009-05-30 23:43:11.377 UTC | 35 | 2014-04-10 18:44:30.97 UTC | 2013-11-30 14:39:36.037 UTC | null | 759,866 | null | 7,894 | null | 1 | 105 | php|apc|opcode-cache|xcache|eaccelerator | 103,125 | <p>APC is going to be included in PHP 6, and I'd guess it has been chosen for good reason :)</p>
<p>It's fairly easy to install and certainly speeds things up.</p> |
93,260 | A free tool to check C/C++ source code against a set of coding standards? | <p>It looks quite easy to find such a tool for Java (<a href="http://checkstyle.sourceforge.net/" rel="noreferrer">Checkstyle</a>, <a href="http://jcsc.sourceforge.net/" rel="noreferrer">JCSC</a>), but I can't seem to find one for C/C++. I am not looking for a lint-like static code analyzer, I only would like to check against coding standards like variable naming, capitalization, spacing, identation, bracket placement, and so on.</p> | 93,291 | 12 | 1 | null | 2008-09-18 14:50:24.997 UTC | 66 | 2019-03-26 08:18:31.75 UTC | 2008-09-18 15:08:59.773 UTC | Serge | 1,007 | Drealmer | 12,291 | null | 1 | 156 | c++|c|coding-style | 127,803 | <p>The only tool I know is <a href="http://bitbucket.org/verateam/vera" rel="nofollow noreferrer">Vera</a>. Haven't used it, though, so can't comment how viable it is. <strike><a href="http://www.inspirel.com/vera/ce/demo.html" rel="nofollow noreferrer">Demo</a> looks promising.</strike></p> |
805,872 | How do I draw a shadow under a UIView? | <p>I'm trying to draw a shadow under the bottom edge of a <code>UIView</code> in Cocoa Touch. I understand that I should use <code>CGContextSetShadow()</code> to draw the shadow, but the Quartz 2D programming guide is a little vague:</p>
<ol>
<li>Save the graphics state.</li>
<li>Call the function <code>CGContextSetShadow</code>, passing the appropriate values.</li>
<li>Perform all the drawing to which you want to apply shadows.</li>
<li>Restore the graphics state</li>
</ol>
<p>I've tried the following in a <code>UIView</code> subclass:</p>
<pre><code>- (void)drawRect:(CGRect)rect {
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(currentContext);
CGContextSetShadow(currentContext, CGSizeMake(-15, 20), 5);
CGContextRestoreGState(currentContext);
[super drawRect: rect];
}
</code></pre>
<p>..but this doesn't work for me and I'm a bit stuck about (a) where to go next and (b) if there's anything I need to do to my <code>UIView</code> to make this work?</p> | 806,723 | 16 | 0 | null | 2009-04-30 08:07:04.053 UTC | 159 | 2019-11-11 15:58:21.637 UTC | 2013-06-01 12:17:41.5 UTC | null | 1,571,232 | null | 96,455 | null | 1 | 358 | iphone|objective-c|ios|cocoa-touch|core-graphics | 256,094 | <p>In your current code, you save the <code>GState</code> of the current context, configure it to draw a shadow .. and the restore it to what it was before you configured it to draw a shadow. Then, finally, you invoke the superclass's implementation of <code>drawRect</code>: .</p>
<p>Any drawing that should be affected by the shadow setting needs to happen <i>after</i> </p>
<pre><code>CGContextSetShadow(currentContext, CGSizeMake(-15, 20), 5);
</code></pre>
<p>but <i>before</i></p>
<pre><code>CGContextRestoreGState(currentContext);
</code></pre>
<p>So if you want the superclass's <code>drawRect:</code> to be 'wrapped' in a shadow, then how about if you rearrange your code like this?</p>
<pre><code>- (void)drawRect:(CGRect)rect {
CGContextRef currentContext = UIGraphicsGetCurrentContext();
CGContextSaveGState(currentContext);
CGContextSetShadow(currentContext, CGSizeMake(-15, 20), 5);
[super drawRect: rect];
CGContextRestoreGState(currentContext);
}
</code></pre> |
105,776 | How do I restore a dump file from mysqldump? | <p>I was given a MySQL database file that I need to restore as a database on my Windows Server 2008 machine.</p>
<p>I tried using MySQL Administrator, but I got the following error:</p>
<blockquote>
<p>The selected file was generated by
mysqldump and cannot be restored by
this application.</p>
</blockquote>
<p>How do I get this working?</p> | 105,798 | 18 | 1 | null | 2008-09-19 21:27:00.673 UTC | 190 | 2021-10-07 00:40:18.317 UTC | 2018-06-17 08:45:54.397 UTC | null | 19,163 | Zack | 83 | null | 1 | 632 | mysql|sql|database | 950,759 | <p>It should be as simple as running this: </p>
<pre><code>mysql -u <user> -p < db_backup.dump
</code></pre>
<p>If the dump is of a single database you may have to add a line at the top of the file:</p>
<pre><code>USE <database-name-here>;
</code></pre>
<p>If it was a dump of many databases, the use statements are already in there.</p>
<p>To run these commands, open up a command prompt (in Windows) and <code>cd</code> to the directory where the <code>mysql.exe</code> executable is (you may have to look around a bit for it, it'll depend on how you installed mysql, i.e. standalone or as part of a package like WAMP). Once you're in that directory, you should be able to just type the command as I have it above.</p> |
197,769 | When is JavaScript's eval() not evil? | <p>I'm writing some JavaScript code to parse user-entered functions (for spreadsheet-like functionality). Having parsed the formula I <em>could</em> convert it into JavaScript and run <code>eval()</code> on it to yield the result.</p>
<p>However, I've always shied away from using <code>eval()</code> if I can avoid it because it's evil (and, rightly or wrongly, I've always thought it is even more evil in JavaScript, because the code to be evaluated might be changed by the user).</p>
<p>So, when it is OK to use it?</p> | 198,031 | 27 | 15 | null | 2008-10-13 14:28:28.683 UTC | 100 | 2022-06-23 08:24:50.417 UTC | 2017-01-13 22:30:05.057 UTC | Richard Turner | 63,550 | Richard Turner | 12,559 | null | 1 | 291 | javascript|coding-style|eval | 106,175 | <p>I'd like to take a moment to address the premise of your question - that eval() is "<em>evil</em>". The word "<em>evil</em>", as used by programming language people, usually means "dangerous", or more precisely "able to cause lots of harm with a simple-looking command". So, when is it OK to use something dangerous? When you know what the danger is, and when you're taking the appropriate precautions.</p>
<p>To the point, let's look at the dangers in the use of eval(). There are probably many small hidden dangers just like everything else, but the two big risks - the reason why eval() is considered evil - are performance and code injection.</p>
<ul>
<li>Performance - eval() runs the interpreter/compiler. If your code is compiled, then this is a big hit, because you need to call a possibly-heavy compiler in the middle of run-time. However, JavaScript is still mostly an interpreted language, which means that calling eval() is not a big performance hit in the general case (but see my specific remarks below).</li>
<li>Code injection - eval() potentially runs a string of code under elevated privileges. For example, a program running as administrator/root would never want to eval() user input, because that input could potentially be "rm -rf /etc/important-file" or worse. Again, JavaScript in a browser doesn't have that problem, because the program is running in the user's own account anyway. Server-side JavaScript could have that problem.</li>
</ul>
<p>On to your specific case. From what I understand, you're generating the strings yourself, so assuming you're careful not to allow a string like "rm -rf something-important" to be generated, there's no code injection risk (but please remember, it's <em>very very hard</em> to ensure this in the general case). Also, if you're running in the browser then code injection is a pretty minor risk, I believe.</p>
<p>As for performance, you'll have to weight that against ease of coding. It is my opinion that if you're parsing the formula, you might as well compute the result during the parse rather than run another parser (the one inside eval()). But it may be easier to code using eval(), and the performance hit will probably be unnoticeable. It looks like eval() in this case is no more evil than any other function that could possibly save you some time.</p> |
6,435,868 | What happens when you have two jQuery $(document).ready calls in two JavaScript files used on the same HTML page? | <p>I have a question on jQuery <code>$(document).ready</code></p>
<p>Let's say we have a HTML page which includes 2 <strong>JavaScript</strong> files</p>
<pre><code><script language="javascript" src="script1.js" ></script>
<script language="javascript" src="script2.js" ></script>
</code></pre>
<p>Now let's say in both these script files, we have <code>$(document)</code> as follows</p>
<p>Inside <strong>script1.js</strong>:</p>
<pre><code>$(document).ready(function(){
globalVar = 1;
})
</code></pre>
<p>Inside <strong>script2.js</strong>:</p>
<pre><code>$(document).ready(function(){
globalVar = 2;
})
</code></pre>
<p>Now my <strong>Questions</strong> are:</p>
<blockquote>
<ol>
<li>Will both these ready event function get fired ? </li>
<li>If yes, what will the order in which they get fired, since the
document will be ready at the same
time for both of them?</li>
<li>Is this approach recommended OR we should ideally have only 1
$(document).ready ?</li>
<li>Is the order of execution same across all the browsers (IE,FF,etc)?</li>
</ol>
</blockquote>
<p>Thank you.</p> | 6,435,913 | 5 | 2 | null | 2011-06-22 06:37:29.943 UTC | 5 | 2016-08-12 05:18:43.04 UTC | 2011-08-03 16:31:28.6 UTC | null | 20,578 | null | 485,743 | null | 1 | 35 | javascript|jquery|html|dom|document-ready | 21,121 | <blockquote>
<ol>
<li>Will both these ready event function get fired ?</li>
</ol>
</blockquote>
<p>Yes, they will both get fired.</p>
<blockquote>
<ol start="2">
<li>what will the order in which they get fired, since the document will be ready at the same time for both of them?</li>
</ol>
</blockquote>
<p>In the way they appear (top to bottom), because the ready event will be fired once, and all the event listeners will get notified one after another.</p>
<blockquote>
<ol start="3">
<li>Is this approach recommended OR we should ideally have only 1 $(document).ready ?</li>
</ol>
</blockquote>
<p>It is OK to do it like that. If you can have them in the same block code it would be easier to manage, but that's all there is to it. <em>Update</em>: Apparently I forgot to mention, you will increase the size of your JavaScript code if you do this in multiple files.</p>
<blockquote>
<ol start="4">
<li>Is the order of execution same across all the browsers (IE,FF,etc)?</li>
</ol>
</blockquote>
<p>Yes, because jQuery takes the cross-browser normalization at hand.</p> |
6,556,559 | Youtube API - Extract video ID | <p>I am coding a functionality that allows users to enter a Youtube video URL. I would like to extract the video ID from these urls.</p>
<p>Does Youtube API support some kind of function where I pass the link and it gives the video ID in return. Or do I have to parse the string myself?</p>
<p>I am using PHP ... I would appreciate any pointers / code samples in this regard.</p>
<p>Thanks</p> | 6,556,662 | 9 | 5 | null | 2011-07-02 10:51:36.897 UTC | 30 | 2020-09-26 14:21:32.25 UTC | 2011-07-02 11:06:25.303 UTC | null | 367,456 | null | 295,654 | null | 1 | 33 | php|youtube | 51,115 | <p>Here is an example function that uses a regular expression to extract the youtube ID from a URL:</p>
<pre><code>/**
* get youtube video ID from URL
*
* @param string $url
* @return string Youtube video id or FALSE if none found.
*/
function youtube_id_from_url($url) {
$pattern =
'%^# Match any youtube URL
(?:https?://)? # Optional scheme. Either http or https
(?:www\.)? # Optional www subdomain
(?: # Group host alternatives
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com
(?: # Group path alternatives
/embed/ # Either /embed/
| /v/ # or /v/
| /watch\?v= # or /watch\?v=
) # End path alternatives.
) # End host alternatives.
([\w-]{10,12}) # Allow 10-12 for 11 char youtube id.
$%x'
;
$result = preg_match($pattern, $url, $matches);
if ($result) {
return $matches[1];
}
return false;
}
echo youtube_id_from_url('http://youtu.be/NLqAF9hrVbY'); # NLqAF9hrVbY
</code></pre>
<p>It's an adoption <a href="https://stackoverflow.com/questions/5830387/php-regex-find-all-youtube-video-ids-in-string/5831191#5831191">of the answer from a similar question</a>.</p>
<hr>
<p>It's not directly the API you're looking for but probably helpful. Youtube has an <a href="http://oembed.com/" rel="noreferrer">oembed</a> service:</p>
<pre><code>$url = 'http://youtu.be/NLqAF9hrVbY';
var_dump(json_decode(file_get_contents(sprintf('http://www.youtube.com/oembed?url=%s&format=json', urlencode($url)))));
</code></pre>
<p>Which provides some more meta-information about the URL:</p>
<pre><code>object(stdClass)#1 (13) {
["provider_url"]=>
string(23) "http://www.youtube.com/"
["title"]=>
string(63) "Hang Gliding: 3 Flights in 8 Days at Northside Point of the Mtn"
["html"]=>
string(411) "<object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/NLqAF9hrVbY?version=3"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/NLqAF9hrVbY?version=3" type="application/x-shockwave-flash" width="425" height="344" allowscriptaccess="always" allowfullscreen="true"></embed></object>"
["author_name"]=>
string(11) "widgewunner"
["height"]=>
int(344)
["thumbnail_width"]=>
int(480)
["width"]=>
int(425)
["version"]=>
string(3) "1.0"
["author_url"]=>
string(39) "http://www.youtube.com/user/widgewunner"
["provider_name"]=>
string(7) "YouTube"
["thumbnail_url"]=>
string(48) "http://i3.ytimg.com/vi/NLqAF9hrVbY/hqdefault.jpg"
["type"]=>
string(5) "video"
["thumbnail_height"]=>
int(360)
}
</code></pre>
<p>But the ID is not a direct part of the response. However it might contain the information you're looking for and it might be useful to validate the youtube URL.</p> |
6,987,334 | Separate Back Stack for each tab in Android using Fragments | <p>I'm trying to implement tabs for navigation in an Android app. Since TabActivity and ActivityGroup are deprecated I would like to implement it using Fragments instead.</p>
<p>I know how to set up one fragment for each tab and then switch fragments when a tab is clicked. But how can I have a separate back stack for each tab?</p>
<p>For an example Fragment A and B would be under Tab 1 and Fragment C and D under Tab 2. When the app is started Fragment A is shown and Tab 1 is selected. Then Fragment A might be replaced with Fragment B. When Tab 2 is selected Fragment C should be displayed. If Tab 1 is then selected Fragment B should once again be displayed. At this point it should be possible to use the back button to show Fragment A.</p>
<p>Also, it is important that the state for each tab is maintained when the device is rotated.</p>
<p>BR
Martin</p> | 7,089,151 | 12 | 0 | null | 2011-08-08 19:14:13.517 UTC | 146 | 2022-08-08 11:13:41.237 UTC | 2013-09-18 13:09:05.087 UTC | null | 422,060 | null | 884,651 | null | 1 | 160 | android|tabs|android-fragments | 78,370 | <p>The framework won't currently do this for you automatically. You will need to build and manage your own back stacks for each tab.</p>
<p>To be honest, this seems like a really questionable thing to do. I can't imagine it resulting in a decent UI -- if the back key is going to do different things depending on the tab I am, especially if the back key also has its normal behavior of closing the entire activity when at the top of the stack... sounds nasty.</p>
<p>If you are trying to build something like a web browser UI, to get a UX that is natural to the user is going to involve a lot of subtle tweaks of behavior depending on context, so you'll definitely need to do your own back stack management rather than rely on some default implementation in the framework. For an example try paying attention to how the back key interacts with the standard browser in the various ways you can go in and out of it. (Each "window" in the browser is essentially a tab.)</p> |
42,425,892 | When trying to invoke def, I get: parameter 'self' unfilled | <p>I'm trying to write a class to randomly pick a number of songs from a dictionary. The whole point of it is to be able to simply type <code>DJ.chooseListing()</code> for example to execute the random selection. Alas it gives me an error I can't really find anywhere else on the web, and I feel the answer is very simple.</p>
<pre><code>class DJ:
# put song variables here in this format: trackName = Track("string of song to be displayed", 'music/filename.ogg')
trackRickAstleyNever = Track("Never gonna give you up", 'music/rick.ogg')
trackShootingStars = Track("Shooting Stars", 'music/shoot.ogg')
dictSongs = {
# put songs here like this: 'name': varName,
'nevergonnagiveyouup': trackRickAstleyNever,
'shootingstars': trackShootingStars,
}
"""
arrayRandomized = [
# Put future songs here in this format: songs['name'],
]
"""
arrayChosen = []
trackChosen = ""
def chooseListing(self):
for i in xrange(4):
self.arrayChosen.append(random.choice(self.dictSongs))
def chooseTrack(self):
self.trackChosen = random.choice(self.arrayChosen)
DJ.chooseListing()
</code></pre> | 42,426,435 | 1 | 6 | null | 2017-02-23 20:47:56.64 UTC | 2 | 2017-02-24 18:28:19.793 UTC | 2017-02-24 18:28:19.793 UTC | null | 3,890,632 | null | 7,440,695 | null | 1 | 17 | python-2.7|class|oop|self | 45,979 | <p>A function defined in a class is a method. A method's first argument will be filled automatically when you call it <em>on an instance</em> of the class. You're defining a <code>chooseListing</code> method, but when you call it, you're not creating an instance. If there's no instance, there's nothing that can be passed as <code>self</code>, which leads to your exception. Try:</p>
<pre><code>dj = DJ()
dj.chooseListing()
</code></pre>
<p>You may still need to make some other fixes to your class though, since currently all of its attributes are class attributes (which are shared by all instances). If you create mutltiple <code>DJ</code> instances, they will all share the same <code>arrayChosen</code> list, which is probably not what you intend. You should move your assignments to an <code>__init__</code> method, where you can make them instance attributes (by assigning on <code>self</code>):</p>
<pre><code>def __init__(self):
self.dictSongs = { # this might still make sense as a class attribute if it is constant
'nevergonnagiveyouup': trackRickAstleyNever,
'shootingstars': trackShootingStars,
}
self.arrayChosen = [] # these however should certainly be instance attributes
self.trackChosen = ""
</code></pre>
<p>I left the <code>Track</code> instances out of the <code>__init__</code> method, but that might not be correct if they have internal state that shouldn't be shared between DJs.</p> |
12,065,568 | Load Image from My.Resources to a Picturebox (VB.NET) | <p>I'm having trouble loading an image from My.Resources. I have already tried a no. of codes like....:</p>
<ol>
<li><p><code>PictureBox1.Image = My.Resources.Online_lime_icon;</code> And</p></li>
<li><p><code>PictureBox1.Image = CType(My.Resources.ResourceManager.GetObject("Online_lime_icon"), Image)</code></p></li>
</ol>
<p>but it would still return:</p>
<pre><code>Picturebox1.Image = Nothing
</code></pre> | 12,065,760 | 1 | 0 | null | 2012-08-22 02:21:55.19 UTC | null | 2012-08-22 05:37:01.597 UTC | 2012-08-22 02:48:54.093 UTC | null | 142,822 | null | 1,615,710 | null | 1 | 2 | vb.net|picturebox|my.resources | 52,563 | <p>Try to convert it <code>ToBitMap()</code></p>
<pre><code> PictureBox1.Image = My.Resources.Online_lime_icon.ToBitmap()
</code></pre>
<p>EDIT:</p>
<p>@user1615710 : My.Resources.Online_lime_icon doesn't have .ToBitmap. It only has .ToString.</p>
<p>That means you've <code>String</code> resource and I think it represents <code>fileName</code> with or without absolute path.</p>
<p>Try to print/show the content of <code>My.Resources.Online_lime_icon</code></p>
<pre><code> Debug.Print(My.Resources.Online_lime_icon) 'or
MsgBox(My.Resources.Online_lime_icon)
</code></pre>
<p>If it is <em>real</em> path then load the image via,</p>
<pre><code> PictureBox1.Image = Image.FromFile(My.Resources.Online_lime_icon)
</code></pre> |
15,725,273 | Python: OSError: [Errno 2] No such file or directory: '' | <p>I have a 100 lines, 3 years old python scraper that now bug. Starting lines are:</p>
<pre><code>import urllib, re, os, sys, time # line 1: import modules
os.chdir(os.path.dirname(sys.argv[0])) # line 2: all works in script's folder > relative address
# (rest of my script here!)
</code></pre>
<p>When run, </p>
<pre><code>$cd /my/folder/
$python script.py
</code></pre>
<p>I receive the error:</p>
<pre><code>python script.py
Traceback (most recent call last):
File "script.py", line 2, in <module>
os.chdir(os.path.dirname(sys.argv[0]))
OSError: [Errno 2] No such file or directory: ''
</code></pre>
<p><strong>How should I read this error and what to do ?</strong></p> | 15,725,342 | 4 | 0 | null | 2013-03-31 01:04:57.353 UTC | 12 | 2021-08-26 06:41:50.697 UTC | 2013-03-31 01:14:29.203 UTC | null | 1,974,961 | null | 1,974,961 | null | 1 | 22 | python|python-2.7|python-module | 167,501 | <p>Have you noticed that you don't get the error if you run</p>
<pre><code>python ./script.py
</code></pre>
<p>instead of</p>
<pre><code>python script.py
</code></pre>
<p>This is because <code>sys.argv[0]</code> will read <code>./script.py</code> in the former case, which gives <code>os.path.dirname</code> something to work with. When you don't specify a path, <code>sys.argv[0]</code> reads simply <code>script.py</code>, and <code>os.path.dirname</code> cannot determine a path.</p> |
15,895,670 | Converting an XML file to string type | <p>How can we write an XML file into a string variable?
Here is the code I have,the variable content is supposed to return an XML string:</p>
<pre><code> public string GetValues2()
{
string content = "";
XmlTextWriter textWriter = new XmlTextWriter(content, null);
textWriter.WriteStartElement("Student");
textWriter.WriteStartElement("r", "RECORD", "urn:record");
textWriter.WriteStartElement("Name", "");
textWriter.WriteString("Student");
textWriter.WriteEndElement();
textWriter.Close();
return contents;
}
</code></pre> | 15,895,696 | 4 | 5 | null | 2013-04-09 07:17:23.55 UTC | 6 | 2021-06-10 15:36:49.413 UTC | null | null | null | null | 1,380,271 | null | 1 | 23 | c#|xml | 95,371 | <p>Something like this</p>
<pre><code>string xmlString = System.IO.File.ReadAllText(fileName);
</code></pre>
<p>Here is good answer to create <code>XmlDocument</code>
<a href="https://stackoverflow.com/questions/1542073/xdocument-or-xmldocument">XDocument or XMLDocument</a> </p> |
15,694,470 | Javascript wait() function | <p>I want to create a JavaScript <code>wait()</code> function.</p>
<p>What should I edit?</p>
<pre><code>function wait(waitsecs) {
setTimeout(donothing(), 'waitsecs');
}
function donothing() {
//
}
</code></pre> | 15,694,534 | 2 | 7 | null | 2013-03-29 00:24:44.547 UTC | 8 | 2019-10-16 09:03:47.96 UTC | 2019-10-16 09:03:47.96 UTC | null | 6,381,711 | null | 2,214,704 | null | 1 | 30 | javascript|function|wait | 172,359 | <p>Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).</p>
<p>To specifically address your problem, you should remove the brackets after <code>donothing</code> in your <code>setTimeout</code> call, and make <code>waitsecs</code> a number not a string:</p>
<pre><code>console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');
</code></pre>
<p>But that won't stop execution; "after" will be logged before your function runs.</p>
<p>To wait properly, you can use anonymous functions:</p>
<pre><code>console.log('before');
setTimeout(function(){
console.log('after');
},500);
</code></pre>
<p>All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use <code>setInterval</code> / <code>clearInterval</code> if it needs to loop.</p> |
16,016,023 | What is the use of a persistence layer in any application? | <p>I have to create an application in which I am asked to create an persistence layer in the application. The application is in .net. I have created a business layer and a presentation layer but I don't know how and why I should create a persistence layer.</p>
<p>I googled and came to know that persistence layer is used for storing and retrieving data usually from a database.</p>
<p>Can anybody explain in detail?</p> | 16,016,198 | 6 | 0 | null | 2013-04-15 13:10:15.577 UTC | 22 | 2021-09-14 11:27:45.79 UTC | 2018-02-17 13:47:21.373 UTC | null | 5,837,076 | user1556433 | null | null | 1 | 47 | c#|.net | 54,266 | <p>the reason for you to build a DAL ( Data Access Layer ) or any other kind of intermediate layer between database engine and Business / Application logic, is that by adding this layer in the between you isolate the rest / upper layers of your application from the specific database engine / technology you are using right now.</p>
<p>This has several advantages, like easier migration to other storage engines, better encapsulation of database logic in a single layer ( easier to replace or modify later depending on how well you have designed your cross-layer interfaces etc...)</p>
<p>see my answer here, it is an example about ASP.NET MVC and EF but the structuring of solution and projects is actually technology independent: <a href="https://stackoverflow.com/questions/7474267/mvc3-and-entity-framework/7474357#7474357">MVC3 and Entity Framework</a></p>
<p>Also read some articles to better understand this matter, for example: <a href="http://www.developerfusion.com/article/84492/net-and-data-persistence/" rel="noreferrer">http://www.developerfusion.com/article/84492/net-and-data-persistence/</a></p> |
33,455,041 | ASP.NET 5, EF 7 and SQLite - SQLite Error 1: 'no such table: Blog' | <p>I followed the <a href="http://ef.readthedocs.org/en/latest/getting-started/aspnet5.html">Getting Started on ASP.NET 5</a> guide about Entity Framework 7 and I replaced MicrosoftSqlServer with Sqlite, the only difference in the code is in Startup.cs:</p>
<pre><code>services.AddEntityFramework()
.AddSqlite()
.AddDbContext<BloggingContext>(options => options.UseSqlite("Filename=db.db"));
</code></pre>
<p>When I run the website and navigate to /Blogs, I get an error: </p>
<blockquote>
<p>Microsoft.Data.Sqlite.SqliteException was unhandled by user code<br>
ErrorCode=-2147467259 HResult=-2147467259 Message=SQLite Error 1:
'no such table: Blog' Source=Microsoft.Data.Sqlite<br>
SqliteErrorCode=1 StackTrace:
at Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(Int32 rc,
Sqlite3Handle db)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior
behavior)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteDbDataReader(CommandBehavior
behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.Data.Entity.Query.Internal.QueryingEnumerable.Enumerator.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.d__1`2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at Microsoft.Data.Entity.Query.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at EFGetStarted.AspNet5.Controllers.BlogsController.Index() in d:\arthur\documents\visual studio
2015\Projects\EFGetStarted.AspNet5\src\EFGetStarted.AspNet5\Controllers\BlogsController.cs:regel
18 InnerException:</p>
</blockquote>
<p>I understand this as if there is no table called 'Blog', but when I open the .db file in DB Browser for SQLite, there actually is a table called 'Blog':</p>
<p><a href="https://i.stack.imgur.com/37kPn.png"><img src="https://i.stack.imgur.com/37kPn.png" alt="Screenshot from DB Browser for SQLite showing a table called 'Blog'"></a></p>
<p>Does SQLite require other changes in the code, or is this an error in the SQLite connector for Entity Framework?</p> | 33,483,556 | 7 | 9 | null | 2015-10-31 18:22:14.333 UTC | 8 | 2022-05-01 14:26:05.583 UTC | null | null | null | null | 3,731,203 | null | 1 | 46 | asp.net|entity-framework|sqlite|asp.net-core|entity-framework-core | 41,348 | <p>It is very likely the database actually being opened by EF is not the file you are opening in DB Browser. SQLite use the process current working directory, which if launched in IIS or other servers, can be a different folder than your source code directory. (See issues <a href="https://github.com/aspnet/Microsoft.Data.Sqlite/issues/132" rel="noreferrer">https://github.com/aspnet/Microsoft.Data.Sqlite/issues/132</a> and <a href="https://github.com/aspnet/Microsoft.Data.Sqlite/issues/55" rel="noreferrer">https://github.com/aspnet/Microsoft.Data.Sqlite/issues/55</a>). </p>
<p>To ensure your db file is in the right place, use an absolute path. Example:</p>
<pre><code>public class Startup
{
private IApplicationEnvironment _appEnv;
public Startup(IApplicationEnvironment appEnv)
{
_appEnv = appEnv;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlite()
.AddDbContext<MyContext>(
options => { options.UseSqlite($"Data Source={_appEnv.ApplicationBasePath}/data.db"); });
}
}
</code></pre> |
13,370,317 | SQLAlchemy default DateTime | <p>This is my declarative model:</p>
<pre><code>import datetime
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Test(Base):
__tablename__ = 'test'
id = Column(Integer, primary_key=True)
created_date = DateTime(default=datetime.datetime.utcnow)
</code></pre>
<p>However, when I try to import this module, I get this error:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "orm/models2.py", line 37, in <module>
class Test(Base):
File "orm/models2.py", line 41, in Test
created_date = sqlalchemy.DateTime(default=datetime.datetime.utcnow)
TypeError: __init__() got an unexpected keyword argument 'default'
</code></pre>
<p>If I use an Integer type, I can set a default value. What's going on?</p> | 13,370,382 | 10 | 2 | null | 2012-11-13 22:55:02.98 UTC | 88 | 2022-05-26 19:49:44.73 UTC | 2019-04-19 01:59:32.84 UTC | null | 7,232,335 | null | 135,199 | null | 1 | 262 | python|date|sqlalchemy | 311,992 | <p><code>DateTime</code> doesn't have a default key as an input. The default key should be an input to the <code>Column</code> function. Try this:</p>
<pre><code>import datetime
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Test(Base):
__tablename__ = 'test'
id = Column(Integer, primary_key=True)
created_date = Column(DateTime, default=datetime.datetime.utcnow)
</code></pre> |
13,358,244 | tf.exe history * getting "Unable to determine the source control server." | <p>We have just upgraded from TFS 2010 to TFS 2012 and we are getting problems with </p>
<p>tf.exe history *</p>
<p>getting the following error message</p>
<p>"Unable to determine the source control server."</p> | 13,642,120 | 2 | 1 | null | 2012-11-13 09:29:40.407 UTC | 4 | 2017-09-15 10:10:39.463 UTC | null | null | null | null | 58,309 | null | 1 | 30 | msbuild | 22,800 | <p>Had the same problem and tried all sorts of values for /collection, finally hit the right one and all TFS2012 tf commands started working again.</p>
<p>In Team Explorer in VS right click the server name and select properties, you need the entire URL parameter including http, the port number, everything.
for me that was</p>
<pre><code>http://devserver:8080/tfs/defaultcollection
</code></pre>
<p>so the command is just</p>
<pre><code>tf workspaces /collection:"http://devserver:8080/tfs/defaultcollection"
</code></pre> |
13,243,638 | symfony2: how to access service from template | <p>If I created a service is there a way to access it from twig, without creating a twig.extension?</p> | 13,245,994 | 2 | 0 | null | 2012-11-06 02:52:22.997 UTC | 12 | 2021-06-04 08:44:21.917 UTC | null | null | null | null | 907,828 | null | 1 | 48 | php|symfony | 35,660 | <p>You can set the service a twig global variable in <code>config.yml</code>, e.g</p>
<pre><code>#app/config/config.yml
twig:
globals:
your_service: "@your_service"
</code></pre>
<p>And in your <code>template.html.twig</code> file you can invoke your service this way:</p>
<pre><code>{{ your_service.someMethod(twig_variable) }}
</code></pre>
<p>See <a href="http://symfony.com/doc/current/reference/configuration/twig.html" rel="noreferrer">here</a>.</p> |
13,751,412 | Why would font names need quotes? | <p>As far as I know, one needs to use double or single quotes for fonts if they contain spaces, like:</p>
<pre><code>font-family: "Times New Roman", Times;
font-family: 'Times New Roman', Times;
</code></pre>
<p>But on Google Fonts (<a href="http://www.google.com/webfont" rel="noreferrer">http://www.google.com/webfont</a>), I also see </p>
<pre><code>font-family: 'Margarine', cursive;
</code></pre>
<p>Some even use it like so:</p>
<pre><code>font-family: 'Margarine', 'Helvetica', arial;
</code></pre>
<p>I find this weird, as the following works as well:</p>
<pre><code>font-family: Arial, Helvetica, sans-serif;
font-family: Cambria, serif;
</code></pre>
<p>So what is the correct usage of quotes around font names in CSS?</p> | 13,752,149 | 5 | 1 | null | 2012-12-06 19:52:32.83 UTC | 12 | 2021-02-19 19:54:15.967 UTC | 2014-03-01 00:44:52.613 UTC | null | 1,136,709 | null | 594,423 | null | 1 | 69 | css|fonts|conventions | 33,221 | <p>You can always put a specific font family name in quotes, double or single, so <code>Arial</code>, <code>"Arial"</code>, and <code>'Arial'</code> are equivalent. Only the CSS-defined generic font family names like <code>sans-serif</code> must be written without quotes.</p>
<p>Contrary to popular belief, a font name consisting of space-separated names such as <code>Times New Roman</code> need not be quoted. However, the <a href="https://www.w3.org/TR/2018/REC-css-fonts-3-20180920/#propdef-font-family" rel="noreferrer">spec</a> <em>recommends</em> “to quote font family names that contain white space, digits, or punctuation characters other than hyphens”</p> |
39,767,718 | pandas assign with new column name as string | <p>I recently discovered pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.assign.html" rel="noreferrer">"assign" method</a> which I find very elegant.
My issue is that the name of the new column is assigned as keyword, so it cannot have spaces or dashes in it. </p>
<pre><code>df = DataFrame({'A': range(1, 11), 'B': np.random.randn(10)})
df.assign(ln_A = lambda x: np.log(x.A))
A B ln_A
0 1 0.426905 0.000000
1 2 -0.780949 0.693147
2 3 -0.418711 1.098612
3 4 -0.269708 1.386294
4 5 -0.274002 1.609438
5 6 -0.500792 1.791759
6 7 1.649697 1.945910
7 8 -1.495604 2.079442
8 9 0.549296 2.197225
9 10 -0.758542 2.302585
</code></pre>
<p>but what if I want to name the new column "ln(A)" for example?
E.g. </p>
<pre><code>df.assign(ln(A) = lambda x: np.log(x.A))
df.assign("ln(A)" = lambda x: np.log(x.A))
File "<ipython-input-7-de0da86dce68>", line 1
df.assign(ln(A) = lambda x: np.log(x.A))
SyntaxError: keyword can't be an expression
</code></pre>
<p>I know I could rename the column right after the .assign call, but I want to understand more about this method and its syntax.</p> | 41,759,638 | 2 | 3 | null | 2016-09-29 10:25:08.033 UTC | 12 | 2017-01-20 08:59:02.88 UTC | null | null | null | null | 6,108,661 | null | 1 | 57 | python|pandas|assign|columnname | 29,680 | <p>You can pass the keyword arguments to <code>assign</code> as a dictionary, like so:</p>
<pre><code>kwargs = {"ln(A)" : lambda x: np.log(x.A)}
df.assign(**kwargs)
A B ln(A)
0 1 0.500033 0.000000
1 2 -0.392229 0.693147
2 3 0.385512 1.098612
3 4 -0.029816 1.386294
4 5 -2.386748 1.609438
5 6 -1.828487 1.791759
6 7 0.096117 1.945910
7 8 -2.867469 2.079442
8 9 -0.731787 2.197225
9 10 -0.686110 2.302585
</code></pre> |
24,311,293 | Powershell System.Array to CSV file | <p>I am having some difficulty getting an Export-Csv to work. I am creating an array like this...</p>
<pre><code>[pscustomobject] @{
Servername = $_.Servername
Name = $_.Servername
Blk = ""
Blk2 = ""
Method = "RDP"
Port = "3389"
}
</code></pre>
<p>The issue I have is when I try to export that to a CSV I get garbage that looks like this... </p>
<blockquote>
<p>"9e210fe47d09416682b841769c78b8a3",,,,,</p>
</blockquote>
<p>I have read a ton of articles addressing this issue, but I just don't understand how to get the data right.</p> | 24,311,567 | 3 | 2 | null | 2014-06-19 16:09:02.123 UTC | 1 | 2017-06-08 14:11:40.607 UTC | 2017-06-08 14:11:40.607 UTC | null | 1,654,121 | null | 2,441,037 | null | 1 | 11 | powershell|csv | 74,949 | <p>For testing, I built a CSV file w/ the servernames, and read it in, and the following works in PS4:</p>
<pre><code>$serverList = import-csv "datafile.csv"
$AllObjects = @()
$serverList | ForEach-Object {
$AllObjects += [pscustomobject]@{
Servername = $_.Servername
Name = $_.Servername
Blk = ""
Blk2 = ""
Method = "RDP"
Port = "3389"
}
}
$AllObjects | Export-Csv -Path "outfile.csv" -NoTypeInformation
</code></pre> |
3,613,615 | How to validate X509 certificate? | <p>I have to write a tool which validates if a X509 certificate is valid or not (input = cert path / subject and password). How can I do that? I don't know much about certs...</p> | 3,613,802 | 2 | 2 | null | 2010-08-31 22:13:08.853 UTC | 3 | 2017-11-17 14:12:12.547 UTC | null | null | null | null | 42,024 | null | 1 | 10 | c#|.net|certificate|x509certificate | 49,463 | <p>Take a look at <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.verify.aspx" rel="nofollow noreferrer">X509Certificate2.Verify()</a> </p> |
3,818,512 | SQL update one column from another column in another table | <p>I read various post's prior to this. but none of them seemed to work for me. </p>
<p>As the title suggests, I am trying to update one column from a column in another table. I don't recall having problems with this before..</p>
<p><b>1.</b> Table: user_settings.contact_id, I want to update with contacts.id <code>where (user_settings.account_id == contacts_account_id)</code></p>
<p><b>2.</b> Previously Contacts were linked to user accounts via the account_id. However, now we want to link a contact to <code>user_settings</code> via <code>contacts.id</code></p>
<p>Below are a few examples of what I have tried, though none of them have worked. I would be interested in A.) Why they don't work and B.) What should I do instead.</p>
<p>Example A:</p>
<pre><code>UPDATE user_settings
SET user_settings.contact_id = contacts.id
FROM user_settings
INNER JOIN contacts ON user_settings.account_id = contacts.account_id
</code></pre>
<p>Example B:</p>
<pre><code>UPDATE (SELECT A.contact_id id1, B.id id2
FROM user_settings A, contacts B
WHERE user_settings.account_id = contacts.account_id)
SET id1 = id2
</code></pre>
<p>Example C:</p>
<pre><code>UPDATE user_settings
SET user_settings.contact_id = (SELECT id
FROM contacts
WHERE (user_settings.account_id = contacts.account_id)
WHERE EXISTS ( user_settings.account_id = contacts.account_id )
</code></pre>
<p>I feel like my brain just shutdown on me and would appreciate any bumps to reboot it. Thanks :)</p> | 3,818,533 | 2 | 1 | null | 2010-09-29 03:25:40.813 UTC | 7 | 2015-11-25 23:05:12.917 UTC | 2011-02-05 11:27:14.977 UTC | null | 241,776 | null | 403,682 | null | 1 | 20 | mysql|join|sql-update | 60,293 | <p>According to MySQL documentation, to do a cross table update, you can't use a join (like in other databases), but instead use a where clause:</p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/update.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/update.html</a></p>
<p>I think something like this should work:</p>
<pre><code>UPDATE User_Settings, Contacts
SET User_Settings.Contact_ID = Contacts.ID
WHERE User_Settings.Account_ID = Contacts.Account_ID
</code></pre> |
3,868,515 | Difference using @Id and @EmbeddedId for a compound key | <p>I've created an entity that uses @Id to point to an @Embeddable compound key. Everything I believe works fine as is. However, after switching @Id to @EmbeddedId everything continues to work fine as far as I can tell.</p>
<p><b>Before:</b></p>
<pre><code>@Entity
public final class MyEntity {
private CompoundKey id;
@Id
public CompoundKey getId() {
return id;
}
public void setId(CompoundKey id) {
this.id = id;
}
</code></pre>
<p><b>After:</b></p>
<pre><code>@Entity
public final class MyEntity {
private CompoundKey id;
@EmbeddedId
public CompoundKey getId() {
return id;
}
public void setId(CompoundKey id) {
this.id = id;
}
</code></pre>
<p>Is there a difference between using the @Id and @EmbeddedId annotations when referencing a compound key?</p> | 3,868,629 | 2 | 0 | null | 2010-10-05 23:26:19.27 UTC | 6 | 2021-08-26 11:33:38.39 UTC | null | null | null | null | 30,563 | null | 1 | 21 | java|hibernate | 68,880 | <p>I'm actually surprised the <strong>"before"</strong> version is working. According to the specification, the correct way to map your <code>Embeddable</code> compound key is the <strong>"after"</strong> version. Quoting the JPA 1.0 specification:</p>
<blockquote>
<h3>2.1.4 Primary Keys and Entity Identity</h3>
<p>Every entity must have a primary key.</p>
<p>The primary key must be defined on the
entity that is the root of the entity
hierarchy or on a mapped superclass of
the entity hierarchy. The primary key
must be defined exactly once in an
entity hierarchy.</p>
<p><strong>A simple (i.e., non-composite) primary
key must correspond to a single
persistent field or property of the
entity class. The <code>Id</code> annotation is
used to denote a simple primary key.</strong>
See section 9.1.8.</p>
<p>A composite primary key must
correspond to either a single
persistent field or property or to a
set of such fields or properties as
described below. A primary key class
must be defined to represent a
composite primary key. Composite
primary keys typically arise when
mapping from legacy databases when the
database key is comprised of several
columns. <strong>The <code>EmbeddedId</code> and and
<code>IdClass</code> annotations are used to
denote composite primary keys. See
sections 9.1.14 and 9.1.15.</strong></p>
<p>The primary key (or field or property
of a composite primary key) should be
one of the following types: any Java
primitive type; any primitive wrapper
type; <code>java.lang.String</code>;
<code>java.util.Date</code>; <code>java.sql.Date</code>. In
general, however, approximate numeric
types (e.g., floating point types)
should never be used in primary keys.
Entities whose primary keys use types
other than these will not be portable.
If generated primary keys are
used, only integral types will be
portable. If <code>java.util.Date</code> is used as
a primary key field or property, the
temporal type should be specified as
DATE.</p>
<p>...</p>
</blockquote>
<p>And later:</p>
<blockquote>
<h3>9.1.14 EmbeddedId Annotation</h3>
<p>The <code>EmbeddedId</code> annotation is applied
to a persistent field or property of
an entity class or mapped superclass
to denote a composite primary key that
is an embeddable class. The embeddable
class must be annotated as
<code>Embeddable</code>.</p>
<p>There must be only one <code>EmbeddedId</code>
annotation and no Id annotation when
the <code>EmbeddedId</code> annotation is used.</p>
</blockquote> |
3,569,075 | overriding or setting web service endpoint at runtime for code generated with wsimport | <p>Using code that was generated with <code>wsimport</code>, can the service endpoint be overridden without having to regenerate the code?</p>
<p>I have written a simple java webservice, following are the steps:</p>
<ol>
<li>I compile the java class and generate a war file</li>
<li>Deploy the war file to my app server (tomcat)</li>
<li>Access the WSDL via the URL e.g. localhost:8080/service/helloservice?wsdl</li>
<li>use the URL with wsimport.bat to generate client classes for example: <code>wsimport http://localhost:8080/service/helloservice?Wsdl</code></li>
<li>I use those classes in my client app to call the service</li>
</ol>
<p>The problem is that is the service is deployed on an app server running on port other than 8080, the communication between client and service never happens. I am trying to know what is the best way to create stubs that does not have server and port hardcoded in the stub used by the client.</p> | 3,569,291 | 2 | 1 | null | 2010-08-25 18:29:08.273 UTC | 23 | 2017-05-29 15:36:15.057 UTC | 2012-02-16 20:00:59.987 UTC | null | 171,012 | null | 363,808 | null | 1 | 52 | java|jax-ws | 58,732 | <p>Your client can set the end-point in the service "port" at runtime via the <a href="http://download.oracle.com/javase/6/docs/api/javax/xml/ws/BindingProvider.html" rel="noreferrer">BindingProvider</a> interface.</p>
<p>Consider the JAX-WS client in <a href="http://download.oracle.com/docs/cd/E17802_01/webservices/webservices/docs/2.0/tutorial/doc/JAXWS3.html" rel="noreferrer">this JAX-WS tutorial</a>. Another way to write this code would be:</p>
<pre><code>HelloService service = new HelloService();
Hello port = service.getHelloPort();
BindingProvider bindingProvider = (BindingProvider) port;
bindingProvider.getRequestContext().put(
BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
"http://foo:8086/HelloWhatever");
String response = port.sayHello(name);
</code></pre>
<p><em>Caveat: I haven't downloaded the tutorial code and tested this code against it.</em></p> |
29,480,890 | When to save data to database, onPause() or onStop()? | <p>I know this question has been asked a million times, I myself though that I already knew the answer and that the correct one was that the only guaranteed call is to onPause(), so you should save your data there.</p>
<p>However, in many places of android documentation they always suggest not doing heavy work (such as writing data in database) in the onPause() method as it will delay the transition between the activities.</p>
<p>According to <a href="http://developer.android.com/guide/components/activities.html">Android Developer Guide in Table 1</a></p>
<blockquote>
<p>onPause(): This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on. It should do whatever it does very quickly, because the next activity will not be resumed until it returns.</p>
<p>Killable: YES</p>
</blockquote>
<p>Then according to <a href="http://developer.android.com/reference/android/app/Activity.html">Android Developer Reference Guide in the similar table</a>.</p>
<p>It says the same thing but:</p>
<blockquote>
<p>Killable: Pre-HONEYCOMB</p>
</blockquote>
<p>And they add a little note that says:</p>
<blockquote>
<p>Be aware that these semantics will change slightly between applications targeting platforms starting with HONEYCOMB vs. those targeting prior platforms. <strong>Starting with Honeycomb, an application is not in the killable state until its onStop() has returned</strong>. This impacts when onSaveInstanceState(Bundle) may be called (it may be safely called after onPause() and allows and application to safely wait until onStop() to save persistent state.</p>
</blockquote>
<hr>
<p>Killable</p>
<blockquote>
<p>Note the "Killable" column in the above table -- for those methods that are marked as being killable, <strong>after</strong> that method returns the process hosting the activity may killed by the system at any time without another line of its code being executed.</p>
</blockquote>
<p><strong>FOR POST-HONEYCOMB (i dont care about earlier versions):</strong>
So, is it OK to assume that any Android device (including different ROMS) will ensure a call to onStop on the activity? And this is the best place to make any time consuming storage writing of the App?</p>
<p><em>Note: This is extremely confusing as most answers here, sites, books, and even online android tests take as a correct answer that you should save it in onPause and NOT in onStop.</em></p> | 29,496,430 | 3 | 4 | null | 2015-04-06 22:43:12.733 UTC | 8 | 2020-07-22 10:11:41.447 UTC | 2015-04-07 14:43:55.663 UTC | null | 3,219,997 | null | 3,219,997 | null | 1 | 18 | android|android-activity|android-lifecycle|android-database | 10,099 | <blockquote>
<p>When to save data to database, onPause() or onStop()?</p>
</blockquote>
<p>Either. They are nearly identical, particularly on Android 3.0+.</p>
<p>If the activity that is taking over the foreground is a typical full-screen activity, so that the earlier activity is no longer visible, <code>onPause()</code> and <code>onStop()</code> will be called in rapid succession.</p>
<p>If the activity that is taking over the foreground is themed to be more like a dialog, where the earlier activity is still visible, <code>onPause()</code> will be called, but not <code>onStop()</code>, until such time as the activity is no longer visible (e.g., user now presses HOME).</p>
<p>Most apps aren't worried about the "themed to be more like a dialog" scenario, in which case <code>onPause()</code> and <code>onStop()</code> are called one right after the next, and you can fork your background thread to save your data in whichever of those makes sense to you.</p>
<blockquote>
<p>However, in many places of android documentation they always suggest not doing heavy work (such as writing data in database) in the onPause() method as it will delay the transition between the activities.</p>
</blockquote>
<p>The same is true of <code>onStop()</code>, as both of those methods are called on the main application thread.</p>
<blockquote>
<p>So, is it OK to assume that any Android device (including different ROMS) will ensure a call to onStop on the activity?</p>
</blockquote>
<p>Both <code>onPause()</code> and <code>onStop()</code> will have the same characteristics from the standpoint of process termination. Either both should be called (normal case) or neither will be called (e.g., you crash, the battery pops out the back of the phone).</p>
<blockquote>
<p>And this is the best place to make any time consuming storage writing of the App?</p>
</blockquote>
<p>Either <code>onPause()</code> or <code>onStop()</code> are fine places to trigger the work, done on a background thread, to persist your data. If you prefer to do that work in <code>onStop()</code>, you are absolutely welcome to do so. Personally, I'm an <code>onPause()</code> kind of guy.</p> |
16,432,576 | oracle database connection in web.config asp.net | <p>I know I can create a connection string in the c# class itself, but I am trying to avoid doing that. I want to create the connection in the web.config, which I read is more secure. Nevertheless I couldn't find any example that has the following attributes specified:</p>
<blockquote>
<ul>
<li>Host name</li>
<li>Port</li>
<li>SID</li>
<li>Username</li>
<li>Password</li>
<li>Connection Name</li>
</ul>
</blockquote>
<p>Could anyone help please with creating this in webconfig? I am connecting to oracle DB. </p> | 16,434,430 | 3 | 1 | null | 2013-05-08 04:19:00.003 UTC | 5 | 2017-12-29 00:10:39.363 UTC | null | null | null | null | 464,885 | null | 1 | 15 | c#|asp.net|oracle | 76,477 | <p>Here is the template:</p>
<pre><code> <connectionStrings>
<add name="{ConnectionName}"
connectionString="Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;"
providerName="Oracle.DataAccess.Client"/>
</connectionStrings>
</code></pre>
<p>Here is one of mine - minus a real TNS name and username and password:</p>
<pre><code> <add name="MSOL" connectionString="Data Source={TNS_NAME};User ID={username};Password={password};pooling=true;min pool size=5;Max Pool Size=60" providerName="Oracle.DataAccess.Client"/>
</code></pre> |
16,370,911 | How to get Spring RabbitMQ to create a new Queue? | <p>In my (limited) experience with rabbit-mq, if you create a new listener for a queue that doesn't exist yet, the queue is automatically created. I'm trying to use the Spring AMQP project with rabbit-mq to set up a listener, and I'm getting an error instead. This is my xml config:</p>
<pre><code><rabbit:connection-factory id="rabbitConnectionFactory" host="172.16.45.1" username="test" password="password" />
<rabbit:listener-container connection-factory="rabbitConnectionFactory" >
<rabbit:listener ref="testQueueListener" queue-names="test" />
</rabbit:listener-container>
<bean id="testQueueListener" class="com.levelsbeyond.rabbit.TestQueueListener">
</bean>
</code></pre>
<p>I get this in my RabbitMq logs:</p>
<pre><code>=ERROR REPORT==== 3-May-2013::23:17:24 ===
connection <0.1652.0>, channel 1 - soft error:
{amqp_error,not_found,"no queue 'test' in vhost '/'",'queue.declare'}
</code></pre>
<p>And a similar error from AMQP:</p>
<pre><code>2013-05-03 23:17:24,059 ERROR [org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer] (SimpleAsyncTaskExecutor-1) - Consumer received fatal exception on startup
org.springframework.amqp.rabbit.listener.FatalListenerStartupException: Cannot prepare queue for listener. Either the queue doesn't exist or the broker will not allow us to use it.
</code></pre>
<p>It would seem from the stack trace that the queue is getting created in a "passive" mode- Can anyone point out how I would create the queue not using the passive mode so I don't see this error? Or am I missing something else?</p> | 16,377,097 | 5 | 0 | null | 2013-05-04 05:31:18.81 UTC | 3 | 2022-01-12 11:08:29.487 UTC | null | null | null | null | 520,730 | null | 1 | 22 | java|spring|rabbitmq|amqp | 48,320 | <p>What seemed to resolve my issue was adding an admin. Here is my xml:</p>
<p></p>
<pre><code><rabbit:listener-container connection-factory="rabbitConnectionFactory" >
<rabbit:listener ref="orderQueueListener" queues="test.order" />
</rabbit:listener-container>
<rabbit:queue name="test.order"></rabbit:queue>
<rabbit:admin id="amqpAdmin" connection-factory="rabbitConnectionFactory"/>
<bean id="orderQueueListener" class="com.levelsbeyond.rabbit.OrderQueueListener">
</bean>
</code></pre> |
16,276,557 | Using MongoDB from client with Javascript | <p>I am trying to use MongoDB with just javascript from client, but MongoDB's documentation on how to achieve this is very confusing.</p>
<p>On <a href="http://docs.mongodb.org/ecosystem/drivers/javascript/" rel="noreferrer">this</a> webpage there is nothing to download, I was expecting to see something like mongo.js.</p>
<p><a href="https://github.com/mongodb/mongo/blob/master/src/mongo/shell/mongo.js" rel="noreferrer">Here</a> I did find mongo.js, and using <a href="http://docs.mongodb.org/manual/tutorial/write-scripts-for-the-mongo-shell/" rel="noreferrer">this</a> I am trying to make it work but with no luck. </p>
<p>The Javascript console in Google Chrome is saying:</p>
<blockquote>
<p>Uncaught TypeError: Object [object Object] has no method 'init'</p>
</blockquote>
<p>In this snippet from mongo.js:</p>
<pre><code>if ( typeof Mongo == "undefined" ){
Mongo = function( host ){
this.init( host );
}
}
</code></pre>
<p>Does anyone have any tips on using MongoDB with pure Javascript?</p> | 16,277,603 | 3 | 0 | null | 2013-04-29 10:38:26.313 UTC | 5 | 2021-11-23 21:12:03.27 UTC | 2015-01-06 12:33:07.193 UTC | null | 1,542,891 | null | 1,019,691 | null | 1 | 28 | javascript|mongodb | 38,604 | <p>The documentation you linked to is about accessing MongoDB with <strong>server</strong>-sided Javascript using the node.js framework.</p>
<p>MongoDB does offer a REST webservice allowing rudimentary queries through XmlHttpRequests. To enable it, you have to start mongod with the <code>--rest</code> parameter. You can then query it like this:</p>
<pre><code>http://127.0.0.1:28017/yourDatabase/yourCollection/?filter_name=Bob
</code></pre>
<p>You can query this URL with an AJAX XmlHttpRequest like any webservice. It will access a database on localhost and return JSON equivalent to a query like this:</p>
<pre><code>yourDatabase.yourCollection.find({name:"Bob"});
</code></pre>
<p>This interface, however, is very rudimentary. It only offers simple find queries. But there are 3rd party middleware layers which expose more advanced functionality. This feature and a list of 3rd party solutions is documented here:</p>
<p><a href="http://docs.mongodb.org/ecosystem/tools/http-interfaces/" rel="noreferrer">http://docs.mongodb.org/ecosystem/tools/http-interfaces/</a></p> |
16,363,890 | Unable to copy/paste in MinGW shell | <p>I just installed MinGW on Windows and I'm unable to copy/paste as I am used to on Linux or even PuTTY. What is the trick for copying and pasting text (e.g. from chrome) into MinGW shell?</p> | 16,363,972 | 7 | 0 | null | 2013-05-03 16:45:43.817 UTC | 16 | 2022-01-05 12:29:03.31 UTC | 2022-01-05 12:29:03.31 UTC | null | 1,879,699 | null | 788,171 | null | 1 | 106 | mingw|copy-paste | 46,420 | <p>Right-click on the title bar of the command window and select 'Properties', then on the 'Options' tab tick the box for the 'QuickEdit mode', then click 'Ok'.</p>
<p>After that you can paste text from the clipboard using the right mouse-button, highlight text while holding down the left mouse-button and copy selected text using the <kbd>ENTER</kbd> key.</p>
<p><strong>This procedure works on Windows 7/8, not Windows 10.</strong></p> |
16,199,002 | How do I view / replay a chrome network debugger har file saved with content? | <p>I love the network debugger, that being said, what programs are out there that let me step forward and backward through multiple 'hars' so I can replay them? if the 'hars' are saved with content, can the replay handle that as well?</p>
<p>right now I just read through in textpad, but if I have to present any of my findings a nice 'har player' could greatly help non-technical folk.</p> | 24,702,480 | 12 | 2 | null | 2013-04-24 17:57:14.117 UTC | 30 | 2022-09-07 14:24:25.9 UTC | null | null | null | null | 176,818 | null | 1 | 164 | debugging|google-chrome|har | 236,483 | <p>There is an HAR Viewer developed by Jan Odvarko that you can use. You either use the online version at</p>
<ul>
<li><a href="http://www.softwareishard.com/har/viewer/" rel="noreferrer">http://www.softwareishard.com/har/viewer/</a> (older version)</li>
<li><a href="http://gitgrimbo.github.io/harviewer/master/" rel="noreferrer">http://gitgrimbo.github.io/harviewer/master/</a> (up-to-date master branch)</li>
</ul>
<p>Or download the source-code at <a href="https://github.com/janodvarko/harviewer" rel="noreferrer">https://github.com/janodvarko/harviewer</a>.</p>
<p>EDIT: Chrome 62 DevTools include HAR import functionality.
<a href="https://developers.google.com/web/updates/2017/08/devtools-release-notes#har-imports" rel="noreferrer">https://developers.google.com/web/updates/2017/08/devtools-release-notes#har-imports</a></p> |
17,267,216 | How to use for each loop in c++ | <pre><code>#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main() {
string str("hello world!");
for (auto &c : str)
c = toupper(c);
cout << str;
return 0;
}
</code></pre>
<p>This c++ code does not compile.
Error msg:
main.cpp:21: error: a function-definition is not allowed here before ':' token
Question:
Is there a for each loop in c++ (range for loop?)?
what is wrong with the for each loop above?</p>
<p>Thanks in advance.</p> | 17,267,263 | 2 | 2 | null | 2013-06-24 02:24:03.693 UTC | 3 | 2013-06-24 02:31:10.903 UTC | null | null | null | null | 2,514,756 | null | 1 | 14 | c++ | 52,264 | <p>The code is valid, as can be demonstrated on an <a href="http://ideone.com/msj6Ai" rel="noreferrer">online compiler</a>.</p>
<p>Please refer to your compiler documentation to be sure you have enabled C++11. The option is often called <code>-std=c++11</code>. You might have to download an upgrade; check your package manager for GCC (currently at 4.8) or Clang (currently 3.3).</p> |
27,277,219 | Scroll UICollectionView to bottom | <p>I would like to scroll the UICollectionView to the bottom so the last item is in the view. I have tried to use scrollToItemAtIndexPath but it does not seem to be working. I want this to happen after I have completed a query with Parse.com</p>
<p>Thanks</p>
<pre><code> var query = PFQuery(className:"Chat")
// query.whereKey("user", equalTo:currentUser)
query.whereKey("rideId", equalTo:currentObjectId)
query.orderByDescending("createdAt")
query.includeKey("user")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
// The find succeeded.
NSLog("Successfully retrieved \(objects.count) scores.")
// Do something with the found objects
for object in objects {
NSLog("%@", object.objectId)
var testId = object.objectId
println(testId)
self.orderedIdArray.append(testId)
var message = object.objectForKey("message") as String
self.messageString = message
self.messageArray.append(self.messageString)
println(message)
var nameId = object.objectForKey("user") as PFUser
var username = nameId.username as String
self.nameString = username
self.namesArray.append(self.nameString)
println("username: \(username)")
self.collectionView?.reloadData()
}
} else {
// Log details of the failure
NSLog("Error: %@ %@", error, error.userInfo!)
}
NSLog("Ordered: %@", self.orderedIdArray)
}
</code></pre> | 27,278,130 | 13 | 4 | null | 2014-12-03 16:49:58.243 UTC | 8 | 2020-09-28 04:52:11.633 UTC | null | null | null | null | 3,976,008 | null | 1 | 26 | swift|uicollectionview | 24,245 | <p>I have added the lines below to run once the query is complete.</p>
<pre><code>var item = self.collectionView(self.collectionView!, numberOfItemsInSection: 0) - 1
var lastItemIndex = NSIndexPath(forItem: item, inSection: 0)
self.collectionView?.scrollToItemAtIndexPath(lastItemIndex, atScrollPosition: UICollectionViewScrollPosition.Top, animated: false)
</code></pre>
<p>Update to <strong>Swift 5</strong></p>
<pre><code>let item = self.collectionView(self.collectionView, numberOfItemsInSection: 0) - 1
let lastItemIndex = IndexPath(item: item, section: 0)
self.collectionView.scrollToItem(at: lastItemIndex, at: .top, animated: true)
</code></pre> |
26,991,807 | Calculate time difference in minutes in SQL Server | <p>I need the time difference between two times in minutes. I am having the start time and end time as shown below:</p>
<pre><code>start time | End Time
11:15:00 | 13:15:00
10:45:00 | 18:59:00
</code></pre>
<p>I need the output for first row as 45,60,15 which corresponds to the time difference between 11:15 and 12:00, 12:00 and 13:00, 13:00 and 13:15 respectively.</p> | 26,992,202 | 6 | 7 | null | 2014-11-18 10:17:43.323 UTC | 8 | 2020-08-31 06:20:50.017 UTC | 2018-04-12 10:33:25.117 UTC | null | 1,369,235 | null | 1,565,133 | null | 1 | 31 | sql|sql-server|sql-server-2008|datetime|difference | 231,226 | <p>The following works as expected:</p>
<pre><code>SELECT Diff = CASE DATEDIFF(HOUR, StartTime, EndTime)
WHEN 0 THEN CAST(DATEDIFF(MINUTE, StartTime, EndTime) AS VARCHAR(10))
ELSE CAST(60 - DATEPART(MINUTE, StartTime) AS VARCHAR(10)) +
REPLICATE(',60', DATEDIFF(HOUR, StartTime, EndTime) - 1) +
+ ',' + CAST(DATEPART(MINUTE, EndTime) AS VARCHAR(10))
END
FROM (VALUES
(CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
(CAST('10:45' AS TIME), CAST('18:59' AS TIME)),
(CAST('10:45' AS TIME), CAST('11:59' AS TIME))
) t (StartTime, EndTime);
</code></pre>
<p>To get 24 columns, you could use 24 case expressions, something like:</p>
<pre><code>SELECT [0] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 0
THEN DATEDIFF(MINUTE, StartTime, EndTime)
ELSE 60 - DATEPART(MINUTE, StartTime)
END,
[1] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 1
THEN DATEPART(MINUTE, EndTime)
WHEN DATEDIFF(HOUR, StartTime, EndTime) > 1 THEN 60
END,
[2] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 2
THEN DATEPART(MINUTE, EndTime)
WHEN DATEDIFF(HOUR, StartTime, EndTime) > 2 THEN 60
END -- ETC
FROM (VALUES
(CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
(CAST('10:45' AS TIME), CAST('18:59' AS TIME)),
(CAST('10:45' AS TIME), CAST('11:59' AS TIME))
) t (StartTime, EndTime);
</code></pre>
<p>The following also works, and may end up shorter than repeating the same case expression over and over:</p>
<pre><code>WITH Numbers (Number) AS
( SELECT ROW_NUMBER() OVER(ORDER BY t1.N) - 1
FROM (VALUES (1), (1), (1), (1), (1), (1)) AS t1 (N)
CROSS JOIN (VALUES (1), (1), (1), (1)) AS t2 (N)
), YourData AS
( SELECT StartTime, EndTime
FROM (VALUES
(CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
(CAST('09:45' AS TIME), CAST('18:59' AS TIME)),
(CAST('10:45' AS TIME), CAST('11:59' AS TIME))
) AS t (StartTime, EndTime)
), PivotData AS
( SELECT t.StartTime,
t.EndTime,
n.Number,
MinuteDiff = CASE WHEN n.Number = 0 AND DATEDIFF(HOUR, StartTime, EndTime) = 0 THEN DATEDIFF(MINUTE, StartTime, EndTime)
WHEN n.Number = 0 THEN 60 - DATEPART(MINUTE, StartTime)
WHEN DATEDIFF(HOUR, t.StartTime, t.EndTime) <= n.Number THEN DATEPART(MINUTE, EndTime)
ELSE 60
END
FROM YourData AS t
INNER JOIN Numbers AS n
ON n.Number <= DATEDIFF(HOUR, StartTime, EndTime)
)
SELECT *
FROM PivotData AS d
PIVOT
( MAX(MinuteDiff)
FOR Number IN
( [0], [1], [2], [3], [4], [5],
[6], [7], [8], [9], [10], [11],
[12], [13], [14], [15], [16], [17],
[18], [19], [20], [21], [22], [23]
)
) AS pvt;
</code></pre>
<p>It works by joining to a table of 24 numbers, so the case expression doesn't need to be repeated, then rolling these 24 numbers back up into columns using <code>PIVOT</code></p> |
19,709,722 | TortoiseSVN: Adding additional files after using SVN Checkout dialog "Only this item" option | <p>Our department is planning on using the "SVN Checkout" option within Tortoise SVN. In that dialog, we select the "Only this item" option and then we click the "Choose items" button and choose all the relevant files we want to check-out. Let's assume a user will make a mistake, and forgot to check out an important file. What is the easiest way to go back and choose that file (or list of files) from trunk?</p>
<p><img src="https://i.stack.imgur.com/YetZO.jpg" alt="enter image description here"></p>
<h1>EDIT:</h1>
<p><strong>Suggested changes to @Chad's answer:</strong></p>
<p><strong>A.) If the parent folder of the folder(s) or file(s) you are checking out DOES NOT EXIST in the working copy, then do the following:</strong></p>
<ol>
<li>Open a <strong>Repo-browser</strong> for the repository.</li>
<li>Right-click the files that were missed and choose <strong>Checkout...</strong>.</li>
<li><em>Fix/Set the Checkout directory to where the files should go (add the folders from the folder you clicked to the parent folder of the folder/file you are checking out and make sure you are using backslash characters)</em></li>
<li>Click <strong>OK</strong>.</li>
<li>You will get a warning that the "Target folder is not empty". Go ahead and choose the <strong>Checkout into the non empty folder</strong> option.</li>
</ol>
<p>The files will be added to the working copy.</p>
<p><strong>DISCLAIMER:</strong> <em>If you do not follow step #3, the working copy of the checked out files will be in a strange location not relative to the rest of the files.</em></p>
<p><strong>B.) If the parent folder of the folder(s) or file(s) you are checking out DOES EXIST in the working copy, then do the following:</strong></p>
<ol>
<li>Open a <strong>Repo-browser</strong> for the repository.</li>
<li><em>Navigate to the parent folder of the file you intend to checkout (avoids the step of having to fix the "Checkout Directory")</em></li>
<li>Right-click the files that were missed and choose <strong>Checkout...</strong>.</li>
<li>Click <strong>OK</strong>.</li>
<li>You will get a warning that the "Target folder is not empty". Go ahead and choose the <strong>Checkout into the non empty folder</strong> option.</li>
</ol>
<p>The files will be added to the working copy.</p>
<h1>EDIT #2:</h1>
<p><strong>Suggested update to @gbjbaanb's proposed answer:</strong></p>
<p><strong>To include new folders/files to working copy:</strong></p>
<ol>
<li>Right click root folder of checked out folder > select "TortoiseSVN" > select "Repo-browser"</li>
<li>Enter credentials (if authentication is cleared in TortoiseSVN > Settings > Saved Data) > click "OK"</li>
<li>Right click items in either the file explorer panel or the file detail panel within the Repository Browser dialog > select "Update item to Revision" > take all defaults in the Update to Revision dialog > click "OK" </li>
<li>Enter credentials (if authentication is cleared in TortoiseSVN > Settings > Saved Data) > click "OK"</li>
</ol>
<p><strong>NOTE:</strong> <em>Repeat step #3 and #4 for all new folders/files being added</em></p>
<p><strong>DISCLAIMER:</strong> <em>Assume you are only adding new folders or files to your working copy/checked out folder.</em></p>
<p><strong>To exclude folders/files from working copy:</strong></p>
<ol>
<li>Right click folder or file you wish to exclude</li>
<li>Select Tortoise SVN > Update to Revision</li>
<li>Click "Choose items..." button under the "Update Depth" section of the Update to Revision dialog</li>
<li>Enter credentials (if authentication is cleared in TortoiseSVN > Settings > Saved Data) > click "OK"</li>
<li>Uncheck relevant folder(s) or file(s) > click "OK"</li>
</ol>
<p>That's the method I used with a very large repository. Only the bits I needed were checked out, when I needed them.</p> | 19,714,889 | 2 | 3 | null | 2013-10-31 14:51:15.827 UTC | 5 | 2017-11-10 19:56:40.113 UTC | 2017-11-10 19:56:40.113 UTC | null | 6,296,561 | null | 640,205 | null | 1 | 31 | svn|tortoisesvn|svn-checkout|sparse-checkout | 14,590 | <p>You right-click on the root, select repo-browser, find the relevant bits you want to download to your working copy, right click and select the "update to revision". </p>
<p>To remove items you have downloaded, right click on the item in your working copy, select the same menu (update to revision) and select "exclude" from the depth box.</p>
<p>That's the method I used with a very large repository. Only the bits I needed were checked out, when I needed them.</p> |
19,301,516 | Override JS function from another file | <p>Im trying to override a JS function from Bigcartel. I have no access to the JS file.</p>
<p>The original is:</p>
<pre><code>updateCart: function(cart) {
$('aside .cart .count, .main header .cart').htmlHighlight(cart.item_count);
return $('aside .cart .total').htmlHighlight(Format.money(cart.total, true, true));
},
</code></pre>
<p>And i am trying to change it to this:</p>
<pre><code>updateCart: function(cart) {
$('aside .cart .count, .sml .cart, .big .cart .count').htmlHighlight(cart.item_count);
return $('aside .cart .total').htmlHighlight(Format.money(cart.total, true, true));
},
</code></pre>
<p>I am aware that others have asked similar questions, but i am a complete noob when it comes to understanding how to implement JS (i only know how to tweek through trial and error)</p>
<p>If any one could be so kind as to help me out by <em>giving me the answer</em> that would be great.</p>
<p>Thanks,</p>
<p>iWed- </p>
<hr>
<p><strong>EDIT [10.10.13 :: 21:24hr]</strong></p>
<p>To clarify, i do not have direct access to the original JS file. i can only view it through chrome. I only have access to html files. It is for a Big cartel theme Edit. </p>
<p>Here is a link to to copied JS using chrome.
Line 216 is the code, if this helps : <a href="http://jsfiddle.net/w9GTJ/" rel="noreferrer">http://jsfiddle.net/w9GTJ/</a></p> | 19,301,622 | 2 | 5 | null | 2013-10-10 16:40:34.397 UTC | 5 | 2015-05-27 17:56:34.153 UTC | 2014-02-26 16:56:04.223 UTC | null | 3,347,601 | null | 1,003,252 | null | 1 | 10 | javascript|overriding|bigcartel | 39,294 | <p><strong>EDIT:</strong> You are in luck. From the posted code you can see that the updateCart method is exported on the window.Store global object. The solution is to add this code after the original script loaded: </p>
<pre><code>window.Store.updateCart = function(cart) {
$('aside .cart .count, .sml .cart, .big .cart .count').htmlHighlight(cart.item_count);
return $('aside .cart .total').htmlHighlight(Format.money(cart.total, true, true));
};
</code></pre>
<p><strong>Explanation for a general situation:</strong></p>
<p>All scripts loaded in a web page run in the same global scope, so overwriting a variable is as simple as inserting your script afterwards:</p>
<pre><code><script>
var x = 5; // original script
</script>
<script>
x = 2; // your inserted script
</script>
</code></pre>
<p>From the looks of it, your function is defined as property of an object:</p>
<pre><code>var x = {
updateCart : function(cart) {
// stuff
}
}
</code></pre>
<p>So to overwrite it you need to do:</p>
<pre><code>x.updateCart = function(cart) {
// your code
}
</code></pre>
<p>Finally, there is one situation where you simply can't overwrite it, if function is private in the original code:</p>
<pre><code>function() {
var x = {
updateCart: function(){}
}
}()
// No way to access x.updateCart here
</code></pre> |
21,894,450 | How to add constructors/destructors to an unnamed class? | <p>Is there a way to declare a constructor or a destructor in an unnamed class? Consider the following </p>
<pre><code>void f()
{
struct {
// some implementation
} inst1, inst2;
// f implementation - usage of instances
}
</code></pre>
<p>Follow up question : The instances are ofcourse constructed (and destroyed) as any stack based object. What gets called? Is it a mangled name automatically assigned by the compiler? </p> | 21,894,571 | 3 | 9 | null | 2014-02-19 22:59:16.057 UTC | 10 | 2015-12-07 16:21:06.51 UTC | 2015-12-07 16:21:06.51 UTC | null | 2,877,241 | null | 2,567,683 | null | 1 | 48 | c++|class|constructor|destructor|declaration | 14,992 | <p>You can not declare a constructor or destructor for an unnamed class because the constructor and destructor names need to match the class name. In your example, the unnamed class is local. It has no linkage so neither mangled name is created.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.