qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
68,283 | <p>What's a quick and easy way to view and edit ID3 tags (artist, album, etc.) using C#?</p>
| [
{
"answer_id": 68306,
"author": "tslocum",
"author_id": 1662,
"author_profile": "https://Stackoverflow.com/users/1662",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.novell.com/products/linuxpackages/opensuse11.1/taglib-sharp.html\" rel=\"noreferrer\">TagLib Sharp</a... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10606/"
] | What's a quick and easy way to view and edit ID3 tags (artist, album, etc.) using C#? | Thirding [TagLib Sharp](https://github.com/mono/taglib-sharp).
```
TagLib.File f = TagLib.File.Create(path);
f.Tag.Album = "New Album Title";
f.Save();
``` |
68,291 | <p>If you were running a news site that created a list of 10 top news stories, and you wanted to make tweaks to your algorithm and see if people liked the new top story mix better, how would you approach this? </p>
<p>Simple Click logging in the DB associated with the post entry? </p>
<p>A/B testing where you would show one version of the algorithm togroup A and another to group B and measure the clicks? </p>
<p>What sort of characteristics would you base your decision on as to whether the changes were better? </p>
| [
{
"answer_id": 68306,
"author": "tslocum",
"author_id": 1662,
"author_profile": "https://Stackoverflow.com/users/1662",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.novell.com/products/linuxpackages/opensuse11.1/taglib-sharp.html\" rel=\"noreferrer\">TagLib Sharp</a... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281/"
] | If you were running a news site that created a list of 10 top news stories, and you wanted to make tweaks to your algorithm and see if people liked the new top story mix better, how would you approach this?
Simple Click logging in the DB associated with the post entry?
A/B testing where you would show one version of the algorithm togroup A and another to group B and measure the clicks?
What sort of characteristics would you base your decision on as to whether the changes were better? | Thirding [TagLib Sharp](https://github.com/mono/taglib-sharp).
```
TagLib.File f = TagLib.File.Create(path);
f.Tag.Album = "New Album Title";
f.Save();
``` |
68,327 | <p>I create a new Button object but did not specify the <code>command</code> option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created?</p>
| [
{
"answer_id": 68455,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 2,
"selected": false,
"text": "<p>Sure; just use the <code>bind</code> method to specify the callback after the button has been created. I've just ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
] | I create a new Button object but did not specify the `command` option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created? | Though [Eli Courtwright's](https://stackoverflow.com/questions/68327/change-command-method-for-tkinter-button-in-python#68455) program will work fine¹, what you really seem to want though is just a way to reconfigure after instantiation any attribute which you could have set when you instantiated². How you do so is by way of the configure() method.
```
from Tkinter import Tk, Button
def goodbye_world():
print "Goodbye World!\nWait, I changed my mind!"
button.configure(text = "Hello World!", command=hello_world)
def hello_world():
print "Hello World!\nWait, I changed my mind!"
button.configure(text = "Goodbye World!", command=goodbye_world)
root = Tk()
button = Button(root, text="Hello World!", command=hello_world)
button.pack()
root.mainloop()
```
¹ "fine" if you use only the mouse; if you care about tabbing and using [Space] or [Enter] on buttons, then you will have to implement (duplicating existing code) keypress events too. Setting the `command` option through `.configure` is much easier.
² the only attribute that can't change after instantiation is `name`. |
68,335 | <p>I have a text file on my local machine that is generated by a daily Python script run in cron. </p>
<p>I would like to add a bit of code to have that file sent securely to my server over SSH.</p>
| [
{
"answer_id": 68365,
"author": "pdq",
"author_id": 8598,
"author_profile": "https://Stackoverflow.com/users/8598",
"pm_score": 7,
"selected": true,
"text": "<p>You can call the <a href=\"https://en.wikipedia.org/wiki/Secure_copy\" rel=\"noreferrer\"><code>scp</code></a> bash command (it... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10668/"
] | I have a text file on my local machine that is generated by a daily Python script run in cron.
I would like to add a bit of code to have that file sent securely to my server over SSH. | You can call the [`scp`](https://en.wikipedia.org/wiki/Secure_copy) bash command (it copies files over [SSH](https://en.wikipedia.org/wiki/Secure_Shell)) with [`subprocess.run`](https://docs.python.org/library/subprocess.html#subprocess.run):
```
import subprocess
subprocess.run(["scp", FILE, "USER@SERVER:PATH"])
#e.g. subprocess.run(["scp", "foo.bar", "joe@srvr.net:/path/to/foo.bar"])
```
If you're creating the file that you want to send in the same Python program, you'll want to call `subprocess.run` command outside the `with` block you're using to open the file (or call `.close()` on the file first if you're not using a `with` block), so you know it's flushed to disk from Python.
You need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn't ask for a password). |
68,352 | <p>I use this question in interviews and I wonder what the best solution is.</p>
<p>Write a Perl sub that takes <em>n</em> lists, and then returns 2^<em>n</em>-1 lists telling you which items are in which lists; that is, which items are only in the first list, the second, list, both the first and second list, and all other combinations of lists. Assume that <em>n</em> is reasonably small (less than 20).</p>
<p>For example:</p>
<pre><code>list_compare([1, 3], [2, 3]);
=> ([1], [2], [3]);
</code></pre>
<p>Here, the first result list gives all items that are only in list 1, the second result list gives all items that are only in list 2, and the third result list gives all items that are in both lists.</p>
<pre><code>list_compare([1, 3, 5, 7], [2, 3, 6, 7], [4, 5, 6, 7])
=> ([1], [2], [3], [4], [5], [6], [7])
</code></pre>
<p>Here, the first list gives all items that are only in list 1, the second list gives all items that are only in list 2, and the third list gives all items that are in both lists 1 and 2, as in the first example. The fourth list gives all items that are only in list 3, the fifth list gives all items that are only in lists 1 and 3, the sixth list gives all items that are only in lists 2 and 3, and the seventh list gives all items that are in all 3 lists.</p>
<p>I usually give this problem as a follow up to the subset of this problem for <em>n</em>=2.</p>
<p>What is the solution? </p>
<p>Follow-up: The items in the lists are strings. There might be duplicates, but since they are just strings, duplicates should be squashed in the output. Order of the items in the output lists doesn't matter, the order of the lists themselves does.</p>
| [
{
"answer_id": 68417,
"author": "nohat",
"author_id": 3101,
"author_profile": "https://Stackoverflow.com/users/3101",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my solution:</p>\n\n<p>Construct a hash whose keys are the union of all the elements in the input lists, and the val... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3101/"
] | I use this question in interviews and I wonder what the best solution is.
Write a Perl sub that takes *n* lists, and then returns 2^*n*-1 lists telling you which items are in which lists; that is, which items are only in the first list, the second, list, both the first and second list, and all other combinations of lists. Assume that *n* is reasonably small (less than 20).
For example:
```
list_compare([1, 3], [2, 3]);
=> ([1], [2], [3]);
```
Here, the first result list gives all items that are only in list 1, the second result list gives all items that are only in list 2, and the third result list gives all items that are in both lists.
```
list_compare([1, 3, 5, 7], [2, 3, 6, 7], [4, 5, 6, 7])
=> ([1], [2], [3], [4], [5], [6], [7])
```
Here, the first list gives all items that are only in list 1, the second list gives all items that are only in list 2, and the third list gives all items that are in both lists 1 and 2, as in the first example. The fourth list gives all items that are only in list 3, the fifth list gives all items that are only in lists 1 and 3, the sixth list gives all items that are only in lists 2 and 3, and the seventh list gives all items that are in all 3 lists.
I usually give this problem as a follow up to the subset of this problem for *n*=2.
What is the solution?
Follow-up: The items in the lists are strings. There might be duplicates, but since they are just strings, duplicates should be squashed in the output. Order of the items in the output lists doesn't matter, the order of the lists themselves does. | Your given solution can be simplified quite a bit still.
In the first loop, you can use plain addition since you are only ever ORing with single bits, and you can narrow the scope of `$bit` by iterating over indices. In the second loop, you can subtract 1 from the index instead of producing an unnecessary 0th output list element that needs to be `shift`ed off, and where you unnecessarily iterate m\*n times (where m is the number of output lists and n is the number of unique elements), iterating over the unique elements would reduce the iterations to just n (which is a significant win in typical use cases where m is much larger than n), *and* would simplify the code.
```
sub list_compare {
my ( @list ) = @_;
my %dest;
for my $i ( 0 .. $#list ) {
my $bit = 2**$i;
$dest{$_} += $bit for @{ $list[ $i ] };
}
my @output_list;
for my $val ( keys %dest ) {
push @{ $output_list[ $dest{ $val } - 1 ] }, $val;
}
return \@output_list;
}
```
Note also that once thought of in this way, the result gathering process can be written very concisely with the aid of the [List::Part](http://search.cpan.org/perldoc?List::Part) module:
```
use List::Part;
sub list_compare {
my ( @list ) = @_;
my %dest;
for my $i ( 0 .. $#list ) {
my $bit = 2**$i;
$dest{$_} += $bit for @{ $list[ $i ] };
}
return [ part { $dest{ $_ } - 1 } keys %dest ];
}
```
But note that `list_compare` is a terrible name. Something like `part_elems_by_membership` would be much better. Also, the imprecisions in your question Ben Tilly pointed out need to be rectified. |
68,372 | <p>We all know how to use <code><ctrl>-R</code> to reverse search through history, but did you know you can use <code><ctrl>-S</code> to forward search if you set <code>stty stop ""</code>? Also, have you ever tried running bind -p to see all of your keyboard shortcuts listed? There are over 455 on Mac OS X by default. </p>
<p>What is your single most favorite obscure trick, keyboard shortcut or shopt configuration using bash?</p>
| [
{
"answer_id": 68386,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>Well, this may be a bit off topic, but if you are an Emacs user, I would say \"emacs\" is the most powerful trick... bef... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3499/"
] | We all know how to use `<ctrl>-R` to reverse search through history, but did you know you can use `<ctrl>-S` to forward search if you set `stty stop ""`? Also, have you ever tried running bind -p to see all of your keyboard shortcuts listed? There are over 455 on Mac OS X by default.
What is your single most favorite obscure trick, keyboard shortcut or shopt configuration using bash? | When running commands, sometimes I'll want to run a command with the previous ones arguments. To do that, you can use this shortcut:
```
$ mkdir /tmp/new
$ cd !!:*
```
Occasionally, in lieu of using find, I'll break-out a one-line loop if I need to run a bunch of commands on a list of files.
```
for file in *.wav; do lame "$file" "$(basename "$file" .wav).mp3" ; done;
```
Configuring the command-line history options in my .bash\_login (or .bashrc) is really useful. The following is a cadre of settings that I use on my Macbook Pro.
Setting the following makes bash erase duplicate commands in your history:
```
export HISTCONTROL="erasedups:ignoreboth"
```
I also jack my history size up pretty high too. Why not? It doesn't seem to slow anything down on today's microprocessors.
```
export HISTFILESIZE=500000
export HISTSIZE=100000
```
Another thing that I do is ignore some commands from my history. No need to remember the exit command.
```
export HISTIGNORE="&:[ ]*:exit"
```
You definitely want to set histappend. Otherwise, bash overwrites your history when you exit.
```
shopt -s histappend
```
Another option that I use is cmdhist. This lets you save multi-line commands to the history as one command.
```
shopt -s cmdhist
```
Finally, on Mac OS X (if you're not using vi mode), you'll want to reset <CTRL>-S from being scroll stop. This prevents bash from being able to interpret it as forward search.
```
stty stop ""
``` |
68,391 | <p>In an effort to reduce code duplication in my little Rails app, I've been working on getting common code between my models into it's own separate module, so far so good.</p>
<p>The model stuff is fairly easy, I just have to include the module at the beginning, e.g.:</p>
<pre><code>class Iso < Sale
include Shared::TracksSerialNumberExtension
include Shared::OrderLines
extend Shared::Filtered
include Sendable::Model
validates_presence_of :customer
validates_associated :lines
owned_by :customer
def initialize( params = nil )
super
self.created_at ||= Time.now.to_date
end
def after_initialize
end
order_lines :despatched
# tracks_serial_numbers :items
sendable :customer
def created_at=( date )
write_attribute( :created_at, Chronic.parse( date ) )
end
end
</code></pre>
<p>This is working fine, now however, I'm going to have some controller and view code that's going to be common between these models as well, so far I have this for my sendable stuff:</p>
<pre><code># This is a module that is used for pages/forms that are can be "sent"
# either via fax, email, or printed.
module Sendable
module Model
def self.included( klass )
klass.extend ClassMethods
end
module ClassMethods
def sendable( class_to_send_to )
attr_accessor :fax_number,
:email_address,
:to_be_faxed,
:to_be_emailed,
:to_be_printed
@_class_sending_to ||= class_to_send_to
include InstanceMethods
end
def class_sending_to
@_class_sending_to
end
end # ClassMethods
module InstanceMethods
def after_initialize( )
super
self.to_be_faxed = false
self.to_be_emailed = false
self.to_be_printed = false
target_class = self.send( self.class.class_sending_to )
if !target_class.nil?
self.fax_number = target_class.send( :fax_number )
self.email_address = target_class.send( :email_address )
end
end
end
end # Module Model
end # Module Sendable
</code></pre>
<p>Basically I'm planning on just doing an include Sendable::Controller, and Sendable::View (or the equivalent) for the controller and the view, but, is there a cleaner way to do this? I 'm after a neat way to have a bunch of common code between my model, controller, and view.</p>
<p>Edit: Just to clarify, this just has to be shared across 2 or 3 models.</p>
| [
{
"answer_id": 68934,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 3,
"selected": false,
"text": "<p>If that code needs to get added to all models and all controllers, you could always do the following:</p>\n\n<pre><code># m... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841/"
] | In an effort to reduce code duplication in my little Rails app, I've been working on getting common code between my models into it's own separate module, so far so good.
The model stuff is fairly easy, I just have to include the module at the beginning, e.g.:
```
class Iso < Sale
include Shared::TracksSerialNumberExtension
include Shared::OrderLines
extend Shared::Filtered
include Sendable::Model
validates_presence_of :customer
validates_associated :lines
owned_by :customer
def initialize( params = nil )
super
self.created_at ||= Time.now.to_date
end
def after_initialize
end
order_lines :despatched
# tracks_serial_numbers :items
sendable :customer
def created_at=( date )
write_attribute( :created_at, Chronic.parse( date ) )
end
end
```
This is working fine, now however, I'm going to have some controller and view code that's going to be common between these models as well, so far I have this for my sendable stuff:
```
# This is a module that is used for pages/forms that are can be "sent"
# either via fax, email, or printed.
module Sendable
module Model
def self.included( klass )
klass.extend ClassMethods
end
module ClassMethods
def sendable( class_to_send_to )
attr_accessor :fax_number,
:email_address,
:to_be_faxed,
:to_be_emailed,
:to_be_printed
@_class_sending_to ||= class_to_send_to
include InstanceMethods
end
def class_sending_to
@_class_sending_to
end
end # ClassMethods
module InstanceMethods
def after_initialize( )
super
self.to_be_faxed = false
self.to_be_emailed = false
self.to_be_printed = false
target_class = self.send( self.class.class_sending_to )
if !target_class.nil?
self.fax_number = target_class.send( :fax_number )
self.email_address = target_class.send( :email_address )
end
end
end
end # Module Model
end # Module Sendable
```
Basically I'm planning on just doing an include Sendable::Controller, and Sendable::View (or the equivalent) for the controller and the view, but, is there a cleaner way to do this? I 'm after a neat way to have a bunch of common code between my model, controller, and view.
Edit: Just to clarify, this just has to be shared across 2 or 3 models. | You could pluginize it (use script/generate plugin).
Then in your init.rb just do something like:
```
ActiveRecord::Base.send(:include, PluginName::Sendable)
ActionController::Base.send(:include, PluginName::SendableController)
```
And along with your self.included that should work just fine.
Check out some of the acts\_\* plugins, it's a pretty common pattern (<http://github.com/technoweenie/acts_as_paranoid/tree/master/init.rb>, check line 30) |
68,408 | <p>Is there any <strong>simple algorithm</strong> to determine the likeliness of 2 names representing the same person? </p>
<p>I'm not asking for something of the level that Custom department might be using. Just a simple algorithm that would tell me if 'James T. Clark' is most likely the same name as 'J. Thomas Clark' or 'James Clerk'.</p>
<p>If there is an algorithm in <code>C#</code> that would be great, but I can translate from any language.</p>
| [
{
"answer_id": 68422,
"author": "Antti",
"author_id": 6037,
"author_profile": "https://Stackoverflow.com/users/6037",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Levenshtein_distance\" rel=\"nofollow noreferrer\">Levenshtein</a> is close, although... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3610/"
] | Is there any **simple algorithm** to determine the likeliness of 2 names representing the same person?
I'm not asking for something of the level that Custom department might be using. Just a simple algorithm that would tell me if 'James T. Clark' is most likely the same name as 'J. Thomas Clark' or 'James Clerk'.
If there is an algorithm in `C#` that would be great, but I can translate from any language. | I've faced similar problem and tried to use Levenstein distance first, but it did not work well for me. I came up with an algorithm that gives you "similarity" value between two strings (higher value means more similar strings, "1" for identical strings). This value is not very meaningful by itself (if not "1", always 0.5 or less), but works quite well when you throw in Hungarian Matrix to find matching pairs from two lists of strings.
Use like this:
```
PartialStringComparer cmp = new PartialStringComparer();
tbResult.Text = cmp.Compare(textBox1.Text, textBox2.Text).ToString();
```
The code behind:
```
public class SubstringRange {
string masterString;
public string MasterString {
get { return masterString; }
set { masterString = value; }
}
int start;
public int Start {
get { return start; }
set { start = value; }
}
int end;
public int End {
get { return end; }
set { end = value; }
}
public int Length {
get { return End - Start; }
set { End = Start + value;}
}
public bool IsValid {
get { return MasterString.Length >= End && End >= Start && Start >= 0; }
}
public string Contents {
get {
if(IsValid) {
return MasterString.Substring(Start, Length);
} else {
return "";
}
}
}
public bool OverlapsRange(SubstringRange range) {
return !(End < range.Start || Start > range.End);
}
public bool ContainsRange(SubstringRange range) {
return range.Start >= Start && range.End <= End;
}
public bool ExpandTo(string newContents) {
if(MasterString.Substring(Start).StartsWith(newContents, StringComparison.InvariantCultureIgnoreCase) && newContents.Length > Length) {
Length = newContents.Length;
return true;
} else {
return false;
}
}
}
public class SubstringRangeList: List<SubstringRange> {
string masterString;
public string MasterString {
get { return masterString; }
set { masterString = value; }
}
public SubstringRangeList(string masterString) {
this.MasterString = masterString;
}
public SubstringRange FindString(string s){
foreach(SubstringRange r in this){
if(r.Contents.Equals(s, StringComparison.InvariantCultureIgnoreCase))
return r;
}
return null;
}
public SubstringRange FindSubstring(string s){
foreach(SubstringRange r in this){
if(r.Contents.StartsWith(s, StringComparison.InvariantCultureIgnoreCase))
return r;
}
return null;
}
public bool ContainsRange(SubstringRange range) {
foreach(SubstringRange r in this) {
if(r.ContainsRange(range))
return true;
}
return false;
}
public bool AddSubstring(string substring) {
bool result = false;
foreach(SubstringRange r in this) {
if(r.ExpandTo(substring)) {
result = true;
}
}
if(FindSubstring(substring) == null) {
bool patternfound = true;
int start = 0;
while(patternfound){
patternfound = false;
start = MasterString.IndexOf(substring, start, StringComparison.InvariantCultureIgnoreCase);
patternfound = start != -1;
if(patternfound) {
SubstringRange r = new SubstringRange();
r.MasterString = this.MasterString;
r.Start = start++;
r.Length = substring.Length;
if(!ContainsRange(r)) {
this.Add(r);
result = true;
}
}
}
}
return result;
}
private static bool SubstringRangeMoreThanOneChar(SubstringRange range) {
return range.Length > 1;
}
public float Weight {
get {
if(MasterString.Length == 0 || Count == 0)
return 0;
float numerator = 0;
int denominator = 0;
foreach(SubstringRange r in this.FindAll(SubstringRangeMoreThanOneChar)) {
numerator += r.Length;
denominator++;
}
if(denominator == 0)
return 0;
return numerator / denominator / MasterString.Length;
}
}
public void RemoveOverlappingRanges() {
SubstringRangeList l = new SubstringRangeList(this.MasterString);
l.AddRange(this);//create a copy of this list
foreach(SubstringRange r in l) {
if(this.Contains(r) && this.ContainsRange(r)) {
Remove(r);//try to remove the range
if(!ContainsRange(r)) {//see if the list still contains "superset" of this range
Add(r);//if not, add it back
}
}
}
}
public void AddStringToCompare(string s) {
for(int start = 0; start < s.Length; start++) {
for(int len = 1; start + len <= s.Length; len++) {
string part = s.Substring(start, len);
if(!AddSubstring(part))
break;
}
}
RemoveOverlappingRanges();
}
}
public class PartialStringComparer {
public float Compare(string s1, string s2) {
SubstringRangeList srl1 = new SubstringRangeList(s1);
srl1.AddStringToCompare(s2);
SubstringRangeList srl2 = new SubstringRangeList(s2);
srl2.AddStringToCompare(s1);
return (srl1.Weight + srl2.Weight) / 2;
}
}
```
Levenstein distance one is much simpler (adapted from <http://www.merriampark.com/ld.htm>):
```
public class Distance {
/// <summary>
/// Compute Levenshtein distance
/// </summary>
/// <param name="s">String 1</param>
/// <param name="t">String 2</param>
/// <returns>Distance between the two strings.
/// The larger the number, the bigger the difference.
/// </returns>
public static int LD(string s, string t) {
int n = s.Length; //length of s
int m = t.Length; //length of t
int[,] d = new int[n + 1, m + 1]; // matrix
int cost; // cost
// Step 1
if(n == 0) return m;
if(m == 0) return n;
// Step 2
for(int i = 0; i <= n; d[i, 0] = i++) ;
for(int j = 0; j <= m; d[0, j] = j++) ;
// Step 3
for(int i = 1; i <= n; i++) {
//Step 4
for(int j = 1; j <= m; j++) {
// Step 5
cost = (t.Substring(j - 1, 1) == s.Substring(i - 1, 1) ? 0 : 1);
// Step 6
d[i, j] = System.Math.Min(System.Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
}
``` |
68,444 | <p>We have a program that produces several SWF files, some CSS and XML files, all of which need to be deployed for the thing to work.</p>
<p>Is there a program or technique out there for wrapping all these files together into a single SWF file?</p>
| [
{
"answer_id": 68474,
"author": "Brent",
"author_id": 10680,
"author_profile": "https://Stackoverflow.com/users/10680",
"pm_score": 0,
"selected": false,
"text": "<p>I think you can just drag them into the library of your main swf and make references to them. At least the other SWFs you ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6277/"
] | We have a program that produces several SWF files, some CSS and XML files, all of which need to be deployed for the thing to work.
Is there a program or technique out there for wrapping all these files together into a single SWF file? | If you use the Flex compiler (`mxmlc` or FlexBuilder) you can embed SWF files and create them at runtime, more or less like you would create any display object:
```
package {
public class Assets {
[Embed(source="another.swf")]
public var another : Class;
}
}
```
The code above embeds the file `another.swf` and makes it possible to create it in another SWF, like this:
```
package {
import flash.display.Sprite;
public class MyFancySite extends Sprite {
public function MyFancySprite( ) {
var theOther : DisplayObject = new Assets.another();
addChild(theOther);
}
}
}
```
CSS, XML and any other file can be embedded in a similar fashion. Here's a description: <http://livedocs.adobe.com/flex/3/html/help.html?content=embed_4.html> |
68,477 | <p>Is there a way to send a file using POST from a Python script?</p>
| [
{
"answer_id": 68502,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": false,
"text": "<p>Yes. You'd use the <code>urllib2</code> module, and encode using the <code>multipart/form-data</code> content type. ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | Is there a way to send a file using POST from a Python script? | From: <https://requests.readthedocs.io/en/latest/user/quickstart/#post-a-multipart-encoded-file>
Requests makes it very simple to upload Multipart-encoded files:
```
with open('report.xls', 'rb') as f:
r = requests.post('http://httpbin.org/post', files={'report.xls': f})
```
That's it. I'm not joking - this is one line of code. The file was sent. Let's check:
```
>>> r.text
{
"origin": "179.13.100.4",
"files": {
"report.xls": "<censored...binary...data>"
},
"form": {},
"url": "http://httpbin.org/post",
"args": {},
"headers": {
"Content-Length": "3196",
"Accept-Encoding": "identity, deflate, compress, gzip",
"Accept": "*/*",
"User-Agent": "python-requests/0.8.0",
"Host": "httpbin.org:80",
"Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"
},
"data": ""
}
``` |
68,485 | <p>In <b>Prototype</b> I can show a "loading..." image with this code:</p>
<pre><code>var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars,
onLoading: showLoad, onComplete: showResponse} );
function showLoad () {
...
}
</code></pre>
<p>In <b>jQuery</b>, I can load a server page into an element with this:</p>
<pre><code>$('#message').load('index.php?pg=ajaxFlashcard');
</code></pre>
<p>but how do I attach a loading spinner to this command as I did in Prototype?</p>
| [
{
"answer_id": 68503,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 11,
"selected": true,
"text": "<p>There are a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself.</p>... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] | In **Prototype** I can show a "loading..." image with this code:
```
var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars,
onLoading: showLoad, onComplete: showResponse} );
function showLoad () {
...
}
```
In **jQuery**, I can load a server page into an element with this:
```
$('#message').load('index.php?pg=ajaxFlashcard');
```
but how do I attach a loading spinner to this command as I did in Prototype? | There are a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself.
```
$('#loadingDiv')
.hide() // Hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
})
;
```
The ajaxStart/Stop functions will fire whenever you do any Ajax calls.
**Update**: As of jQuery 1.8, the documentation states that `.ajaxStart/Stop` should only be attached to `document`. This would transform the above snippet to:
```
var $loading = $('#loadingDiv').hide();
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});
``` |
68,509 | <p>If I use the following code I lose the ability to right click on variables in the code behind and refactor (rename in this case) them</p>
<pre><code><a href='<%# "/Admin/Content/EditResource.aspx?ResourceId=" + Eval("Id").ToString() %>'>Edit</a>
</code></pre>
<p>I see this practice everywhere but it seems weird to me as I no longer am able to get compile time errors if I change the property name.
My preferred approach is to do something like this</p>
<pre><code><a runat="server" id="MyLink">Edit</a>
</code></pre>
<p>and then in the code behind</p>
<pre><code>MyLink.Href= "/Admin/Content/EditResource.aspx?ResourceId=" + myObject.Id;
</code></pre>
<p>I'm really interested to hear if people think the above approach is better since that's what I always see on popular coding sites and blogs (e.g. Scott Guthrie) and it's smaller code, but I tend to use ASP.NET because it is compiled and prefer to know if something is broken at compile time, not run time.</p>
| [
{
"answer_id": 68530,
"author": "Kilhoffer",
"author_id": 5469,
"author_profile": "https://Stackoverflow.com/users/5469",
"pm_score": 3,
"selected": true,
"text": "<p>I wouldnt call it bad practice (some would disagree, but why did they give us that option in the first place?), but I wou... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6084/"
] | If I use the following code I lose the ability to right click on variables in the code behind and refactor (rename in this case) them
```
<a href='<%# "/Admin/Content/EditResource.aspx?ResourceId=" + Eval("Id").ToString() %>'>Edit</a>
```
I see this practice everywhere but it seems weird to me as I no longer am able to get compile time errors if I change the property name.
My preferred approach is to do something like this
```
<a runat="server" id="MyLink">Edit</a>
```
and then in the code behind
```
MyLink.Href= "/Admin/Content/EditResource.aspx?ResourceId=" + myObject.Id;
```
I'm really interested to hear if people think the above approach is better since that's what I always see on popular coding sites and blogs (e.g. Scott Guthrie) and it's smaller code, but I tend to use ASP.NET because it is compiled and prefer to know if something is broken at compile time, not run time. | I wouldnt call it bad practice (some would disagree, but why did they give us that option in the first place?), but I would say that you'll improve overall readability and maintainability if you do not submit to this practice. You already conveyed out a good point, and that is IDE feature limitation (i.e., design time inspection, compile time warning, etc.).
I could go on and on about how many principles it violates (code reuse, separation of concerns, etc.), but I can think of many applications out there that break nearly every principle, but still work after several years. I for one, prefer to make my code as modular and maintainable as possible. |
68,537 | <p>A basic problem I run into quite often, but ever found a clean solution to, is one where you want to code behaviour for interaction between different objects of a common base class or interface. To make it a bit concrete, I'll throw in an example;</p>
<p><em>Bob has been coding on a strategy game which supports "cool geographical effects". These round up to simple constraints such as if troops are walking in water, they are slowed 25%. If they are walking on grass, they are slowed 5%, and if they are walking on pavement they are slowed by 0%.</em></p>
<p><em>Now, management told Bob that they needed new sorts of troops. There would be jeeps, boats and also hovercrafts. Also, they wanted jeeps to take damage if they went drove into water, and hovercrafts would ignore all three of the terrain types. Rumor has it also that they might add another terrain type with even more features than slowing units down and taking damage.</em></p>
<p>A very rough pseudo code example follows:</p>
<pre><code>public interface ITerrain
{
void AffectUnit(IUnit unit);
}
public class Water : ITerrain
{
public void AffectUnit(IUnit unit)
{
if (unit is HoverCraft)
{
// Don't affect it anyhow
}
if (unit is FootSoldier)
{
unit.SpeedMultiplier = 0.75f;
}
if (unit is Jeep)
{
unit.SpeedMultiplier = 0.70f;
unit.Health -= 5.0f;
}
if (unit is Boat)
{
// Don't affect it anyhow
}
/*
* List grows larger each day...
*/
}
}
public class Grass : ITerrain
{
public void AffectUnit(IUnit unit)
{
if (unit is HoverCraft)
{
// Don't affect it anyhow
}
if (unit is FootSoldier)
{
unit.SpeedMultiplier = 0.95f;
}
if (unit is Jeep)
{
unit.SpeedMultiplier = 0.85f;
}
if (unit is Boat)
{
unit.SpeedMultiplier = 0.0f;
unit.Health = 0.0f;
Boat boat = unit as Boat;
boat.DamagePropeller();
// Perhaps throw in an explosion aswell?
}
/*
* List grows larger each day...
*/
}
}
</code></pre>
<p>As you can see, things would have been better if Bob had a solid design document from the beginning. As the number of units and terrain types grow, so does code complexity. Not only does Bob have to worry about figuring out which members might need to be added to the unit interface, but he also has to repeat alot of code. It's very likely that new terrain types require additional information from what can be obtained from the basic IUnit interface. </p>
<p>Each time we add another unit into the game, each terrain must be updated to handle the new unit. Clearly, this makes for a lot of repetition, not to mention the ugly runtime check which determines the type of unit being dealt with. I've opted out calls to the specific subtypes in this example, but those kinds of calls are neccessary to make. <em>An example would be that when a boat hits land, its propeller should be damaged. Not all units have propellers.</em></p>
<p>I am unsure what this kind of problem is called, but it is a many-to-many dependence which I have a hard time decoupling. I don't fancy having 100's of overloads for each IUnit subclass on ITerrain as I would want to come clean with coupling.</p>
<p>Any light on this problem is highly sought after. Perhaps I'm thinking way out of orbit all together?</p>
| [
{
"answer_id": 68560,
"author": "Jiaaro",
"author_id": 2908,
"author_profile": "https://Stackoverflow.com/users/2908",
"pm_score": 0,
"selected": false,
"text": "<p>Old idea:</p>\n\n<blockquote>\n <p>Make a class iTerrain and another\n class iUnit which accepts an argument\n which is ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2166173/"
] | A basic problem I run into quite often, but ever found a clean solution to, is one where you want to code behaviour for interaction between different objects of a common base class or interface. To make it a bit concrete, I'll throw in an example;
*Bob has been coding on a strategy game which supports "cool geographical effects". These round up to simple constraints such as if troops are walking in water, they are slowed 25%. If they are walking on grass, they are slowed 5%, and if they are walking on pavement they are slowed by 0%.*
*Now, management told Bob that they needed new sorts of troops. There would be jeeps, boats and also hovercrafts. Also, they wanted jeeps to take damage if they went drove into water, and hovercrafts would ignore all three of the terrain types. Rumor has it also that they might add another terrain type with even more features than slowing units down and taking damage.*
A very rough pseudo code example follows:
```
public interface ITerrain
{
void AffectUnit(IUnit unit);
}
public class Water : ITerrain
{
public void AffectUnit(IUnit unit)
{
if (unit is HoverCraft)
{
// Don't affect it anyhow
}
if (unit is FootSoldier)
{
unit.SpeedMultiplier = 0.75f;
}
if (unit is Jeep)
{
unit.SpeedMultiplier = 0.70f;
unit.Health -= 5.0f;
}
if (unit is Boat)
{
// Don't affect it anyhow
}
/*
* List grows larger each day...
*/
}
}
public class Grass : ITerrain
{
public void AffectUnit(IUnit unit)
{
if (unit is HoverCraft)
{
// Don't affect it anyhow
}
if (unit is FootSoldier)
{
unit.SpeedMultiplier = 0.95f;
}
if (unit is Jeep)
{
unit.SpeedMultiplier = 0.85f;
}
if (unit is Boat)
{
unit.SpeedMultiplier = 0.0f;
unit.Health = 0.0f;
Boat boat = unit as Boat;
boat.DamagePropeller();
// Perhaps throw in an explosion aswell?
}
/*
* List grows larger each day...
*/
}
}
```
As you can see, things would have been better if Bob had a solid design document from the beginning. As the number of units and terrain types grow, so does code complexity. Not only does Bob have to worry about figuring out which members might need to be added to the unit interface, but he also has to repeat alot of code. It's very likely that new terrain types require additional information from what can be obtained from the basic IUnit interface.
Each time we add another unit into the game, each terrain must be updated to handle the new unit. Clearly, this makes for a lot of repetition, not to mention the ugly runtime check which determines the type of unit being dealt with. I've opted out calls to the specific subtypes in this example, but those kinds of calls are neccessary to make. *An example would be that when a boat hits land, its propeller should be damaged. Not all units have propellers.*
I am unsure what this kind of problem is called, but it is a many-to-many dependence which I have a hard time decoupling. I don't fancy having 100's of overloads for each IUnit subclass on ITerrain as I would want to come clean with coupling.
Any light on this problem is highly sought after. Perhaps I'm thinking way out of orbit all together? | Terrain has-a Terrain Attribute
Terrain Attributes are multidimensional.
Units has-a Propulsion.
Propulsion is compatible able with Terrain Attributes.
Units move by a Terrain visit with Propulsion as an argument.
That gets delegated to the Propulsion.
Units *may* get affected by terrain as part of the visit.
Unit code knows nothing about propulsion.
Terrain types can change w/o changing anything except Terrain Attributes and Propulsion.
Propuslion's constructors protect existing units from new methods of travel. |
68,541 | <p>When trying to use <code>libxml2</code> as myself I get an error saying the package cannot be found. If I run as as super user I am able to import fine.</p>
<p>I have installed <code>python25</code> and all <code>libxml2</code> and <code>libxml2-py25</code> related libraries via fink and own the entire path including the library. Any ideas why I'd still need to sudo?</p>
| [
{
"answer_id": 69513,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 2,
"selected": false,
"text": "<p>Check your path by running:</p>\n\n<pre><code>'echo $PATH'\n</code></pre>\n"
},
{
"answer_id": 70895,
"autho... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | When trying to use `libxml2` as myself I get an error saying the package cannot be found. If I run as as super user I am able to import fine.
I have installed `python25` and all `libxml2` and `libxml2-py25` related libraries via fink and own the entire path including the library. Any ideas why I'd still need to sudo? | Check your path by running:
```
'echo $PATH'
``` |
68,565 | <p>I like the XMLReader class for it's simplicity and speed. But I like the xml_parse associated functions as it better allows for error recovery. It would be nice if the XMLReader class would throw exceptions for things like invalid entity refs instead of just issuinng a warning.</p>
| [
{
"answer_id": 68580,
"author": "ctcherry",
"author_id": 10322,
"author_profile": "https://Stackoverflow.com/users/10322",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://us2.php.net/simplexml\" rel=\"nofollow noreferrer\">SimpleXML</a> seems to do a good job for me.</p>\n... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I like the XMLReader class for it's simplicity and speed. But I like the xml\_parse associated functions as it better allows for error recovery. It would be nice if the XMLReader class would throw exceptions for things like invalid entity refs instead of just issuinng a warning. | I'd avoid SimpleXML if you can. Though it looks very tempting by getting to avoid a lot of "ugly" code, it's just what the name suggests: simple. For example, it can't handle this:
```
<p>
Here is <strong>a very simple</strong> XML document.
</p>
```
Bite the bullet and go to the DOM Functions. The power of it far outweighs the little bit extra complexity. If you're familiar at all with DOM manipulation in Javascript, you'll feel right at home with this library. |
68,569 | <p>I am a C++/C# developer and never spent time working on web pages. I would like to put text (randomly and diagonally perhaps) in large letters across the background of some pages. I want to be able to read the foreground text and also be able to read the "watermark". I understand that is probably more of a function of color selection. </p>
<p>I have been unsuccessful in my attempts to do what I want. I would imagine this to be very simple for someone with the web design tools or html knowledge. </p>
| [
{
"answer_id": 68591,
"author": "dawnerd",
"author_id": 69503,
"author_profile": "https://Stackoverflow.com/users/69503",
"pm_score": 2,
"selected": false,
"text": "<p>You could make an image with the watermark and then set the image as the background via css.</p>\n\n<p>For example:</p>\... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10755/"
] | I am a C++/C# developer and never spent time working on web pages. I would like to put text (randomly and diagonally perhaps) in large letters across the background of some pages. I want to be able to read the foreground text and also be able to read the "watermark". I understand that is probably more of a function of color selection.
I have been unsuccessful in my attempts to do what I want. I would imagine this to be very simple for someone with the web design tools or html knowledge. | ```
<style type="text/css">
#watermark {
color: #d0d0d0;
font-size: 200pt;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
position: absolute;
width: 100%;
height: 100%;
margin: 0;
z-index: -1;
left:-100px;
top:-200px;
}
</style>
```
This lets you use just text as the watermark - good for dev/test versions of a web page.
```
<div id="watermark">
<p>This is the test version.</p>
</div>
``` |
68,572 | <p>I have a question that I may be over thinking at this point but here goes...</p>
<p>I have 2 classes Users and Groups. Users and groups have a many to many relationship and I was thinking that the join table group_users I wanted to have an IsAuthorized property (because some groups are private -- users will need authorization). </p>
<p><strong>Would you recommend creating a class for the join table as well as the User and Groups table?</strong> Currently my classes look like this.</p>
<pre><code>public class Groups
{
public Groups()
{
members = new List<Person>();
}
...
public virtual IList<Person> members { get; set; }
}
public class User
{
public User()
{
groups = new Groups()
}
...
public virtual IList<Groups> groups{ get; set; }
}
</code></pre>
<p>My mapping is like the following in both classes (I'm only showing the one in the users mapping but they are very similar):</p>
<pre><code>HasManyToMany<Groups>(x => x.Groups)
.WithTableName("GroupMembers")
.WithParentKeyColumn("UserID")
.WithChildKeyColumn("GroupID")
.Cascade.SaveUpdate();
</code></pre>
<p><strong>Should I write a class for the join table that looks like this?</strong></p>
<pre><code>public class GroupMembers
{
public virtual string GroupID { get; set; }
public virtual string PersonID { get; set; }
public virtual bool WaitingForAccept { get; set; }
}
</code></pre>
<p>I would really like to be able to adjust the group membership status and I guess I'm trying to think of the best way to go about this. </p>
| [
{
"answer_id": 68591,
"author": "dawnerd",
"author_id": 69503,
"author_profile": "https://Stackoverflow.com/users/69503",
"pm_score": 2,
"selected": false,
"text": "<p>You could make an image with the watermark and then set the image as the background via css.</p>\n\n<p>For example:</p>\... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385358/"
] | I have a question that I may be over thinking at this point but here goes...
I have 2 classes Users and Groups. Users and groups have a many to many relationship and I was thinking that the join table group\_users I wanted to have an IsAuthorized property (because some groups are private -- users will need authorization).
**Would you recommend creating a class for the join table as well as the User and Groups table?** Currently my classes look like this.
```
public class Groups
{
public Groups()
{
members = new List<Person>();
}
...
public virtual IList<Person> members { get; set; }
}
public class User
{
public User()
{
groups = new Groups()
}
...
public virtual IList<Groups> groups{ get; set; }
}
```
My mapping is like the following in both classes (I'm only showing the one in the users mapping but they are very similar):
```
HasManyToMany<Groups>(x => x.Groups)
.WithTableName("GroupMembers")
.WithParentKeyColumn("UserID")
.WithChildKeyColumn("GroupID")
.Cascade.SaveUpdate();
```
**Should I write a class for the join table that looks like this?**
```
public class GroupMembers
{
public virtual string GroupID { get; set; }
public virtual string PersonID { get; set; }
public virtual bool WaitingForAccept { get; set; }
}
```
I would really like to be able to adjust the group membership status and I guess I'm trying to think of the best way to go about this. | ```
<style type="text/css">
#watermark {
color: #d0d0d0;
font-size: 200pt;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
position: absolute;
width: 100%;
height: 100%;
margin: 0;
z-index: -1;
left:-100px;
top:-200px;
}
</style>
```
This lets you use just text as the watermark - good for dev/test versions of a web page.
```
<div id="watermark">
<p>This is the test version.</p>
</div>
``` |
68,578 | <p>Is there a way to fall through multiple case statements without stating <code>case value:</code> repeatedly?</p>
<p>I know this works:</p>
<pre><code>switch (value)
{
case 1:
case 2:
case 3:
// Do some stuff
break;
case 4:
case 5:
case 6:
// Do some different stuff
break;
default:
// Default stuff
break;
}
</code></pre>
<p>but I'd like to do something like this:</p>
<pre><code>switch (value)
{
case 1,2,3:
// Do something
break;
case 4,5,6:
// Do something
break;
default:
// Do the Default
break;
}
</code></pre>
<p>Is this syntax I'm thinking of from a different language, or am I missing something?</p>
| [
{
"answer_id": 68611,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 10,
"selected": true,
"text": "<p>There is no syntax in C++ nor C# for the second method you mentioned. </p>\n\n<p>There's nothing wrong with your fi... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7870/"
] | Is there a way to fall through multiple case statements without stating `case value:` repeatedly?
I know this works:
```
switch (value)
{
case 1:
case 2:
case 3:
// Do some stuff
break;
case 4:
case 5:
case 6:
// Do some different stuff
break;
default:
// Default stuff
break;
}
```
but I'd like to do something like this:
```
switch (value)
{
case 1,2,3:
// Do something
break;
case 4,5,6:
// Do something
break;
default:
// Do the Default
break;
}
```
Is this syntax I'm thinking of from a different language, or am I missing something? | There is no syntax in C++ nor C# for the second method you mentioned.
There's nothing wrong with your first method. If however you have very big ranges, just use a series of if statements. |
68,583 | <p>I have the following code snippet.</p>
<pre><code>$items['A'] = "Test";
$items['B'] = "Test";
$items['C'] = "Test";
$items['D'] = "Test";
$index = 0;
foreach($items as $key => $value)
{
echo "$index is a $key containing $value\n";
$index++;
}
</code></pre>
<p>Expected output:</p>
<pre><code>0 is a A containing Test
1 is a B containing Test
2 is a C containing Test
3 is a D containing Test
</code></pre>
<p>Is there a way to leave out the <code>$index</code> variable?</p>
| [
{
"answer_id": 68612,
"author": "Brent",
"author_id": 10680,
"author_profile": "https://Stackoverflow.com/users/10680",
"pm_score": 5,
"selected": true,
"text": "<p>Your $index variable there kind of misleading. That number isn't the index, your \"A\", \"B\", \"C\", \"D\" keys are. You c... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/264/"
] | I have the following code snippet.
```
$items['A'] = "Test";
$items['B'] = "Test";
$items['C'] = "Test";
$items['D'] = "Test";
$index = 0;
foreach($items as $key => $value)
{
echo "$index is a $key containing $value\n";
$index++;
}
```
Expected output:
```
0 is a A containing Test
1 is a B containing Test
2 is a C containing Test
3 is a D containing Test
```
Is there a way to leave out the `$index` variable? | Your $index variable there kind of misleading. That number isn't the index, your "A", "B", "C", "D" keys are. You can still access the data through the numbered index $index[1], but that's really not the point. If you really want to keep the numbered index, I'd almost restructure the data:
```
$items[] = array("A", "Test");
$items[] = array("B", "Test");
$items[] = array("C", "Test");
$items[] = array("D", "Test");
foreach($items as $key => $value) {
echo $key.' is a '.$value[0].' containing '.$value[1];
}
``` |
68,598 | <p>I've seen this done in Borland's <a href="https://en.wikipedia.org/wiki/Turbo_C++" rel="noreferrer">Turbo C++</a> environment, but I'm not sure how to go about it for a C# application I'm working on. Are there best practices or gotchas to look out for?</p>
| [
{
"answer_id": 68722,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 6,
"selected": false,
"text": "<p>In Windows Forms, set the control's AllowDrop property, then listen for DragEnter event and DragDrop event.</p... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I've seen this done in Borland's [Turbo C++](https://en.wikipedia.org/wiki/Turbo_C++) environment, but I'm not sure how to go about it for a C# application I'm working on. Are there best practices or gotchas to look out for? | Some sample code:
```
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
this.AllowDrop = true;
this.DragEnter += new DragEventHandler(Form1_DragEnter);
this.DragDrop += new DragEventHandler(Form1_DragDrop);
}
void Form1_DragEnter(object sender, DragEventArgs e) {
if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
}
void Form1_DragDrop(object sender, DragEventArgs e) {
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files) Console.WriteLine(file);
}
}
``` |
68,610 | <p>I am having problems getting text within a table to appear centered in IE. </p>
<p>In Firefox 2, 3 and Safari everything work fine, but for some reason, the text doesn't appear centered in IE 6 or 7. </p>
<p>I'm using:</p>
<pre class="lang-css prettyprint-override"><code>h2 {
font: 300 12px "Helvetica", serif;
text-align: center;
text-transform: uppercase;
}
</code></pre>
<p>I've also tried adding <code>margin-left:auto;</code>, <code>margin-right:auto</code> and <code>position:relative;</code> </p>
<p>to no avail. </p>
| [
{
"answer_id": 68621,
"author": "Mike Becatti",
"author_id": 6617,
"author_profile": "https://Stackoverflow.com/users/6617",
"pm_score": 3,
"selected": true,
"text": "<p>The table cell needs the text-align: center.</p>\n"
},
{
"answer_id": 68637,
"author": "nickf",
"autho... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10761/"
] | I am having problems getting text within a table to appear centered in IE.
In Firefox 2, 3 and Safari everything work fine, but for some reason, the text doesn't appear centered in IE 6 or 7.
I'm using:
```css
h2 {
font: 300 12px "Helvetica", serif;
text-align: center;
text-transform: uppercase;
}
```
I've also tried adding `margin-left:auto;`, `margin-right:auto` and `position:relative;`
to no avail. | The table cell needs the text-align: center. |
68,624 | <p>I would like to parse a string such as <code>p1=6&p2=7&p3=8</code> into a <code>NameValueCollection</code>.</p>
<p>What is the most elegant way of doing this when you don't have access to the <code>Page.Request</code> object?</p>
| [
{
"answer_id": 68639,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 0,
"selected": false,
"text": "<p>Hit up Request.QueryString.Keys for a NameValueCollection of all query string parameters.</p>\n"
},
{
"answer_id... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4998/"
] | I would like to parse a string such as `p1=6&p2=7&p3=8` into a `NameValueCollection`.
What is the most elegant way of doing this when you don't have access to the `Page.Request` object? | There's a built-in .NET utility for this: [HttpUtility.ParseQueryString](http://msdn.microsoft.com/en-us/library/ms150046.aspx)
```cs
// C#
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);
```
```vb
' VB.NET
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)
```
You may need to replace `querystring` with `new Uri(fullUrl).Query`. |
68,630 | <p>Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? </p>
| [
{
"answer_id": 68638,
"author": "ctcherry",
"author_id": 10322,
"author_profile": "https://Stackoverflow.com/users/10322",
"pm_score": 2,
"selected": false,
"text": "<p>Tuples should be slightly more efficient and because of that, faster, than lists because they are immutable.</p>\n"
}... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? | The [`dis`](https://docs.python.org/3/library/dis.html) module disassembles the byte code for a function and is useful to see the difference between tuples and lists.
In this case, you can see that accessing an element generates identical code, but that assigning a tuple is much faster than assigning a list.
```
>>> def a():
... x=[1,2,3,4,5]
... y=x[2]
...
>>> def b():
... x=(1,2,3,4,5)
... y=x[2]
...
>>> import dis
>>> dis.dis(a)
2 0 LOAD_CONST 1 (1)
3 LOAD_CONST 2 (2)
6 LOAD_CONST 3 (3)
9 LOAD_CONST 4 (4)
12 LOAD_CONST 5 (5)
15 BUILD_LIST 5
18 STORE_FAST 0 (x)
3 21 LOAD_FAST 0 (x)
24 LOAD_CONST 2 (2)
27 BINARY_SUBSCR
28 STORE_FAST 1 (y)
31 LOAD_CONST 0 (None)
34 RETURN_VALUE
>>> dis.dis(b)
2 0 LOAD_CONST 6 ((1, 2, 3, 4, 5))
3 STORE_FAST 0 (x)
3 6 LOAD_FAST 0 (x)
9 LOAD_CONST 2 (2)
12 BINARY_SUBSCR
13 STORE_FAST 1 (y)
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
``` |
68,633 | <p>I need a Regex that will match a java method declaration. I have come up with one that will match a method declaration, but it requires the opening bracket of the method to be on the same line as the declaration. If you have any suggestions to improve my regex or simply have a better one then please submit an answer.</p>
<p>Here is my regex: <code>"\w+ +\w+ *\(.*\) *\{"</code></p>
<p>For those who do not know what a java method looks like I'll provide a basic one:</p>
<pre><code>int foo()
{
}
</code></pre>
<p>There are several optional parts to java methods that may be added as well but those are the only parts that a method is guaranteed to have.</p>
<p>Update:
My current Regex is <code>"\w+ +\w+ *\([^\)]*\) *\{"</code> so as to prevent the situation that Mike and adkom described.</p>
| [
{
"answer_id": 68669,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 3,
"selected": true,
"text": "<p>Have you considered matching the actual possible keywords? such as:</p>\n\n<pre><code>(?:(?:public)|(?:private)|(?:static... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340/"
] | I need a Regex that will match a java method declaration. I have come up with one that will match a method declaration, but it requires the opening bracket of the method to be on the same line as the declaration. If you have any suggestions to improve my regex or simply have a better one then please submit an answer.
Here is my regex: `"\w+ +\w+ *\(.*\) *\{"`
For those who do not know what a java method looks like I'll provide a basic one:
```
int foo()
{
}
```
There are several optional parts to java methods that may be added as well but those are the only parts that a method is guaranteed to have.
Update:
My current Regex is `"\w+ +\w+ *\([^\)]*\) *\{"` so as to prevent the situation that Mike and adkom described. | Have you considered matching the actual possible keywords? such as:
```
(?:(?:public)|(?:private)|(?:static)|(?:protected)\s+)*
```
It might be a bit more likely to match correctly, though it might also make the regex harder to read... |
68,640 | <p>Is it possible in C# to have a Struct with a member variable which is a Class type? If so, where does the information get stored, on the Stack, the Heap, or both?</p>
| [
{
"answer_id": 68681,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 6,
"selected": true,
"text": "<p>Yes, you can. The pointer to the class member variable is stored <strike>on the stack</strike> with the rest of the s... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10722/"
] | Is it possible in C# to have a Struct with a member variable which is a Class type? If so, where does the information get stored, on the Stack, the Heap, or both? | Yes, you can. The pointer to the class member variable is stored on the stack with the rest of the struct's values, and the class instance's data is stored on the heap.
Structs can also contain class definitions as members (inner classes).
Here's some really useless code that at least compiles and runs to show that it's possible:
```
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MyStr m = new MyStr();
m.Foo();
MyStr.MyStrInner mi = new MyStr.MyStrInner();
mi.Bar();
Console.ReadLine();
}
}
public class Myclass
{
public int a;
}
struct MyStr
{
Myclass mc;
public void Foo()
{
mc = new Myclass();
mc.a = 1;
}
public class MyStrInner
{
string x = "abc";
public string Bar()
{
return x;
}
}
}
}
``` |
68,645 | <p>How do I create class (i.e. <a href="https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods" rel="nofollow noreferrer">static</a>) variables or methods in Python?</p>
| [
{
"answer_id": 68672,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 12,
"selected": true,
"text": "<p>Variables declared inside the class definition, but not inside a method are class or static variables:</p>\n<pre><cod... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2246/"
] | How do I create class (i.e. [static](https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods)) variables or methods in Python? | Variables declared inside the class definition, but not inside a method are class or static variables:
```
>>> class MyClass:
... i = 3
...
>>> MyClass.i
3
```
As @[millerdev](https://stackoverflow.com/questions/68645/static-class-variables-in-python#answer-69067) points out, this creates a class-level `i` variable, but this is distinct from any instance-level `i` variable, so you could have
```
>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)
```
This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.
See [what the Python tutorial has to say on the subject of classes and class objects](https://docs.python.org/3/tutorial/classes.html#class-objects).
@Steve Johnson has already answered regarding [static methods](http://web.archive.org/web/20090214211613/http://pyref.infogami.com/staticmethod), also documented under ["Built-in Functions" in the Python Library Reference](https://docs.python.org/3/library/functions.html#staticmethod).
```
class C:
@staticmethod
def f(arg1, arg2, ...): ...
```
@beidy recommends [classmethod](https://docs.python.org/3/library/functions.html#classmethod)s over staticmethod, as the method then receives the class type as the first argument. |
68,651 | <p>If I pass PHP variables with <code>.</code> in their names via $_GET PHP auto-replaces them with <code>_</code> characters. For example:</p>
<pre><code><?php
echo "url is ".$_SERVER['REQUEST_URI']."<p>";
echo "x.y is ".$_GET['x.y'].".<p>";
echo "x_y is ".$_GET['x_y'].".<p>";
</code></pre>
<p>... outputs the following:</p>
<pre><code>url is /SpShipTool/php/testGetUrl.php?x.y=a.b
x.y is .
x_y is a.b.
</code></pre>
<p>... my question is this: is there <strong>any</strong> way I can get this to stop? Cannot for the life of me figure out what I've done to deserve this</p>
<p>PHP version I'm running with is 5.2.4-2ubuntu5.3.</p>
| [
{
"answer_id": 68710,
"author": "Jeremy Privett",
"author_id": 560,
"author_profile": "https://Stackoverflow.com/users/560",
"pm_score": 2,
"selected": false,
"text": "<p>The reason this happens is because of PHP's old register_globals functionality. The . character is not a valid charac... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If I pass PHP variables with `.` in their names via $\_GET PHP auto-replaces them with `_` characters. For example:
```
<?php
echo "url is ".$_SERVER['REQUEST_URI']."<p>";
echo "x.y is ".$_GET['x.y'].".<p>";
echo "x_y is ".$_GET['x_y'].".<p>";
```
... outputs the following:
```
url is /SpShipTool/php/testGetUrl.php?x.y=a.b
x.y is .
x_y is a.b.
```
... my question is this: is there **any** way I can get this to stop? Cannot for the life of me figure out what I've done to deserve this
PHP version I'm running with is 5.2.4-2ubuntu5.3. | Here's PHP.net's explanation of why it does it:
>
> ### Dots in incoming variable names
>
>
> Typically, PHP does not alter the
> names of variables when they are
> passed into a script. However, it
> should be noted that the dot (period,
> full stop) is not a valid character in
> a PHP variable name. For the reason,
> look at it:
>
>
>
> ```
> <?php
> $varname.ext; /* invalid variable name */
> ?>
>
> ```
>
> Now, what
> the parser sees is a variable named
> $varname, followed by the string
> concatenation operator, followed by
> the barestring (i.e. unquoted string
> which doesn't match any known key or
> reserved words) 'ext'. Obviously, this
> doesn't have the intended result.
>
>
> For this reason, it is important to
> note that PHP will automatically
> replace any dots in incoming variable
> names with underscores.
>
>
>
That's from <http://ca.php.net/variables.external>.
Also, according to [this comment](http://ca.php.net/manual/en/language.variables.external.php#81080) these other characters are converted to underscores:
>
> The full list of field-name characters that PHP converts to \_ (underscore) is the following (not just dot):
>
>
> * chr(32) ( ) (space)
> * chr(46) (.) (dot)
> * chr(91) ([) (open square bracket)
> * chr(128) - chr(159) (various)
>
>
>
So it looks like you're stuck with it, so you'll have to convert the underscores back to dots in your script using [dawnerd's suggestion](https://stackoverflow.com/questions/68651/can-i-get-php-to-stop-replacing-characters-in-get-or-post-arrays#68667) (I'd just use [str\_replace](http://php.net/str_replace) though.) |
68,666 | <p>Why does the following code sometimes causes an Exception with the contents "CLIPBRD_E_CANT_OPEN":</p>
<pre><code>Clipboard.SetText(str);
</code></pre>
<p>This usually occurs the first time the Clipboard is used in the application and not after that.</p>
| [
{
"answer_id": 68857,
"author": "Tadmas",
"author_id": 3750,
"author_profile": "https://Stackoverflow.com/users/3750",
"pm_score": 6,
"selected": true,
"text": "<p>Actually, I think this is the <a href=\"https://cloudblogs.microsoft.com/enterprisemobility/2006/11/20/why-does-my-shared-cl... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10784/"
] | Why does the following code sometimes causes an Exception with the contents "CLIPBRD\_E\_CANT\_OPEN":
```
Clipboard.SetText(str);
```
This usually occurs the first time the Clipboard is used in the application and not after that. | Actually, I think this is the [fault of the Win32 API](https://cloudblogs.microsoft.com/enterprisemobility/2006/11/20/why-does-my-shared-clipboard-not-work-part-2/).
To set data in the clipboard, you have to [open it](http://msdn.microsoft.com/en-us/library/ms649048(VS.85).aspx) first. Only one process can have the clipboard open at a time. So, when you check, if another process has the clipboard open *for any reason*, your attempt to open it will fail.
It just so happens that Terminal Services keeps track of the clipboard, and on older versions of Windows (pre-Vista), you have to open the clipboard to see what's inside... which ends up blocking you. The only solution is to wait until Terminal Services closes the clipboard and try again.
It's important to realize that this is not specific to Terminal Services, though: it can happen with anything. Working with the clipboard in Win32 is a giant race condition. But, since by design you're only supposed to muck around with the clipboard in response to user input, this usually doesn't present a problem. |
68,677 | <p>I'm using SQL Server 2000 to print out some values from a table using <code>PRINT</code>. With most non-string data, I can cast to nvarchar to be able to print it, but binary values attempt to convert using the bit representation of characters. For example:</p>
<pre><code>DECLARE @binvalue binary(4)
SET @binvalue = 0x12345678
PRINT CAST(@binvalue AS nvarchar)
</code></pre>
<p>Expected:</p>
<blockquote>
<p>0x12345678</p>
</blockquote>
<p>Instead, it prints two gibberish characters.</p>
<p>How can I print the value of binary data? Is there a built-in or do I need to roll my own?</p>
<p>Update: This isn't the only value on the line, so I can't just PRINT @binvalue. It's something more like PRINT N'other stuff' + ???? + N'more stuff'. Not sure if that makes a difference: I didn't try just PRINT @binvalue by itself.</p>
| [
{
"answer_id": 68858,
"author": "Ricardo C",
"author_id": 232589,
"author_profile": "https://Stackoverflow.com/users/232589",
"pm_score": 2,
"selected": false,
"text": "<pre><code>DECLARE @binvalue binary(4)\nSET @binvalue = 0x61000000\nPRINT @binvalue \nPRINT cast('a' AS binary(4))\nPRI... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3750/"
] | I'm using SQL Server 2000 to print out some values from a table using `PRINT`. With most non-string data, I can cast to nvarchar to be able to print it, but binary values attempt to convert using the bit representation of characters. For example:
```
DECLARE @binvalue binary(4)
SET @binvalue = 0x12345678
PRINT CAST(@binvalue AS nvarchar)
```
Expected:
>
> 0x12345678
>
>
>
Instead, it prints two gibberish characters.
How can I print the value of binary data? Is there a built-in or do I need to roll my own?
Update: This isn't the only value on the line, so I can't just PRINT @binvalue. It's something more like PRINT N'other stuff' + ???? + N'more stuff'. Not sure if that makes a difference: I didn't try just PRINT @binvalue by itself. | If you were on Sql Server 2005 you could use this:
```
print master.sys.fn_varbintohexstr(@binvalue)
```
I don't think that exists on 2000, though, so you might have to roll your own. |
68,688 | <p>What is the best solution of defaultButton and "Enter key pressed" for ASP.NET 2.0-3.5 forms?</p>
| [
{
"answer_id": 68700,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 2,
"selected": false,
"text": "<p>Just add the \"defaultbutton\" attribute to the form and set it to the ID of the button you want to be the default. </p>\n\n... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10778/"
] | What is the best solution of defaultButton and "Enter key pressed" for ASP.NET 2.0-3.5 forms? | Just add the "defaultbutton" attribute to the form and set it to the ID of the button you want to be the default.
```
<form defaultbutton="button1" runat="server">
<asp:textbox id="textbox1" runat="server"/>
<asp:button id="button1" text="Button1" runat="server"/>
</form>
```
NOTE: This only works in ASP.NET 2.0+ |
68,711 | <p>any idea how if the following is possible in PHP as a single line ?:</p>
<pre><code><?php
$firstElement = functionThatReturnsAnArray()[0];
</code></pre>
<p>... It doesn't seem to 'take'. I need to do this as a 2-stepper:</p>
<pre><code><?php
$allElements = functionThatReturnsAnArray();
$firstElement = $allElements[0];
</code></pre>
<p>... just curious - other languages I play with allow things like this, and I'm lazy enoug to miss this in PHP ... any insight appreciated ...</p>
| [
{
"answer_id": 68716,
"author": "owenmarshall",
"author_id": 9806,
"author_profile": "https://Stackoverflow.com/users/9806",
"pm_score": 3,
"selected": false,
"text": "<p>Unfortunately, that is not possible with PHP. You have to use two lines to do it.</p>\n"
},
{
"answer_id": 68... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | any idea how if the following is possible in PHP as a single line ?:
```
<?php
$firstElement = functionThatReturnsAnArray()[0];
```
... It doesn't seem to 'take'. I need to do this as a 2-stepper:
```
<?php
$allElements = functionThatReturnsAnArray();
$firstElement = $allElements[0];
```
... just curious - other languages I play with allow things like this, and I'm lazy enoug to miss this in PHP ... any insight appreciated ... | Try:
```
<?php
$firstElement = reset(functionThatReturnsAnArray());
```
If you're just looking for the first element of the array. |
68,750 | <p>This should hopefully be a simple one.</p>
<p>I would like to add an extension method to the System.Web.Mvc.ViewPage< T > class.</p>
<p>How should this extension method look?</p>
<p>My first intuitive thought is something like this:</p>
<pre><code>namespace System.Web.Mvc
{
public static class ViewPageExtensions
{
public static string GetDefaultPageTitle(this ViewPage<Type> v)
{
return "";
}
}
}
</code></pre>
<p><strong>Solution</strong></p>
<p>The general solution is <a href="https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772">this answer</a>.</p>
<p>The specific solution to extending the System.Web.Mvc.ViewPage class is <a href="https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68802">my answer</a> below, which started from the <a href="https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772">general solution</a>.</p>
<p>The difference is in the specific case you need both a generically typed method declaration AND a statement to enforce the generic type as a reference type.</p>
| [
{
"answer_id": 68772,
"author": "David Thibault",
"author_id": 5903,
"author_profile": "https://Stackoverflow.com/users/5903",
"pm_score": 5,
"selected": true,
"text": "<p>I don't have VS installed on my current machine, but I think the syntax would be:</p>\n\n<pre><code>namespace System... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | This should hopefully be a simple one.
I would like to add an extension method to the System.Web.Mvc.ViewPage< T > class.
How should this extension method look?
My first intuitive thought is something like this:
```
namespace System.Web.Mvc
{
public static class ViewPageExtensions
{
public static string GetDefaultPageTitle(this ViewPage<Type> v)
{
return "";
}
}
}
```
**Solution**
The general solution is [this answer](https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772).
The specific solution to extending the System.Web.Mvc.ViewPage class is [my answer](https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68802) below, which started from the [general solution](https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772).
The difference is in the specific case you need both a generically typed method declaration AND a statement to enforce the generic type as a reference type. | I don't have VS installed on my current machine, but I think the syntax would be:
```
namespace System.Web.Mvc
{
public static class ViewPageExtensions
{
public static string GetDefaultPageTitle<T>(this ViewPage<T> v)
{
return "";
}
}
}
``` |
68,774 | <p>I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way?</p>
| [
{
"answer_id": 68796,
"author": "The.Anti.9",
"author_id": 2128,
"author_profile": "https://Stackoverflow.com/users/2128",
"pm_score": 7,
"selected": true,
"text": "<p>Opening sockets in python is pretty simple. You really just need something like this:</p>\n\n<pre><code>import socket\ns... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324/"
] | I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way? | Opening sockets in python is pretty simple. You really just need something like this:
```
import socket
sock = socket.socket()
sock.connect((address, port))
```
and then you can `send()` and `recv()` like any other socket |
68,843 | <p>How does the compiler know the prototype of sleep function or even printf function, when I did not include any header file in the first place?</p>
<p>Moreover, if I specify <code>sleep(1,1,"xyz")</code> or any arbitrary number of arguments, the compiler still compiles it.
But the strange thing is that gcc is able to find the definition of this function at link time, I don't understand how is this possible, because actual <code>sleep()</code> function takes a single argument only, but our program mentioned three arguments.</p>
<pre><code>/********************************/
int main()
{
short int i;
for(i = 0; i<5; i++)
{
printf("%d",i);`print("code sample");`
sleep(1);
}
return 0;
}
</code></pre>
| [
{
"answer_id": 68861,
"author": "Jason Dagit",
"author_id": 5113,
"author_profile": "https://Stackoverflow.com/users/5113",
"pm_score": 2,
"selected": false,
"text": "<p>C will guess int for unknown types. So, it probably thinks sleep has this prototype:</p>\n\n<pre><code>int sleep(int)... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How does the compiler know the prototype of sleep function or even printf function, when I did not include any header file in the first place?
Moreover, if I specify `sleep(1,1,"xyz")` or any arbitrary number of arguments, the compiler still compiles it.
But the strange thing is that gcc is able to find the definition of this function at link time, I don't understand how is this possible, because actual `sleep()` function takes a single argument only, but our program mentioned three arguments.
```
/********************************/
int main()
{
short int i;
for(i = 0; i<5; i++)
{
printf("%d",i);`print("code sample");`
sleep(1);
}
return 0;
}
``` | Lacking a more specific prototype, the compiler will assume that the function returns int and takes whatever number of arguments you provide.
Depending on the CPU architecture arguments can be passed in registers (for example, a0 through a3 on MIPS) or by pushing them onto the stack as in the original x86 calling convention. In either case, passing extra arguments is harmless. The called function won't use the registers passed in nor reference the extra arguments on the stack, but nothing bad happens.
Passing in fewer arguments is more problematic. The called function will use whatever garbage happened to be in the appropriate register or stack location, and hijinks may ensue. |
68,993 | <p>Say I have a line in an emacs buffer that looks like this:</p>
<pre><code>foo -option1 value1 -option2 value2 -option3 value3 \
-option4 value4 ...
</code></pre>
<p>I want it to look like this:</p>
<pre><code>foo -option1 value1 \
-option2 value2 \
-option3 value3 \
-option4 value4 \
...
</code></pre>
<p>I want each option/value pair on a separate line. I also want those subsequent lines indented appropriately according to mode rather than to add a fixed amount of whitespace. I would prefer that the code work on the current block, stopping at the first non-blank line or line that does not contain an option/value pair though I could settle for it working on a selected region. </p>
<p>Anybody know of an elisp function to do this? </p>
| [
{
"answer_id": 69032,
"author": "Jason Dagit",
"author_id": 5113,
"author_profile": "https://Stackoverflow.com/users/5113",
"pm_score": 1,
"selected": false,
"text": "<p>In this case I would use a macro. You can start recording a macro with C-x (, and stop recording it with C-x ). When... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7432/"
] | Say I have a line in an emacs buffer that looks like this:
```
foo -option1 value1 -option2 value2 -option3 value3 \
-option4 value4 ...
```
I want it to look like this:
```
foo -option1 value1 \
-option2 value2 \
-option3 value3 \
-option4 value4 \
...
```
I want each option/value pair on a separate line. I also want those subsequent lines indented appropriately according to mode rather than to add a fixed amount of whitespace. I would prefer that the code work on the current block, stopping at the first non-blank line or line that does not contain an option/value pair though I could settle for it working on a selected region.
Anybody know of an elisp function to do this? | Nobody had what I was looking for so I decided to dust off my elisp manual and do it myself. This seems to work well enough, though the output isn't precisely what I asked for. In this version the first option goes on a line by itself instead of staying on the first line like in my original question.
```lisp
(defun tcl-multiline-options ()
"spread option/value pairs across multiple lines with continuation characters"
(interactive)
(save-excursion
(tcl-join-continuations)
(beginning-of-line)
(while (re-search-forward " -[^ ]+ +" (line-end-position) t)
(goto-char (match-beginning 0))
(insert " \\\n")
(goto-char (+(match-end 0) 3))
(indent-according-to-mode)
(forward-sexp))))
(defun tcl-join-continuations ()
"join multiple continuation lines into a single physical line"
(interactive)
(while (progn (end-of-line) (char-equal (char-before) ?\\))
(forward-line 1))
(while (save-excursion (end-of-line 0) (char-equal (char-before) ?\\))
(end-of-line 0)
(delete-char -1)
(delete-char 1)
(fixup-whitespace)))
``` |
68,999 | <p>I'm using a Java socket, connected to a server.
If I send a HEADER http request, how can I measure the response time from the server? Must I use a provided java timer, or is there an easier way?</p>
<p>I'm looking for a short answer, I don't want to use other protocols etc. Obviously do I neither want to have a solution that ties my application to a specific OS. Please people, IN-CODE solutions only. </p>
| [
{
"answer_id": 69105,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 4,
"selected": false,
"text": "<p>You can use time and curl and time on the command-line. The -I argument for curl instructs it to only request the header.<... | 2008/09/16 | [
"https://Stackoverflow.com/questions/68999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10889/"
] | I'm using a Java socket, connected to a server.
If I send a HEADER http request, how can I measure the response time from the server? Must I use a provided java timer, or is there an easier way?
I'm looking for a short answer, I don't want to use other protocols etc. Obviously do I neither want to have a solution that ties my application to a specific OS. Please people, IN-CODE solutions only. | I would say it depends on what exact interval you are trying measure, the amount of time from the last byte of the request that you send until the first byte of the response that you receive? Or until the entire response is received? Or are you trying to measure the server-side time only?
If you're trying to measure the server side processing time only, you're going to have a difficult time factoring out the amount of time spent in network transit for your request to arrive and the response to return. Otherwise, since you're managing the request yourself through a Socket, you can measure the elapsed time between any two moments by checking the System timer and computing the difference. For example:
```
public void sendHttpRequest(byte[] requestData, Socket connection) {
long startTime = System.nanoTime();
writeYourRequestData(connection.getOutputStream(), requestData);
byte[] responseData = readYourResponseData(connection.getInputStream());
long elapsedTime = System.nanoTime() - startTime;
System.out.println("Total elapsed http request/response time in nanoseconds: " + elapsedTime);
}
```
This code would measure the time from when you begin writing out your request to when you finish receiving the response, and print the result (assuming you have your specific read/write methods implemented). |
69,000 | <p>I have a WPF application in VS 2008 with some web service references. For varying reasons (max message size, authentication methods) I need to manually define a number of settings in the WPF client's app.config for the service bindings.</p>
<p>Unfortunately, this means that when I update the service references in the project we end up with a mess - multiple bindings and endpoints. Visual Studio creates new bindings and endpoints with a numeric suffix (ie "Service1" as a duplicate of "Service"), resulting in an invalid configuration as there may only be a single binding per service reference in a project.</p>
<p>This is easy to duplicate - just create a simple "Hello World" ASP.Net web service and WPF application in a solution, change the maxBufferSize and maxReceivedMessageSize in the app.config binding and then update the service reference.</p>
<p>At the moment we are working around this by simply undoing checkout on the app.config after updating the references but I can't help but think there must be a better way!</p>
<p>Also, the settings we need to manually change are:</p>
<pre><code><security mode="TransportCredentialOnly">
<transport clientCredentialType="Ntlm" />
</security>
</code></pre>
<p>and:</p>
<pre><code><binding maxBufferSize="655360" maxReceivedMessageSize="655360" />
</code></pre>
<p>We use a service factory class so if these settings are somehow able to be set programmatically that would work, although the properties don't seem to be exposed.</p>
| [
{
"answer_id": 69154,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 0,
"selected": false,
"text": "<p>Somehow I prefer using svcutil.exe directly than to use the \"Add Service Reference\" feature of Visual Studio :P This is ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10890/"
] | I have a WPF application in VS 2008 with some web service references. For varying reasons (max message size, authentication methods) I need to manually define a number of settings in the WPF client's app.config for the service bindings.
Unfortunately, this means that when I update the service references in the project we end up with a mess - multiple bindings and endpoints. Visual Studio creates new bindings and endpoints with a numeric suffix (ie "Service1" as a duplicate of "Service"), resulting in an invalid configuration as there may only be a single binding per service reference in a project.
This is easy to duplicate - just create a simple "Hello World" ASP.Net web service and WPF application in a solution, change the maxBufferSize and maxReceivedMessageSize in the app.config binding and then update the service reference.
At the moment we are working around this by simply undoing checkout on the app.config after updating the references but I can't help but think there must be a better way!
Also, the settings we need to manually change are:
```
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Ntlm" />
</security>
```
and:
```
<binding maxBufferSize="655360" maxReceivedMessageSize="655360" />
```
We use a service factory class so if these settings are somehow able to be set programmatically that would work, although the properties don't seem to be exposed. | Create a .Bat file which uses svcutil, for proxygeneration, that has the settings that is right for your project. It's fairly easy. Clicking on the batfile, to generate new proxyfiles whenever the interface have been changed is easy.
The batch can then later be used in automated builds. Then you only need to set up the app.config (or web.config) once. We generally separate the different configs for different environments, such as dev, test prod.
Example (watch out for linebreaks):
```
REM generate meta data
call "SVCUTIL.EXE" /t:metadata "MyProject.dll" /reference:"MyReference.dll"
REM making sure the file is writable
attrib -r "MyServiceProxy.cs"
REM create new proxy file
call "SVCUTIL.EXE" /t:code *.wsdl *.xsd /serializable /serializer:Auto /collectionType:System.Collections.Generic.List`1 /out:"MyServiceProxy.cs" /namespace:*,MY.Name.Space /reference:"MyReference.dll"
```
:)
//W |
69,030 | <p>I have a script for OS X 10.5 that focuses the Search box in the Help menu of any application. I have it on a key combination and, much like Spotlight, I want it to toggle when I run the script. So, I want to detect if the search box is already focused for typing, and if so, type Esc instead of clicking the Help menu.</p>
<p>Here is the script as it stands now:</p>
<pre><code>tell application "System Events"
tell (first process whose frontmost is true)
set helpMenuItem to menu bar item "Help" of menu bar 1
click helpMenuItem
end tell
end tell
</code></pre>
<p>And I'm thinking of something like this:</p>
<pre><code>tell application "System Events"
tell (first process whose frontmost is true)
set helpMenuItem to menu bar item "Help" of menu bar 1
set searchBox to menu item 1 of menu of helpMenuItem
if (searchBox's focused) = true then
key code 53 -- type esc
else
click helpMenuItem
end if
end tell
end tell
</code></pre>
<p>... but I get this error:</p>
<blockquote>
<p>Can’t get focused of {menu item 1 of menu "Help" of menu bar item "Help" of menu bar 1 of application process "Script Editor" of application "System Events"}.</p>
</blockquote>
<p>So is there a way I can get my script to detect whether the search box is already focused?</p>
<hr>
<p>I solved my problem by <a href="https://stackoverflow.com/questions/69391/">working around it</a>. I still don't know how to check if a menu item is selected though, so I will leave this topic open.</p>
| [
{
"answer_id": 69404,
"author": "tjw",
"author_id": 11029,
"author_profile": "https://Stackoverflow.com/users/11029",
"pm_score": 3,
"selected": true,
"text": "<p>Using /Developer/Applications/Utilities/Accessibility Tools/Accessibility Inspector.app you can use the built-in accessibilit... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10906/"
] | I have a script for OS X 10.5 that focuses the Search box in the Help menu of any application. I have it on a key combination and, much like Spotlight, I want it to toggle when I run the script. So, I want to detect if the search box is already focused for typing, and if so, type Esc instead of clicking the Help menu.
Here is the script as it stands now:
```
tell application "System Events"
tell (first process whose frontmost is true)
set helpMenuItem to menu bar item "Help" of menu bar 1
click helpMenuItem
end tell
end tell
```
And I'm thinking of something like this:
```
tell application "System Events"
tell (first process whose frontmost is true)
set helpMenuItem to menu bar item "Help" of menu bar 1
set searchBox to menu item 1 of menu of helpMenuItem
if (searchBox's focused) = true then
key code 53 -- type esc
else
click helpMenuItem
end if
end tell
end tell
```
... but I get this error:
>
> Can’t get focused of {menu item 1 of menu "Help" of menu bar item "Help" of menu bar 1 of application process "Script Editor" of application "System Events"}.
>
>
>
So is there a way I can get my script to detect whether the search box is already focused?
---
I solved my problem by [working around it](https://stackoverflow.com/questions/69391/). I still don't know how to check if a menu item is selected though, so I will leave this topic open. | Using /Developer/Applications/Utilities/Accessibility Tools/Accessibility Inspector.app you can use the built-in accessibility system to look at properties of the UI element under the mouse. Take special note of the cmd-F7 action to lock focus on an element and the Refresh button. Sadly the element and property names don't directly match those in the script suite, but you can look at the dictionary for System Events or usually guess the right terminology.
Using this you can determine two things. First, the `focused` property isn't on the `menu item`, but rather there is a `text field` within the `menu item` that is focused. Second, the menu item has a `selected` property.
With this, I came up with:
```
tell application "System Events"
tell (first process whose frontmost is true)
set helpMenuItem to menu bar item "Help" of menu bar 1
-- Use reference form to avoid building intermediate object specifiers, which Accessibility apparently isn't good at resolving after the fact.
set searchBox to a reference to menu item 1 of menu of helpMenuItem
set searchField to a reference to text field 1 of searchBox
if searchField's focused is true then
key code 53 -- type esc
else
click helpMenuItem
end if
end tell
end tell
```
Though this still doesn't work. The key event isn't firing as far as I can tell, so something may still be hinky with the `focused` property on the text field.
Anyway, your `click` again solution seems much easier. |
69,068 | <p>How can I split long commands over multiple lines in a batch file?</p>
| [
{
"answer_id": 69079,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 11,
"selected": true,
"text": "<p>You can break up long lines with the caret <code>^</code> as long as you remember that the caret and the newline following i... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How can I split long commands over multiple lines in a batch file? | You can break up long lines with the caret `^` as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. *([More on that below.](https://stackoverflow.com/a/21000752/157247))*
Example:
```
copy file1.txt file2.txt
```
would be written as:
```
copy file1.txt^
file2.txt
``` |
69,089 | <p>We have a web application that uses SQL Server 2008 as the database. Our users are able to do full-text searches on particular columns in the database. SQL Server's full-text functionality does not seem to provide support for hit highlighting. Do we need to build this ourselves or is there perhaps some library or knowledge around on how to do this? </p>
<p>BTW the application is written in C# so a .Net solution would be ideal but not necessary as we could translate.</p>
| [
{
"answer_id": 74932,
"author": "WIDBA",
"author_id": 10868,
"author_profile": "https://Stackoverflow.com/users/10868",
"pm_score": 1,
"selected": false,
"text": "<p>You might be missing the point of the database in this instance. Its job is to return the data to you that satisfies the ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1899/"
] | We have a web application that uses SQL Server 2008 as the database. Our users are able to do full-text searches on particular columns in the database. SQL Server's full-text functionality does not seem to provide support for hit highlighting. Do we need to build this ourselves or is there perhaps some library or knowledge around on how to do this?
BTW the application is written in C# so a .Net solution would be ideal but not necessary as we could translate. | Expanding on Ishmael's idea, it's not the final solution, but I think it's a good way to start.
Firstly we need to get the list of words that have been retrieved with the full-text engine:
```
declare @SearchPattern nvarchar(1000) = 'FORMSOF (INFLECTIONAL, " ' + @SearchString + ' ")'
declare @SearchWords table (Word varchar(100), Expansion_type int)
insert into @SearchWords
select distinct display_term, expansion_type
from sys.dm_fts_parser(@SearchPattern, 1033, 0, 0)
where special_term = 'Exact Match'
```
There is already quite a lot one can expand on, for example the search pattern is quite basic; also there are probably better ways to filter out the words you don't need, but it least it gives you a list of stem words etc. that would be matched by full-text search.
After you get the results you need, you can use RegEx to parse through the result set (or preferably only a subset to speed it up, although I haven't yet figured out a good way to do so). For this I simply use two while loops and a bunch of temporary table and variables:
```
declare @FinalResults table
while (select COUNT(*) from @PrelimResults) > 0
begin
select top 1 @CurrID = [UID], @Text = Text from @PrelimResults
declare @TextLength int = LEN(@Text )
declare @IndexOfDot int = CHARINDEX('.', REVERSE(@Text ), @TextLength - dbo.RegExIndexOf(@Text, '\b' + @FirstSearchWord + '\b') + 1)
set @Text = SUBSTRING(@Text, case @IndexOfDot when 0 then 0 else @TextLength - @IndexOfDot + 3 end, 300)
while (select COUNT(*) from @TempSearchWords) > 0
begin
select top 1 @CurrWord = Word from @TempSearchWords
set @Text = dbo.RegExReplace(@Text, '\b' + @CurrWord + '\b', '<b>' + SUBSTRING(@Text, dbo.RegExIndexOf(@Text, '\b' + @CurrWord + '\b'), LEN(@CurrWord) + 1) + '</b>')
delete from @TempSearchWords where Word = @CurrWord
end
insert into @FinalResults
select * from @PrelimResults where [UID] = @CurrID
delete from @PrelimResults where [UID] = @CurrID
end
```
**Several notes:**
1. Nested while loops probably aren't the most efficient way of doing it, however nothing else comes to mind. If I were to use cursors, it would essentially be the same thing?
2. `@FirstSearchWord` here to refers to the first instance in the text of one of the original search words, so essentially the text you are replacing is only going to be in the summary. Again, it's quite a basic method, some sort of text cluster finding algorithm would probably be handy.
3. To get RegEx in the first place, you need CLR user-defined functions. |
69,104 | <p>A J2ME client is sending HTTP POST requests with chunked transfer encoding.</p>
<p>When ASP.NET (in both IIS6 and WebDev.exe.server) tries to read the request it sets the Content-Length to 0. I guess this is ok because the Content-length is unknown when the request is loaded.</p>
<p>However, when I read the Request.InputStream to the end, it returns 0.</p>
<p>Here's the code I'm using to read the input stream.</p>
<pre><code>using (var reader = new StreamReader(httpRequestBodyStream, BodyTextEncoding)) {
string readString = reader.ReadToEnd();
Console.WriteLine("CharSize:" + readString.Length);
return BodyTextEncoding.GetBytes(readString);
}
</code></pre>
<p>I can simulate the behaiviour of the client with Fiddler, e.g.</p>
<p><strong>URL</strong>
<a href="http://localhost:15148/page.aspx" rel="nofollow noreferrer">http://localhost:15148/page.aspx</a></p>
<p><strong>Headers:</strong>
User-Agent: Fiddler
Transfer-Encoding: Chunked
Host: somesite.com:15148</p>
<p><strong>Body</strong>
rabbits rabbits rabbits rabbits. thanks for coming, it's been very useful!</p>
<p>My body reader from above will return a zero length byte array...lame...</p>
<p>Does anyone know how to enable chunked encoding on IIS and ASP.NET Development Server (cassini)?</p>
<p>I found <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;278998" rel="nofollow noreferrer">this script</a> for IIS but it isn't working.</p>
| [
{
"answer_id": 80576,
"author": "Andrew",
"author_id": 15127,
"author_profile": "https://Stackoverflow.com/users/15127",
"pm_score": 1,
"selected": false,
"text": "<p>That url does not work any more, so it's hard to test this directly. I wondered if this would work, and google turned up... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/209/"
] | A J2ME client is sending HTTP POST requests with chunked transfer encoding.
When ASP.NET (in both IIS6 and WebDev.exe.server) tries to read the request it sets the Content-Length to 0. I guess this is ok because the Content-length is unknown when the request is loaded.
However, when I read the Request.InputStream to the end, it returns 0.
Here's the code I'm using to read the input stream.
```
using (var reader = new StreamReader(httpRequestBodyStream, BodyTextEncoding)) {
string readString = reader.ReadToEnd();
Console.WriteLine("CharSize:" + readString.Length);
return BodyTextEncoding.GetBytes(readString);
}
```
I can simulate the behaiviour of the client with Fiddler, e.g.
**URL**
<http://localhost:15148/page.aspx>
**Headers:**
User-Agent: Fiddler
Transfer-Encoding: Chunked
Host: somesite.com:15148
**Body**
rabbits rabbits rabbits rabbits. thanks for coming, it's been very useful!
My body reader from above will return a zero length byte array...lame...
Does anyone know how to enable chunked encoding on IIS and ASP.NET Development Server (cassini)?
I found [this script](http://support.microsoft.com/default.aspx?scid=kb;en-us;278998) for IIS but it isn't working. | Seems to be official: [Cassini does not support `Transfer-Encoding: chunked` requests.](http://msdn.microsoft.com/en-us/library/ee960144.aspx)
>
> By default, the client sends large
> binary streams by using a chunked HTTP
> Transfer-Encoding. **Because the ASP.NET
> Development Server does not support
> this kind of encoding**, you cannot use
> this Web server to host a streaming
> data service that must accept large
> binary streams.
>
>
> |
69,107 | <p>What is the best way to refactor the attached code to accommodate multiple email addresses?</p>
<p>The attached HTML/jQuery is complete and works for the first email address. I can setup the other two by copy/pasting and changing the code. But I would like to just refactor the existing code to handle multiple email address fields.</p>
<pre><code><html>
<head>
<script src="includes/jquery/jquery-1.2.6.min.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function() {
var validateUsername = $('#Email_Address_Status_Icon_1');
$('#Email_Address_1').keyup(function() {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validateUsername.removeClass('error').html('Validating Email');
this.timer = setTimeout(function() {
if (IsEmail(t.value)) {
validateUsername.html('Valid Email');
} else {
validateUsername.html('Not a valid Email');
};
}, 200);
this.lastValue = this.value;
}
});
});
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (regex.test(email)) return true;
else return false;
}
</script>
</head>
<body>
<div>
<label for="Email_Address_1">Friend #1</label></div>
<input type="text" ID="Email_Address_1">
<span id="Email_Address_Status_Icon_1"></span>
</div>
<div>
<label for="Email_Address_2">Friend #2</label></div>
<input type="text" id="Email_Address_2">
<span id="Email_Address_Status_Icon_2"></span>
</div>
<div>
<label for="Email_Address_3">Friend #3</label></div>
<input type="text" id="Email_Address_3">
<span id="Email_Address_Status_Icon_3"></span>
</div>
</form>
</body>
</html>
</code></pre>
| [
{
"answer_id": 69148,
"author": "Pandincus",
"author_id": 2273,
"author_profile": "https://Stackoverflow.com/users/2273",
"pm_score": 3,
"selected": true,
"text": "<p>Instead of using IDs for your email fields, you can give them each a class:</p>\n\n<pre><code><div>\n <label ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] | What is the best way to refactor the attached code to accommodate multiple email addresses?
The attached HTML/jQuery is complete and works for the first email address. I can setup the other two by copy/pasting and changing the code. But I would like to just refactor the existing code to handle multiple email address fields.
```
<html>
<head>
<script src="includes/jquery/jquery-1.2.6.min.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function() {
var validateUsername = $('#Email_Address_Status_Icon_1');
$('#Email_Address_1').keyup(function() {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validateUsername.removeClass('error').html('Validating Email');
this.timer = setTimeout(function() {
if (IsEmail(t.value)) {
validateUsername.html('Valid Email');
} else {
validateUsername.html('Not a valid Email');
};
}, 200);
this.lastValue = this.value;
}
});
});
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (regex.test(email)) return true;
else return false;
}
</script>
</head>
<body>
<div>
<label for="Email_Address_1">Friend #1</label></div>
<input type="text" ID="Email_Address_1">
<span id="Email_Address_Status_Icon_1"></span>
</div>
<div>
<label for="Email_Address_2">Friend #2</label></div>
<input type="text" id="Email_Address_2">
<span id="Email_Address_Status_Icon_2"></span>
</div>
<div>
<label for="Email_Address_3">Friend #3</label></div>
<input type="text" id="Email_Address_3">
<span id="Email_Address_Status_Icon_3"></span>
</div>
</form>
</body>
</html>
``` | Instead of using IDs for your email fields, you can give them each a class:
```
<div>
<label for="Email_Address_1">Friend #1</label></div>
<input type="text" class="email">
<span></span>
</div>
<div>
<label for="Email_Address_2">Friend #2</label></div>
<input type="text" class="email">
<span></span>
</div>
<div>
<label for="Email_Address_3">Friend #3</label></div>
<input type="text" class="email">
<span></span>
</div>
```
Then, instead of selecting $("#Email\_Address\_Status\_Icon\_1"), you can select $("input.email"), which would give you a jQuery wrapped set of all input elements of class email.
Finally, instead of referring to the status icon explicitly with an id, you could simply say:
```
$(this).next("span").removeClass('error').html('Validating Email');
```
'this' would be the email field, so 'this.next()' would give you its next sibling. We apply the "span" selector on top of that just to be sure we're getting what we intend to. $(this).next() would work the same way.
This way, you are referring to the status icon in a relative manner.
Hope this helps! |
69,115 | <p>Below is my current char* to hex string function. I wrote it as an exercise in bit manipulation. It takes ~7ms on a AMD Athlon MP 2800+ to hexify a 10 million byte array. Is there any trick or other way that I am missing?</p>
<p>How can I make this faster?</p>
<p>Compiled with -O3 in g++</p>
<pre><code>static const char _hex2asciiU_value[256][2] =
{ {'0','0'}, {'0','1'}, /* snip..., */ {'F','E'},{'F','F'} };
std::string char_to_hex( const unsigned char* _pArray, unsigned int _len )
{
std::string str;
str.resize(_len*2);
char* pszHex = &str[0];
const unsigned char* pEnd = _pArray + _len;
clock_t stick, etick;
stick = clock();
for( const unsigned char* pChar = _pArray; pChar != pEnd; pChar++, pszHex += 2 ) {
pszHex[0] = _hex2asciiU_value[*pChar][0];
pszHex[1] = _hex2asciiU_value[*pChar][1];
}
etick = clock();
std::cout << "ticks to hexify " << etick - stick << std::endl;
return str;
}
</code></pre>
<p><strong>Updates</strong></p>
<p>Added timing code</p>
<p><a href="https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#69126">Brian R. Bondy</a>: replace the std::string with a heap alloc'd buffer and change ofs*16 to ofs << 4 - however the heap allocated buffer seems to slow it down? - result ~11ms</p>
<p><a href="https://stackoverflow.com/questions/69115/#69305">Antti Sykäri</a>:replace inner loop with </p>
<pre><code> int upper = *pChar >> 4;
int lower = *pChar & 0x0f;
pszHex[0] = pHex[upper];
pszHex[1] = pHex[lower];
</code></pre>
<p>result ~8ms</p>
<p><a href="https://stackoverflow.com/questions/69115?sort=votes#69218">Robert</a>: replace <code>_hex2asciiU_value</code> with a full 256-entry table, sacrificing memory space but result ~7ms!</p>
<p><a href="https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#70254">HoyHoy</a>: Noted it was producing incorrect results</p>
| [
{
"answer_id": 69126,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 2,
"selected": false,
"text": "<p>For one, instead of multiplying by <code>16</code> do a <code>bitshift << 4</code></p>\n\n<p>Also don't use t... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/716/"
] | Below is my current char\* to hex string function. I wrote it as an exercise in bit manipulation. It takes ~7ms on a AMD Athlon MP 2800+ to hexify a 10 million byte array. Is there any trick or other way that I am missing?
How can I make this faster?
Compiled with -O3 in g++
```
static const char _hex2asciiU_value[256][2] =
{ {'0','0'}, {'0','1'}, /* snip..., */ {'F','E'},{'F','F'} };
std::string char_to_hex( const unsigned char* _pArray, unsigned int _len )
{
std::string str;
str.resize(_len*2);
char* pszHex = &str[0];
const unsigned char* pEnd = _pArray + _len;
clock_t stick, etick;
stick = clock();
for( const unsigned char* pChar = _pArray; pChar != pEnd; pChar++, pszHex += 2 ) {
pszHex[0] = _hex2asciiU_value[*pChar][0];
pszHex[1] = _hex2asciiU_value[*pChar][1];
}
etick = clock();
std::cout << "ticks to hexify " << etick - stick << std::endl;
return str;
}
```
**Updates**
Added timing code
[Brian R. Bondy](https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#69126): replace the std::string with a heap alloc'd buffer and change ofs\*16 to ofs << 4 - however the heap allocated buffer seems to slow it down? - result ~11ms
[Antti Sykäri](https://stackoverflow.com/questions/69115/#69305):replace inner loop with
```
int upper = *pChar >> 4;
int lower = *pChar & 0x0f;
pszHex[0] = pHex[upper];
pszHex[1] = pHex[lower];
```
result ~8ms
[Robert](https://stackoverflow.com/questions/69115?sort=votes#69218): replace `_hex2asciiU_value` with a full 256-entry table, sacrificing memory space but result ~7ms!
[HoyHoy](https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#70254): Noted it was producing incorrect results | At the cost of more memory you can create a full 256-entry table of the hex codes:
```
static const char _hex2asciiU_value[256][2] =
{ {'0','0'}, {'0','1'}, /* ..., */ {'F','E'},{'F','F'} };
```
Then direct index into the table, no bit fiddling required.
```
const char *pHexVal = pHex[*pChar];
pszHex[0] = pHexVal[0];
pszHex[1] = pHexVal[1];
``` |
69,159 | <p>I'm using MediaTemple's Grid Server (shared/grid hosting) to run some MySQL/PHP sites I'm writing and noticed that I wasn't closing one of my MySQL connections, which caused my site to error out: </p>
<pre><code>"Too Many Connections"
</code></pre>
<p>I can't log in anywhere to close the connections manually. </p>
<p><strong>Is that any way to close open connections using a script or other type of command?.</strong> </p>
<p>Should I just wait?</p>
| [
{
"answer_id": 69171,
"author": "owenmarshall",
"author_id": 9806,
"author_profile": "https://Stackoverflow.com/users/9806",
"pm_score": 1,
"selected": false,
"text": "<p>If you can't log into MySQL at all, you will probably have to contact your hosting provider to kill the connections.<... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9803/"
] | I'm using MediaTemple's Grid Server (shared/grid hosting) to run some MySQL/PHP sites I'm writing and noticed that I wasn't closing one of my MySQL connections, which caused my site to error out:
```
"Too Many Connections"
```
I can't log in anywhere to close the connections manually.
**Is that any way to close open connections using a script or other type of command?.**
Should I just wait? | If you can't log into MySQL at all, you will probably have to contact your hosting provider to kill the connections.
If you can use the MySQL shell, you can use the [show processlist](http://dev.mysql.com/doc/refman/5.0/en/show-processlist.html) command to view connections, then use the [kill](http://dev.mysql.com/doc/refman/5.0/en/kill.html) command to remove the connections.
It's been my experience that hung SQL connections tend to stay that way, unfortunately. |
69,188 | <p><a href="http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx" rel="nofollow noreferrer">http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx</a></p>
<p>This post shows how to test setting a cookie and then seeing it in ViewData. What I what to do is see if the correct cookies were written (values and name). Any reply, blog post or article will be greatly appreciated.</p>
| [
{
"answer_id": 69535,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": -1,
"selected": false,
"text": "<pre><code>function ReadCookie(cookieName) {\n var theCookie=\"\"+document.cookie;\n var ind=theCookie.indexOf(cookie... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438/"
] | <http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx>
This post shows how to test setting a cookie and then seeing it in ViewData. What I what to do is see if the correct cookies were written (values and name). Any reply, blog post or article will be greatly appreciated. | Are you looking for something more like this? (untested, just typed it up in the reply box)
```
var cookies = new HttpCookieCollection();
controller.ControllerContext = new FakeControllerContext(controller, cookies);
var result = controller.TestCookie() as ViewResult;
Assert.AreEqual("somevaluethatshouldbethere", cookies["somecookieitem"].Value);
```
As in, did you mean you want to test the writing of a cookie instead of reading one?
Please make your request clearer if possible :) |
69,192 | <p>Suppose we have two stacks and no other temporary variable.</p>
<p>Is to possible to "construct" a queue data structure using only the two stacks?</p>
| [
{
"answer_id": 69206,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 4,
"selected": false,
"text": "<p>The time complexities would be worse, though. A good queue implementation does everything in constant time.</p>\n\n<p><stro... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7086/"
] | Suppose we have two stacks and no other temporary variable.
Is to possible to "construct" a queue data structure using only the two stacks? | Keep 2 stacks, let's call them `inbox` and `outbox`.
**Enqueue**:
* Push the new element onto `inbox`
**Dequeue**:
* If `outbox` is empty, refill it by popping each element from `inbox` and pushing it onto `outbox`
* Pop and return the top element from `outbox`
Using this method, each element will be in each stack exactly once - meaning each element will be pushed twice and popped twice, giving amortized constant time operations.
Here's an implementation in Java:
```java
public class Queue<E>
{
private Stack<E> inbox = new Stack<E>();
private Stack<E> outbox = new Stack<E>();
public void queue(E item) {
inbox.push(item);
}
public E dequeue() {
if (outbox.isEmpty()) {
while (!inbox.isEmpty()) {
outbox.push(inbox.pop());
}
}
return outbox.pop();
}
}
``` |
69,209 | <p>Is it possible to delete a middle node in the single linked list when the only information available we have is the pointer to the node to be deleted and not the pointer to the previous node?After deletion the previous node should point to the node next to deleted node. </p>
| [
{
"answer_id": 69214,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 0,
"selected": false,
"text": "<p>yes, but you can't delink it. If you don't care about corrupting memory, go ahead ;-)</p>\n"
},
{
"answer_i... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7086/"
] | Is it possible to delete a middle node in the single linked list when the only information available we have is the pointer to the node to be deleted and not the pointer to the previous node?After deletion the previous node should point to the node next to deleted node. | It's definitely more a quiz rather than a real problem. However, if we are allowed to make some assumption, it can be solved in O(1) time. To do it, the strictures the list points to must be copyable. The algorithm is as the following:
We have a list looking like: ... -> Node(i-1) -> Node(i) -> Node(i+1) -> ... and we need to delete Node(i).
1. Copy data (not pointer, the data itself) from Node(i+1) to Node(i), the list will look like: ... -> Node(i-1) -> Node(i+1) -> Node(i+1) -> ...
2. Copy the NEXT of second Node(i+1) into a temporary variable.
3. Now Delete the second Node(i+1), it doesn't require pointer to the previous node.
Pseudocode:
```
void delete_node(Node* pNode)
{
pNode->Data = pNode->Next->Data; // Assume that SData::operator=(SData&) exists.
Node* pTemp = pNode->Next->Next;
delete(pNode->Next);
pNode->Next = pTemp;
}
```
Mike. |
69,250 | <p>In most C or C++ environments, there is a "debug" mode and a "release" mode compilation.<br>
Looking at the difference between the two, you find that the debug mode adds the debug symbols (often the -g option on lots of compilers) but it also disables most optimizations.<br>
In "release" mode, you usually have all sorts of optimizations turned on.<br>
Why the difference?</p>
| [
{
"answer_id": 69252,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 6,
"selected": true,
"text": "<p>Without any optimization on, the flow through your code is linear. If you are on line 5 and single step, you step to line... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
] | In most C or C++ environments, there is a "debug" mode and a "release" mode compilation.
Looking at the difference between the two, you find that the debug mode adds the debug symbols (often the -g option on lots of compilers) but it also disables most optimizations.
In "release" mode, you usually have all sorts of optimizations turned on.
Why the difference? | Without any optimization on, the flow through your code is linear. If you are on line 5 and single step, you step to line 6. With optimization on, you can get instruction re-ordering, loop unrolling and all sorts of optimizations.
For example:
```
void foo() {
1: int i;
2: for(i = 0; i < 2; )
3: i++;
4: return;
```
In this example, without optimization, you could single step through the code and hit lines 1, 2, 3, 2, 3, 2, 4
With optimization on, you might get an execution path that looks like: 2, 3, 3, 4 or even just 4! (The function does nothing after all...)
Bottom line, debugging code with optimization enabled can be a royal pain! Especially if you have large functions.
Note that turning on optimization changes the code! In certain environment (safety critical systems), this is unacceptable and the code being debugged has to be the code shipped. Gotta debug with optimization on in that case.
While the optimized and non-optimized code should be "functionally" equivalent, under certain circumstances, the behavior will change.
Here is a simplistic example:
````
int* ptr = 0xdeadbeef; // some address to memory-mapped I/O device
*ptr = 0; // setup hardware device
while(*ptr == 1) { // loop until hardware device is done
// do something
}
````
With optimization off, this is straightforward, and you kinda know what to expect.
However, if you turn optimization on, a couple of things might happen:
* The compiler might optimize the while block away (we init to 0, it'll never be 1)
* Instead of accessing memory, pointer access might be moved to a register->No I/O Update
* memory access might be cached (not necessarily compiler optimization related)
In all these cases, the behavior would be drastically different and most likely wrong. |
69,262 | <p>I am wondering if there is a method or format string I'm missing in .NET to convert the following:</p>
<pre><code> 1 to 1st
2 to 2nd
3 to 3rd
4 to 4th
11 to 11th
101 to 101st
111 to 111th
</code></pre>
<p><a href="http://www.dotnet-friends.com/fastcode/csharp/fastcodeincsc3bd4149-03d0-40fe-90fd-63bcee77b43e.aspx" rel="noreferrer">This link</a> has a bad example of the basic principle involved in writing your own function, but I am more curious if there is an inbuilt capacity I'm missing.</p>
<p><strong>Solution</strong></p>
<p>Scott Hanselman's answer is the accepted one because it answers the question directly.</p>
<p>For a solution however, see <a href="https://stackoverflow.com/questions/69262/is-there-an-easy-way-in-net-to-get-st-nd-rd-and-th-endings-for-numbers#69284">this great answer</a>.</p>
| [
{
"answer_id": 69279,
"author": "Scott Hanselman",
"author_id": 6380,
"author_profile": "https://Stackoverflow.com/users/6380",
"pm_score": 7,
"selected": true,
"text": "<p>No, there is no inbuilt capability in the .NET Base Class Library.</p>\n"
},
{
"answer_id": 69284,
"aut... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | I am wondering if there is a method or format string I'm missing in .NET to convert the following:
```
1 to 1st
2 to 2nd
3 to 3rd
4 to 4th
11 to 11th
101 to 101st
111 to 111th
```
[This link](http://www.dotnet-friends.com/fastcode/csharp/fastcodeincsc3bd4149-03d0-40fe-90fd-63bcee77b43e.aspx) has a bad example of the basic principle involved in writing your own function, but I am more curious if there is an inbuilt capacity I'm missing.
**Solution**
Scott Hanselman's answer is the accepted one because it answers the question directly.
For a solution however, see [this great answer](https://stackoverflow.com/questions/69262/is-there-an-easy-way-in-net-to-get-st-nd-rd-and-th-endings-for-numbers#69284). | No, there is no inbuilt capability in the .NET Base Class Library. |
69,275 | <p>I'm trying to draw a graph on an ASP webpage. I'm hoping an API can be helpful, but so far I have not been able to find one. </p>
<p>The graph contains labeled nodes and unlabeled directional edges.
The ideal output would be something like <a href="http://en.wikipedia.org/wiki/Image:6n-graf.svg" rel="noreferrer">this</a>. </p>
<p>Anybody know of anything pre-built than can help?</p>
| [
{
"answer_id": 69285,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 2,
"selected": false,
"text": "<p>I am not sure about ASP interface, but you may want to check out <a href=\"http://www.graphviz.org/\" rel=\"nofollow no... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165305/"
] | I'm trying to draw a graph on an ASP webpage. I'm hoping an API can be helpful, but so far I have not been able to find one.
The graph contains labeled nodes and unlabeled directional edges.
The ideal output would be something like [this](http://en.wikipedia.org/wiki/Image:6n-graf.svg).
Anybody know of anything pre-built than can help? | Definitely [graphviz](http://graphviz.org). The image on the wikipedia link you are pointing at was made in graphviz. From its description page the graph description file looked like this:
```
graph untitled {
graph[bgcolor="transparent"];
node [fontname="Bitstream Vera Sans", fontsize="22.00", shape=circle, style="bold,filled" fillcolor=white];
edge [style=bold];
1;2;3;4;5;6;
6 -- 4 -- 5 -- 1 -- 2 -- 3 -- 4;
2 -- 5;
}
```
If that code were saved into a file input.dot, the command they would have used to actually generate the graph would probably have been:
```
neato -Tsvg input.dot > graph.svg
``` |
69,277 | <p>I have an Enumerable array</p>
<pre><code>int meas[] = new double[] {3, 6, 9, 12, 15, 18};
</code></pre>
<p>On each successive call to the mock's method that I'm testing I want to return a value from that array.</p>
<pre><code>using(_mocks.Record()) {
Expect.Call(mocked_class.GetValue()).Return(meas);
}
using(_mocks.Playback()) {
foreach(var i in meas)
Assert.AreEqual(i, mocked_class.GetValue();
}
</code></pre>
<p>Does anyone have an idea how I can do this?</p>
| [
{
"answer_id": 69382,
"author": "vrdhn",
"author_id": 414441,
"author_profile": "https://Stackoverflow.com/users/414441",
"pm_score": 0,
"selected": false,
"text": "<p>IMHO, yield will handle this.\n<a href=\"http://msdn.microsoft.com/en-us/library/9k7k7cf0%28VS.80%29.aspx\" rel=\"nofoll... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | I have an Enumerable array
```
int meas[] = new double[] {3, 6, 9, 12, 15, 18};
```
On each successive call to the mock's method that I'm testing I want to return a value from that array.
```
using(_mocks.Record()) {
Expect.Call(mocked_class.GetValue()).Return(meas);
}
using(_mocks.Playback()) {
foreach(var i in meas)
Assert.AreEqual(i, mocked_class.GetValue();
}
```
Does anyone have an idea how I can do this? | There is alway static fake object, but this question is about rhino-mocks, so I present you with the way I'll do it.
The trick is that you create a local variable as the counter, and use it in your anonymous delegate/lambda to keep track of where you are on the array. Notice that I didn't handle the case that GetValue() is called more than 6 times.
```
var meas = new int[] { 3, 6, 9, 12, 15, 18 };
using (mocks.Record())
{
int forMockMethod = 0;
SetupResult.For(mocked_class.GetValue()).Do(
new Func<int>(() => meas[forMockMethod++])
);
}
using(mocks.Playback())
{
foreach (var i in meas)
Assert.AreEqual(i, mocked_class.GetValue());
}
``` |
69,296 | <p>I have a a property defined as:</p>
<pre><code>[XmlArray("delete", IsNullable = true)]
[XmlArrayItem("contact", typeof(ContactEvent)),
XmlArrayItem("sms", typeof(SmsEvent))]
public List<Event> Delete { get; set; }
</code></pre>
<p>If the List<> Delete has no items</p>
<pre><code><delete />
</code></pre>
<p>is emitted. If the List<> Delete is set to null</p>
<pre><code><delete xsi:nil="true" />
</code></pre>
<p>is emitted. Is there a way using attributes to get the delete element not to be emitted if the collection has no items?</p>
<p><a href="https://stackoverflow.com/questions/69296/xml-serialization-and-empty-collections#69407">Greg</a> - Perfect thanks, I didn't even read the IsNullable documentation just assumed it was signalling it as not required.</p>
<p><a href="https://stackoverflow.com/questions/69296/xml-serialization-and-empty-collections#69518">Rob Cooper</a> - I was trying to avoid ISerializable, but Gregs suggestion works. I did run into the problem you outlined in (1), I broke a bunch of code by just returning null if the collection was zero length. To get around this I created a EventsBuilder class (the class I am serializing is called Events) that managed all the lifetime/creation of the underlying objects of the Events class that spits our Events classes for serialization.</p>
| [
{
"answer_id": 69315,
"author": "Craig Eddy",
"author_id": 5557,
"author_profile": "https://Stackoverflow.com/users/5557",
"pm_score": 0,
"selected": false,
"text": "<p>You could always implement IXmlSerializer and perform the serialization manually.</p>\n\n<p>See <a href=\"http://www.co... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2281/"
] | I have a a property defined as:
```
[XmlArray("delete", IsNullable = true)]
[XmlArrayItem("contact", typeof(ContactEvent)),
XmlArrayItem("sms", typeof(SmsEvent))]
public List<Event> Delete { get; set; }
```
If the List<> Delete has no items
```
<delete />
```
is emitted. If the List<> Delete is set to null
```
<delete xsi:nil="true" />
```
is emitted. Is there a way using attributes to get the delete element not to be emitted if the collection has no items?
[Greg](https://stackoverflow.com/questions/69296/xml-serialization-and-empty-collections#69407) - Perfect thanks, I didn't even read the IsNullable documentation just assumed it was signalling it as not required.
[Rob Cooper](https://stackoverflow.com/questions/69296/xml-serialization-and-empty-collections#69518) - I was trying to avoid ISerializable, but Gregs suggestion works. I did run into the problem you outlined in (1), I broke a bunch of code by just returning null if the collection was zero length. To get around this I created a EventsBuilder class (the class I am serializing is called Events) that managed all the lifetime/creation of the underlying objects of the Events class that spits our Events classes for serialization. | If you set IsNullable=false or just remove it (it is false by default), then the "delete" element will not be emitted. This will work only if the collection equals to null.
My guess is that there is a confusion between "nullability" in terms of .NET, and the one related to nullable elements in XML -- those that are marked by xml:nil attribute. XmlArrayAttribute.IsNullable property controls the latter. |
69,352 | <p>What I'm doing is I have a full-screen form, with no title bar, and consequently lacks the minimize/maximize/close buttons found in the upper-right hand corner. I'm wanting to replace that functionality with a keyboard short-cut and a context menu item, but I can't seem to find an event to trigger to minimize the form.</p>
| [
{
"answer_id": 69359,
"author": "JP Richardson",
"author_id": 10333,
"author_profile": "https://Stackoverflow.com/users/10333",
"pm_score": 5,
"selected": false,
"text": "<pre><code>FormName.WindowState = FormWindowState.Minimized;\n</code></pre>\n"
},
{
"answer_id": 69362,
"... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7516/"
] | What I'm doing is I have a full-screen form, with no title bar, and consequently lacks the minimize/maximize/close buttons found in the upper-right hand corner. I'm wanting to replace that functionality with a keyboard short-cut and a context menu item, but I can't seem to find an event to trigger to minimize the form. | ```
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == 'm')
this.WindowState = FormWindowState.Minimized;
}
``` |
69,391 | <p>In OS X, in order to quickly get at menu items from the keyboard, I want to be able to type a key combination, have it run a script, and have the script focus the Search field in the Help menu. It should work just like the key combination for Spotlight, so if I run it again, it should dismiss the menu. I can run the script with Quicksilver, but how can I write the script?</p>
| [
{
"answer_id": 69393,
"author": "easeout",
"author_id": 10906,
"author_profile": "https://Stackoverflow.com/users/10906",
"pm_score": 2,
"selected": true,
"text": "<p>Here is the script I came up with.</p>\n\n<pre><code>tell application \"System Events\"\n tell (first process whose fr... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10906/"
] | In OS X, in order to quickly get at menu items from the keyboard, I want to be able to type a key combination, have it run a script, and have the script focus the Search field in the Help menu. It should work just like the key combination for Spotlight, so if I run it again, it should dismiss the menu. I can run the script with Quicksilver, but how can I write the script? | Here is the script I came up with.
```
tell application "System Events"
tell (first process whose frontmost is true)
click menu "Help" of menu bar 1
end tell
end tell
``` |
69,398 | <p>i have scenario where i have to provide my own control template for a few WPF controls - i.e. GridViewHeader. when you take a look at control template for GridViewHEader in blend, it is agregated from several other controls, which in some cases are styled for that control only - i.e. this splitter between columns.
those templates, obviously are resources hidden somewhere in system...dll (or somewhwere in themes dll's).
so, my question is - is there a way to reference those predefined templates? so far, i've ended up having my own copies of them in my resources, but i don't like that approach.</p>
<p>here is sample scenario:
i have a GridViewColumnHeader:</p>
<pre><code> <Style TargetType="{x:Type GridViewColumnHeader}" x:Key="gridViewColumnStyle">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="Background" Value="{StaticResource GridViewHeaderBackgroundColor}"/>
<Setter Property="BorderBrush" Value="{StaticResource GridViewHeaderForegroundColor}"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Padding" Value="2,0,2,0"/>
<Setter Property="Foreground" Value="{StaticResource GridViewHeaderForegroundColor}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GridViewColumnHeader}">
<Grid SnapsToDevicePixels="true" Tag="Header" Name="Header">
<ContentPresenter Name="HeaderContent" Margin="0,0,0,1" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
<Canvas>
<Thumb x:Name="PART_HeaderGripper" Style="{StaticResource GridViewColumnHeaderGripper}"/>
</Canvas>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
</Trigger>
<Trigger Property="IsPressed" Value="true">
<Setter TargetName="HeaderContent" Property="Margin" Value="1,1,0,0"/>
</Trigger>
<Trigger Property="Height" Value="Auto">
<Setter Property="MinHeight" Value="20"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>so far - nothing interesting, but say, i want to add some extra functionality straight in the template - i'd leave cotnent presenter as is, add my controls next to it and i'd like to leave Thumb with defaults from framework. i've found themes provided by microsoft <a href="http://msdn.microsoft.com/en-us/library/aa358533.aspx" rel="nofollow noreferrer">here</a>:</p>
<p>the theme for Thumb looks like that:</p>
<pre><code><Style x:Key="GridViewColumnHeaderGripper"
TargetType="{x:Type Thumb}">
<Setter Property="Canvas.Right"
Value="-9"/>
<Setter Property="Width"
Value="18"/>
<Setter Property="Height"
Value="{Binding Path=ActualHeight,RelativeSource={RelativeSource TemplatedParent}}"/>
<Setter Property="Padding"
Value="0"/>
<Setter Property="Background"
Value="{StaticResource GridViewColumnHeaderBorderBackground}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Thumb}">
<Border Padding="{TemplateBinding Padding}"
Background="Transparent">
<Rectangle HorizontalAlignment="Center"
Width="1"
Fill="{TemplateBinding Background}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>so far - i have to copy & paste that style, while i'd prefer to get reference to it from resources.</p>
| [
{
"answer_id": 69427,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 2,
"selected": false,
"text": "<p>Referencing internal resources that are 100% subject to change isn't serviceable - better to just copy it. </p>\n"
},
... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11013/"
] | i have scenario where i have to provide my own control template for a few WPF controls - i.e. GridViewHeader. when you take a look at control template for GridViewHEader in blend, it is agregated from several other controls, which in some cases are styled for that control only - i.e. this splitter between columns.
those templates, obviously are resources hidden somewhere in system...dll (or somewhwere in themes dll's).
so, my question is - is there a way to reference those predefined templates? so far, i've ended up having my own copies of them in my resources, but i don't like that approach.
here is sample scenario:
i have a GridViewColumnHeader:
```
<Style TargetType="{x:Type GridViewColumnHeader}" x:Key="gridViewColumnStyle">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="Background" Value="{StaticResource GridViewHeaderBackgroundColor}"/>
<Setter Property="BorderBrush" Value="{StaticResource GridViewHeaderForegroundColor}"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Padding" Value="2,0,2,0"/>
<Setter Property="Foreground" Value="{StaticResource GridViewHeaderForegroundColor}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GridViewColumnHeader}">
<Grid SnapsToDevicePixels="true" Tag="Header" Name="Header">
<ContentPresenter Name="HeaderContent" Margin="0,0,0,1" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
<Canvas>
<Thumb x:Name="PART_HeaderGripper" Style="{StaticResource GridViewColumnHeaderGripper}"/>
</Canvas>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
</Trigger>
<Trigger Property="IsPressed" Value="true">
<Setter TargetName="HeaderContent" Property="Margin" Value="1,1,0,0"/>
</Trigger>
<Trigger Property="Height" Value="Auto">
<Setter Property="MinHeight" Value="20"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
so far - nothing interesting, but say, i want to add some extra functionality straight in the template - i'd leave cotnent presenter as is, add my controls next to it and i'd like to leave Thumb with defaults from framework. i've found themes provided by microsoft [here](http://msdn.microsoft.com/en-us/library/aa358533.aspx):
the theme for Thumb looks like that:
```
<Style x:Key="GridViewColumnHeaderGripper"
TargetType="{x:Type Thumb}">
<Setter Property="Canvas.Right"
Value="-9"/>
<Setter Property="Width"
Value="18"/>
<Setter Property="Height"
Value="{Binding Path=ActualHeight,RelativeSource={RelativeSource TemplatedParent}}"/>
<Setter Property="Padding"
Value="0"/>
<Setter Property="Background"
Value="{StaticResource GridViewColumnHeaderBorderBackground}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Thumb}">
<Border Padding="{TemplateBinding Padding}"
Background="Transparent">
<Rectangle HorizontalAlignment="Center"
Width="1"
Fill="{TemplateBinding Background}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
so far - i have to copy & paste that style, while i'd prefer to get reference to it from resources. | Referencing internal resources that are 100% subject to change isn't serviceable - better to just copy it. |
69,411 | <p>What is the best way to copy a directory (with sub-dirs and files) from one remote Linux server to another remote Linux server? I have connected to both using SSH client (like Putty). I have root access to both. </p>
| [
{
"answer_id": 69418,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 3,
"selected": false,
"text": "<p>rsync -avlzp /path/to/folder name@remote.server:/path/to/remote/folder</p>\n"
},
{
"answer_id": 69419,
"auth... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | What is the best way to copy a directory (with sub-dirs and files) from one remote Linux server to another remote Linux server? I have connected to both using SSH client (like Putty). I have root access to both. | There are two ways I usually do this, both use ssh:
```
scp -r sourcedir/ user@dest.com:/dest/dir/
```
or, the more robust and faster (in terms of transfer speed) method:
```
rsync -auv -e ssh --progress sourcedir/ user@dest.com:/dest/dir/
```
Read the man pages for each command if you want more details about how they work. |
69,430 | <p>I'm building an HTML UI with some text elements, such as tab names, which look bad when selected. Unfortunately, it's very easy for a user to double-click a tab name, which selects it by default in many browsers.</p>
<p>I might be able to solve this with a JavaScript trick (I'd like to see those answers, too) -- but I'm really hoping there's something in CSS/HTML directly that works across all browsers.</p>
| [
{
"answer_id": 69474,
"author": "Dave Rutledge",
"author_id": 2486915,
"author_profile": "https://Stackoverflow.com/users/2486915",
"pm_score": 3,
"selected": false,
"text": "<p>Absolutely position divs over the text area with a z-index higher and give these divs a transparent <a href=\"... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3561/"
] | I'm building an HTML UI with some text elements, such as tab names, which look bad when selected. Unfortunately, it's very easy for a user to double-click a tab name, which selects it by default in many browsers.
I might be able to solve this with a JavaScript trick (I'd like to see those answers, too) -- but I'm really hoping there's something in CSS/HTML directly that works across all browsers. | In most browsers, this can be achieved using CSS:
```css
*.unselectable {
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
/*
Introduced in IE 10.
See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
*/
-ms-user-select: none;
user-select: none;
}
```
For IE < 10 and Opera, you will need to use the `unselectable` attribute of the element you wish to be unselectable. You can set this using an attribute in HTML:
```
<div id="foo" unselectable="on" class="unselectable">...</div>
```
Sadly this property isn't inherited, meaning you have to put an attribute in the start tag of every element inside the `<div>`. If this is a problem, you could instead use JavaScript to do this recursively for an element's descendants:
```
function makeUnselectable(node) {
if (node.nodeType == 1) {
node.setAttribute("unselectable", "on");
}
var child = node.firstChild;
while (child) {
makeUnselectable(child);
child = child.nextSibling;
}
}
makeUnselectable(document.getElementById("foo"));
``` |
69,440 | <p>I'm wondering if there's any way to write CSS specifically for Safari using only CSS. I know there has to be something out there, but I haven't found it yet.</p>
| [
{
"answer_id": 69446,
"author": "dawnerd",
"author_id": 69503,
"author_profile": "https://Stackoverflow.com/users/69503",
"pm_score": 2,
"selected": false,
"text": "<p>So wait, you want to write CSS for Safari using only CSS? I think you answered your own question. Webkit has really good... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8970/"
] | I'm wondering if there's any way to write CSS specifically for Safari using only CSS. I know there has to be something out there, but I haven't found it yet. | I think the question is valid. I agree with the other responses, but it doesn't mean it's a terrible question. I've only ever had to use a Safari CSS hack once as a temporary solution and later got rid of it. I agree that you shouldn't have to target just Safari, but no harm in knowing how to do it.
FYI, this hack only targets Safari 3, and also targets Opera 9.
```
@media screen and (-webkit-min-device-pixel-ratio:0) {
/* Safari 3.0 and Opera 9 rules here */
}
``` |
69,445 | <p>I'm using the After Effects CS3 Javascript API to dynamically create and change text layers in a composition.</p>
<p>Or at least I'm trying to because I can't seem to find the right property to change to alter the actual text of the TextLayer object.</p>
| [
{
"answer_id": 69462,
"author": "dawnerd",
"author_id": 69503,
"author_profile": "https://Stackoverflow.com/users/69503",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not an expert with After Effects, but I have messed around with it. I think <a href=\"http://library.creativecow.net... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147/"
] | I'm using the After Effects CS3 Javascript API to dynamically create and change text layers in a composition.
Or at least I'm trying to because I can't seem to find the right property to change to alter the actual text of the TextLayer object. | Hmm, must read docs harder next time.
```
var theComposition = app.project.item(1);
var theTextLayer = theComposition.layers[1];
theTextLayer.property("Source Text").setValue("This text is from code");
``` |
69,470 | <p>Is there a way to get the current xml data when we make our own custom XPath function (see here).</p>
<p>I know you have access to an <code>XPathContext</code> but is this enough?</p>
<p><strong>Example:</strong></p>
<p>Our XML:</p>
<pre><code><foo>
<bar>smang</bar>
<fizz>buzz</fizz>
</foo>
</code></pre>
<p>Our XSL:</p>
<pre><code><xsl:template match="/">
<xsl:value-of select="ourFunction()" />
</xsl:template>
</code></pre>
<p>How do we get the entire XML tree?</p>
<p><strong>Edit:</strong> To clarify: I'm creating a custom function that ends up executing static Java code (it's a Saxon feature). So, in this Java code, I wish to be able to get elements from the XML tree, such as bar and fizz, and their CDATA, such as smang and buzz.</p>
| [
{
"answer_id": 69478,
"author": "Yann Ramin",
"author_id": 9167,
"author_profile": "https://Stackoverflow.com/users/9167",
"pm_score": 2,
"selected": false,
"text": "<p>There is the classic 'ab' (apachebench) program. More power comes from <a href=\"http://jakarta.apache.org/jmeter/\" re... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] | Is there a way to get the current xml data when we make our own custom XPath function (see here).
I know you have access to an `XPathContext` but is this enough?
**Example:**
Our XML:
```
<foo>
<bar>smang</bar>
<fizz>buzz</fizz>
</foo>
```
Our XSL:
```
<xsl:template match="/">
<xsl:value-of select="ourFunction()" />
</xsl:template>
```
How do we get the entire XML tree?
**Edit:** To clarify: I'm creating a custom function that ends up executing static Java code (it's a Saxon feature). So, in this Java code, I wish to be able to get elements from the XML tree, such as bar and fizz, and their CDATA, such as smang and buzz. | There is the classic 'ab' (apachebench) program. More power comes from [JMmeter](http://jakarta.apache.org/jmeter/). For server health, I recommend Munin, which can painlessly capture data from several systems and aggregate it on one page. |
69,480 | <p>I have a script that renders graphs in gnuplot. The graphs all end up with an ugly white background. How do I change this? (Ideally, with a command that goes into a gnuplot script, as opposed to a command-line option or something in a settings file)</p>
| [
{
"answer_id": 69510,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 2,
"selected": false,
"text": "<p>It is a setting for some terminal (windows use background). Check out colorbox including its bdefault.</p>\n\n<p>/Alla... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
] | I have a script that renders graphs in gnuplot. The graphs all end up with an ugly white background. How do I change this? (Ideally, with a command that goes into a gnuplot script, as opposed to a command-line option or something in a settings file) | Ooh, found it. It's along the lines of:
```
set terminal png x222222 xffffff
``` |
69,546 | <p>I have a multi-frame layout. One of the frames contains a form, which I am submitting through XMLHttpRequest. Now when I use document.write() to rewrite the frame with the form, and the new page I am adding contains any javascript then the javascript is not exectuted in IE6?</p>
<p>For example:</p>
<pre><code>document.write("<html><head><script>alert(1);</script></head><body>test</body></html>");
</code></pre>
<p>In the above case the page content is replaced with test but the alert() isn't executed. This works fine in Firefox.</p>
<p>What is a workaround to the above problem? </p>
| [
{
"answer_id": 69655,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 1,
"selected": false,
"text": "<p>Workaround is to programmatically add <code><script></code> blocks to head DOM element in JavaScript at Callb... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a multi-frame layout. One of the frames contains a form, which I am submitting through XMLHttpRequest. Now when I use document.write() to rewrite the frame with the form, and the new page I am adding contains any javascript then the javascript is not exectuted in IE6?
For example:
```
document.write("<html><head><script>alert(1);</script></head><body>test</body></html>");
```
In the above case the page content is replaced with test but the alert() isn't executed. This works fine in Firefox.
What is a workaround to the above problem? | Workaround is to programmatically add `<script>` blocks to head DOM element in JavaScript at Callback function or call eval() method. It's only way you can make this work in IE 6. |
69,561 | <p>gnuplot is giving the error: "sh: kpsexpand: not found." </p>
<p>I feel like the guy in Office Space when he saw "PC LOAD LETTER". What the heck is kpsexpand?</p>
<p>I searched Google, and there were a lot of pages that make reference to kpsexpand, and say not to worry about it, but I can't find anything, anywhere that actually explains <em>what it is.</em></p>
<p>Even the man page stinks:</p>
<pre><code>$ man kpsexpand
kpsetool - script to make teTeX-style kpsetool, kpsexpand, and kpsepath available
</code></pre>
<p>Edit: Again, I'm not asking what to do -- I know what to do, thanks to Google. What I'm wondering is what the darn thing <em>is.</em></p>
| [
{
"answer_id": 69575,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<p>This is on the first page of google search results for \"kpexpand gnuplot\":</p>\n\n<p><a href=\"http://dschneller.blogspot.c... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
] | gnuplot is giving the error: "sh: kpsexpand: not found."
I feel like the guy in Office Space when he saw "PC LOAD LETTER". What the heck is kpsexpand?
I searched Google, and there were a lot of pages that make reference to kpsexpand, and say not to worry about it, but I can't find anything, anywhere that actually explains *what it is.*
Even the man page stinks:
```
$ man kpsexpand
kpsetool - script to make teTeX-style kpsetool, kpsexpand, and kpsepath available
```
Edit: Again, I'm not asking what to do -- I know what to do, thanks to Google. What I'm wondering is what the darn thing *is.* | kpsexpand, kpsetool and kpsepath are all wrappers for kpsewhich that deals with finding tex-related files
kpsexpand is used to expand environment varibles.
Say $VAR1 is "Hello World" and $VAR2 is "/home/where/I/belong" then
```
$ kpsexpand $VAR1
```
will return
```
Hello World
```
and
```
$ kpsexpand $VAR2
```
will return
```
/home/where/I/belong
```
`kpsewhich` is reminiscent to `which` just like `which progname` will search the directories in the $PATH environment variable and return the path of the first found progname, `kpsewhich filename` will search the directories in the various tex-paths, fonts, packages, etc. for filename.
to find out more lookup kpsewhich either in man or on google, and check out the source of kpsexpand
```
less `which kpsexpand`
```
Cheers
/B2S |
69,591 | <p>I want to create a regexp in Emacs that matches exactly 3 digits. For example, I want to match the following:</p>
<pre><code>123
345
789
</code></pre>
<p>But not</p>
<pre><code>1234
12
12 23
</code></pre>
<p>If I use <code>[0-9]+</code> I match any single string of digits. I thought <code>[0-9]{3}</code> would work, but when tested in re-builder it doesn't match anything.</p>
| [
{
"answer_id": 69593,
"author": "mike511",
"author_id": 9593,
"author_profile": "https://Stackoverflow.com/users/9593",
"pm_score": -1,
"selected": false,
"text": "<p>It's pretty simple:</p>\n\n<pre><code>[0-9][0-9][0-9]\n</code></pre>\n"
},
{
"answer_id": 69615,
"author": "J... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6180/"
] | I want to create a regexp in Emacs that matches exactly 3 digits. For example, I want to match the following:
```
123
345
789
```
But not
```
1234
12
12 23
```
If I use `[0-9]+` I match any single string of digits. I thought `[0-9]{3}` would work, but when tested in re-builder it doesn't match anything. | If you're entering the regex interactively, and want to use `{3}`, you need to use backslashes to escape the curly braces. If you don't want to match any part of the longer strings of numbers, use `\b` to match word boundaries around the numbers. This leaves:
```
\b[0-9]\{3\}\b
```
For those wanting more information about `\b`, see [the docs](http://www.gnu.org/software/emacs/manual/html_node/emacs/Regexp-Backslash.html#Regexp-Backslash):
>
> matches the empty string, but only at the beginning or end of a word. Thus, `\bfoo\b`
> matches any occurrence of `foo` as a separate word.
> `\bballs?\b` matches `ball` or `balls` as a separate word.
> `\b` matches at the beginning or end of the buffer regardless of what text appears next to it.
>
>
>
If you do want to use this regex from elisp code, as always, you must escape the backslashes one more time. For example:
```
(highlight-regexp "\\b[0-9]\\{3\\}\\b")
``` |
69,645 | <p>I want to take a screenshot via a python script and unobtrusively save it.</p>
<p>I'm only interested in the Linux solution, and should support any X based environment.</p>
| [
{
"answer_id": 70237,
"author": "Slava V",
"author_id": 37141,
"author_profile": "https://Stackoverflow.com/users/37141",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import ImageGrab\nimg = ImageGrab.grab()\nimg.save('test.jpg','JPEG')\n</code></pre>\n\n<p>this requires Python ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1724701/"
] | I want to take a screenshot via a python script and unobtrusively save it.
I'm only interested in the Linux solution, and should support any X based environment. | This works without having to use scrot or ImageMagick.
```
import gtk.gdk
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
print "The size of the window is %d x %d" % sz
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
if (pb != None):
pb.save("screenshot.png","png")
print "Screenshot saved to screenshot.png."
else:
print "Unable to get the screenshot."
```
Borrowed from <http://ubuntuforums.org/showpost.php?p=2681009&postcount=5> |
69,676 | <p>How do I get Asterisk to forward incoming calls based on matching the incoming call number with a number to forward to? Both numbers are stored in a MySQL database.</p>
| [
{
"answer_id": 69689,
"author": "willurd",
"author_id": 1943957,
"author_profile": "https://Stackoverflow.com/users/1943957",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://scottstuff.net/blog/articles/2004/08/09/database-driven-call-forwarding-with-asterisk\" rel=\"nofol... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11176/"
] | How do I get Asterisk to forward incoming calls based on matching the incoming call number with a number to forward to? Both numbers are stored in a MySQL database. | The solution I was looking for ended up looking like this:
```
[default]
exten => _X.,1,Set(ARRAY(${EXTEN}_phone)=${DTC_ICF(phone_number,${EXTEN})})
exten => _X.,n(callphone),Dial(SIP/metaswitch/${${EXTEN}_phone},26)
exten => _X.,n(end),Hangup()
``` |
69,695 | <p>I am trying to use a stringstream object in VC++ (VStudio 2003) butI am getting an error when I use the overloaded << operator to try and set some manipulators. </p>
<p>I am trying the following: </p>
<pre><code>int SomeInt = 1;
stringstream StrStream;
StrStream << std::setw(2) << SomeInt;
</code></pre>
<p>This will not compile (error C2593: 'operator <<' is ambiguous).<br>
Does VStudio 2003 support using manipulators in this way?<br>
I know that I can just set the width directly on the stringstream object e.g. StrStream.width(2);<br>
I was wondering why the more usual method doesn't work?</p>
| [
{
"answer_id": 69721,
"author": "Jesse Beder",
"author_id": 112,
"author_profile": "https://Stackoverflow.com/users/112",
"pm_score": 2,
"selected": true,
"text": "<p>Are you sure you included all of the right headers? The following compiles for me in VS2003:</p>\n\n<pre><code>#include &... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1682/"
] | I am trying to use a stringstream object in VC++ (VStudio 2003) butI am getting an error when I use the overloaded << operator to try and set some manipulators.
I am trying the following:
```
int SomeInt = 1;
stringstream StrStream;
StrStream << std::setw(2) << SomeInt;
```
This will not compile (error C2593: 'operator <<' is ambiguous).
Does VStudio 2003 support using manipulators in this way?
I know that I can just set the width directly on the stringstream object e.g. StrStream.width(2);
I was wondering why the more usual method doesn't work? | Are you sure you included all of the right headers? The following compiles for me in VS2003:
```
#include <iostream>
#include <sstream>
#include <iomanip>
int main()
{
int SomeInt = 1;
std::stringstream StrStream;
StrStream << std::setw(2) << SomeInt;
return 0;
}
``` |
69,702 | <pre><code>public static void main(String[] args) {
List<? extends Object> mylist = new ArrayList<Object>();
mylist.add("Java"); // compile error
}
</code></pre>
<p>The above code does not allow you to add elements to the list and wild cards can only be used as a signature in methods, again not for adding but only for accessing.
In this case what purpose does the above fulfil ??</p>
| [
{
"answer_id": 69797,
"author": "Ren",
"author_id": 11188,
"author_profile": "https://Stackoverflow.com/users/11188",
"pm_score": 1,
"selected": false,
"text": "<p>With java generics using wildcards, you are allowed the above declaration assuming you are only going to read from it. </p>\... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193/"
] | ```
public static void main(String[] args) {
List<? extends Object> mylist = new ArrayList<Object>();
mylist.add("Java"); // compile error
}
```
The above code does not allow you to add elements to the list and wild cards can only be used as a signature in methods, again not for adding but only for accessing.
In this case what purpose does the above fulfil ?? | Let's say you have an interface and two classes:
```
interface IResult {}
class AResult implements IResult {}
class BResult implements IResult {}
```
Then you have classes that return a list as a result:
```
interface ITest<T extends IResult> {
List<T> getResult();
}
class ATest implements ITest<AResult> {
// look, overridden!
List<AResult> getResult();
}
class BTest implements ITest<BResult> {
// overridden again!
List<BResult> getResult();
}
```
It's a good solution, when you need "covariant returns", but you return collections instead of your own objects. The big plus is that you don't have to cast objects when using ATest and BTest independently from the ITest interface. However, when using ITest interface, you cannot add anything to the list that was returned - as you cannot determine, what object types the list really contains! If it would be allowed, you would be able to add BResult to List<AResult> (returned as List<? extends T>), which doesn't make any sense.
So you have to remember this: List<? extends X> defines a list that could be easily overridden, but which is read-only. |
69,722 | <p>I have a dl containing some input boxes that I "clone" with a bit of JavaScript like: </p>
<pre><code>var newBox = document.createElement('dl');
var sourceBox = document.getElementById(oldkey);
newBox.innerHTML = sourceBox.innerHTML;
newBox.id = newkey;
document.getElementById('boxes').appendChild(columnBox);
</code></pre>
<p>In IE, the form in sourceBox is duplicated in newBox, complete with user-supplied values. In Firefox, last value entered in the orginal sourceBox is not present in newBox. How do I make this "stick?"</p>
| [
{
"answer_id": 69795,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 1,
"selected": false,
"text": "<p>You could try the <code>cloneNode</code> method. It might do a better job of copying the contents. It should also be fast... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6997/"
] | I have a dl containing some input boxes that I "clone" with a bit of JavaScript like:
```
var newBox = document.createElement('dl');
var sourceBox = document.getElementById(oldkey);
newBox.innerHTML = sourceBox.innerHTML;
newBox.id = newkey;
document.getElementById('boxes').appendChild(columnBox);
```
In IE, the form in sourceBox is duplicated in newBox, complete with user-supplied values. In Firefox, last value entered in the orginal sourceBox is not present in newBox. How do I make this "stick?" | [Firefox vs. IE: innerHTML handling](https://stackoverflow.com/questions/36778/firefox-vs-ie-innerhtml-handling#36793) ? |
69,738 | <p>I am working with an open-source UNIX tool that is implemented in C++, and I need to change some code to get it to do what I want. I would like to make the smallest possible change in hopes of getting my patch accepted upstream. Solutions that are implementable in standard C++ and do not create more external dependencies are preferred.</p>
<p>Here is my problem. I have a C++ class -- let's call it "A" -- that currently uses fprintf() to print its heavily formatted data structures to a file pointer. In its print function, it also recursively calls the identically defined print functions of several member classes ("B" is an example). There is another class C that has a member std::string "foo" that needs to be set to the print() results of an instance of A. Think of it as a to_str() member function for A.</p>
<p>In pseudocode:</p>
<pre><code>class A {
public:
...
void print(FILE* f);
B b;
...
};
...
void A::print(FILE *f)
{
std::string s = "stuff";
fprintf(f, "some %s", s);
b.print(f);
}
class C {
...
std::string foo;
bool set_foo(std::str);
...
}
...
A a = new A();
C c = new C();
...
// wish i knew how to write A's to_str()
c.set_foo(a.to_str());
</code></pre>
<p>I should mention that C is fairly stable, but A and B (and the rest of A's dependents) are in a state of flux, so the less code changes necessary the better. The current print(FILE* F) interface also needs to be preserved. I have considered several approaches to implementing A::to_str(), each with advantages and disadvantages:</p>
<ol>
<li><p>Change the calls to fprintf() to sprintf()</p>
<ul>
<li>I wouldn't have to rewrite any format strings</li>
<li>print() could be reimplemented as: fprint(f, this.to_str());</li>
<li>But I would need to manually allocate char[]s, merge a lot of c strings , and finally convert the character array to a std::string</li>
</ul></li>
<li><p>Try to catch the results of a.print() in a string stream</p>
<ul>
<li>I would have to convert all of the format strings to << output format. There are hundreds of fprintf()s to convert :-{</li>
<li>print() would have to be rewritten because there is no standard way that I know of to create an output stream from a UNIX file handle (though <a href="http://synflood.at/blog/index.php?/archives/456-One-word-of-warning-about-stdio_filebuf.html" rel="nofollow noreferrer">this guy says it may be possible</a>).</li>
</ul></li>
<li><p>Use Boost's string <a href="http://www.boost.org/doc/libs/1_36_0/libs/format/doc/format.html" rel="nofollow noreferrer">format library</a></p>
<ul>
<li>More external dependencies. Yuck.</li>
<li>Format's syntax is different enough from printf() to be annoying: </li>
</ul>
<p>printf(format_str, args) -> cout << boost::format(format_str) % arg1 % arg2 % etc</p></li>
<li><p>Use Qt's <a href="https://doc.qt.io/qt-5/qstring.html#asprintf%3E" rel="nofollow noreferrer">QString::asprintf()</a></p>
<ul>
<li>A different external dependency.</li>
</ul></li>
</ol>
<p>So, have I exhausted all possible options? If so, which do you think is my best bet? If not, what have I overlooked?</p>
<p>Thanks.</p>
| [
{
"answer_id": 69762,
"author": "Assaf Lavie",
"author_id": 11208,
"author_profile": "https://Stackoverflow.com/users/11208",
"pm_score": 0,
"selected": false,
"text": "<p>Is this about serialization? Or printing proper?\nIf the former, consider boost::serialization as well. It's all abo... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8146/"
] | I am working with an open-source UNIX tool that is implemented in C++, and I need to change some code to get it to do what I want. I would like to make the smallest possible change in hopes of getting my patch accepted upstream. Solutions that are implementable in standard C++ and do not create more external dependencies are preferred.
Here is my problem. I have a C++ class -- let's call it "A" -- that currently uses fprintf() to print its heavily formatted data structures to a file pointer. In its print function, it also recursively calls the identically defined print functions of several member classes ("B" is an example). There is another class C that has a member std::string "foo" that needs to be set to the print() results of an instance of A. Think of it as a to\_str() member function for A.
In pseudocode:
```
class A {
public:
...
void print(FILE* f);
B b;
...
};
...
void A::print(FILE *f)
{
std::string s = "stuff";
fprintf(f, "some %s", s);
b.print(f);
}
class C {
...
std::string foo;
bool set_foo(std::str);
...
}
...
A a = new A();
C c = new C();
...
// wish i knew how to write A's to_str()
c.set_foo(a.to_str());
```
I should mention that C is fairly stable, but A and B (and the rest of A's dependents) are in a state of flux, so the less code changes necessary the better. The current print(FILE\* F) interface also needs to be preserved. I have considered several approaches to implementing A::to\_str(), each with advantages and disadvantages:
1. Change the calls to fprintf() to sprintf()
* I wouldn't have to rewrite any format strings
* print() could be reimplemented as: fprint(f, this.to\_str());
* But I would need to manually allocate char[]s, merge a lot of c strings , and finally convert the character array to a std::string
2. Try to catch the results of a.print() in a string stream
* I would have to convert all of the format strings to << output format. There are hundreds of fprintf()s to convert :-{
* print() would have to be rewritten because there is no standard way that I know of to create an output stream from a UNIX file handle (though [this guy says it may be possible](http://synflood.at/blog/index.php?/archives/456-One-word-of-warning-about-stdio_filebuf.html)).
3. Use Boost's string [format library](http://www.boost.org/doc/libs/1_36_0/libs/format/doc/format.html)
* More external dependencies. Yuck.
* Format's syntax is different enough from printf() to be annoying:printf(format\_str, args) -> cout << boost::format(format\_str) % arg1 % arg2 % etc
4. Use Qt's [QString::asprintf()](https://doc.qt.io/qt-5/qstring.html#asprintf%3E)
* A different external dependency.
So, have I exhausted all possible options? If so, which do you think is my best bet? If not, what have I overlooked?
Thanks. | I am using #3: the boost string format library - but I have to admit that I've never had any problem with the differences in format specifications.
Works like a charm for me - and the external dependencies could be worse (a very stable library)
Edited: adding an example how to use boost::format instead of printf:
```
sprintf(buffer, "This is a string with some %s and %d numbers", "strings", 42);
```
would be something like this with the boost::format library:
```
string = boost::str(boost::format("This is a string with some %s and %d numbers") %"strings" %42);
```
Hope this helps clarify the usage of boost::format
I've used boost::format as a sprintf / printf replacement in 4 or 5 applications (writing formatted strings to files, or custom output to logfiles) and never had problems with format differences. There may be some (more or less obscure) format specifiers which are differently - but I never had a problem.
In contrast I had some format specifications I couldn't really do with streams (as much as I remember) |
69,743 | <p>I am trying to populate a string with a double value using a <code>sprintf</code> like this:</p>
<pre><code>sprintf(S, "%f", val);
</code></pre>
<p>But the precision is being cut off to six decimal places. I need about 10 decimal places for the precision.</p>
<p>How can that be achieved?</p>
| [
{
"answer_id": 69747,
"author": "Yann Ramin",
"author_id": 9167,
"author_profile": "https://Stackoverflow.com/users/9167",
"pm_score": 3,
"selected": false,
"text": "<p>What you want is a modifier:</p>\n\n<pre><code>sprintf(S, \"%.10f\", val);\n</code></pre>\n\n<p>man sprintf will have m... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11212/"
] | I am trying to populate a string with a double value using a `sprintf` like this:
```
sprintf(S, "%f", val);
```
But the precision is being cut off to six decimal places. I need about 10 decimal places for the precision.
How can that be achieved? | %[width].[precision]
Width should include the decimal point.
%8.2 means 8 characters wide; 5 digits before the point and 2 after. One character is reserved for the point.
5 + 1 + 2 = 8 |
69,748 | <p>Another easy one hopefully.</p>
<p>Let's say I have a collection like this:</p>
<pre><code>List<DateTime> allDates;
</code></pre>
<p>I want to turn that into </p>
<pre><code>List<List<DateTime>> dividedDates;
</code></pre>
<p>where each List in 'dividedDates' contains all of the dates in 'allDates' that belong to a distinct year.</p>
<p>Is there a bit of LINQ trickery that my tired mind can't pick out right now?</p>
<p><strong>Solution</strong></p>
<p>The Accepted Answer is correct.</p>
<p>Thanks, I don't think I was aware of the 'into' bit of GroupBy and I was trying to use the .GroupBy() sort of methods rather than the SQL like syntax. And thanks for confirming the ToList() amendment and including it in the Accepted Answer :-)</p>
| [
{
"answer_id": 69769,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": true,
"text": "<pre><code>var q = from date in allDates \n group date by date.Year into datesByYear\n select datesByYear... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | Another easy one hopefully.
Let's say I have a collection like this:
```
List<DateTime> allDates;
```
I want to turn that into
```
List<List<DateTime>> dividedDates;
```
where each List in 'dividedDates' contains all of the dates in 'allDates' that belong to a distinct year.
Is there a bit of LINQ trickery that my tired mind can't pick out right now?
**Solution**
The Accepted Answer is correct.
Thanks, I don't think I was aware of the 'into' bit of GroupBy and I was trying to use the .GroupBy() sort of methods rather than the SQL like syntax. And thanks for confirming the ToList() amendment and including it in the Accepted Answer :-) | ```
var q = from date in allDates
group date by date.Year into datesByYear
select datesByYear.ToList();
q.ToList(); //returns List<List<DateTime>>
``` |
69,761 | <p>I'd like to to associate a file extension to the current executable in C#.
This way when the user clicks on the file afterwards in explorer, it'll run my executable with the given file as the first argument.
Ideally it'd also set the icon for the given file extensions to the icon for my executable.
Thanks all.</p>
| [
{
"answer_id": 69805,
"author": "Steve Morgan",
"author_id": 5806,
"author_profile": "https://Stackoverflow.com/users/5806",
"pm_score": 2,
"selected": false,
"text": "<p>The file associations are defined in the registry under HKEY_CLASSES_ROOT.</p>\n\n<p>There's a VB.NET example <a href... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'd like to to associate a file extension to the current executable in C#.
This way when the user clicks on the file afterwards in explorer, it'll run my executable with the given file as the first argument.
Ideally it'd also set the icon for the given file extensions to the icon for my executable.
Thanks all. | There doesn't appear to be a .Net API for directly managing file associations but you can use the Registry classes for reading and writing the keys you need to.
You'll need to create a key under HKEY\_CLASSES\_ROOT with the name set to your file extension (eg: ".txt"). Set the default value of this key to a unique name for your file type, such as "Acme.TextFile". Then create another key under HKEY\_CLASSES\_ROOT with the name set to "Acme.TextFile". Add a subkey called "DefaultIcon" and set the default value of the key to the file containing the icon you wish to use for this file type. Add another sibling called "shell". Under the "shell" key, add a key for each action you wish to have available via the Explorer context menu, setting the default value for each key to the path to your executable followed by a space and "%1" to represent the path to the file selected.
For instance, here's a sample registry file to create an association between .txt files and EmEditor:
```
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\.txt]
@="emeditor.txt"
[HKEY_CLASSES_ROOT\emeditor.txt]
@="Text Document"
[HKEY_CLASSES_ROOT\emeditor.txt\DefaultIcon]
@="%SystemRoot%\\SysWow64\\imageres.dll,-102"
[HKEY_CLASSES_ROOT\emeditor.txt\shell]
[HKEY_CLASSES_ROOT\emeditor.txt\shell\open]
[HKEY_CLASSES_ROOT\emeditor.txt\shell\open\command]
@="\"C:\\Program Files\\EmEditor\\EMEDITOR.EXE\" \"%1\""
[HKEY_CLASSES_ROOT\emeditor.txt\shell\print]
[HKEY_CLASSES_ROOT\emeditor.txt\shell\print\command]
@="\"C:\\Program Files\\EmEditor\\EMEDITOR.EXE\" /p \"%1\""
``` |
69,766 | <p>I'm working on VS 2005 and something has gone wrong on my machine. Suddenly, out of the blue, I can no longer build deployment files.
The build message is:</p>
<pre><code>ERROR: An error occurred generating a bootstrapper: Invalid syntax.
ERROR: General failure building bootstrapper
ERROR: Unrecoverable build error
</code></pre>
<p>A quick Google search brings up the last 2 lines, but nobody in cyberspace has ever reported the first message before. (Hooray! I'm first at SOMETHING on the 'net!)</p>
<p>Other machines in my office are able to do the build.
My machine has been able to do the build before. I have no idea what changed that upset the delicate balance of things on my box.
I have also tried all the traditional rituals i.e. closing Visual Studio, blowing away all the bin and obj folders, rebooting, etc. to no avail.</p>
<p>For simplicity's sake, I created a little "Hello World" app with a deployment file.
Herewith the build output:</p>
<pre><code>------ Build started: Project: HelloWorld, Configuration: Debug Any CPU ------
HelloWorld -> C:\Vault\Multi Client\Tests\HelloWorld\HelloWorld\bin\Debug\HelloWorld.exe
------ Starting pre-build validation for project 'HelloWorldSetup' ------
------ Pre-build validation for project 'HelloWorldSetup' completed ------
------ Build started: Project: HelloWorldSetup, Configuration: Debug ------
Building file 'C:\Vault\Multi Client\Tests\HelloWorld\HelloWorldSetup\Debug\HelloWorldSetup.msi'...
ERROR: An error occurred generating a bootstrapper: Invalid syntax.
ERROR: General failure building bootstrapper
ERROR: Unrecoverable build error
========== Build: 1 succeeded or up-to-date, 1 failed, 0 skipped ==========
</code></pre>
<p>I am using:</p>
<ul>
<li>MS Visual Studio 2005 Version 8.0.50727.762 (SP .050727-7600) </li>
<li>.NET Framework Version 2.0.50727 </li>
<li>OS: Windows XP Pro</li>
</ul>
<p>Again, I have no idea what changed. All I know is that one day everything was working fine; the next day I suddenly can't do any deployment builds at all (though all other projects still compile fine).</p>
<p>I posted <a href="http://social.msdn.microsoft.com/forums/en-US/vssetup/thread/240c82e9-1696-4618-846c-aaae21427a52/" rel="nofollow noreferrer">this on MSDN</a> about a month ago, and they don't seem to know what's going on, either.</p>
<p>Anyone have any idea what this is about?</p>
<hr>
<p>@Brad Wilson: Thanks, but if you read my original post, you'll see that I already did start an entire solution from scratch, and that didn't help.</p>
<hr>
<p>@deemer: I went through all the pain of uninstalling and reinstalling, even though I didn't have your recommended reading while waiting... and - Misery! - still the same error reappears. It seems that my computer has somehow been branded as unsuitable for doing deployment builds ever again.</p>
<p>Does anyone have any idea where this "secret switch" might be?</p>
| [
{
"answer_id": 69809,
"author": "deemer",
"author_id": 11192,
"author_profile": "https://Stackoverflow.com/users/11192",
"pm_score": 1,
"selected": false,
"text": "<p>If it doesn't build only on the one machine, then either you've managed to make that machine different, or the VS2005 ins... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7850/"
] | I'm working on VS 2005 and something has gone wrong on my machine. Suddenly, out of the blue, I can no longer build deployment files.
The build message is:
```
ERROR: An error occurred generating a bootstrapper: Invalid syntax.
ERROR: General failure building bootstrapper
ERROR: Unrecoverable build error
```
A quick Google search brings up the last 2 lines, but nobody in cyberspace has ever reported the first message before. (Hooray! I'm first at SOMETHING on the 'net!)
Other machines in my office are able to do the build.
My machine has been able to do the build before. I have no idea what changed that upset the delicate balance of things on my box.
I have also tried all the traditional rituals i.e. closing Visual Studio, blowing away all the bin and obj folders, rebooting, etc. to no avail.
For simplicity's sake, I created a little "Hello World" app with a deployment file.
Herewith the build output:
```
------ Build started: Project: HelloWorld, Configuration: Debug Any CPU ------
HelloWorld -> C:\Vault\Multi Client\Tests\HelloWorld\HelloWorld\bin\Debug\HelloWorld.exe
------ Starting pre-build validation for project 'HelloWorldSetup' ------
------ Pre-build validation for project 'HelloWorldSetup' completed ------
------ Build started: Project: HelloWorldSetup, Configuration: Debug ------
Building file 'C:\Vault\Multi Client\Tests\HelloWorld\HelloWorldSetup\Debug\HelloWorldSetup.msi'...
ERROR: An error occurred generating a bootstrapper: Invalid syntax.
ERROR: General failure building bootstrapper
ERROR: Unrecoverable build error
========== Build: 1 succeeded or up-to-date, 1 failed, 0 skipped ==========
```
I am using:
* MS Visual Studio 2005 Version 8.0.50727.762 (SP .050727-7600)
* .NET Framework Version 2.0.50727
* OS: Windows XP Pro
Again, I have no idea what changed. All I know is that one day everything was working fine; the next day I suddenly can't do any deployment builds at all (though all other projects still compile fine).
I posted [this on MSDN](http://social.msdn.microsoft.com/forums/en-US/vssetup/thread/240c82e9-1696-4618-846c-aaae21427a52/) about a month ago, and they don't seem to know what's going on, either.
Anyone have any idea what this is about?
---
@Brad Wilson: Thanks, but if you read my original post, you'll see that I already did start an entire solution from scratch, and that didn't help.
---
@deemer: I went through all the pain of uninstalling and reinstalling, even though I didn't have your recommended reading while waiting... and - Misery! - still the same error reappears. It seems that my computer has somehow been branded as unsuitable for doing deployment builds ever again.
Does anyone have any idea where this "secret switch" might be? | **SOLUTION!**
Thanks to Michael Bleifer of Microsoft support - I installed .NET 2.0 SP1, and the problem was solved! |
69,768 | <p>Mac OS X ships with apache pre-installed, but the files are in non-standard locations. This question is a place to collect information about where configuration files live, and how to tweak the apache installation to do things like serve php pages.</p>
| [
{
"answer_id": 69784,
"author": "ctcherry",
"author_id": 10322,
"author_profile": "https://Stackoverflow.com/users/10322",
"pm_score": 5,
"selected": true,
"text": "<p>Apache Config file is: /private/etc/apache2/httpd.conf</p>\n\n<p>Default DocumentRoot is: /Library/Webserver/Documents/<... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3575/"
] | Mac OS X ships with apache pre-installed, but the files are in non-standard locations. This question is a place to collect information about where configuration files live, and how to tweak the apache installation to do things like serve php pages. | Apache Config file is: /private/etc/apache2/httpd.conf
Default DocumentRoot is: /Library/Webserver/Documents/
To enable PHP, at around line 114 (maybe) in the /private/etc/apache2/httpd.conf file is the following line:
```
#LoadModule php5_module libexec/apache2/libphp5.so
```
Remove the pound sign to uncomment the line so now it looks like this:
```
LoadModule php5_module libexec/apache2/libphp5.so
```
Restart Apache: System Preferences -> Sharing -> Un-check "Web Sharing" and re-check it.
**OR**
```
$ sudo apachectl restart
``` |
69,843 | <p>Does anybody have useful example of <code>this</code> assignment inside a C# method? I have been asked for it once during job interview, and I am still interested in answer myself. </p>
| [
{
"answer_id": 69851,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": -1,
"selected": false,
"text": "<p>You cannot overwrite \"this\". It points to the current object instance.</p>\n"
},
{
"answer_id": 69878,
... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
] | Does anybody have useful example of `this` assignment inside a C# method? I have been asked for it once during job interview, and I am still interested in answer myself. | The other answers are incorrect when they say you cannot assign to 'this'. True, you can't for a class type, but you *can* for a struct type:
```
public struct MyValueType
{
public int Id;
public void Swap(ref MyValueType other)
{
MyValueType temp = this;
this = other;
other = temp;
}
}
```
At any point a struct can alter itself by assigning to 'this' like so. |
69,849 | <p>When is it a good idea to use factory methods within an object instead of a Factory class?</p>
| [
{
"answer_id": 69861,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 3,
"selected": false,
"text": "<p>It's really a matter of taste. Factory classes can be abstracted/interfaced away as necessary, whereas factory methods... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | When is it a good idea to use factory methods within an object instead of a Factory class? | I like thinking about design pattens in terms of my classes being 'people,' and the patterns are the ways that the people talk to each other.
So, to me the factory pattern is like a hiring agency. You've got someone that will need a variable number of workers. This person may know some info they need in the people they hire, but that's it.
So, when they need a new employee, they call the hiring agency and tell them what they need. Now, to actually *hire* someone, you need to know a lot of stuff - benefits, eligibility verification, etc. But the person hiring doesn't need to know any of this - the hiring agency handles all of that.
In the same way, using a Factory allows the consumer to create new objects without having to know the details of how they're created, or what their dependencies are - they only have to give the information they actually want.
```
public interface IThingFactory
{
Thing GetThing(string theString);
}
public class ThingFactory : IThingFactory
{
public Thing GetThing(string theString)
{
return new Thing(theString, firstDependency, secondDependency);
}
}
```
So, now the consumer of the ThingFactory can get a Thing, without having to know about the dependencies of the Thing, except for the string data that comes from the consumer. |
69,913 | <p>What is the reason browsers do not correctly recognize:</p>
<pre><code><script src="foobar.js" /> <!-- self-closing script element -->
</code></pre>
<p>Only this is recognized:</p>
<pre><code><script src="foobar.js"></script>
</code></pre>
<p>Does this break the concept of XHTML support?</p>
<p>Note: This statement is correct at least for all IE (6-8 beta 2).</p>
| [
{
"answer_id": 69984,
"author": "squadette",
"author_id": 7754,
"author_profile": "https://Stackoverflow.com/users/7754",
"pm_score": 10,
"selected": true,
"text": "<p>The non-normative appendix ‘HTML Compatibility Guidelines’ of the XHTML 1 specification says:</p>\n<p><a href=\"http://w... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10778/"
] | What is the reason browsers do not correctly recognize:
```
<script src="foobar.js" /> <!-- self-closing script element -->
```
Only this is recognized:
```
<script src="foobar.js"></script>
```
Does this break the concept of XHTML support?
Note: This statement is correct at least for all IE (6-8 beta 2). | The non-normative appendix ‘HTML Compatibility Guidelines’ of the XHTML 1 specification says:
[С.3. Element Minimization and Empty Element Content](http://www.w3.org/TR/xhtml1/#C_3)
>
> Given an empty instance of an element whose content model is not `EMPTY` (for example, an empty title or paragraph) do not use the minimized form (e.g. use `<p> </p>` and not `<p />`).
>
>
>
[XHTML DTD](http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict) specifies script elements as:
```
<!-- script statements, which may include CDATA sections -->
<!ELEMENT script (#PCDATA)>
``` |
69,928 | <p>The company has the traditional complex organizational structure, defining the amount of levels using the letter 'n' rather than an actual number. I will try and express the structure I'm trying to achieve in mono-spaced font: </p>
<pre><code> Alice
,--------|-------,------,------,
Bob Fred Jack Kim Lucy
| |
Charlie Greg
Darren Henry
Eric
</code></pre>
<p>As you can see it's not symmetrical, as Jack, Kim and Lucy report to Alice but have no reports of their own. </p>
<p>Using a <code>TreeView</code> with an <code>ItemsPanel</code> containing a <code>StackPanel</code> and <code>Orientation="Horizontal"</code> is <a href="http://www.codeproject.com/KB/WPF/CustomTreeViewLayout.aspx" rel="nofollow noreferrer">easy enough</a>, but this can result in a very large <code>TreeView</code> once some people have 20 others reporting to them! You can <a href="http://www.codeproject.com/KB/WPF/AdvancedCustomTreeViewLyt.aspx" rel="nofollow noreferrer">also use</a> <code>Triggers</code> to peek into whether a <code>TreeViewItem</code> has children with <code>Property="TreeViewItem.HasItems"</code>, but this is not in the same context as the before-mentioned <code>ItemsPanel</code>. <em>Eg: I can tell that Fred has reports, but not whether they have reports of their own.</em> </p>
<p>So, can you conditionally format <code>TreeViewItems</code> to be Vertical if they have no children of their own?</p>
| [
{
"answer_id": 69952,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 2,
"selected": false,
"text": "<p>Josh Smith has a excecllent CodeProject article about TreeView. Read it <a href=\"http://www.codeproject.com/KB/WPF/Ad... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/952/"
] | The company has the traditional complex organizational structure, defining the amount of levels using the letter 'n' rather than an actual number. I will try and express the structure I'm trying to achieve in mono-spaced font:
```
Alice
,--------|-------,------,------,
Bob Fred Jack Kim Lucy
| |
Charlie Greg
Darren Henry
Eric
```
As you can see it's not symmetrical, as Jack, Kim and Lucy report to Alice but have no reports of their own.
Using a `TreeView` with an `ItemsPanel` containing a `StackPanel` and `Orientation="Horizontal"` is [easy enough](http://www.codeproject.com/KB/WPF/CustomTreeViewLayout.aspx), but this can result in a very large `TreeView` once some people have 20 others reporting to them! You can [also use](http://www.codeproject.com/KB/WPF/AdvancedCustomTreeViewLyt.aspx) `Triggers` to peek into whether a `TreeViewItem` has children with `Property="TreeViewItem.HasItems"`, but this is not in the same context as the before-mentioned `ItemsPanel`. *Eg: I can tell that Fred has reports, but not whether they have reports of their own.*
So, can you conditionally format `TreeViewItems` to be Vertical if they have no children of their own? | I did end up using tips from the linked article, which I'd already read through but didn't think would help me.
The meat of it happens here, in a converter:
```
<ValueConversion(GetType(ItemsPresenter), GetType(Orientation))> _
Public Class ItemsPanelOrientationConverter
Implements IValueConverter
Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, _
ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) _
As Object Implements System.Windows.Data.IValueConverter.Convert
'The 'value' argument should reference an ItemsPresenter.'
Dim itemsPresenter As ItemsPresenter = TryCast(value, ItemsPresenter)
If itemsPresenter Is Nothing Then
Return Binding.DoNothing
End If
'The ItemsPresenter''s templated parent should be a TreeViewItem.'
Dim item As TreeViewItem = TryCast(itemsPresenter.TemplatedParent, TreeViewItem)
If item Is Nothing Then
Return Binding.DoNothing
End If
For Each i As Object In item.Items
Dim element As StaffMember = TryCast(i, StaffMember)
If element.IsManager Then
'If this element has children, then return Horizontal'
Return Orientation.Horizontal
End If
Next
'Must be a stub ItemPresenter'
Return Orientation.Vertical
End Function
```
Which in turn gets consumed in a style I created for the TreeView:
```
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate >
<ItemsPanelTemplate.Resources>
<local:ItemsPanelOrientationConverter x:Key="conv" />
</ItemsPanelTemplate.Resources>
<StackPanel IsItemsHost="True"
Orientation="{Binding
RelativeSource={x:Static RelativeSource.TemplatedParent},
Converter={StaticResource conv}}" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
``` |
69,934 | <p>I've been unsuccessful in getting Emacs to switch from 8 space tabs to 4 space tabs when pressing the <kbd>TAB</kbd> in buffers with the major mode <code>text-mode</code>. I've added the following to my <code>.emacs</code>:</p>
<pre><code>(setq-default indent-tabs-mode nil)
(setq-default tab-width 4)
;;; And I have tried
(setq indent-tabs-mode nil)
(setq tab-width 4)
</code></pre>
<p>No matter how I change my <code>.emacs</code> file (or my buffer's local variables) the <kbd>TAB</kbd> button always does the same thing.</p>
<ol>
<li>If there is no text above, indent <strong>8</strong> spaces</li>
<li>If there is text on the previous line, indent to the beginning of the second word</li>
</ol>
<p>As much as I love Emacs this is getting annoying. Is there a way to make Emacs to at least indent 4 space when there's not text in the previous line?</p>
| [
{
"answer_id": 69992,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried</p>\n\n<pre><code>(setq tab-width 4)\n</code></pre>\n"
},
{
"answer_id": 70027,
"author": "Bert... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
] | I've been unsuccessful in getting Emacs to switch from 8 space tabs to 4 space tabs when pressing the `TAB` in buffers with the major mode `text-mode`. I've added the following to my `.emacs`:
```
(setq-default indent-tabs-mode nil)
(setq-default tab-width 4)
;;; And I have tried
(setq indent-tabs-mode nil)
(setq tab-width 4)
```
No matter how I change my `.emacs` file (or my buffer's local variables) the `TAB` button always does the same thing.
1. If there is no text above, indent **8** spaces
2. If there is text on the previous line, indent to the beginning of the second word
As much as I love Emacs this is getting annoying. Is there a way to make Emacs to at least indent 4 space when there's not text in the previous line? | >
> Do not confuse variable `tab-width` with variable `tab-stop-list`.
> The former is used for the display of literal `TAB` characters.
> The latter controls what characters are inserted when you press the `TAB` character in certain modes.
>
>
>
-- [GNU Emacs Manual](https://www.gnu.org/software/emacs/manual/html_node/efaq/Changing-the-length-of-a-Tab.html)
```
(customize-variable (quote tab-stop-list))
```
or add *tab-stop-list* entry to *custom-set-variables* in *.emacs* file:
```
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(tab-stop-list (quote (4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 84 88 92 96 100 104 108 112 116 120))))
```
Another way to edit the tab behavior is with with `M-x edit-tab-stops`.
See the [GNU Emacs Manual on Tab Stops](https://www.gnu.org/software/emacs/manual/html_node/emacs/Tab-Stops.html) for more information on `edit-tab-stops`. |
69,959 | <p>After successfully building dblink on solaris 10 using Sun C 5.9
SunOS_sparc 2007/05/03 and gmake.</p>
<p>I ran gmake installcheck and got the following output:</p>
<pre><code>========== running regression test queries ==========
test dblink ... FAILED
======================
1 of 1 tests failed.
</code></pre>
<p>The differences that caused some tests to fail can be viewed in the
file "./regression.diffs". A copy of the test summary that you see
above is saved in the file "./regression.out".</p>
<p>First error in regression.diffs file:</p>
<blockquote>
<p>psql:dblink.sql:11: ERROR: could not load library "/apps/postgresql/
lib/dblink.so": ld.so.1: postgre
s: fatal: relocation error: file /apps/postgresql/lib/dblink.so:
symbol PG_GETARG_TEXT_PP: referenced symbol not found</p>
</blockquote>
<p>I am running postgreSQL version 8.2.4 with the latest dblink source.</p>
<p>Has anyone got any idea what I need to do to solve this problem.
Thanks. </p>
| [
{
"answer_id": 73275,
"author": "Grant Johnson",
"author_id": 12518,
"author_profile": "https://Stackoverflow.com/users/12518",
"pm_score": 0,
"selected": false,
"text": "<p>Does the file it is looking for actually exist? Is it in that location?</p>\n\n<p>It may be one of a few things ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5385/"
] | After successfully building dblink on solaris 10 using Sun C 5.9
SunOS\_sparc 2007/05/03 and gmake.
I ran gmake installcheck and got the following output:
```
========== running regression test queries ==========
test dblink ... FAILED
======================
1 of 1 tests failed.
```
The differences that caused some tests to fail can be viewed in the
file "./regression.diffs". A copy of the test summary that you see
above is saved in the file "./regression.out".
First error in regression.diffs file:
>
> psql:dblink.sql:11: ERROR: could not load library "/apps/postgresql/
> lib/dblink.so": ld.so.1: postgre
> s: fatal: relocation error: file /apps/postgresql/lib/dblink.so:
> symbol PG\_GETARG\_TEXT\_PP: referenced symbol not found
>
>
>
I am running postgreSQL version 8.2.4 with the latest dblink source.
Has anyone got any idea what I need to do to solve this problem.
Thanks. | To solve this issue I tried using the 8.2 dblink sources, instead of the latest version.
You also need to make sure you use gnu make not the sun make. |
69,998 | <p>How do I prevent vim from replacing spaces with tabs when autoindent is on?</p>
<p>An example: if I have two tabs and 7 spaces in the beginning of the line, and <code>tabstop=3</code>, and I press Enter, the next line has four tabs and 1 space in the beginning, but I don't want that...</p>
| [
{
"answer_id": 70034,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.jwz.org/doc/tabs-vs-spaces.html\" rel=\"nofollow noreferrer\">Maybe the bottom of this can help you?</a></... | 2008/09/16 | [
"https://Stackoverflow.com/questions/69998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How do I prevent vim from replacing spaces with tabs when autoindent is on?
An example: if I have two tabs and 7 spaces in the beginning of the line, and `tabstop=3`, and I press Enter, the next line has four tabs and 1 space in the beginning, but I don't want that... | It is perhaps a good idea not to use tabs at all.
```
:set expandtab
```
If you want to replace all the tabs in your file to 3 spaces (which will look pretty similar to `tabstop=3`):
```
:%s/^I/ /
```
(where `^I` is the `TAB` character)
From the VIM online help:
```
'tabstop' 'ts' number (default 8)
local to buffer
Number of spaces that a <Tab> in the file counts for. Also see
|:retab| command, and 'softtabstop' option.
Note: Setting 'tabstop' to any other value than 8 can make your file
appear wrong in many places (e.g., when printing it).
There are four main ways to use tabs in Vim:
1. Always keep 'tabstop' at 8, set 'softtabstop' and 'shiftwidth' to 4
(or 3 or whatever you prefer) and use 'noexpandtab'. Then Vim
will use a mix of tabs and spaces, but typing <Tab> and <BS> will
behave like a tab appears every 4 (or 3) characters.
2. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use
'expandtab'. This way you will always insert spaces. The
formatting will never be messed up when 'tabstop' is changed.
3. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use a
|modeline| to set these values when editing the file again. Only
works when using Vim to edit the file.
4. Always set 'tabstop' and 'shiftwidth' to the same value, and
'noexpandtab'. This should then work (for initial indents only)
for any tabstop setting that people use. It might be nice to have
tabs after the first non-blank inserted as spaces if you do this
though. Otherwise aligned comments will be wrong when 'tabstop' is
changed.
``` |
70,013 | <p>Is there any way to know if I'm compiling under a specific Microsoft Visual Studio version?</p>
| [
{
"answer_id": 70021,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": -1,
"selected": false,
"text": "<p>In visual studio, go to help | about and look at the version of Visual Studio that you're using to compile your app.</p>\n"... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11234/"
] | Is there any way to know if I'm compiling under a specific Microsoft Visual Studio version? | `_MSC_VER` and possibly `_MSC_FULL_VER` is what you need. You can also examine [visualc.hpp](https://www.boost.org/doc/libs/master/boost/config/compiler/visualc.hpp) in any recent boost install for some usage examples.
Some values for the more recent versions of the compiler are:
```
MSVC++ 14.24 _MSC_VER == 1924 (Visual Studio 2019 version 16.4)
MSVC++ 14.23 _MSC_VER == 1923 (Visual Studio 2019 version 16.3)
MSVC++ 14.22 _MSC_VER == 1922 (Visual Studio 2019 version 16.2)
MSVC++ 14.21 _MSC_VER == 1921 (Visual Studio 2019 version 16.1)
MSVC++ 14.2 _MSC_VER == 1920 (Visual Studio 2019 version 16.0)
MSVC++ 14.16 _MSC_VER == 1916 (Visual Studio 2017 version 15.9)
MSVC++ 14.15 _MSC_VER == 1915 (Visual Studio 2017 version 15.8)
MSVC++ 14.14 _MSC_VER == 1914 (Visual Studio 2017 version 15.7)
MSVC++ 14.13 _MSC_VER == 1913 (Visual Studio 2017 version 15.6)
MSVC++ 14.12 _MSC_VER == 1912 (Visual Studio 2017 version 15.5)
MSVC++ 14.11 _MSC_VER == 1911 (Visual Studio 2017 version 15.3)
MSVC++ 14.1 _MSC_VER == 1910 (Visual Studio 2017 version 15.0)
MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015 version 14.0)
MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013 version 12.0)
MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012 version 11.0)
MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010 version 10.0)
MSVC++ 9.0 _MSC_FULL_VER == 150030729 (Visual Studio 2008, SP1)
MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008 version 9.0)
MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005 version 8.0)
MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio .NET 2003 version 7.1)
MSVC++ 7.0 _MSC_VER == 1300 (Visual Studio .NET 2002 version 7.0)
MSVC++ 6.0 _MSC_VER == 1200 (Visual Studio 6.0 version 6.0)
MSVC++ 5.0 _MSC_VER == 1100 (Visual Studio 97 version 5.0)
```
The version number above of course refers to the major version of your Visual studio you see in the about box, not to the year in the name. A thorough list can be found [here](https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B#Internal_version_numbering). [Starting recently](https://blogs.msdn.microsoft.com/vcblog/2016/10/05/visual-c-compiler-version/), Visual Studio will start updating its ranges monotonically, meaning you should check ranges, rather than exact compiler values.
`cl.exe /?` will give a hint of the used version, e.g.:
```
c:\program files (x86)\microsoft visual studio 11.0\vc\bin>cl /?
Microsoft (R) C/C++ Optimizing Compiler Version 17.00.50727.1 for x86
.....
``` |
70,074 | <p>I'm new to Ruby, so I'm having some trouble understanding this weird exception problem I'm having. I'm using the ruby-aaws gem to access Amazon ECS: <a href="http://www.caliban.org/ruby/ruby-aws/" rel="nofollow noreferrer">http://www.caliban.org/ruby/ruby-aws/</a>. This defines a class Amazon::AWS:Error:</p>
<pre><code>module Amazon
module AWS
# All dynamically generated exceptions occur within this namespace.
#
module Error
# An exception generator class.
#
class AWSError
attr_reader :exception
def initialize(xml)
err_class = xml.elements['Code'].text.sub( /^AWS.*\./, '' )
err_msg = xml.elements['Message'].text
unless Amazon::AWS::Error.const_defined?( err_class )
Amazon::AWS::Error.const_set( err_class,
Class.new( StandardError ) )
end
ex_class = Amazon::AWS::Error.const_get( err_class )
@exception = ex_class.new( err_msg )
end
end
end
end
end
</code></pre>
<p>This means that if you get an errorcode like <code>AWS.InvalidParameterValue</code>, this will produce (in its exception variable) a new class <code>Amazon::AWS::Error::InvalidParameterValue</code> which is a subclass of <code>StandardError</code>.</p>
<p>Now here's where it gets weird. I have some code that looks like this:</p>
<pre><code>begin
do_aws_stuff
rescue Amazon::AWS::Error => error
puts "Got an AWS error"
end
</code></pre>
<p>Now, if <code>do_aws_stuff</code> throws a <code>NameError</code>, my rescue block gets triggered. It seems that Amazon::AWS::Error isn't the superclass of the generated error - I guess since it's a module everything is a subclass of it? Certainly if I do:</p>
<pre><code>irb(main):007:0> NameError.new.kind_of?(Amazon::AWS::Error)
=> true
</code></pre>
<p>It says <code>true</code>, which I find confusing, especially given this:</p>
<pre><code>irb(main):009:0> NameError.new.kind_of?(Amazon::AWS)
=> false
</code></pre>
<p>What's going on, and how am I supposed to separate out AWS errors from other type of errors? Should I do something like:</p>
<pre><code>begin
do_aws_stuff
rescue => error
if error.class.to_s =~ /^Amazon::AWS::Error/
puts "Got an AWS error"
else
raise error
end
end
</code></pre>
<p>That seems exceptionally janky. The errors thrown aren't class AWSError either - they're raised like this:</p>
<pre><code>error = Amazon::AWS::Error::AWSError.new( xml )
raise error.exception
</code></pre>
<p>So the exceptions I'm looking to <code>rescue</code> from are the generated exception types that only inherit from StandardError.</p>
<p>To clarify, I have two questions:</p>
<ol>
<li><p>Why is NameError, a Ruby built in exception, a <code>kind_of?(Amazon::AWS::Error)</code>, which is a module?<br>
<strong>Answer:</strong> I had said <code>include Amazon::AWS::Error</code> at the top of my file, thinking it was kind of like a Java import or C++ include. What this actually did was add everything defined in <code>Amazon::AWS::Error</code> (present and future) to the implicit Kernel class, which is an ancestor of every class. This means <strong>anything</strong> would pass <code>kind_of?(Amazon::AWS::Error)</code>.</p></li>
<li><p>How can I best distinguish the dynamically-created exceptions in <code>Amazon::AWS::Error</code> from random other exceptions from elsewhere?</p></li>
</ol>
| [
{
"answer_id": 70127,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 1,
"selected": false,
"text": "<p>Well, from what I can tell:</p>\n\n<pre><code>Class.new( StandardError )\n</code></pre>\n\n<p>Is creating a new class wit... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11284/"
] | I'm new to Ruby, so I'm having some trouble understanding this weird exception problem I'm having. I'm using the ruby-aaws gem to access Amazon ECS: <http://www.caliban.org/ruby/ruby-aws/>. This defines a class Amazon::AWS:Error:
```
module Amazon
module AWS
# All dynamically generated exceptions occur within this namespace.
#
module Error
# An exception generator class.
#
class AWSError
attr_reader :exception
def initialize(xml)
err_class = xml.elements['Code'].text.sub( /^AWS.*\./, '' )
err_msg = xml.elements['Message'].text
unless Amazon::AWS::Error.const_defined?( err_class )
Amazon::AWS::Error.const_set( err_class,
Class.new( StandardError ) )
end
ex_class = Amazon::AWS::Error.const_get( err_class )
@exception = ex_class.new( err_msg )
end
end
end
end
end
```
This means that if you get an errorcode like `AWS.InvalidParameterValue`, this will produce (in its exception variable) a new class `Amazon::AWS::Error::InvalidParameterValue` which is a subclass of `StandardError`.
Now here's where it gets weird. I have some code that looks like this:
```
begin
do_aws_stuff
rescue Amazon::AWS::Error => error
puts "Got an AWS error"
end
```
Now, if `do_aws_stuff` throws a `NameError`, my rescue block gets triggered. It seems that Amazon::AWS::Error isn't the superclass of the generated error - I guess since it's a module everything is a subclass of it? Certainly if I do:
```
irb(main):007:0> NameError.new.kind_of?(Amazon::AWS::Error)
=> true
```
It says `true`, which I find confusing, especially given this:
```
irb(main):009:0> NameError.new.kind_of?(Amazon::AWS)
=> false
```
What's going on, and how am I supposed to separate out AWS errors from other type of errors? Should I do something like:
```
begin
do_aws_stuff
rescue => error
if error.class.to_s =~ /^Amazon::AWS::Error/
puts "Got an AWS error"
else
raise error
end
end
```
That seems exceptionally janky. The errors thrown aren't class AWSError either - they're raised like this:
```
error = Amazon::AWS::Error::AWSError.new( xml )
raise error.exception
```
So the exceptions I'm looking to `rescue` from are the generated exception types that only inherit from StandardError.
To clarify, I have two questions:
1. Why is NameError, a Ruby built in exception, a `kind_of?(Amazon::AWS::Error)`, which is a module?
**Answer:** I had said `include Amazon::AWS::Error` at the top of my file, thinking it was kind of like a Java import or C++ include. What this actually did was add everything defined in `Amazon::AWS::Error` (present and future) to the implicit Kernel class, which is an ancestor of every class. This means **anything** would pass `kind_of?(Amazon::AWS::Error)`.
2. How can I best distinguish the dynamically-created exceptions in `Amazon::AWS::Error` from random other exceptions from elsewhere? | Ok, I'll try to help here :
First a module is not a class, it allows you to mix behaviour in a class. second see the following example :
```
module A
module B
module Error
def foobar
puts "foo"
end
end
end
end
class StandardError
include A::B::Error
end
StandardError.new.kind_of?(A::B::Error)
StandardError.new.kind_of?(A::B)
StandardError.included_modules #=> [A::B::Error,Kernel]
```
kind\_of? tells you that yes, Error does possess All of A::B::Error behaviour (which is normal since it includes A::B::Error) however it does not include all the behaviour from A::B and therefore is not of the A::B kind. (duck typing)
Now there is a very good chance that ruby-aws reopens one of the superclass of NameError and includes Amazon::AWS:Error in there. (monkey patching)
You can find out programatically where the module is included in the hierarchy with the following :
```
class Class
def has_module?(module_ref)
if self.included_modules.include?(module_ref) and not self.superclass.included_modules.include?(module_ref)
puts self.name+" has module "+ module_ref.name
else
self.superclass.nil? ? false : self.superclass.has_module?(module_ref)
end
end
end
StandardError.has_module?(A::B::Error)
NameError.has_module?(A::B::Error)
```
Regarding your second question I can't see anything better than
```
begin
#do AWS error prone stuff
rescue Exception => e
if Amazon::AWS::Error.constants.include?(e.class.name)
#awsError
else
whatever
end
end
```
(edit -- above code doesn't work as is : name includes module prefix which is not the case of the constants arrays. You should definitely contact the lib maintainer the AWSError class looks more like a factory class to me :/ )
I don't have ruby-aws here and the caliban site is blocked by the company's firewall so I can't test much further.
Regarding the include : that might be the thing doing the monkey patching on the StandardError hierarchy. I am not sure anymore but most likely doing it at the root of a file outside every context is including the module on Object or on the Object metaclass. (this is what would happen in IRB, where the default context is Object, not sure about in a file)
from the [pickaxe on modules](http://www.rubycentral.com/pickaxe/tut_modules.html) :
`A couple of points about the include statement before we go on. First, it has nothing to do with files. C programmers use a preprocessor directive called #include to insert the contents of one file into another during compilation. The Ruby include statement simply makes a reference to a named module. If that module is in a separate file, you must use require to drag that file in before using include.`
(edit -- I can't seem to be able to comment using this browser :/ yay for locked in platforms) |
70,090 | <p>How can I visually customize autocomplete fields in Wicket (change colors, fonts, etc.)?</p>
| [
{
"answer_id": 77292,
"author": "Loren_",
"author_id": 13703,
"author_profile": "https://Stackoverflow.com/users/13703",
"pm_score": 4,
"selected": true,
"text": "<p>You can use CSS to modify the look of this component. For the Ajax auto-complete component in 1.3 the element you want to... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11384/"
] | How can I visually customize autocomplete fields in Wicket (change colors, fonts, etc.)? | You can use CSS to modify the look of this component. For the Ajax auto-complete component in 1.3 the element you want to override is div.wicket-aa, so for example you might do:
```
div.wicket-aa {
background-color:white;
border:1px solid #CCCCCC;
color:black;
}
div.wicket-aa ul {
list-style-image:none;
list-style-position:outside;
list-style-type:none;
margin:0pt;
padding:5px;
}
div.wicket-aa ul li.selected {
background-color:#CCCCCC;
}
``` |
70,096 | <p>I've been looking for a way to convert an mp3 to aac programmatically or via the command line with no luck. Ideally, I'd have a snippet of code that I could call from my rails app that converts an mp3 to an aac. I installed ffmpeg and libfaac and was able to create an aac file with the following command:</p>
<p><code>ffmpeg -i test.mp3 -acodec libfaac -ab 163840 dest.aac</code></p>
<p>When i change the output file's name to dest.m4a, it doesn't play in iTunes. </p>
<p>Thanks! </p>
| [
{
"answer_id": 70117,
"author": "Dark Shikari",
"author_id": 11206,
"author_profile": "https://Stackoverflow.com/users/11206",
"pm_score": 2,
"selected": false,
"text": "<p>There are only three free AAC encoders that I know of that are available through a commandline interface:</p>\n\n<o... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I've been looking for a way to convert an mp3 to aac programmatically or via the command line with no luck. Ideally, I'd have a snippet of code that I could call from my rails app that converts an mp3 to an aac. I installed ffmpeg and libfaac and was able to create an aac file with the following command:
`ffmpeg -i test.mp3 -acodec libfaac -ab 163840 dest.aac`
When i change the output file's name to dest.m4a, it doesn't play in iTunes.
Thanks! | [FFmpeg](http://en.wikipedia.org/wiki/Ffmpeg) provides AAC encoding facilities if you've compiled them in. If you are using Windows you can grab full binaries from [here](http://arrozcru.no-ip.org/ffmpeg_builds/)
```
ffmpeg -i source.mp3 -acodec libfaac -ab 128k dest.aac
```
I'm not sure how you would call this from ruby.
Also, be sure to set the bitrate appropriately. |
70,123 | <p>If I have a table structure that is: </p>
<pre><code>code, description, isdeleted
</code></pre>
<p>where <code>code</code> is the primary key.</p>
<p>The user creates a record, then later on deletes it. Because I am using soft deletes the <code>isdeleted</code> will be set to true. Then in my queries I would be doing a select with the where clause <code>and not isdeleted</code></p>
<p>Now if a user goes to create a new record they may see that code 'ABC' doesn't exist so they tried to recreate it. The select statement won't find it because of the where clause. But there will be a primary key index error.</p>
<p>Should the user be allowed to re-use the record? I would think not since the idea of the soft delete is to keep the record for queries on older data so that joins to the 'deleted' record still work. If the user was allowed to re-use the code then they could change the description which might change the view of the historical data. But is it too harsh to stop them from using that code at all?</p>
<p>Or should I be using a completely hidden primary key and then the 'code' field can be re-used?</p>
| [
{
"answer_id": 70149,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 2,
"selected": false,
"text": "<p>I know many people have argued that the data should be natural, but you should be using a primary key that is completely sep... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11355/"
] | If I have a table structure that is:
```
code, description, isdeleted
```
where `code` is the primary key.
The user creates a record, then later on deletes it. Because I am using soft deletes the `isdeleted` will be set to true. Then in my queries I would be doing a select with the where clause `and not isdeleted`
Now if a user goes to create a new record they may see that code 'ABC' doesn't exist so they tried to recreate it. The select statement won't find it because of the where clause. But there will be a primary key index error.
Should the user be allowed to re-use the record? I would think not since the idea of the soft delete is to keep the record for queries on older data so that joins to the 'deleted' record still work. If the user was allowed to re-use the code then they could change the description which might change the view of the historical data. But is it too harsh to stop them from using that code at all?
Or should I be using a completely hidden primary key and then the 'code' field can be re-used? | I know many people have argued that the data should be natural, but you should be using a primary key that is completely separate from your data if you're going to be supporting soft deletes without the intention of always re-using the previous record when this situation arises.
Having a divorced primary key will allow you to have multiple records with the same 'code' value, and it will allow you to "undelete" (otherwise, why bother with a soft delete?) a value without worrying about overwriting something else.
Personally, I prefer the numeric auto-incremented style of ID, but there are many proponents of GUIDs. |
70,143 | <p>I have a xslt stylesheet with multiple <code>xsl:import</code>s and I want to merge them all into the one xslt file.</p>
<p>It is a limitation of the system we are using where it passes around the xsl stylesheet as a string object stored in memory. This is transmitted to remote machine where it performs the transformation. Since it is not being loaded from disk the href links are broken, so we need to remove the <code>xsl:import</code>s from the stylesheet.</p>
<p>Are there any tools out there which can do this?</p>
| [
{
"answer_id": 70180,
"author": "chrisb",
"author_id": 8262,
"author_profile": "https://Stackoverflow.com/users/8262",
"pm_score": 0,
"selected": false,
"text": "<p>Why would you want to? They're usually seperated for a reason afterall (often maintainability)</p>\n\n<p>You could always ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/716/"
] | I have a xslt stylesheet with multiple `xsl:import`s and I want to merge them all into the one xslt file.
It is a limitation of the system we are using where it passes around the xsl stylesheet as a string object stored in memory. This is transmitted to remote machine where it performs the transformation. Since it is not being loaded from disk the href links are broken, so we need to remove the `xsl:import`s from the stylesheet.
Are there any tools out there which can do this? | You can use an XSL stylesheet to merge your stylesheets. However, this is equivalent to using the xsl:include element, not xsl:import (as Azat Razetdinov has already pointed out). You can read up on the difference [here](http://www.w3.org/TR/xslt#section-Combining-Stylesheets).
Therefore you should first replace the xsl:import's with xsl:include's, resolve any conflicts and test whether you still get the correct results. After that, you could use the following stylesheet to merge your existing stylesheets into one. Just apply it to your master stylesheet:
```
<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="xsl:include">
<xsl:copy-of select="document(@href)/xsl:stylesheet/*"/>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
```
The first template replaces all xsl:include's with the included stylesheets by using the document function, which reads in the file referenced in the href attribute. The second template is the [identity transformation](https://stackoverflow.com/questions/56837/how-can-i-make-an-exact-copy-of-a-xml-nodes-children-with-xslt).
I've tested it with Xalan and it seems to work fine. |
70,150 | <p>I am looking for attributes I can use to ensure the best runtime performance for my .Net application by giving hints to the loader, JIT compiler or ngen.</p>
<p>For example we have <a href="http://msdn.microsoft.com/en-us/library/k2wxda47.aspx" rel="noreferrer">DebuggableAttribute</a> which should be set to not debug and not disable optimization for optimal performance.</p>
<pre><code>[Debuggable(false, false)]
</code></pre>
<p>Are there any others I should know about?</p>
| [
{
"answer_id": 70168,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 1,
"selected": false,
"text": "<p>I found another: <a href=\"http://msdn.microsoft.com/en-us/library/system.resources.neutralresourceslanguageattribut... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1242/"
] | I am looking for attributes I can use to ensure the best runtime performance for my .Net application by giving hints to the loader, JIT compiler or ngen.
For example we have [DebuggableAttribute](http://msdn.microsoft.com/en-us/library/k2wxda47.aspx) which should be set to not debug and not disable optimization for optimal performance.
```
[Debuggable(false, false)]
```
Are there any others I should know about? | Ecma-335 specifies some more CompilationRelaxations for relaxed exception handling (so-called e-relaxed calls) in Annex F "Imprecise faults", but they have not been exposed by Microsoft.
Specifically CompilationRelaxations.RelaxedArrayExceptions and CompilationRelaxations.RelaxedNullReferenceException are mentioned there.
It'd be intersting what happens when you just try some integers in the CompilationRelaxationsAttribute's ctor ;) |
70,161 | <p>As we all know numbers can be written either in numerics, or called by their names. While there are a lot of examples to be found that convert 123 into one hundred twenty three, I could not find good examples of how to convert it the other way around.</p>
<p>Some of the caveats:</p>
<ol>
<li>cardinal/nominal or ordinal: "one" and "first"</li>
<li>common spelling mistakes: "forty"/"fourty"</li>
<li>hundreds/thousands: 2100 -> "twenty one hundred" and also "two thousand and one hundred"</li>
<li>separators: "eleven hundred fifty two", but also "elevenhundred fiftytwo" or "eleven-hundred fifty-two" and whatnot</li>
<li>colloquialisms: "thirty-something"</li>
<li>fractions: 'one third', 'two fifths'</li>
<li>common names: 'a dozen', 'half'</li>
</ol>
<p>And there are probably more caveats possible that are not yet listed.
Suppose the algorithm needs to be very robust, and even understand spelling mistakes.</p>
<p>What fields/papers/studies/algorithms should I read to learn how to write all this?
Where is the information?</p>
<blockquote>
<p>PS: My final parser should actually understand 3 different languages, English, Russian and Hebrew. And maybe at a later stage more languages will be added. Hebrew also has male/female numbers, like "one man" and "one woman" have a different "one" — "ehad" and "ahat". Russian also has some of its own complexities.</p>
</blockquote>
<p>Google does a great job at this. For example:</p>
<p><a href="http://www.google.com/search?q=two+thousand+and+one+hundred+plus+five+dozen+and+four+fifths+in+decimal" rel="noreferrer">http://www.google.com/search?q=two+thousand+and+one+hundred+plus+five+dozen+and+four+fifths+in+decimal</a></p>
<p>(the reverse is also possible <a href="http://www.google.com/search?q=999999999999+in+english" rel="noreferrer">http://www.google.com/search?q=999999999999+in+english</a>)</p>
| [
{
"answer_id": 70198,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "<p>I have some code I wrote a while ago: <a href=\"https://github.com/ghewgill/text2num\" rel=\"nofollow noreferrer\">text... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11414/"
] | As we all know numbers can be written either in numerics, or called by their names. While there are a lot of examples to be found that convert 123 into one hundred twenty three, I could not find good examples of how to convert it the other way around.
Some of the caveats:
1. cardinal/nominal or ordinal: "one" and "first"
2. common spelling mistakes: "forty"/"fourty"
3. hundreds/thousands: 2100 -> "twenty one hundred" and also "two thousand and one hundred"
4. separators: "eleven hundred fifty two", but also "elevenhundred fiftytwo" or "eleven-hundred fifty-two" and whatnot
5. colloquialisms: "thirty-something"
6. fractions: 'one third', 'two fifths'
7. common names: 'a dozen', 'half'
And there are probably more caveats possible that are not yet listed.
Suppose the algorithm needs to be very robust, and even understand spelling mistakes.
What fields/papers/studies/algorithms should I read to learn how to write all this?
Where is the information?
>
> PS: My final parser should actually understand 3 different languages, English, Russian and Hebrew. And maybe at a later stage more languages will be added. Hebrew also has male/female numbers, like "one man" and "one woman" have a different "one" — "ehad" and "ahat". Russian also has some of its own complexities.
>
>
>
Google does a great job at this. For example:
<http://www.google.com/search?q=two+thousand+and+one+hundred+plus+five+dozen+and+four+fifths+in+decimal>
(the reverse is also possible <http://www.google.com/search?q=999999999999+in+english>) | I was playing around with a PEG parser to do what you wanted (and may post that as a separate answer later) when I noticed that there's a very simple algorithm that does a remarkably good job with common forms of numbers in English, Spanish, and German, at the very least.
Working with English for example, you need a dictionary that maps words to values in the obvious way:
```
"one" -> 1, "two" -> 2, ... "twenty" -> 20,
"dozen" -> 12, "score" -> 20, ...
"hundred" -> 100, "thousand" -> 1000, "million" -> 1000000
```
...and so forth
The algorithm is just:
```
total = 0
prior = null
for each word w
v <- value(w) or next if no value defined
prior <- case
when prior is null: v
when prior > v: prior+v
else prior*v
else
if w in {thousand,million,billion,trillion...}
total <- total + prior
prior <- null
total = total + prior unless prior is null
```
For example, this progresses as follows:
```
total prior v unconsumed string
0 _ four score and seven
4 score and seven
0 4
20 and seven
0 80
_ seven
0 80
7
0 87
87
total prior v unconsumed string
0 _ two million four hundred twelve thousand eight hundred seven
2 million four hundred twelve thousand eight hundred seven
0 2
1000000 four hundred twelve thousand eight hundred seven
2000000 _
4 hundred twelve thousand eight hundred seven
2000000 4
100 twelve thousand eight hundred seven
2000000 400
12 thousand eight hundred seven
2000000 412
1000 eight hundred seven
2000000 412000
1000 eight hundred seven
2412000 _
8 hundred seven
2412000 8
100 seven
2412000 800
7
2412000 807
2412807
```
And so on. I'm not saying it's perfect, but for a quick and dirty it does quite well.
---
Addressing your specific list on edit:
1. cardinal/nominal or ordinal: "one" and "first" -- **just put them in the dictionary**
2. english/british: "fourty"/"forty" -- **ditto**
3. hundreds/thousands:
2100 -> "twenty one hundred" and also "two thousand and one hundred" -- **works as is**
4. separators: "eleven hundred fifty two", but also "elevenhundred fiftytwo" or "eleven-hundred fifty-two" and whatnot -- **just define "next word" to be the longest prefix that matches a defined word, or up to the next non-word if none do, for a start**
5. colloqialisms: "thirty-something" -- **works**
6. fragments: 'one third', 'two fifths' -- **uh, not yet...**
7. common names: 'a dozen', 'half' -- **works; you can even do things like "a half dozen"**
Number 6 is the only one I don't have a ready answer for, and that's because of the ambiguity between ordinals and fractions (in English at least) added to the fact that my last cup of coffee was *many* hours ago. |
70,216 | <p>In Java, you often see a META-INF folder containing some meta files. What is the purpose of this folder and what can I put there?</p>
| [
{
"answer_id": 70221,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 8,
"selected": false,
"text": "<p>From <a href=\"http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html\" rel=\"noreferrer\">the official JAR File S... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11429/"
] | In Java, you often see a META-INF folder containing some meta files. What is the purpose of this folder and what can I put there? | Generally speaking, you should not put anything into META-INF yourself. Instead, you should rely upon whatever you use to package up your JAR. This is one of the areas where I think Ant really excels: specifying JAR file manifest attributes. It's very easy to say something like:
```
<jar ...>
<manifest>
<attribute name="Main-Class" value="MyApplication"/>
</manifest>
</jar>
```
At least, I think that's easy... :-)
The point is that META-INF should be considered an internal Java *meta* directory. Don't mess with it! Any files you want to include with your JAR should be placed in some other sub-directory or at the root of the JAR itself. |
70,272 | <p>I have an application with one form in it, and on the Load method I need to hide the form. </p>
<p>The form will display itself when it has a need to (think along the lines of a outlook 2003 style popup), but I can' figure out how to hide the form on load without something messy.</p>
<p>Any suggestions?</p>
| [
{
"answer_id": 70282,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": -1,
"selected": false,
"text": "<p>Here is a simple approach:<br>\nIt's in C# (I don't have VB compiler at the moment)</p>\n\n<pre><code>public Form1()\n{\n ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1500/"
] | I have an application with one form in it, and on the Load method I need to hide the form.
The form will display itself when it has a need to (think along the lines of a outlook 2003 style popup), but I can' figure out how to hide the form on load without something messy.
Any suggestions? | I'm coming at this from C#, but should be very similar in vb.net.
In your main program file, in the Main method, you will have something like:
```
Application.Run(new MainForm());
```
This creates a new main form and limits the lifetime of the application to the lifetime of the main form.
However, if you remove the parameter to Application.Run(), then the application will be started with no form shown and you will be free to show and hide forms as much as you like.
Rather than hiding the form in the Load method, initialize the form before calling Application.Run(). I'm assuming the form will have a NotifyIcon on it to display an icon in the task bar - this can be displayed even if the form itself is not yet visible. Calling `Form.Show()` or `Form.Hide()` from handlers of NotifyIcon events will show and hide the form respectively. |
70,303 | <p>I have a structure in C#:</p>
<pre><code>public struct UserInfo
{
public string str1
{
get;
set;
}
public string str2
{
get;
set;
}
}
</code></pre>
<p>The only rule is that <code>UserInfo(str1="AA", str2="BB").Equals(UserInfo(str1="BB", str2="AA"))</code></p>
<p>How to override the GetHashCode function for this structure? </p>
| [
{
"answer_id": 70323,
"author": "VolkerK",
"author_id": 4833,
"author_profile": "https://Stackoverflow.com/users/4833",
"pm_score": 0,
"selected": false,
"text": "<p>Many possibilities. E.g.<br /></p>\n\n<p><code>\nreturn str1.GetHashCode() ^ str1.GetHashCode()\n</code></p>\n"
},
{
... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] | I have a structure in C#:
```
public struct UserInfo
{
public string str1
{
get;
set;
}
public string str2
{
get;
set;
}
}
```
The only rule is that `UserInfo(str1="AA", str2="BB").Equals(UserInfo(str1="BB", str2="AA"))`
How to override the GetHashCode function for this structure? | [MSDN](http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx):
A hash function must have the following properties:
>
> * If two objects compare as equal, the `GetHashCode` method for each object must return the same value. However, if two objects do not compare as equal, the `GetHashCode` methods for the two object do not have to return different values.
> * The `GetHashCode` method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's `Equals` method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.
> * For the best performance, a hash function must generate a random distribution for all input.
>
>
>
Taking it into account correct way is:
```
return str1.GetHashCode() ^ str2.GetHashCode()
```
`^` can be substituted with other commutative operation |
70,318 | <p>Experienced with Rails / ActiveRecord 2.1.1</p>
<ul>
<li>You create a first version with (for example) ruby script\generate scaffold product title:string description:text image_url:string</li>
<li>This create (for example) a migration file called 20080910122415_create_products.rb</li>
<li>You apply the migration with rake db:migrate</li>
<li>Now, you add a field to the product table with ruby script\generate migration add_price_to_product price:decimal</li>
<li>This create a migration file called 20080910125745_add_price_to_product.rb</li>
<li>If you try to run rake db:migrate, it will actually revert the first migration, not apply the next one! So your product table will get destroyed!</li>
<li>But if you ran rake alone, it would have told you that one migration was pending</li>
</ul>
<p>Pls note that applying rake db:migrate (once the table has been destroyed) will apply all migrations in order.</p>
<p>The only workaround I found is to specify the version of the new migration as in: </p>
<pre><code>rake db:migrate version=20080910125745
</code></pre>
<p>So I'm wondering: is this an expected new behavior?</p>
| [
{
"answer_id": 70771,
"author": "Jean",
"author_id": 7898,
"author_profile": "https://Stackoverflow.com/users/7898",
"pm_score": 2,
"selected": true,
"text": "<p>You should be able to use </p>\n\n<pre><code>rake db:migrate:up \n</code></pre>\n\n<p>to force it to go forward, but then you ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11477/"
] | Experienced with Rails / ActiveRecord 2.1.1
* You create a first version with (for example) ruby script\generate scaffold product title:string description:text image\_url:string
* This create (for example) a migration file called 20080910122415\_create\_products.rb
* You apply the migration with rake db:migrate
* Now, you add a field to the product table with ruby script\generate migration add\_price\_to\_product price:decimal
* This create a migration file called 20080910125745\_add\_price\_to\_product.rb
* If you try to run rake db:migrate, it will actually revert the first migration, not apply the next one! So your product table will get destroyed!
* But if you ran rake alone, it would have told you that one migration was pending
Pls note that applying rake db:migrate (once the table has been destroyed) will apply all migrations in order.
The only workaround I found is to specify the version of the new migration as in:
```
rake db:migrate version=20080910125745
```
So I'm wondering: is this an expected new behavior? | You should be able to use
```
rake db:migrate:up
```
to force it to go forward, but then you risk missing interleaved migrations from other people on your team
if you run
```
rake db:migrate
```
twice, it will reapply all your migrations.
I encounter the same behavior on windows with SQLite, it might be a bug specific to such an environment.
**Edit** -- I found why. In the railstie database.rake task you have the following code :
```
desc "Migrate the database through scripts in db/migrate. Target specific version with VERSION=x. Turn off output with VERBOSE=false."
task :migrate => :environment do
ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
ActiveRecord::Migrator.migrate("db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
end
```
Then in my environment variables I have
```
echo %Version% #=> V3.5.0f
```
in Ruby
```
ENV["VERSION"] # => V3.5.0f
ENV["VERSION"].to_i #=>0 not nil !
```
thus the rake task calls
```
ActiveRecord::Migrator.migrate("db/migrate/", 0)
```
and in ActiveRecord::Migrator we have :
```
class Migrator#:nodoc:
class << self
def migrate(migrations_path, target_version = nil)
case
when target_version.nil? then up(migrations_path, target_version)
when current_version > target_version then down(migrations_path, target_version)
else up(migrations_path, target_version)
end
end
```
Yes, `rake db:migrate VERSION=0` is the long version for `rake db:migrate:down`
**Edit** - I would go update the lighthouse bug but I the super company proxy forbids that I connect there
In the meantime you may try to unset Version before you call migrate ... |
70,324 | <p>What is the main difference between an inner class and a static nested class in Java? Does design / implementation play a role in choosing one of these?</p>
| [
{
"answer_id": 70339,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 3,
"selected": false,
"text": "<p>Ummm… An inner class <em>is</em> a nested class… Do you mean anonymous class and inner class?</p>\n<p>Edit: If you actual... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193/"
] | What is the main difference between an inner class and a static nested class in Java? Does design / implementation play a role in choosing one of these? | From the [Java Tutorial](http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html):
>
> Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.
>
>
>
Static nested classes are accessed using the enclosing class name:
```
OuterClass.StaticNestedClass
```
For example, to create an object for the static nested class, use this syntax:
```
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
```
Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:
```
class OuterClass {
...
class InnerClass {
...
}
}
```
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
```
OuterClass outerObject = new OuterClass()
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
```
see: [Java Tutorial - Nested Classes](http://download.oracle.com/javase/tutorial/java/javaOO/nested.html)
For completeness note that there is also such a thing as an [inner class *without* an enclosing instance](https://stackoverflow.com/questions/20468856/is-it-true-that-every-inner-class-requires-an-enclosing-instance):
```
class A {
int t() { return 1; }
static A a = new A() { int t() { return 2; } };
}
```
Here, `new A() { ... }` is an *inner class defined in a static context* and does not have an enclosing instance. |
70,366 | <p>When trying to commit to a cvs branch after adding a new file I get this error</p>
<pre><code>Assertion failed: key != NULL, file hash.c, line 317
</code></pre>
<p>Any idea how to fix it so I can check my code in?<br>
Both server and client are Linux and there are pre-commits involved.</p>
| [
{
"answer_id": 70441,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps there is some kind of pre-commit check on your repository, see <a href=\"http://ximbiot.com/cvs/manual/cvs... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7873/"
] | When trying to commit to a cvs branch after adding a new file I get this error
```
Assertion failed: key != NULL, file hash.c, line 317
```
Any idea how to fix it so I can check my code in?
Both server and client are Linux and there are pre-commits involved. | >
> sleep-er writes:
>
>
>
> >
> > Not sure what the issue was but I solved it by going onto the server and deleting the file Attic/newfile.v in the repository and adding it again.
> >
> >
> >
>
>
>
The "Attic" is the place where deleted files go in CVS. At some point in the past, someone checked in newfile.v, and at some later point it was deleted, hence moved to the Attic.
By deleting the ,v file from the repository you corrupted older commits that included the file "newfile". Do not do this.
The correct way is to restore the deleted file, then replace its content by the new file.
According to <http://www.cs.indiana.edu/~machrist/notes/cvs.html>
>
> To recover a file that has been removed from the repository, you essentially need to update that file to its last revision number (before it was actually deleted). For example:
>
>
> cvs update -r 1.7 deleted\_file
>
>
> This will recover deleted\_file in your working repository. To find deleted files and their last revision number, issue cvs log at the command prompt.
>
>
>
Edited in reply to comment to explain what the ,v file in the Attic means. |
70,371 | <p>I'm trying out ASP.NET MVC routing and have of course stumbled across a problem. I have a section, /Admin/Pages/, and this is also accessible through /Pages/, which it shouldn't. What could I be missing?</p>
<p>The routing code in global.asax:</p>
<pre><code>public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Pages", // Route name
"Admin/Pages/{action}/{id}", // URL with parameters
// Parameter defaults
new { controller = "Pages", action = "Index", id = "" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
// Parameter defaults
new { controller = "Home", action = "Index", id = "" }
);
}
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 70396,
"author": "Steve Morgan",
"author_id": 5806,
"author_profile": "https://Stackoverflow.com/users/5806",
"pm_score": 4,
"selected": true,
"text": "<p>I'd suggest adding an explicit route for /Pages/ at the beginning.</p>\n\n<p>The problem is that it's being handled by... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11334/"
] | I'm trying out ASP.NET MVC routing and have of course stumbled across a problem. I have a section, /Admin/Pages/, and this is also accessible through /Pages/, which it shouldn't. What could I be missing?
The routing code in global.asax:
```
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Pages", // Route name
"Admin/Pages/{action}/{id}", // URL with parameters
// Parameter defaults
new { controller = "Pages", action = "Index", id = "" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
// Parameter defaults
new { controller = "Home", action = "Index", id = "" }
);
}
```
Thanks! | I'd suggest adding an explicit route for /Pages/ at the beginning.
The problem is that it's being handled by the Default route and deriving:
controller = "Pages"
action = "Index"
id = ""
which are exactly the same as the parameters for your Admin route. |
70,386 | <p>There are three places where menus show up in the new MFC functionality (Feature Pack):</p>
<ul>
<li>In menu bars (CMFCMenuBar)</li>
<li>In popup menus (CMFCPopupMenu)</li>
<li>In the 'dropdown menu' version of CMFCButton</li>
</ul>
<p>I want to put icons (high-color and with transparancy) in the menus in all of them. I have found CFrameWndEx::OnDrawMenuImage() which I can use to custom draw the icons in front of the menu bar items. It's not very convenient, having to implement icon drawing in 2008, but it works. For the others I haven't found a solution yet. Is there an automagic way to set icons for menus?</p>
| [
{
"answer_id": 72654,
"author": "Nevermind",
"author_id": 12366,
"author_profile": "https://Stackoverflow.com/users/12366",
"pm_score": 2,
"selected": false,
"text": "<p>I believe (but I may be wrong) that these classes are the same as the BCGToolbar classes that were included in MFC whe... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11449/"
] | There are three places where menus show up in the new MFC functionality (Feature Pack):
* In menu bars (CMFCMenuBar)
* In popup menus (CMFCPopupMenu)
* In the 'dropdown menu' version of CMFCButton
I want to put icons (high-color and with transparancy) in the menus in all of them. I have found CFrameWndEx::OnDrawMenuImage() which I can use to custom draw the icons in front of the menu bar items. It's not very convenient, having to implement icon drawing in 2008, but it works. For the others I haven't found a solution yet. Is there an automagic way to set icons for menus? | This is how I got it to work:
### First
, as the others said, create an invisible toolbar next to your main toolbar (I'm using the usual names based on AppWizard's names):
```
MainFrm.h:
class CMainFrame
{
//...
CMFCToolBar m_wndToolBar;
CMFCToolBar m_wndInvisibleToolBar;
//...
};
MainFrm.cpp:
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
//...
// Normal, visible toolbar
if(m_wndToolBar.Create(this,
TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC))
{
VERIFY( m_wndToolBar.LoadToolBar(
theApp.m_bHiColorIcons ? IDR_MAINFRAME_256 : IDR_MAINFRAME) );
// Only the docking makes the toolbar visible
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
DockPane(&m_wndToolBar);
}
// Invisible toolbar; simply calling Create(this) seems to be enough
if(m_wndInvisibleToolBar.Create(this))
{
// Just load, no docking and stuff
VERIFY( m_wndInvisibleToolBar.LoadToolBar(IDR_OTHERTOOLBAR) );
}
}
```
### Second: The images and toolbar resources
`IDR_MAINFRAME` and `IDR_MAINFRAME_256` were generated by AppWizard. The former is the ugly 16 color version and the latter is the interesting high color version.
Despite its name, if I remember correctly, even the AppWizard-generated image has 24bit color depth. The cool thing: Just replace it with a 32bit image and that'll work, too.
There is the invisible toolbar `IDR_OTHERTOOLBAR`: I created a toolbar with the resource editor. Just some dummy icons and the command IDs. VS then generated a bitmap which I replaced with my high color version. Done!
### Note
Don't open the toolbars with the resource editor: It may have to convert it to 4bit before it can do anything with it. And even *if* you let it do that (because, behind Visual Studio's back, wou're going to replace the result with the high color image again, ha!), I found that it (sometimes?) simply cannot edit the toolbar. Very strange.
In that case I advise to directly edit the .rc file. |
70,389 | <p>I have apache 2.2 and tomcat 5.5 running on a Windows XP machine.</p>
<p>Which tomcat/apache connector is the easiest to set up and is well documented? </p>
| [
{
"answer_id": 70432,
"author": "Chris Broadfoot",
"author_id": 3947,
"author_profile": "https://Stackoverflow.com/users/3947",
"pm_score": 0,
"selected": false,
"text": "<p><code>mod_jk</code>, or simply just use <code>mod_proxy</code> even though it's not really a Tomcat connector.</p>... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8633/"
] | I have apache 2.2 and tomcat 5.5 running on a Windows XP machine.
Which tomcat/apache connector is the easiest to set up and is well documented? | `[mod\_proxy\_ajp](http://httpd.apache.org/docs/2.2/mod/mod_proxy.html)` would be the easiest to use if you are using Apache 2.2. It is part of the Apache distribution so you don't need to install any additional software.
In your `httpd.conf` you need to make sure that `mod_proxy` and `mod_proxy_ajp` are loaded:
```
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
```
Then you can use the [ProxyPass](http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypass) and [ProxyPassReverse](http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypassreverse) directives as follows:
```
ProxyPass /portal ajp://localhost:8009/portal
ProxyPassReverse /portal ajp://localhost:8009/portal
```
You should consult the Apache 2.2 documentation for a full catalog of the directives available. |
70,397 | <p>So I'm working on a Rails app to get the feeling for the whole thing. I've got a <code>Product</code> model that's a standard ActiveRecord model. However, I also want to get some additional product info from Amazon ECS. So my complete model gets some of its info from the database and some from the web service. My question is, should I:</p>
<ol>
<li><p>Make two models a Product and a ProductAWS, and then tie them together at the controller level.</p></li>
<li><p>Have the Product ActiveRecord model contain a ProductAWS object that does all the AWS stuff?</p></li>
<li><p>Just add all the AWS functionality to my Product model.</p></li>
<li><p>???</p></li>
</ol>
| [
{
"answer_id": 70457,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the <code>composed_of</code> relationship in ActiveRecord. You make a regular class with all the attributes that... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11284/"
] | So I'm working on a Rails app to get the feeling for the whole thing. I've got a `Product` model that's a standard ActiveRecord model. However, I also want to get some additional product info from Amazon ECS. So my complete model gets some of its info from the database and some from the web service. My question is, should I:
1. Make two models a Product and a ProductAWS, and then tie them together at the controller level.
2. Have the Product ActiveRecord model contain a ProductAWS object that does all the AWS stuff?
3. Just add all the AWS functionality to my Product model.
4. ??? | As with most things: it depends. Each of your ideas have merit. If it were me, I'd start out this way:
```
class Product < ActiveRecord::Base
has_one :aws_item
end
class AWSItem
belongs_to :product
end
```
The key questions you want to ask yourself are:
**Are you only going to be offering AWS ECS items, or will you have other products?** If you'll have products that have nothing to do with Amazon, don't care about ASIN, etc, then a has\_one could be the way to go. Or, even better, a polymorphic relationship to a :vendable interface so you can later plug in different extension types.
**Is it just behavior that is different, or is the data going to be largely different too?** Because you might want to consider:
>
>
> ```
> class Product < ActiveRecord::Base
> end
> class AWSItem < Product
> def do_amazon_stuff
> ...
> end
> end
>
> ```
>
>
**How do you want the system to perform when Amazon ECS isn't available?** Should it throw exceptions? Or should you rely on a local cached version of the catalog?
>
>
> ```
> class Product < ActiveRecord::Base
>
> end
>
> class ItemFetcher < BackgrounDRb::Rails
> def do_work
> # .... Make a cached copy of your ECS catalog here.
> # Copy the Amazon stuff into your local model
> end
> end
>
> ```
>
>
Walk through these questions slowly and the answer will become clearer. If it doesn't, start prototyping it out. Good luck! |