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 |
|---|---|---|---|---|---|---|
32,145 | <p>I'm going to try something with the format of this question and I'm very open to suggestions about a better way to handle it.</p>
<p>I didn't want to just dump a bunch of code in the question so I've posted the code for the class on <code>refactormycode</code>.</p>
<p><strong><a href="http://www.refactormycode.com/codes/461-base-class-for-easy-class-property-handling" rel="nofollow noreferrer">base class for easy class property handling</a></strong></p>
<p>My thought was that people can either post code snippets here or make changes on <code>refactormycode</code> and post links back to their refactorings. I'll make upvotes and accept an answer (assuming there's a clear "winner") based on that.</p>
<p>At any rate, on to the class itself:</p>
<p>I see a lot of debate about getter/setter class methods and is it better to just access simple property variables directly or should every class have explicit get/set methods defined, blah blah blah. I like the idea of having explicit methods in case you have to add more logic later. Then you don't have to modify any code that uses the class. However I hate having a million functions that look like this:</p>
<pre><code>public function getFirstName()
{
return $this->firstName;
}
public function setFirstName($firstName)
{
return $this->firstName;
}
</code></pre>
<p>Now I'm sure I'm not the first person to do this (I'm hoping that there's a better way of doing it that someone can suggest to me).</p>
<p>Basically, the PropertyHandler class has a __call magic method. Any methods that come through __call that start with "get" or "set" are then routed to functions that set or retrieve values into an associative array. The key into the array is the name of the calling method after getting or setting. So, if the method coming into __call is "getFirstName", the array key is "FirstName".</p>
<p>I liked using __call because it will automatically take care of the case where the subclass already has a "getFirstName" method defined. My impression (and I may be wrong) is that the __get & __set magic methods don't do that.</p>
<p>So here's an example of how it would work:</p>
<pre><code>class PropTest extends PropertyHandler
{
public function __construct()
{
parent::__construct();
}
}
$props = new PropTest();
$props->setFirstName("Mark");
echo $props->getFirstName();
</code></pre>
<p>Notice that PropTest doesn't actually have "setFirstName" or "getFirstName" methods and neither does PropertyHandler. All that's doing is manipulating array values.</p>
<p>The other case would be where your subclass is already extending something else. Since you can't have true multiple inheritances in PHP, you can make your subclass have a PropertyHandler instance as a private variable. You have to add one more function but then things behave in exactly the same way.</p>
<pre><code>class PropTest2
{
private $props;
public function __construct()
{
$this->props = new PropertyHandler();
}
public function __call($method, $arguments)
{
return $this->props->__call($method, $arguments);
}
}
$props2 = new PropTest2();
$props2->setFirstName('Mark');
echo $props2->getFirstName();
</code></pre>
<p>Notice how the subclass has a __call method that just passes everything along to the PropertyHandler __call method.</p>
<hr>
<p>Another good argument against handling getters and setters this way is that it makes it really hard to document.</p>
<p>In fact, it's basically impossible to use any sort of document generation tool since the explicit methods to be don't documented don't exist.</p>
<p>I've pretty much abandoned this approach for now. It was an interesting learning exercise but I think it sacrifices too much clarity.</p>
| [
{
"answer_id": 32191,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 3,
"selected": false,
"text": "<p>The way I do it is the following:</p>\n\n<pre><code>class test {\n protected $x='';\n protected $y='';\n\n function set... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | I'm going to try something with the format of this question and I'm very open to suggestions about a better way to handle it.
I didn't want to just dump a bunch of code in the question so I've posted the code for the class on `refactormycode`.
**[base class for easy class property handling](http://www.refactormycode.com/codes/461-base-class-for-easy-class-property-handling)**
My thought was that people can either post code snippets here or make changes on `refactormycode` and post links back to their refactorings. I'll make upvotes and accept an answer (assuming there's a clear "winner") based on that.
At any rate, on to the class itself:
I see a lot of debate about getter/setter class methods and is it better to just access simple property variables directly or should every class have explicit get/set methods defined, blah blah blah. I like the idea of having explicit methods in case you have to add more logic later. Then you don't have to modify any code that uses the class. However I hate having a million functions that look like this:
```
public function getFirstName()
{
return $this->firstName;
}
public function setFirstName($firstName)
{
return $this->firstName;
}
```
Now I'm sure I'm not the first person to do this (I'm hoping that there's a better way of doing it that someone can suggest to me).
Basically, the PropertyHandler class has a \_\_call magic method. Any methods that come through \_\_call that start with "get" or "set" are then routed to functions that set or retrieve values into an associative array. The key into the array is the name of the calling method after getting or setting. So, if the method coming into \_\_call is "getFirstName", the array key is "FirstName".
I liked using \_\_call because it will automatically take care of the case where the subclass already has a "getFirstName" method defined. My impression (and I may be wrong) is that the \_\_get & \_\_set magic methods don't do that.
So here's an example of how it would work:
```
class PropTest extends PropertyHandler
{
public function __construct()
{
parent::__construct();
}
}
$props = new PropTest();
$props->setFirstName("Mark");
echo $props->getFirstName();
```
Notice that PropTest doesn't actually have "setFirstName" or "getFirstName" methods and neither does PropertyHandler. All that's doing is manipulating array values.
The other case would be where your subclass is already extending something else. Since you can't have true multiple inheritances in PHP, you can make your subclass have a PropertyHandler instance as a private variable. You have to add one more function but then things behave in exactly the same way.
```
class PropTest2
{
private $props;
public function __construct()
{
$this->props = new PropertyHandler();
}
public function __call($method, $arguments)
{
return $this->props->__call($method, $arguments);
}
}
$props2 = new PropTest2();
$props2->setFirstName('Mark');
echo $props2->getFirstName();
```
Notice how the subclass has a \_\_call method that just passes everything along to the PropertyHandler \_\_call method.
---
Another good argument against handling getters and setters this way is that it makes it really hard to document.
In fact, it's basically impossible to use any sort of document generation tool since the explicit methods to be don't documented don't exist.
I've pretty much abandoned this approach for now. It was an interesting learning exercise but I think it sacrifices too much clarity. | The way I do it is the following:
```
class test {
protected $x='';
protected $y='';
function set_y ($y) {
print "specific function set_y\n";
$this->y = $y;
}
function __call($function , $args) {
print "generic function $function\n";
list ($name , $var ) = split ('_' , $function );
if ($name == 'get' && isset($this->$var)) {
return $this->$var;
}
if ($name == 'set' && isset($this->$var)) {
$this->$var= $args[0];
return;
}
trigger_error ("Fatal error: Call to undefined method test::$function()");
}
}
$p = new test();
$p->set_x(20);
$p->set_y(30);
print $p->get_x();
print $p->get_y();
$p->set_z(40);
```
Which will output (line breaks added for clarity)
```
generic function set_x
specific function set_y
generic function get_x
20
generic function get_y
30
generic function set_z
Notice: Fatal error: Call to undefined method set_z() in [...] on line 16
``` |
32,149 | <p>Does anyone have a trusted Proper Case or PCase algorithm (similar to a UCase or Upper)? I'm looking for something that takes a value such as <code>"GEORGE BURDELL"</code> or <code>"george burdell"</code> and turns it into <code>"George Burdell"</code>.</p>
<p>I have a simple one that handles the simple cases. The ideal would be to have something that can handle things such as <code>"O'REILLY"</code> and turn it into <code>"O'Reilly"</code>, but I know that is tougher.</p>
<p>I am mainly focused on the English language if that simplifies things.</p>
<hr>
<p><strong>UPDATE:</strong> I'm using C# as the language, but I can convert from almost anything (assuming like functionality exists).</p>
<p>I agree that the McDonald's scneario is a tough one. I meant to mention that along with my O'Reilly example, but did not in the original post.</p>
| [
{
"answer_id": 32189,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "<p>What programming language do you use? Many languages allow callback functions for regular expression matches. These... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3203/"
] | Does anyone have a trusted Proper Case or PCase algorithm (similar to a UCase or Upper)? I'm looking for something that takes a value such as `"GEORGE BURDELL"` or `"george burdell"` and turns it into `"George Burdell"`.
I have a simple one that handles the simple cases. The ideal would be to have something that can handle things such as `"O'REILLY"` and turn it into `"O'Reilly"`, but I know that is tougher.
I am mainly focused on the English language if that simplifies things.
---
**UPDATE:** I'm using C# as the language, but I can convert from almost anything (assuming like functionality exists).
I agree that the McDonald's scneario is a tough one. I meant to mention that along with my O'Reilly example, but did not in the original post. | Unless I've misunderstood your question I don't think you need to roll your own, the TextInfo class can do it for you.
```
using System.Globalization;
CultureInfo.InvariantCulture.TextInfo.ToTitleCase("GeOrGE bUrdEll")
```
Will return "George Burdell. And you can use your own culture if there's some special rules involved.
**Update:** [Michael](https://stackoverflow.com/users/1684/michael-wolfenden) (in a comment to this answer) pointed out that this will not work if the input is all caps since the method will assume that it is an acronym. The naive workaround for this is to .ToLower() the text before submitting it to ToTitleCase. |
32,168 | <p>A question related to <a href="https://stackoverflow.com/questions/28002">Regular cast vs. static_cast vs. dynamic_cast</a>:</p>
<p>What cast syntax style do you prefer in C++?</p>
<ul>
<li>C-style cast syntax: <code>(int)foo</code></li>
<li>C++-style cast syntax: <code>static_cast<int>(foo)</code></li>
<li>constructor syntax: <code>int(foo)</code></li>
</ul>
<p>They may not translate to exactly the same instructions (do they?) but their effect should be the same (right?).</p>
<p>If you're just casting between the built-in numeric types, I find C++-style cast syntax too verbose. As a former Java coder I tend to use C-style cast syntax instead, but my local C++ guru insists on using constructor syntax.</p>
<p>What do you think?</p>
| [
{
"answer_id": 32180,
"author": "CiNN",
"author_id": 2566,
"author_profile": "https://Stackoverflow.com/users/2566",
"pm_score": 1,
"selected": false,
"text": "<p>C-style cast syntax, do not error check.\nC++-style cast syntax, does some checking.\nWhen using static_cast, even if it does... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2686/"
] | A question related to [Regular cast vs. static\_cast vs. dynamic\_cast](https://stackoverflow.com/questions/28002):
What cast syntax style do you prefer in C++?
* C-style cast syntax: `(int)foo`
* C++-style cast syntax: `static_cast<int>(foo)`
* constructor syntax: `int(foo)`
They may not translate to exactly the same instructions (do they?) but their effect should be the same (right?).
If you're just casting between the built-in numeric types, I find C++-style cast syntax too verbose. As a former Java coder I tend to use C-style cast syntax instead, but my local C++ guru insists on using constructor syntax.
What do you think? | It's best practice *never* to use C-style casts for three main reasons:
* as already mentioned, no checking is performed here. The programmer simply cannot know which of the various casts is used which weakens strong typing
* the new casts are intentionally visually striking. Since casts often reveal a weakness in the code, it's argued that making casts visible in the code is a good thing.
* this is especially true if searching for casts with an automated tool. Finding C-style casts reliably is nearly impossible.
As palm3D noted:
>
> I find C++-style cast syntax too verbose.
>
>
>
This is intentional, for the reasons given above.
The constructor syntax (official name: function-style cast) is semantically *the same* as the C-style cast and should be avoided as well (except for variable initializations on declaration), for the same reasons. It is debatable whether this should be true even for types that define custom constructors but in Effective C++, Meyers argues that even in those cases you should refrain from using them. To illustrate:
```
void f(auto_ptr<int> x);
f(static_cast<auto_ptr<int> >(new int(5))); // GOOD
f(auto_ptr<int>(new int(5)); // BAD
```
The `static_cast` here will actually call the `auto_ptr` constructor. |
32,173 | <p>I'm trying to disable a bunch of controls with JavaScript (so that they post back values). All the controls work fine except for my radio buttons as they lose their value. In the below code which is called via a recursive function to disable all child controls the Second else (else if (control is <code>RadioButton</code>)) is never hit and the RadioButton control is identified as a <code>Checkbox</code> control.</p>
<pre><code> private static void DisableControl(WebControl control)
{
if (control is CheckBox)
{
((CheckBox)control).InputAttributes.Add("disabled", "disabled");
}
else if (control is RadioButton)
{
}
else if (control is ImageButton)
{
((ImageButton)control).Enabled = false;
}
else
{
control.Attributes.Add("readonly", "readonly");
}
}
</code></pre>
<p>Two Questions:<br>
1. How do I identify which control is a radiobutton? <br>
2. How do I disable it so that it posts back its value?</p>
| [
{
"answer_id": 32203,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Off the top of my head, I think you have to check the \"type\" attribute of the checkbox to determine if it's a radio button... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2808/"
] | I'm trying to disable a bunch of controls with JavaScript (so that they post back values). All the controls work fine except for my radio buttons as they lose their value. In the below code which is called via a recursive function to disable all child controls the Second else (else if (control is `RadioButton`)) is never hit and the RadioButton control is identified as a `Checkbox` control.
```
private static void DisableControl(WebControl control)
{
if (control is CheckBox)
{
((CheckBox)control).InputAttributes.Add("disabled", "disabled");
}
else if (control is RadioButton)
{
}
else if (control is ImageButton)
{
((ImageButton)control).Enabled = false;
}
else
{
control.Attributes.Add("readonly", "readonly");
}
}
```
Two Questions:
1. How do I identify which control is a radiobutton?
2. How do I disable it so that it posts back its value? | I found 2 ways to get this to work, the below code correctly distinguishes between the RadioButton and Checkbox controls.
```
private static void DisableControl(WebControl control)
{
Type controlType = control.GetType();
if (controlType == typeof(CheckBox))
{
((CheckBox)control).InputAttributes.Add("disabled", "disabled");
}
else if (controlType == typeof(RadioButton))
{
((RadioButton)control).InputAttributes.Add("disabled", "true");
}
else if (controlType == typeof(ImageButton))
{
((ImageButton)control).Enabled = false;
}
else
{
control.Attributes.Add("readonly", "readonly");
}
}
```
And the solution I used is to set SubmitDisabledControls="True" in the form element which is not ideal as it allows a user to fiddle with the values but is fine in my scenario. The second solution is to mimic the Disabled behavior and details can be found here: https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx'><https://web.archive.org/web/20210608183803/http://aspnet.4guysfromrolla.com/articles/012506-1.aspx>. |
32,231 | <p>Are there any rapid Database protoyping tools that don't require me to declare a database schema, but rather create it based on the way I'm using my entities.</p>
<p>For example, assuming an empty database (pseudo code):</p>
<pre><code>user1 = new User() // Creates the user table with a single id column
user1.firstName = "Allain" // alters the table to have a firstName column as varchar(255)
user2 = new User() // Reuses the table
user2.firstName = "Bob"
user2.lastName = "Loblaw" // Alters the table to have a last name column
</code></pre>
<p>Since there are logical assumptions that can be made when dynamically creating the schema, and you could always override its choices by using your DB tools to tweak it later.</p>
<p>Also, you could generate your schema by unit testing it this way.</p>
<p>And obviously this is only for prototyping.</p>
<p>Is there anything like this out there?</p>
| [
{
"answer_id": 32297,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"http://code.google.com/appengine/\" rel=\"nofollow noreferrer\">Google's Application Engine</a> works like t... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] | Are there any rapid Database protoyping tools that don't require me to declare a database schema, but rather create it based on the way I'm using my entities.
For example, assuming an empty database (pseudo code):
```
user1 = new User() // Creates the user table with a single id column
user1.firstName = "Allain" // alters the table to have a firstName column as varchar(255)
user2 = new User() // Reuses the table
user2.firstName = "Bob"
user2.lastName = "Loblaw" // Alters the table to have a last name column
```
Since there are logical assumptions that can be made when dynamically creating the schema, and you could always override its choices by using your DB tools to tweak it later.
Also, you could generate your schema by unit testing it this way.
And obviously this is only for prototyping.
Is there anything like this out there? | [Google's Application Engine](http://code.google.com/appengine/) works like this. When you download the toolkit you get a local copy of the database engine for testing. |
32,241 | <p><a href="https://stackoverflow.com/questions/32149/does-anyone-have-a-good-proper-case-algorithm">Using this question</a> as the base is there an alogrithm or coding example to change some text to Pascal or Camel casing.</p>
<p>For example:</p>
<pre><code>mynameisfred
</code></pre>
<p>becomes</p>
<pre><code>Camel: myNameIsFred
Pascal: MyNameIsFred
</code></pre>
| [
{
"answer_id": 32277,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 0,
"selected": false,
"text": "<p>The only way to do that would be to run each section of the word through a dictionary.</p>\n\n<p>\"mynameisfred\" is jus... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1075/"
] | [Using this question](https://stackoverflow.com/questions/32149/does-anyone-have-a-good-proper-case-algorithm) as the base is there an alogrithm or coding example to change some text to Pascal or Camel casing.
For example:
```
mynameisfred
```
becomes
```
Camel: myNameIsFred
Pascal: MyNameIsFred
``` | I found a thread with a bunch of Perl guys arguing the toss on this question over at <http://www.perlmonks.org/?node_id=336331>.
I hope this isn't too much of a non-answer to the question, but I would say you have a bit of a problem in that it would be a very open-ended algorithm which could have a lot of 'misses' as well as hits. For example, say you inputted:-
```
camelCase("hithisisatest");
```
The output could be:-
```
"hiThisIsATest"
```
Or:-
```
"hitHisIsATest"
```
There's no way the algorithm would know which to prefer. You could add some extra code to specify that you'd prefer more common words, but again misses would occur (Peter Norvig wrote a very small spelling corrector over at <http://norvig.com/spell-correct.html> which *might* help algorithm-wise, I wrote a [C# implementation](http://web.archive.org/web/20080930045207/http://www.codegrunt.co.uk/code/cs/spellcorrect/spell-correct.cs) if C#'s your language).
I'd agree with Mark and say you'd be better off having an algorithm that takes a delimited input, i.e. this\_is\_a\_test and converts that. That'd be simple to implement, i.e. in pseudocode:-
```
SetPhraseCase(phrase, CamelOrPascal):
if no delimiters
if camelCase
return lowerFirstLetter(phrase)
else
return capitaliseFirstLetter(phrase)
words = splitOnDelimiter(phrase)
if camelCase
ret = lowerFirstLetter(first word)
else
ret = capitaliseFirstLetter(first word)
for i in 2 to len(words): ret += capitaliseFirstLetter(words[i])
return ret
capitaliseFirstLetter(word):
if len(word) <= 1 return upper(word)
return upper(word[0]) + word[1..len(word)]
lowerFirstLetter(word):
if len(word) <= 1 return lower(word)
return lower(word[0]) + word[1..len(word)]
```
You could also replace my capitaliseFirstLetter() function with a proper case algorithm if you so wished.
A C# implementation of the above described algorithm is as follows (complete console program with test harness):-
```
using System;
class Program {
static void Main(string[] args) {
var caseAlgorithm = new CaseAlgorithm('_');
while (true) {
string input = Console.ReadLine();
if (string.IsNullOrEmpty(input)) return;
Console.WriteLine("Input '{0}' in camel case: '{1}', pascal case: '{2}'",
input,
caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.CamelCase),
caseAlgorithm.SetPhraseCase(input, CaseAlgorithm.CaseMode.PascalCase));
}
}
}
public class CaseAlgorithm {
public enum CaseMode { PascalCase, CamelCase }
private char delimiterChar;
public CaseAlgorithm(char inDelimiterChar) {
delimiterChar = inDelimiterChar;
}
public string SetPhraseCase(string phrase, CaseMode caseMode) {
// You might want to do some sanity checks here like making sure
// there's no invalid characters, etc.
if (string.IsNullOrEmpty(phrase)) return phrase;
// .Split() will simply return a string[] of size 1 if no delimiter present so
// no need to explicitly check this.
var words = phrase.Split(delimiterChar);
// Set first word accordingly.
string ret = setWordCase(words[0], caseMode);
// If there are other words, set them all to pascal case.
if (words.Length > 1) {
for (int i = 1; i < words.Length; ++i)
ret += setWordCase(words[i], CaseMode.PascalCase);
}
return ret;
}
private string setWordCase(string word, CaseMode caseMode) {
switch (caseMode) {
case CaseMode.CamelCase:
return lowerFirstLetter(word);
case CaseMode.PascalCase:
return capitaliseFirstLetter(word);
default:
throw new NotImplementedException(
string.Format("Case mode '{0}' is not recognised.", caseMode.ToString()));
}
}
private string lowerFirstLetter(string word) {
return char.ToLower(word[0]) + word.Substring(1);
}
private string capitaliseFirstLetter(string word) {
return char.ToUpper(word[0]) + word.Substring(1);
}
}
``` |
32,243 | <p>The following PHP code snippet uses GD to resize a browser-uploaded PNG to 128x128. It works great, except that the transparent areas in the original image are being replaced with a solid color- black in my case. </p>
<p>Even though <code>imagesavealpha</code> is set, something isn't quite right.</p>
<p>What's the best way to preserve the transparency in the resampled image?</p>
<pre><code>$uploadTempFile = $myField[ 'tmp_name' ]
list( $uploadWidth, $uploadHeight, $uploadType )
= getimagesize( $uploadTempFile );
$srcImage = imagecreatefrompng( $uploadTempFile );
imagesavealpha( $targetImage, true );
$targetImage = imagecreatetruecolor( 128, 128 );
imagecopyresampled( $targetImage, $srcImage,
0, 0,
0, 0,
128, 128,
$uploadWidth, $uploadHeight );
imagepng( $targetImage, 'out.png', 9 );
</code></pre>
| [
{
"answer_id": 32270,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 4,
"selected": false,
"text": "<p>I believe this should do the trick:</p>\n\n<pre><code>$srcImage = imagecreatefrompng($uploadTempFile);\nimagealphab... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820/"
] | The following PHP code snippet uses GD to resize a browser-uploaded PNG to 128x128. It works great, except that the transparent areas in the original image are being replaced with a solid color- black in my case.
Even though `imagesavealpha` is set, something isn't quite right.
What's the best way to preserve the transparency in the resampled image?
```
$uploadTempFile = $myField[ 'tmp_name' ]
list( $uploadWidth, $uploadHeight, $uploadType )
= getimagesize( $uploadTempFile );
$srcImage = imagecreatefrompng( $uploadTempFile );
imagesavealpha( $targetImage, true );
$targetImage = imagecreatetruecolor( 128, 128 );
imagecopyresampled( $targetImage, $srcImage,
0, 0,
0, 0,
128, 128,
$uploadWidth, $uploadHeight );
imagepng( $targetImage, 'out.png', 9 );
``` | ```
imagealphablending( $targetImage, false );
imagesavealpha( $targetImage, true );
```
did it for me. Thanks ceejayoz.
note, the target image needs the alpha settings, not the source image.
Edit:
full replacement code. See also answers below and their comments. This is not guaranteed to be be perfect in any way, but did achieve my needs at the time.
```
$uploadTempFile = $myField[ 'tmp_name' ]
list( $uploadWidth, $uploadHeight, $uploadType )
= getimagesize( $uploadTempFile );
$srcImage = imagecreatefrompng( $uploadTempFile );
$targetImage = imagecreatetruecolor( 128, 128 );
imagealphablending( $targetImage, false );
imagesavealpha( $targetImage, true );
imagecopyresampled( $targetImage, $srcImage,
0, 0,
0, 0,
128, 128,
$uploadWidth, $uploadHeight );
imagepng( $targetImage, 'out.png', 9 );
``` |
32,260 | <p>Instead of relying on my host to send an email, I was thinking of sending the email messages using my <strong>Gmail</strong> account. The emails are personalized emails to the bands I play on my show. </p>
<p>Is it possible to do it?</p>
| [
{
"answer_id": 32336,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 11,
"selected": true,
"text": "<p>Be sure to use <code>System.Net.Mail</code>, not the deprecated <code>System.Web.Mail</code>. Doing SSL with <code>System.... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2535/"
] | Instead of relying on my host to send an email, I was thinking of sending the email messages using my **Gmail** account. The emails are personalized emails to the bands I play on my show.
Is it possible to do it? | Be sure to use `System.Net.Mail`, not the deprecated `System.Web.Mail`. Doing SSL with `System.Web.Mail` is a gross mess of hacky extensions.
```
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
```
Additionally go to the [*Google Account > Security*](https://myaccount.google.com/security) page and look at the *Signing in to Google > 2-Step Verification* setting.
* If it is enabled, then you have to generate a password allowing .NET to bypass the 2-Step Verification. To do this, click on [*Signing in to Google > App passwords*](https://myaccount.google.com/apppasswords), select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the `fromPassword` constant instead of your standard Gmail password.
* If it is disabled, then you have to turn on [*Less secure app access*](https://myaccount.google.com/lesssecureapps), which is not recommended! So better enable the 2-Step verification. |
32,280 | <p>I am in the middle of reading the excellent <a href="https://rads.stackoverflow.com/amzn/click/com/0132350882" rel="noreferrer" rel="nofollow noreferrer">Clean Code</a></p>
<p>One discussion is regarding passing nulls into a method.</p>
<pre><code>public class MetricsCalculator {
public double xProjection(Point p1, Point p2) {
return (p2.x - p1.x) * 1.5;
}
}
...
calculator.xProjection(null, new Point(12,13));
</code></pre>
<p>It represents different ways of handling this:</p>
<pre><code>public double xProjection(Point p1, Point p2) {
if (p1 == null || p2 == null) {
throw new IllegalArgumentException("Invalid argument for xProjection");
}
return (p2.x - p1.x) * 1.5;
}
public double xProjection(Point p1, Point p2) {
assert p1 != null : "p1 should not be null";
assert p2 != null : "p2 should not be null";
return (p2.x - p1.x) * 1.5;
}
</code></pre>
<p>I prefer the <a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html" rel="noreferrer">assertions</a> approach, but I don't like the fact that assertions are turned off by default.</p>
<p>The book finally states:</p>
<blockquote>
<p>In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default.</p>
</blockquote>
<p>It doesn't really go into how you would enforce this restriction?</p>
<p>Do any of you have strong opinions either way.</p>
| [
{
"answer_id": 32295,
"author": "wvdschel",
"author_id": 2018,
"author_profile": "https://Stackoverflow.com/users/2018",
"pm_score": 1,
"selected": false,
"text": "<p>I generally prefer not doing either, since it's just slowing things down. NullPointerExceptions are thrown later on anywa... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3295/"
] | I am in the middle of reading the excellent [Clean Code](https://rads.stackoverflow.com/amzn/click/com/0132350882)
One discussion is regarding passing nulls into a method.
```
public class MetricsCalculator {
public double xProjection(Point p1, Point p2) {
return (p2.x - p1.x) * 1.5;
}
}
...
calculator.xProjection(null, new Point(12,13));
```
It represents different ways of handling this:
```
public double xProjection(Point p1, Point p2) {
if (p1 == null || p2 == null) {
throw new IllegalArgumentException("Invalid argument for xProjection");
}
return (p2.x - p1.x) * 1.5;
}
public double xProjection(Point p1, Point p2) {
assert p1 != null : "p1 should not be null";
assert p2 != null : "p2 should not be null";
return (p2.x - p1.x) * 1.5;
}
```
I prefer the [assertions](http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html) approach, but I don't like the fact that assertions are turned off by default.
The book finally states:
>
> In most programming languages there is no good way to deal with a null that is passed by a caller accidentally. Because this is the case, the rational approach is to forbid passing null by default.
>
>
>
It doesn't really go into how you would enforce this restriction?
Do any of you have strong opinions either way. | Both the use of assertions and the throwing of exceptions are valid approaches here. Either mechanism can be used to indicate a programming error, not a runtime error, as is the case here.
* Assertions have the advantage of performance as they are typically disabled on production systems.
* Exceptions have the advantage of safety, as the check is always performed.
The choice really depends on the development practices of the project. The project as a whole needs to decide on an assertion policy: if the choice is to enable assertions during all development, then I'd say to use assertions to check this kind of invalid parameter - in a production system, a NullPointerException thrown due to a programming error is unlikely to be able to be caught and handled in a meaningful way anyway and so will act just like an assertion.
Practically though, I know a lot of developers that don't trust that assertions will be enabled when appropriate and so opt for the safety of throwing a NullPointerException.
Of course if you can't enforce a policy for your code (if you're creating a library, for example, and so are dependent on how other developers run your code), you should opt for the safe approach of throwing NullPointerException for those methods that are part of the library's API. |
32,332 | <p>This isn't a design question, really, though it may seem like it. (Well, okay, it's kind of a design question). What I'm wondering is why the C++ <code>std::fstream</code> classes don't take a <code>std::string</code> in their constructor or open methods. Everyone loves code examples so:</p>
<pre><code>#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string filename = "testfile";
std::ifstream fin;
fin.open(filename.c_str()); // Works just fine.
fin.close();
//fin.open(filename); // Error: no such method.
//fin.close();
}
</code></pre>
<p>This gets me all the time when working with files. Surely the C++ library would use <code>std::string</code> wherever possible?</p>
| [
{
"answer_id": 32353,
"author": "Magnus Westin",
"author_id": 2957,
"author_profile": "https://Stackoverflow.com/users/2957",
"pm_score": 0,
"selected": false,
"text": "<p>Is there any class in STL that takes a string... I dont think so (couldnt find any in my quick search). So it's prob... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | This isn't a design question, really, though it may seem like it. (Well, okay, it's kind of a design question). What I'm wondering is why the C++ `std::fstream` classes don't take a `std::string` in their constructor or open methods. Everyone loves code examples so:
```
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string filename = "testfile";
std::ifstream fin;
fin.open(filename.c_str()); // Works just fine.
fin.close();
//fin.open(filename); // Error: no such method.
//fin.close();
}
```
This gets me all the time when working with files. Surely the C++ library would use `std::string` wherever possible? | By taking a C string the C++03 [`std::fstream`](http://en.cppreference.com/w/cpp/io/basic_fstream) class reduced dependency on the `std::string` class. In C++11, however, the `std::fstream` class does allow passing a `std::string` for its constructor parameter.
Now, you may wonder why isn't there a transparent conversion from a `std:string` to a C string, so a class that expects a C string could still take a `std::string` just like a class that expects a `std::string` can take a C string.
The reason is that this would cause a conversion cycle, which in turn may lead to problems. For example, suppose `std::string` would be convertible to a C string so that you could use `std::string`s with `fstream`s. Suppose also that C string are convertible to `std::string`s as is the state in the current standard. Now, consider the following:
```
void f(std::string str1, std::string str2);
void f(char* cstr1, char* cstr2);
void g()
{
char* cstr = "abc";
std::string str = "def";
f(cstr, str); // ERROR: ambiguous
}
```
Because you can convert either way between a `std::string` and a C string the call to `f()` could resolve to either of the two `f()` alternatives, and is thus ambiguous. The solution is to break the conversion cycle by making one conversion direction explicit, which is what the STL chose to do with `c_str()`. |
32,333 | <p>Here's a perfect example of the problem: <a href="http://blog.teksol.info/2009/03/27/argumenterror-on-number-sum-when-using-classifier-bayes.html" rel="nofollow noreferrer">Classifier gem breaks Rails</a>.</p>
<p>** Original question: **</p>
<p>One thing that concerns me as a security professional is that Ruby doesn't have a parallel of Java's package-privacy. That is, this isn't valid Ruby:</p>
<pre><code>public module Foo
public module Bar
# factory method for new Bar implementations
def self.new(...)
SimpleBarImplementation.new(...)
end
def baz
raise NotImplementedError.new('Implementing Classes MUST redefine #baz')
end
end
private class SimpleBarImplementation
include Bar
def baz
...
end
end
end
</code></pre>
<p>It'd be really nice to be able to prevent monkey-patching of Foo::BarImpl. That way, people who rely on the library know that nobody has messed with it. Imagine if somebody changed the implementation of MD5 or SHA1 on you! I can call <code>freeze</code> on these classes, but I have to do it on a class-by-class basis, and other scripts might modify them before I finish securing my application if I'm not <strong>very</strong> careful about load order.</p>
<p>Java provides lots of other tools for defensive programming, many of which are not possible in Ruby. (See Josh Bloch's book for a good list.) Is this really a concern? Should I just stop complaining and use Ruby for lightweight things and not hope for "enterprise-ready" solutions?</p>
<p>(And no, core classes are not frozen by default in Ruby. See below:)</p>
<pre><code>require 'md5'
# => true
MD5.frozen?
# => false
</code></pre>
| [
{
"answer_id": 32471,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 1,
"selected": false,
"text": "<p>I guess Ruby has that a feature - valued more over it being a security issue. Ducktyping too.<br>\nE.g. I can add my own me... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] | Here's a perfect example of the problem: [Classifier gem breaks Rails](http://blog.teksol.info/2009/03/27/argumenterror-on-number-sum-when-using-classifier-bayes.html).
\*\* Original question: \*\*
One thing that concerns me as a security professional is that Ruby doesn't have a parallel of Java's package-privacy. That is, this isn't valid Ruby:
```
public module Foo
public module Bar
# factory method for new Bar implementations
def self.new(...)
SimpleBarImplementation.new(...)
end
def baz
raise NotImplementedError.new('Implementing Classes MUST redefine #baz')
end
end
private class SimpleBarImplementation
include Bar
def baz
...
end
end
end
```
It'd be really nice to be able to prevent monkey-patching of Foo::BarImpl. That way, people who rely on the library know that nobody has messed with it. Imagine if somebody changed the implementation of MD5 or SHA1 on you! I can call `freeze` on these classes, but I have to do it on a class-by-class basis, and other scripts might modify them before I finish securing my application if I'm not **very** careful about load order.
Java provides lots of other tools for defensive programming, many of which are not possible in Ruby. (See Josh Bloch's book for a good list.) Is this really a concern? Should I just stop complaining and use Ruby for lightweight things and not hope for "enterprise-ready" solutions?
(And no, core classes are not frozen by default in Ruby. See below:)
```
require 'md5'
# => true
MD5.frozen?
# => false
``` | Check out [Immutable](http://scie.nti.st/2008/9/17/making-methods-immutable-in-ruby) by Garry Dolley.
You can prevent redefinition of individual methods. |
32,360 | <p>How do you specify that a foreign key constraint should be a 1:1 relationship in transact sql? Is declaring the column UNIQUE enough? Below is my existing code.!</p>
<pre><code>CREATE TABLE [dbo].MyTable(
[MyTablekey] INT IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[OtherTableKey] INT NOT NULL UNIQUE
CONSTRAINT [FK_MyTable_OtherTable] FOREIGN KEY REFERENCES [dbo].[OtherTable]([OtherTableKey]),
...
CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED
(
[MyTableKey] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
</code></pre>
| [
{
"answer_id": 32372,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 2,
"selected": false,
"text": "<p>You could declare the column to be both the primary key and a foreign key. This is a good strategy for \"extension\"... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3400/"
] | How do you specify that a foreign key constraint should be a 1:1 relationship in transact sql? Is declaring the column UNIQUE enough? Below is my existing code.!
```
CREATE TABLE [dbo].MyTable(
[MyTablekey] INT IDENTITY(1,1) NOT FOR REPLICATION NOT NULL,
[OtherTableKey] INT NOT NULL UNIQUE
CONSTRAINT [FK_MyTable_OtherTable] FOREIGN KEY REFERENCES [dbo].[OtherTable]([OtherTableKey]),
...
CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED
(
[MyTableKey] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
``` | A foreign key column with the UNIQUE and NOT NULL constraints that references a UNIQUE, NOT NULL column in another table creates a 1:(0|1) relationship, which is probably what you want.
If there was a true 1:1 relationship, every record in the first table would have a corresponding record in the second table and vice-versa. In that case, you would probably just want to make one table (unless you needed some strange storage optimization). |
32,369 | <p>One of the joys of working for a government healthcare agency is having to deal with all of the paranoia around dealing with PHI (Protected Health Information). Don't get me wrong, I'm all for doing everything possible to protect people's personal information (health, financial, surfing habits, etc.), but sometimes people get a little too jumpy.</p>
<p>Case in point: One of our state customers recently found out that the browser provides the handy feature to save your password. We all know that it has been there for a while and is completely optional and is up to the end user to decide whether or not it is a smart decision to use or not. However, there is a bit of an uproar at the moment and we are being demanded to find a way to disable that functionality for our site.</p>
<p><strong>Question</strong>: Is there a way for a site to tell the browser not to offer to remember passwords? I've been around web development a long time but don't know that I have come across that before.</p>
<p>Any help is appreciated.</p>
| [
{
"answer_id": 32378,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 3,
"selected": false,
"text": "<p>Not really - the only thing you could realistically do is offer advice on the site; maybe, before their first time s... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3262/"
] | One of the joys of working for a government healthcare agency is having to deal with all of the paranoia around dealing with PHI (Protected Health Information). Don't get me wrong, I'm all for doing everything possible to protect people's personal information (health, financial, surfing habits, etc.), but sometimes people get a little too jumpy.
Case in point: One of our state customers recently found out that the browser provides the handy feature to save your password. We all know that it has been there for a while and is completely optional and is up to the end user to decide whether or not it is a smart decision to use or not. However, there is a bit of an uproar at the moment and we are being demanded to find a way to disable that functionality for our site.
**Question**: Is there a way for a site to tell the browser not to offer to remember passwords? I've been around web development a long time but don't know that I have come across that before.
Any help is appreciated. | I'm not sure if it'll work in all browsers but you should try setting autocomplete="off" on the form.
```
<form id="loginForm" action="login.cgi" method="post" autocomplete="off">
```
>
> The easiest and simplest way to disable Form **and Password storage prompts** and prevent form data from being cached in session history is to use the autocomplete form element attribute with value "off".
>
>
>
>
> From <https://developer.mozilla.org/en-US/docs/Web/Security/Securing_your_site/Turning_off_form_autocompletion>
>
>
>
Some minor research shows that this works in IE to but I'll leave no guarantees ;)
[@Joseph](https://stackoverflow.com/questions/32369/disable-browser-save-password-functionality#32408): If it's a strict requirement to pass XHTML validation with the actual markup (don't know why it would be though) you could theoretically add this attribute with javascript afterwards but then users with js disabled (probably a neglectable amount of your userbase or zero if your site requires js) will still have their passwords saved.
Example with jQuery:
```
$('#loginForm').attr('autocomplete', 'off');
``` |
32,397 | <p>On SO 18 Joel mentioned an algorithm that would rank items based on their age and popularity and it's based on gravity. Could someone post this? C# would be lovely, but really any language (well, I can't do LISP) would be fine. </p>
| [
{
"answer_id": 32399,
"author": "Tall Jeff",
"author_id": 1553,
"author_profile": "https://Stackoverflow.com/users/1553",
"pm_score": 5,
"selected": true,
"text": "<p>My understanding is that it is approximately the following from another <a href=\"https://stackoverflow.com/questions/240... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1942/"
] | On SO 18 Joel mentioned an algorithm that would rank items based on their age and popularity and it's based on gravity. Could someone post this? C# would be lovely, but really any language (well, I can't do LISP) would be fine. | My understanding is that it is approximately the following from another [Jeff Atwood](https://stackoverflow.com/questions/24066/what-formula-should-be-used-to-determine-hot-questions) post
```
t = (time of entry post) - (Dec 8, 2005)
x = upvotes - downvotes
y = {1 if x > 0, 0 if x = 0, -1 if x < 0)
z = {1 if x < 1, otherwise x}
log(z) + (y * t)/45000
``` |
32,404 | <p>I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service.</p>
<p>I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to daemonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services.</p>
<p><strong>Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)?</strong> I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines.</p>
<p><i>Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: <b>How is Windows aware of my service? Can I manage it with the native Windows utilities?</b> <strong>What is the equivalent of putting a start/stop script in /etc/init.d?</i></strong></p>
| [
{
"answer_id": 32440,
"author": "Ricardo Reyes",
"author_id": 3399,
"author_profile": "https://Stackoverflow.com/users/3399",
"pm_score": 9,
"selected": true,
"text": "<p>Yes you can. I do it using the pythoncom libraries that come included with <a href=\"http://www.activestate.com/Produ... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
] | I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service.
I am currently aiming for Python and the Django framework as the technologies to implement that service with. I'm pretty sure I figure how to daemonize the Python program in Linux. However, it is an optional spec item that the system should support Windows. I have little experience with Windows programming and no experience at all with Windows services.
**Is it possible to run a Python programs as a Windows service (i. e. run it automatically without user login)?** I won't necessarily have to implement this part, but I need a rough idea how it would be done in order to decide whether to design along these lines.
*Edit: Thanks for all the answers so far, they are quite comprehensive. I would like to know one more thing: **How is Windows aware of my service? Can I manage it with the native Windows utilities?** **What is the equivalent of putting a start/stop script in /etc/init.d?*** | Yes you can. I do it using the pythoncom libraries that come included with [ActivePython](http://www.activestate.com/Products/activepython/index.mhtml) or can be installed with [pywin32](https://sourceforge.net/projects/pywin32/) (Python for Windows extensions).
This is a basic skeleton for a simple service:
```
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "TestService"
_svc_display_name_ = "Test Service"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
pass
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
```
Your code would go in the `main()` method—usually with some kind of infinite loop that might be interrupted by checking a flag, which you set in the `SvcStop` method |
32,414 | <p>We are currently working in a private beta and so are still in the process of making fairly rapid changes, although obviously as usage is starting to ramp up, we will be slowing down this process. That being said, one issue we are running into is that after we push out an update with new JavaScript files, the client browsers still use the cached version of the file and they do not see the update. Obviously, on a support call, we can simply inform them to do a <kbd>ctrl</kbd><kbd>F5</kbd> refresh to ensure that they get the up-to-date files from the server, but it would be preferable to handle this before that time.</p>
<p>Our current thought is to simply attach a version number onto the name of the JavaScript files and then when changes are made, increment the version on the script and update all references. This definitely gets the job done, but updating the references on each release could get cumbersome.</p>
<p>As I'm sure we're not the first ones to deal with this, I figured I would throw it out to the community. How are you ensuring clients update their cache when you update your code? If you're using the method described above, are you using a process that simplifies the change?</p>
| [
{
"answer_id": 32427,
"author": "Huppie",
"author_id": 1830,
"author_profile": "https://Stackoverflow.com/users/1830",
"pm_score": 10,
"selected": true,
"text": "<p>As far as I know a common solution is to add a <code>?<version></code> to the script's src link.</p>\n\n<p>For instan... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2176/"
] | We are currently working in a private beta and so are still in the process of making fairly rapid changes, although obviously as usage is starting to ramp up, we will be slowing down this process. That being said, one issue we are running into is that after we push out an update with new JavaScript files, the client browsers still use the cached version of the file and they do not see the update. Obviously, on a support call, we can simply inform them to do a `ctrl``F5` refresh to ensure that they get the up-to-date files from the server, but it would be preferable to handle this before that time.
Our current thought is to simply attach a version number onto the name of the JavaScript files and then when changes are made, increment the version on the script and update all references. This definitely gets the job done, but updating the references on each release could get cumbersome.
As I'm sure we're not the first ones to deal with this, I figured I would throw it out to the community. How are you ensuring clients update their cache when you update your code? If you're using the method described above, are you using a process that simplifies the change? | As far as I know a common solution is to add a `?<version>` to the script's src link.
For instance:
```
<script type="text/javascript" src="myfile.js?1500"></script>
```
---
>
> I assume at this point that there isn't a better way than find-replace to increment these "version numbers" in all of the script tags?
>
>
>
You might have a version control system do that for you? Most version control systems have a way to automatically inject the revision number on check-in for instance.
It would look something like this:
```
<script type="text/javascript" src="myfile.js?$$REVISION$$"></script>
```
---
Of course, there are always better solutions like [this one](http://blog.greenfelt.net/2009/09/01/caching-javascript-safely/). |
32,428 | <p>I've created an assembly and referenced it in my Reporting Services report. I've tested the report locally (works), and I then uploaded the report to a report server (doesn't work).</p>
<p>Here is the error that is thrown by the custom code I've written.</p>
<blockquote>
<p>System.Security.SecurityException:
Request for the permission of type
'System.Security.Permissions.SecurityPermission,
mscorlib, Version=2.0.0.0,
Culture=neutral,
PublicKeyToken=b77a5c561934e089'
failed. at
System.Security.CodeAccessSecurityEngine.CheckNReturnSO(PermissionToken
permToken, CodeAccessPermission
demand, StackCrawlMark& stackMark,
Int32 unrestrictedOverride, Int32
create) at
System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission
cap, StackCrawlMark& stackMark) at
System.Security.CodeAccessPermission.Assert()
at [Snipped Method Name] at
ReportExprHostImpl.CustomCodeProxy.[Snipped Method Name] The action that failed was:
Demand The type of the first
permission that failed was:
System.Security.Permissions.SecurityPermission
The Zone of the assembly that failed
was: MyComputer</p>
</blockquote>
<p>This project is something I inherited, and I'm not intimately familiar with it. Although I do have the code (now), so I can at least work with it :)</p>
<p>I believe the code that is failing is this:</p>
<pre><code> Dim fio As System.Security.Permissions.FileIOPermission = New System.Security.Permissions.FileIOPermission(Security.Permissions.PermissionState.Unrestricted)
fio.Assert()
</code></pre>
<p>However, this kind of stuff is everywhere too:</p>
<pre><code>Private Declare Function CryptHashData Lib "advapi32.dll" (ByVal hhash As Integer, ByVal pbData As String, ByVal dwDataLen As Integer, ByVal dwFlags As Integer) As Integer
</code></pre>
<p>I can see either of these being things that Reporting Services would not accommodate out of the box.</p>
| [
{
"answer_id": 37379,
"author": "Ian Robinson",
"author_id": 326,
"author_profile": "https://Stackoverflow.com/users/326",
"pm_score": 4,
"selected": true,
"text": "<p>This is how I was able to solve the issue:</p>\n\n<ul>\n<li>strongly sign the custom assembly in question</li>\n<li><p>m... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/326/"
] | I've created an assembly and referenced it in my Reporting Services report. I've tested the report locally (works), and I then uploaded the report to a report server (doesn't work).
Here is the error that is thrown by the custom code I've written.
>
> System.Security.SecurityException:
> Request for the permission of type
> 'System.Security.Permissions.SecurityPermission,
> mscorlib, Version=2.0.0.0,
> Culture=neutral,
> PublicKeyToken=b77a5c561934e089'
> failed. at
> System.Security.CodeAccessSecurityEngine.CheckNReturnSO(PermissionToken
> permToken, CodeAccessPermission
> demand, StackCrawlMark& stackMark,
> Int32 unrestrictedOverride, Int32
> create) at
> System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission
> cap, StackCrawlMark& stackMark) at
> System.Security.CodeAccessPermission.Assert()
> at [Snipped Method Name] at
> ReportExprHostImpl.CustomCodeProxy.[Snipped Method Name] The action that failed was:
> Demand The type of the first
> permission that failed was:
> System.Security.Permissions.SecurityPermission
> The Zone of the assembly that failed
> was: MyComputer
>
>
>
This project is something I inherited, and I'm not intimately familiar with it. Although I do have the code (now), so I can at least work with it :)
I believe the code that is failing is this:
```
Dim fio As System.Security.Permissions.FileIOPermission = New System.Security.Permissions.FileIOPermission(Security.Permissions.PermissionState.Unrestricted)
fio.Assert()
```
However, this kind of stuff is everywhere too:
```
Private Declare Function CryptHashData Lib "advapi32.dll" (ByVal hhash As Integer, ByVal pbData As String, ByVal dwDataLen As Integer, ByVal dwFlags As Integer) As Integer
```
I can see either of these being things that Reporting Services would not accommodate out of the box. | This is how I was able to solve the issue:
* strongly sign the custom assembly in question
* modify the rssrvpolicy.config file to add permissions for the assembly
```
<CodeGroup
class="UnionCodeGroup"
version="1"
PermissionSetName="FullTrust"
Name="Test"
Description="This code group grants the Test code full trust. ">
<IMembershipCondition
class="StrongNameMembershipCondition"
version="1"
PublicKeyBlob="0024000004800000940100000602000000240000575341310004000001000100ab4b135615ca6dfd586aa0c5807b3e07fa7a02b3f376c131e0442607de792a346e64710e82c833b42c672680732f16193ba90b2819a77fa22ac6d41559724b9c253358614c270c651fad5afe9a0f8cbd1e5e79f35e0f04cb3e3b020162ac86f633cf0d205263280e3400d1a5b5781bf6bd12f97917dcdde3c8d03ee61ccba2c0"
/>
</CodeGroup>
```
Side note: here is a great way to get the public key blob of your assembly
[VS trick for obtaining the public key token and blob of a signed assembly](http://www.andrewconnell.com/blog/archive/2006/09/15/4587.aspx). |
32,433 | <p>This query works great:</p>
<pre><code>var pageObject = (from op in db.ObjectPermissions
join pg in db.Pages on op.ObjectPermissionName equals page.PageName
where pg.PageID == page.PageID
select op)
.SingleOrDefault();
</code></pre>
<p>I get a new type with my 'op' fields. Now I want to retrieve my 'pg' fields as well, but</p>
<pre><code>select op, pg).SingleOrDefault();
</code></pre>
<p>doesn't work.</p>
<p>How can I select everything from both tables so that they appear in my new pageObject type?</p>
| [
{
"answer_id": 32445,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>You must create a new anonymous type:</p>\n\n<pre><code> select new { op, pg }\n</code></pre>\n\n<p>Refer to the of... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] | This query works great:
```
var pageObject = (from op in db.ObjectPermissions
join pg in db.Pages on op.ObjectPermissionName equals page.PageName
where pg.PageID == page.PageID
select op)
.SingleOrDefault();
```
I get a new type with my 'op' fields. Now I want to retrieve my 'pg' fields as well, but
```
select op, pg).SingleOrDefault();
```
doesn't work.
How can I select everything from both tables so that they appear in my new pageObject type? | You can use anonymous types for this, i.e.:
```
var pageObject = (from op in db.ObjectPermissions
join pg in db.Pages on op.ObjectPermissionName equals page.PageName
where pg.PageID == page.PageID
select new { pg, op }).SingleOrDefault();
```
This will make pageObject into an IEnumerable of an anonymous type so AFAIK you won't be able to pass it around to other methods, however if you're simply obtaining data to play with in the method you're currently in it's perfectly fine. You can also name properties in your anonymous type, i.e.:-
```
var pageObject = (from op in db.ObjectPermissions
join pg in db.Pages on op.ObjectPermissionName equals page.PageName
where pg.PageID == page.PageID
select new
{
PermissionName = pg,
ObjectPermission = op
}).SingleOrDefault();
```
This will enable you to say:-
```
if (pageObject.PermissionName.FooBar == "golden goose") Application.Exit();
```
For example :-) |
32,460 | <p>Here's the situation: I need to bind a WPF <code>FixedPage</code> against a <code>DataRow</code>. Bindings don't work against <code>DataRows</code>; they work against <code>DataRowViews</code>. I need to do this in the most generic way possible, as I know nothing about and have no control over what is in the <code>DataRow</code>. </p>
<p>What I need is to be able to get a <code>DataRowView</code> for a given <code>DataRow</code>. I can't use the <code>Find()</code> method on the <code>DefaultView</code> because that takes a key, and there is no guarantee the table will have a primary key set.</p>
<p>Does anybody have a suggestion as to the best way to go around this? </p>
| [
{
"answer_id": 32483,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>row.Table.DefaultView[row.Table.Rows.IndexOf(row)]\n</code></pre>\n\n<p>This is an okay answer. But if you find you... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Here's the situation: I need to bind a WPF `FixedPage` against a `DataRow`. Bindings don't work against `DataRows`; they work against `DataRowViews`. I need to do this in the most generic way possible, as I know nothing about and have no control over what is in the `DataRow`.
What I need is to be able to get a `DataRowView` for a given `DataRow`. I can't use the `Find()` method on the `DefaultView` because that takes a key, and there is no guarantee the table will have a primary key set.
Does anybody have a suggestion as to the best way to go around this? | Not Exactly a sexy piece of code but their doesn't seem to be an automated way to find the row without just looping the table.
```
DataRowView newRowView = null;
foreach (DataRowView tempRowView in myDataTable.DefaultView)
{
if (tempRowView.Row == rowToMatch)
newRowView = tempRowView;
}
if (newRow != null)
UseNewRowView(newRowView);
else
HandleRowNotFound();
``` |
32,462 | <p>So I've got a hobby site I'm working on. I've got items that are tagged and I want to associate those items with photos from Flickr. Even with restrictive searches, I might get results numbering in the thousands.</p>
<p>Requirements:</p>
<ol>
<li>I want to display between 10-20 pictures but I want to randomize the photos each time. </li>
<li>I don't want to hit Flickr every time a page request is made. </li>
<li>Not every Flickr photo with the same tags as my item will be relevant.</li>
</ol>
<p>How should I store that number of results and how would I determine which ones are relevant?</p>
| [
{
"answer_id": 32483,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>row.Table.DefaultView[row.Table.Rows.IndexOf(row)]\n</code></pre>\n\n<p>This is an okay answer. But if you find you... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2863/"
] | So I've got a hobby site I'm working on. I've got items that are tagged and I want to associate those items with photos from Flickr. Even with restrictive searches, I might get results numbering in the thousands.
Requirements:
1. I want to display between 10-20 pictures but I want to randomize the photos each time.
2. I don't want to hit Flickr every time a page request is made.
3. Not every Flickr photo with the same tags as my item will be relevant.
How should I store that number of results and how would I determine which ones are relevant? | Not Exactly a sexy piece of code but their doesn't seem to be an automated way to find the row without just looping the table.
```
DataRowView newRowView = null;
foreach (DataRowView tempRowView in myDataTable.DefaultView)
{
if (tempRowView.Row == rowToMatch)
newRowView = tempRowView;
}
if (newRow != null)
UseNewRowView(newRowView);
else
HandleRowNotFound();
``` |
32,537 | <p>For scripting languages, what is the most effective way to utilize a console when developing? Are there ways to be more productive with a console than a "compile and run" only language?</p>
<p>Added clarification: I am thinking more along the lines of Ruby, Python, Boo, etc. Languages that are used for full blown apps, but also have a way to run small snippets of code in a console.</p>
| [
{
"answer_id": 32557,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 1,
"selected": false,
"text": "<p>I think it depends on the console. The usefulness of a CMD console on windows pails in comparison to a Powershell console.... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2001/"
] | For scripting languages, what is the most effective way to utilize a console when developing? Are there ways to be more productive with a console than a "compile and run" only language?
Added clarification: I am thinking more along the lines of Ruby, Python, Boo, etc. Languages that are used for full blown apps, but also have a way to run small snippets of code in a console. | >
> I am thinking more along the lines of Ruby, ...
>
>
>
Well for Ruby the `irb` interactive prompt is a great tool for "practicing" something simple. Here are the things I'll mention about the irb to give you an idea of effective use:
* *Automation*. You are allowed a `.irbrc` file that will be automatically executed when launching irb. That means you can load your favorite libraries or do *whatever* you want in full Ruby automatically. To see what I mean check out some of the ones at [dotfiles.org](https://web.archive.org/web/20110824004021/http://dotfiles.org:80/.irbrc).
* *Autocompletion*. That even makes writing code easier. Can't remember that string method to remove newlines? `"".ch<tab>` produces chop and chomp. *NOTE: you have to enable autocompletion for irb yourself*
* *Divide and Conquer*. irb makes the small things really easy. If you're writing a function to manipulate strings, the ability to test the code interactively right in the prompt saves a lot of time! For instance you can just open up irb and start running functions on an example string and have working and tested code already ready for your library/program.
* *Learning, Experimenting, and Hacking*. Something like this would take a very long time to test in C/C++, even Java. If you tried testing them all at once you might seg-fault and have to start over.
Here I'm just learning how the `String#[]` function works.
```
joe[~]$ irb
>> "12341:asdf"[/\d+/]
# => "12341"
>> "12341:asdf"[/\d*/]
# => "12341"
>> "12341:asdf"[0..5]
# => "12341:"
>> "12341:asdf"[0...5]
# => "12341"
>> "12341:asdf"[0, ':']
TypeError: can't convert String into Integer
from (irb):5:in `[]'
from (irb):5
>> "12341:asdf"[0, 5]
# => "12341"
```
* *Testing and Benchmarking*. Now they are nice and easy to perform. [Here](http://ozmm.org/posts/time_in_irb.html) is someone's idea to emulate the Unix `time` function for quick benchmarking. Just add it to your `.irbrc` file and its always there!
* *Debugging* - I haven't used this much myself but there is always the ability to debug code [like this](https://web.archive.org/web/20080912141043/http://www.rubycentral.com:80/pickaxe/trouble.html). Or pull out some code and run it in the irb to see what its actually doing.
I'm sure I'm missing some things but I hit on my favorite points. You really have zero limitation in shells so you're limited only by what you can think of doing. I almost always have a few shells running. Bash, Javascript, and Ruby's irb to name a few. I use them for a lot of things! |
32,540 | <p>How is your javaScript code organized? Does it follow patterns like MVC, or something else? </p>
<p>I've been working on a side project for some time now, and the further I get, the more my webpage has turned into a full-featured application. Right now, I'm sticking with <a href="http://jquery.com" rel="noreferrer">jQuery</a>, however, the logic on the page is growing to a point where some organization, or dare I say it, "architecture" is needed. My first approach is "MVC-ish":</p>
<ul>
<li>The 'model' is a JSON tree that gets extended with helpers</li>
<li>The view is the DOM plus classes that tweak it</li>
<li>The controller is the object where I connect events handling and kick off view or model manipulation</li>
</ul>
<p>I'm very interested, however, in how other people have built more substantial javaScript apps. I'm not interested in GWT, or other server-oriented approaches... just in the approach of "javaScript + <generic web service-y thingy here>"</p>
<p>Note: earlier I said javaScript "is not really OO, not really functional". This, I think, distracted everyone. Let's put it this way, because javaScript is unique in many ways, and I'm coming from a strongly-typed background, I don't want to force paradigms I know but were developed in very different languages.</p>
| [
{
"answer_id": 32594,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 4,
"selected": true,
"text": "<p>..but Javascript has many facets that <strong>are</strong> OO.</p>\n\n<p>Consider this:</p>\n\n<pre><code>var Vehicle... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3436/"
] | How is your javaScript code organized? Does it follow patterns like MVC, or something else?
I've been working on a side project for some time now, and the further I get, the more my webpage has turned into a full-featured application. Right now, I'm sticking with [jQuery](http://jquery.com), however, the logic on the page is growing to a point where some organization, or dare I say it, "architecture" is needed. My first approach is "MVC-ish":
* The 'model' is a JSON tree that gets extended with helpers
* The view is the DOM plus classes that tweak it
* The controller is the object where I connect events handling and kick off view or model manipulation
I'm very interested, however, in how other people have built more substantial javaScript apps. I'm not interested in GWT, or other server-oriented approaches... just in the approach of "javaScript + <generic web service-y thingy here>"
Note: earlier I said javaScript "is not really OO, not really functional". This, I think, distracted everyone. Let's put it this way, because javaScript is unique in many ways, and I'm coming from a strongly-typed background, I don't want to force paradigms I know but were developed in very different languages. | ..but Javascript has many facets that **are** OO.
Consider this:
```
var Vehicle = jQuery.Class.create({
init: function(name) { this.name = name; }
});
var Car = Vehicle.extend({
fillGas: function(){
this.gas = 100;
}
});
```
I've used this technique to create page-level javascript classes that have their own state, this helps keep it contained (and I often identify areas that I can reuse and put into other classes).
This is also especially useful when you have components/server controls that have their own script to execute, but when you might have multiple instances on the same page. This keeps the state separate. |
32,541 | <p>Anybody have a good example how to deep clone a WPF object, preserving databindings?</p>
<hr>
<p>The marked answer is the first part.</p>
<p>The second part is that you have to create an ExpressionConverter and inject it into the serialization process. Details for this are here:<br>
<a href="http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2801571" rel="noreferrer">http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2801571</a></p>
| [
{
"answer_id": 32575,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 0,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code> public static T DeepClone<T>(T from)\n {\n using (MemoryStream s = new Mem... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Anybody have a good example how to deep clone a WPF object, preserving databindings?
---
The marked answer is the first part.
The second part is that you have to create an ExpressionConverter and inject it into the serialization process. Details for this are here:
<http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2801571> | The simplest way that I've done it is to use a XamlWriter to save the WPF object as a string. The Save method will serialize the object and all of its children in the logical tree. Now you can create a new object and load it with a XamlReader.
ex:
Write the object to xaml (let's say the object was a Grid control):
```
string gridXaml = XamlWriter.Save(myGrid);
```
Load it into a new object:
```
StringReader stringReader = new StringReader(gridXaml);
XmlReader xmlReader = XmlReader.Create(stringReader);
Grid newGrid = (Grid)XamlReader.Load(xmlReader);
``` |
32,550 | <p>When writing a SQL statement in SQL Server 2005, does the READUNCOMMITTED query hint imply NOLOCK or do I have to specify it manually too?</p>
<p>So is:</p>
<pre><code>With (NoLock, ReadUnCommitted)
</code></pre>
<p>the same as:</p>
<pre><code>With (ReadUnCommitted)
</code></pre>
| [
{
"answer_id": 32556,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": -1,
"selected": false,
"text": "<p>I think you can say that</p>\n\n<p>ReadUnCommitted has the abilities of NoLock</p>\n\n<p>However you cannot say that</p>... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | When writing a SQL statement in SQL Server 2005, does the READUNCOMMITTED query hint imply NOLOCK or do I have to specify it manually too?
So is:
```
With (NoLock, ReadUnCommitted)
```
the same as:
```
With (ReadUnCommitted)
``` | Yes they are one and the same |
32,586 | <p>Is there an easy way to discover a File's creation time with Java? The File class only has a method to get the "last modified" time. According to some resources I found on Google, the File class doesn't provide a getCreationTime() method because not all file systems support the idea of a creation time.</p>
<p>The only working solution I found involes shelling out the the command line and executing the "dir" command, which looks like it outputs the file's creation time. I guess this works, I only need to support Windows, but it seems very error prone to me.</p>
<p>Are there any third party libraries that provide the info I need?</p>
<p><strong>Update:</strong> In the end, I don't think it's worth it for me to buy the third party library, but their API does seem pretty good so it's probably a good choice for anyone else that has this problem. </p>
| [
{
"answer_id": 32712,
"author": "Joseph Gordon",
"author_id": 1741,
"author_profile": "https://Stackoverflow.com/users/1741",
"pm_score": 1,
"selected": false,
"text": "<p>I like the answer on <a href=\"http://www.jguru.com/faq/view.jsp?EID=1297118\" rel=\"nofollow noreferrer\">jGuru</a>... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1471/"
] | Is there an easy way to discover a File's creation time with Java? The File class only has a method to get the "last modified" time. According to some resources I found on Google, the File class doesn't provide a getCreationTime() method because not all file systems support the idea of a creation time.
The only working solution I found involes shelling out the the command line and executing the "dir" command, which looks like it outputs the file's creation time. I guess this works, I only need to support Windows, but it seems very error prone to me.
Are there any third party libraries that provide the info I need?
**Update:** In the end, I don't think it's worth it for me to buy the third party library, but their API does seem pretty good so it's probably a good choice for anyone else that has this problem. | With the release of Java 7 there is a built-in way to do this:
```
Path path = Paths.get("path/to/file");
BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
FileTime creationTime = attributes.creationTime();
```
It is important to note that not all operating systems provide this information. I believe in those instances this returns the mtime which is the last modified time.
Windows does provide creation time. |
32,621 | <p>I'm trying to find the latitude and longitude of the corners of my map while in birdseye view. I want to be able to plot pins on the map, but I have hundreds of thousands of addresses that I want to be able to limit to the ones that need to show on the map.</p>
<p>In normal view, VEMap.GetMapView().TopLeftLatLong and .BottomRightLatLong return the coordinates I need; but in Birdseye view they return blank (or encrypted values). The SDK recommends using VEBirdseyeScene.GetBoundingRectangle(), but this returns bounds of up to two miles from the center of my scene which in major cities still returns way too many addresses.</p>
<p>In previous versions of the VE Control, there was an undocumented VEDecoder object I could use to decrypt the LatLong values for the birdseye scenes, but this object seems to have disappeared (probably been renamed). How can I decode these values in version 6.1?</p>
| [
{
"answer_id": 33238,
"author": "MartinHN",
"author_id": 2972,
"author_profile": "https://Stackoverflow.com/users/2972",
"pm_score": 0,
"selected": false,
"text": "<p>According to <a href=\"http://dev.live.com/virtualearth/sdk/\" rel=\"nofollow noreferrer\">http://dev.live.com/virtualear... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
] | I'm trying to find the latitude and longitude of the corners of my map while in birdseye view. I want to be able to plot pins on the map, but I have hundreds of thousands of addresses that I want to be able to limit to the ones that need to show on the map.
In normal view, VEMap.GetMapView().TopLeftLatLong and .BottomRightLatLong return the coordinates I need; but in Birdseye view they return blank (or encrypted values). The SDK recommends using VEBirdseyeScene.GetBoundingRectangle(), but this returns bounds of up to two miles from the center of my scene which in major cities still returns way too many addresses.
In previous versions of the VE Control, there was an undocumented VEDecoder object I could use to decrypt the LatLong values for the birdseye scenes, but this object seems to have disappeared (probably been renamed). How can I decode these values in version 6.1? | Here's the code for getting the Center Lat/Long point of the map. This method works in both Road/Aerial and Birdseye/Oblique map styles.
```
function GetCenterLatLong()
{
//Check if in Birdseye or Oblique Map Style
if (map.GetMapStyle() == VEMapStyle.Birdseye || map.GetMapStyle() == VEMapStyle.BirdseyeHybrid)
{
//IN Birdseye or Oblique Map Style
//Get the BirdseyeScene being displayed
var birdseyeScene = map.GetBirdseyeScene();
//Get approximate center coordinate of the map
var x = birdseyeScene.GetWidth() / 2;
var y = birdseyeScene.GetHeight() / 2;
// Get the Lat/Long
var center = birdseyeScene.PixelToLatLong(new VEPixel(x,y), map.GetZoomLevel());
// Convert the BirdseyeScene LatLong to a normal LatLong we can use
return (new _xy1).Decode(center);
}
else
{
// NOT in Birdseye or Oblique Map Style
return map.GetCenter();
}
}
```
This code was copied from here:
<http://pietschsoft.com/post/2008/06/Virtual-Earth-Get-Center-LatLong-When-In-Birdseye-or-Oblique-Map-Style.aspx> |
32,637 | <p>I am consuming the Twitter API and want to convert all URLs to hyperlinks. </p>
<p>What is the most effective way you've come up with to do this?</p>
<p>from</p>
<pre><code>string myString = "This is my tweet check it out http://tinyurl.com/blah";
</code></pre>
<p>to</p>
<pre><code>This is my tweet check it out <a href="http://tinyurl.com/blah">http://tinyurl.com/>blah</a>
</code></pre>
| [
{
"answer_id": 32648,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 6,
"selected": true,
"text": "<p>Regular expressions are probably your friend for this kind of task:</p>\n\n<pre><code>Regex r = new Regex(@\"(https?://[^... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2347826/"
] | I am consuming the Twitter API and want to convert all URLs to hyperlinks.
What is the most effective way you've come up with to do this?
from
```
string myString = "This is my tweet check it out http://tinyurl.com/blah";
```
to
```
This is my tweet check it out <a href="http://tinyurl.com/blah">http://tinyurl.com/>blah</a>
``` | Regular expressions are probably your friend for this kind of task:
```
Regex r = new Regex(@"(https?://[^\s]+)");
myString = r.Replace(myString, "<a href=\"$1\">$1</a>");
```
The regular expression for matching URLs might need a bit of work. |
32,640 | <p>So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET".</p>
<p>I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest.</p>
<p>I'm using latest version of rhino mocks</p>
| [
{
"answer_id": 32672,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 7,
"selected": true,
"text": "<p>Using MoQ it looks something like this:</p>\n\n<pre><code>var request = new Mock<HttpRequestBase>();\nrequest.Expect(r ... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] | So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET".
I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest.
I'm using latest version of rhino mocks | Using MoQ it looks something like this:
```
var request = new Mock<HttpRequestBase>();
request.Expect(r => r.HttpMethod).Returns("GET");
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Expect(c => c.Request).Returns(request.Object);
var controllerContext = new ControllerContext(mockHttpContext.Object
, new RouteData(), new Mock<ControllerBase>().Object);
```
I think the Rhino Mocks syntax is similar. |
32,649 | <p>When making changes using <code>SubmitChanges()</code>, LINQ sometimes dies with a <code>ChangeConflictException</code> exception with the error message <code>Row not found or changed</code>, without any indication of either the row that has the conflict or the fields with changes that are in conflict, when another user has changed some data in that row.</p>
<p>Is there any way to determine which row has a conflict and which fields they occur in, and also is there a way of getting LINQ to ignore the issue and simply commit the data regardless?</p>
<p>Additionally, does anybody know whether this exception occurs when <em>any</em> data in the row has changed, or only when data has been changed in a field that LINQ is attempting to alter?</p>
| [
{
"answer_id": 32703,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 2,
"selected": false,
"text": "<p>I've gotten this error in a circumstance completely unrelated to what the error message describes.</p>\n\n<p>What I did w... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] | When making changes using `SubmitChanges()`, LINQ sometimes dies with a `ChangeConflictException` exception with the error message `Row not found or changed`, without any indication of either the row that has the conflict or the fields with changes that are in conflict, when another user has changed some data in that row.
Is there any way to determine which row has a conflict and which fields they occur in, and also is there a way of getting LINQ to ignore the issue and simply commit the data regardless?
Additionally, does anybody know whether this exception occurs when *any* data in the row has changed, or only when data has been changed in a field that LINQ is attempting to alter? | Here's a way to see where the conflicts are (this is an MSDN example, so you'll need to heavily customize):
```
try
{
db.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch (ChangeConflictException e)
{
Console.WriteLine("Optimistic concurrency error.");
Console.WriteLine(e.Message);
Console.ReadLine();
foreach (ObjectChangeConflict occ in db.ChangeConflicts)
{
MetaTable metatable = db.Mapping.GetTable(occ.Object.GetType());
Customer entityInConflict = (Customer)occ.Object;
Console.WriteLine("Table name: {0}", metatable.TableName);
Console.Write("Customer ID: ");
Console.WriteLine(entityInConflict.CustomerID);
foreach (MemberChangeConflict mcc in occ.MemberConflicts)
{
object currVal = mcc.CurrentValue;
object origVal = mcc.OriginalValue;
object databaseVal = mcc.DatabaseValue;
MemberInfo mi = mcc.Member;
Console.WriteLine("Member: {0}", mi.Name);
Console.WriteLine("current value: {0}", currVal);
Console.WriteLine("original value: {0}", origVal);
Console.WriteLine("database value: {0}", databaseVal);
}
}
}
```
To make it ignore the problem and commit anyway:
```
db.SubmitChanges(ConflictMode.ContinueOnConflict);
``` |
32,664 | <p>Can anyone tell me if there is a way with generics to limit a generic type argument <code>T</code> to only:</p>
<ul>
<li><code>Int16</code></li>
<li><code>Int32</code></li>
<li><code>Int64</code></li>
<li><code>UInt16</code></li>
<li><code>UInt32</code></li>
<li><code>UInt64</code></li>
</ul>
<p>I'm aware of the <code>where</code> keyword, but can't find an interface for <strong>only</strong> these types,</p>
<p>Something like:</p>
<pre><code>static bool IntegerFunction<T>(T value) where T : INumeric
</code></pre>
| [
{
"answer_id": 32687,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 7,
"selected": false,
"text": "<p>There's no constraint for this. It's a real issue for anyone wanting to use generics for numeric calculations.</p>\n\n<p>I'd g... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736/"
] | Can anyone tell me if there is a way with generics to limit a generic type argument `T` to only:
* `Int16`
* `Int32`
* `Int64`
* `UInt16`
* `UInt32`
* `UInt64`
I'm aware of the `where` keyword, but can't find an interface for **only** these types,
Something like:
```
static bool IntegerFunction<T>(T value) where T : INumeric
``` | This constraint exists in .Net 7.
Check out this [.NET Blog post](https://devblogs.microsoft.com/dotnet/dotnet-7-generic-math/) and the [actual documentation](https://learn.microsoft.com/en-us/dotnet/standard/generics/math).
Starting in .NET 7, you can make use of interfaces such as `INumber` and `IFloatingPoint` to create programs such as:
```
using System.Numerics;
Console.WriteLine(Sum(1, 2, 3, 4, 5));
Console.WriteLine(Sum(10.541, 2.645));
Console.WriteLine(Sum(1.55f, 5, 9.41f, 7));
static T Sum<T>(params T[] numbers) where T : INumber<T>
{
T result = T.Zero;
foreach (T item in numbers)
{
result += item;
}
return result;
}
```
`INumber` is in the `System.Numerics` namespace.
There are also interfaces such as `IAdditionOperators` and `IComparisonOperators` so you can make use of specific operators generically. |
32,694 | <p>I'm trying to use <strong>NIS</strong> for authentication on a st of machines. I had to change one of the user ID numbers for a user account on the NIS server (I changed the userid for <code>username</code> from 500 to 509 to avoid a conflict with a local user account with id 500 on the clients). The problem is that it has not updated properly on the client. </p>
<p>In particular, if I do <code>ypcat passwd | grep username</code>, I get the up-to-date info:</p>
<pre><code>username:*hidden*:509:509:User Name:/home/username:/bin/bash
</code></pre>
<p>But if I do, <code>ypmatch username passwd</code>, it says:</p>
<pre><code>username:*hidden*:500:500:User Name:/home/username:/bin/bash
</code></pre>
<p>This means that when the user logs onto one of the clients, it has the wrong userid, which causes all sorts of problems. I've done <code>"cd /var/yp; make"</code> on the server, and <code>"service ypbind restart"</code> on the client, but that hasn't fixed the problem. Does anybody know what would be causing this and how I can somehow force a refresh on the client? (I'm running Fedora 8 on both client and server).</p>
| [
{
"answer_id": 32770,
"author": "Lorin Hochstein",
"author_id": 742,
"author_profile": "https://Stackoverflow.com/users/742",
"pm_score": 1,
"selected": false,
"text": "<p>OK, I found the problem, I also had to restart the NIS service on the server to get it to refresh everything (<code>... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] | I'm trying to use **NIS** for authentication on a st of machines. I had to change one of the user ID numbers for a user account on the NIS server (I changed the userid for `username` from 500 to 509 to avoid a conflict with a local user account with id 500 on the clients). The problem is that it has not updated properly on the client.
In particular, if I do `ypcat passwd | grep username`, I get the up-to-date info:
```
username:*hidden*:509:509:User Name:/home/username:/bin/bash
```
But if I do, `ypmatch username passwd`, it says:
```
username:*hidden*:500:500:User Name:/home/username:/bin/bash
```
This means that when the user logs onto one of the clients, it has the wrong userid, which causes all sorts of problems. I've done `"cd /var/yp; make"` on the server, and `"service ypbind restart"` on the client, but that hasn't fixed the problem. Does anybody know what would be causing this and how I can somehow force a refresh on the client? (I'm running Fedora 8 on both client and server). | John O pointed me in the right direction.
He is right. If you set "files: 0" in /etc/ypserv.conf, you can get ypserv to not cache files. If you have to restart ypserv after each make, this is the problem.
The real solution is to look in /var/log/messages for this error:
```
ypserv[]: refused connect from 127.0.0.1 to procedure ypproc_clear (,;0)
```
makedbm -c means: send YPPROC\_CLEAR to the local ypserv. The error message in the log means that CLEAR message is getting denied. You need to add 127.0.0.1 to /var/yp/securenets. |
32,717 | <p>I just finished setting up an out-of-place build system for our existing C++ code using inherited property sheets, a feature that seems to be specific to the Visual C++ product. Building out-of-place requires that many of the project settings be changed, and the inherited property sheets allowed me to change all the necessary settings just by attaching a property sheet to the project. I am migrating our team from C++/MFC for UI to C# and WPF, but I need to provide the same out-of-place build functionality, hopefully with the same convenience. I cannot seem to find a way to do this with C# projects - I first looked to see if I could reference an MsBuild targets file, but could not find a way to do this. I know I could just use MsBuild for the whole thing, but that seems more complicated than necessary. Is there a way I can define a macro for a directory and use it in the output path, for example?</p>
| [
{
"answer_id": 32879,
"author": "John Smithers",
"author_id": 1069,
"author_profile": "https://Stackoverflow.com/users/1069",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Is there a way I can define a macro for a directory and use it in the output path </p>\n</blockquot... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3114/"
] | I just finished setting up an out-of-place build system for our existing C++ code using inherited property sheets, a feature that seems to be specific to the Visual C++ product. Building out-of-place requires that many of the project settings be changed, and the inherited property sheets allowed me to change all the necessary settings just by attaching a property sheet to the project. I am migrating our team from C++/MFC for UI to C# and WPF, but I need to provide the same out-of-place build functionality, hopefully with the same convenience. I cannot seem to find a way to do this with C# projects - I first looked to see if I could reference an MsBuild targets file, but could not find a way to do this. I know I could just use MsBuild for the whole thing, but that seems more complicated than necessary. Is there a way I can define a macro for a directory and use it in the output path, for example? | I'm not quite sure what an "out-of-place" build system is, but if you just need the ability to copy the compiled files (or other resources) to other directories you can do so by tying into the MSBuild build targets.
In our projects we move the compiled dlls into lib folders and put the files into the proper locations after a build is complete. To do this we've created a custom build .target file that creates the `Target`'s, `Property`'s, and `ItemGroup`'s that we then use to populate our external output folder.
Our custom targets file looks a bit like this:
```
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectName>TheProject</ProjectName>
<ProjectDepthPath>..\..\</ProjectDepthPath>
<ProjectsLibFolder>..\..\lib\</ProjectsLibFolder>
<LibFolder>$(ProjectsLibFolder)$(ProjectName)\$(Configuration)\</LibFolder>
</PropertyGroup>
<Target Name="DeleteLibFiles">
<Delete Files="@(LibFiles-> '$(ProjectDepthPath)$(LibFolder)%(filename)%(extension)')" TreatErrorsAsWarnings="true" />
</Target>
<Target Name="CopyLibFiles">
<Copy SourceFiles="@(LibFiles)" DestinationFolder="$(ProjectDepthPath)$(LibFolder)" SkipUnchangedFiles="True" />
</Target>
<ItemGroup>
<LibFiles Include=" ">
<Visible>false</Visible>
</LibFiles>
</ItemGroup>
</Project>
```
The .csproj file in Visual Studio then integrates with this custom target file:
```
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" ... >
...
<Import Project="..\..\..\..\build\OurBuildTargets.targets" />
<ItemGroup>
<LibFiles Include="$(OutputPath)$(AssemblyName).dll">
<Visible>false</Visible>
</LibFiles>
</ItemGroup>
<Target Name="BeforeClean" DependsOnTargets="DeleteLibFiles" />
<Target Name="AfterBuild" DependsOnTargets="CopyLibFiles" />
</Project>
```
In a nutshell, this build script first tells MSBuild to load our custom build script, then adds the compiled file to the `LibFiles` ItemGroup, and lastly ties our custom build targets, `DeleteLibFiles` and `CopyLibFiles`, into the build process. We set this up for each project in our solution so only the files that are updated get deleted/copied and each project is responsible for it's own files (dlls, images, etc).
I hope this helps. I apologize if I misunderstood what you mean by out-of-place build system and this is completely useless to you! |
32,744 | <p>For the past few weeks, I've been trying to learn about just how email works. I understand the process of a client receiving mail from a server using POP pretty well. I also understand how a client computer can use SMTP to ask an SMTP server to send a message. However, I'm still missing something...</p>
<p>The way I understand it, outgoing mail has to make three trips:</p>
<ol>
<li>Client (gmail user using Thunderbird) to a server (Gmail)</li>
<li>First server (Gmail) to second server (Hotmail)</li>
<li>Second server (Hotmail) to second client (hotmail user using OS X Mail)</li>
</ol>
<p>As I understand it, step one uses SMTP for the client to communicate. The client authenticates itself somehow (say, with USER and PASS), and then sends a message to the gmail server.</p>
<p>However, I don't understand how gmail server transfers the message to the hotmail server.</p>
<p>For step three, I'm pretty sure, the hotmail server uses POP to send the message to the hotmail client (using authentication, again).</p>
<p>So, the big question is: <strong>when I click send Mail sends my message to my gmail server, how does my gmail server forward the message to, say, a hotmail server so my friend can recieve it?</strong></p>
<p>Thank you so much!</p>
<p>~Jason</p>
<hr>
<p>Thanks, that's been helpful so far.</p>
<p>As I understand it, the first client sends the message to the first server using SMTP, often to an address such as smtp.mail.SOMESERVER.com on port 25 (usually).</p>
<p>Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy).</p>
<p>Then, when the recipient asks RECEIVESERVER for its mail, using POP, s/he recieves the message... right?</p>
<p>Thanks again (especially to dr-jan),</p>
<p>Jason</p>
| [
{
"answer_id": 32754,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 3,
"selected": false,
"text": "<p>You're looking for the Mail Transfer Agent, Wikipedia has <a href=\"http://en.wikipedia.org/wiki/Mail_transfer_agent\" rel=\"... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615/"
] | For the past few weeks, I've been trying to learn about just how email works. I understand the process of a client receiving mail from a server using POP pretty well. I also understand how a client computer can use SMTP to ask an SMTP server to send a message. However, I'm still missing something...
The way I understand it, outgoing mail has to make three trips:
1. Client (gmail user using Thunderbird) to a server (Gmail)
2. First server (Gmail) to second server (Hotmail)
3. Second server (Hotmail) to second client (hotmail user using OS X Mail)
As I understand it, step one uses SMTP for the client to communicate. The client authenticates itself somehow (say, with USER and PASS), and then sends a message to the gmail server.
However, I don't understand how gmail server transfers the message to the hotmail server.
For step three, I'm pretty sure, the hotmail server uses POP to send the message to the hotmail client (using authentication, again).
So, the big question is: **when I click send Mail sends my message to my gmail server, how does my gmail server forward the message to, say, a hotmail server so my friend can recieve it?**
Thank you so much!
~Jason
---
Thanks, that's been helpful so far.
As I understand it, the first client sends the message to the first server using SMTP, often to an address such as smtp.mail.SOMESERVER.com on port 25 (usually).
Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy).
Then, when the recipient asks RECEIVESERVER for its mail, using POP, s/he recieves the message... right?
Thanks again (especially to dr-jan),
Jason | The SMTP server at Gmail (which accepted the message from Thunderbird) will route the message to the final recipient.
It does this by using DNS to find the MX (mail exchanger) record for the domain name part of the destination email address (hotmail.com in this example). The DNS server will return an IP address which the message should be sent to. The server at the destination IP address will hopefully be running SMTP (on the standard port 25) so it can receive the incoming messages.
Once the message has been received by the hotmail server, it is stored until the appropriate user logs in and retrieves their messages using POP (or IMAP).
Jason - to answer your follow up...
>
> Then, SOMESERVER uses SMTP again to send the message to RECEIVESERVER.com on port 25 (not smtp.mail.RECEIVESERVER.com or anything fancy).
>
>
>
That's correct - the domain name to send to is taken as everything after the '@' in the email address of the recipient. Often, RECEIVESERVER.com is an alias for something more specific, say something like incoming.RECEIVESERVER.com, (or, indeed, smtp.mail.RECEIVESERVER.com).
You can use nslookup to query your local DNS servers (this works in Linux and in a Windows cmd window):
```
nslookup
> set type=mx
> stackoverflow.com
Server: 158.155.25.16
Address: 158.155.25.16#53
Non-authoritative answer:
stackoverflow.com mail exchanger = 10 aspmx.l.google.com.
stackoverflow.com mail exchanger = 20 alt1.aspmx.l.google.com.
stackoverflow.com mail exchanger = 30 alt2.aspmx.l.google.com.
stackoverflow.com mail exchanger = 40 aspmx2.googlemail.com.
stackoverflow.com mail exchanger = 50 aspmx3.googlemail.com.
Authoritative answers can be found from:
aspmx.l.google.com internet address = 64.233.183.114
aspmx.l.google.com internet address = 64.233.183.27
>
```
This shows us that email to anyone at stackoverflow.com should be sent to one of the gmail servers shown above.
The Wikipedia article mentioned (<http://en.wikipedia.org/wiki/Mx_record>) discusses the priority numbers shown above (10, 20, ..., 50). |
32,747 | <p>How do I get today's date in C# in mm/dd/yyyy format?</p>
<p>I need to set a string variable to today's date (preferably without the year), but there's got to be a better way than building it month-/-day one piece at a time.</p>
<p>BTW: I'm in the US so M/dd would be correct, e.g. September 11th is 9/11.</p>
<p><em>Note: an answer from kronoz came in that discussed internationalization, and I thought it was awesome enough to mention since I can't make it an 'accepted' answer as well.</em></p>
<p><a href="https://stackoverflow.com/questions/32747/how-do-i-get-todays-date-in-c-in-8282008-format#32819" title="kronoz's answer">kronoz's answer</a></p>
| [
{
"answer_id": 32749,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 9,
"selected": true,
"text": "<pre><code>DateTime.Now.ToString(\"M/d/yyyy\");\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/8... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] | How do I get today's date in C# in mm/dd/yyyy format?
I need to set a string variable to today's date (preferably without the year), but there's got to be a better way than building it month-/-day one piece at a time.
BTW: I'm in the US so M/dd would be correct, e.g. September 11th is 9/11.
*Note: an answer from kronoz came in that discussed internationalization, and I thought it was awesome enough to mention since I can't make it an 'accepted' answer as well.*
[kronoz's answer](https://stackoverflow.com/questions/32747/how-do-i-get-todays-date-in-c-in-8282008-format#32819 "kronoz's answer") | ```
DateTime.Now.ToString("M/d/yyyy");
```
<http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx> |
32,750 | <p>I have a <code>byte[]</code> array, the contents of which represent a TIFF file (as in, if I write out these bytes directly to a file using the <code>BinaryWriter</code> object, it forms a perfectly valid TIFF file) and I'm trying to turn it into a System.Drawing.Image object so that I can use it for later manipulation (feeding into a multipage TIFF object)</p>
<p>The problem I'm having is that the commonly accepted code for this task:</p>
<pre><code> public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms, true);
return returnImage;
}
</code></pre>
<p>doesn't work for me. The second line of the above method where it calls the <code>Image.FromStream</code> method dies at runtime, saying</p>
<pre><code>Parameter Not Valid
</code></pre>
<p>I believe that the method is choking on the fact that this is a TIFF file but I cannot figure out how to make the <code>FromStream</code> method accept this fact.</p>
<p>How do I turn a byte array of a TIFF image into an Image object?</p>
<p>Also, like I said the end goal of this is to have a byte array representing a multipage TIFF file, which contains the TIFF files for which I have byte array objects of right now. If there's a much better way to go about doing this, I'm all for it.</p>
| [
{
"answer_id": 32841,
"author": "Tim",
"author_id": 1970,
"author_profile": "https://Stackoverflow.com/users/1970",
"pm_score": 3,
"selected": true,
"text": "<p><strong>Edit:</strong> The assumption below is not correct, I had a chance to fire up my IDE later and tested with and without ... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2577/"
] | I have a `byte[]` array, the contents of which represent a TIFF file (as in, if I write out these bytes directly to a file using the `BinaryWriter` object, it forms a perfectly valid TIFF file) and I'm trying to turn it into a System.Drawing.Image object so that I can use it for later manipulation (feeding into a multipage TIFF object)
The problem I'm having is that the commonly accepted code for this task:
```
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms, true);
return returnImage;
}
```
doesn't work for me. The second line of the above method where it calls the `Image.FromStream` method dies at runtime, saying
```
Parameter Not Valid
```
I believe that the method is choking on the fact that this is a TIFF file but I cannot figure out how to make the `FromStream` method accept this fact.
How do I turn a byte array of a TIFF image into an Image object?
Also, like I said the end goal of this is to have a byte array representing a multipage TIFF file, which contains the TIFF files for which I have byte array objects of right now. If there's a much better way to go about doing this, I'm all for it. | **Edit:** The assumption below is not correct, I had a chance to fire up my IDE later and tested with and without Write and both populated the MemoryStream correctly.
I think you need to write to your MemeoryStream first.
As if my memory (no pun intended) serves me correctly this:
```
MemoryStream ms = new MemoryStream(byteArrayIn);
```
Creates a memory stream of that size.
You then need to write your byte array contents to the memory stream:
```
ms.Write(byteArrayIn, 0, byteArrayIn.Length);
```
See if that fixes it. |
32,824 | <p>While writing a custom IHttpHandler I came across a behavior that I didn't expect concerning the HttpCachePolicy object.</p>
<p>My handler calculates and sets an entity-tag (using the SetETag method on the HttpCachePolicy associated with the current response object). If I set the cache-control to public using the SetCacheability method everything works like a charm and the server sends along the e-tag header. If I set it to private the e-tag header will be suppressed.</p>
<p>Maybe I just haven't looked hard enough but I haven't seen anything in the HTTP/1.1 spec that would justify this behavior. Why wouldn't you want to send E-Tag to browsers while still prohibiting proxies from storing the data?</p>
<pre><code>using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext ctx) {
ctx.Response.Cache.SetCacheability(HttpCacheability.Private);
ctx.Response.Cache.SetETag("\"static\"");
ctx.Response.ContentType = "text/plain";
ctx.Response.Write("Hello World");
}
public bool IsReusable { get { return true; } }
}
</code></pre>
<p>Will return</p>
<pre>
Cache-Control: private
Content-Type: text/plain; charset=utf-8
Content-Length: 11
</pre>
<p>But if we change it to public it'll return</p>
<pre>
Cache-Control: public
Content-Type: text/plain; charset=utf-8
Content-Length: 11
Etag: "static"
</pre>
<p>I've run this on the ASP.NET development server and IIS6 so far with the same results. Also I'm unable to explicitly set the ETag using</p>
<pre><code>Response.AppendHeader("ETag", "static")
</code></pre>
<p><strong>Update</strong>: It's possible to append the ETag header manually when running in IIS7, I suspect this is caused by the tight integration between ASP.NET and the IIS7 pipeline.</p>
<p><strong>Clarification</strong>: It's a long question but the core question is this: <strong>why does ASP.NET do this, how can I get around it and should I?</strong></p>
<p><strong>Update</strong>: I'm going to accept <a href="https://stackoverflow.com/questions/32824/why-does-httpcacheabilityprivate-suppress-etags#34004">Tony's answer</a> since it's essentially correct (go Tony!). I found that if you want to emulate the HttpCacheability.Private fully you can set the cacheability to ServerAndPrivate but you also have call cache.<a href="http://msdn.microsoft.com/en-us/library/system.web.httpcachepolicy.setomitvarystar.aspx" rel="nofollow noreferrer">SetOmitVaryStar</a>(true) otherwise the cache will add the <strong>Vary: *</strong> header to the output and you don't want that. I'll edit that into the answer when I get edit permissions (or if you see this Tony perhaps you could edit your answer to include that call?)</p>
| [
{
"answer_id": 33555,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 2,
"selected": false,
"text": "<p>Unfortunately if you look at <code>System.Web.HttpCachePolicy.UpdateCachedHeaders()</code> in .NET Reflector you see ... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2114/"
] | While writing a custom IHttpHandler I came across a behavior that I didn't expect concerning the HttpCachePolicy object.
My handler calculates and sets an entity-tag (using the SetETag method on the HttpCachePolicy associated with the current response object). If I set the cache-control to public using the SetCacheability method everything works like a charm and the server sends along the e-tag header. If I set it to private the e-tag header will be suppressed.
Maybe I just haven't looked hard enough but I haven't seen anything in the HTTP/1.1 spec that would justify this behavior. Why wouldn't you want to send E-Tag to browsers while still prohibiting proxies from storing the data?
```
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext ctx) {
ctx.Response.Cache.SetCacheability(HttpCacheability.Private);
ctx.Response.Cache.SetETag("\"static\"");
ctx.Response.ContentType = "text/plain";
ctx.Response.Write("Hello World");
}
public bool IsReusable { get { return true; } }
}
```
Will return
```
Cache-Control: private
Content-Type: text/plain; charset=utf-8
Content-Length: 11
```
But if we change it to public it'll return
```
Cache-Control: public
Content-Type: text/plain; charset=utf-8
Content-Length: 11
Etag: "static"
```
I've run this on the ASP.NET development server and IIS6 so far with the same results. Also I'm unable to explicitly set the ETag using
```
Response.AppendHeader("ETag", "static")
```
**Update**: It's possible to append the ETag header manually when running in IIS7, I suspect this is caused by the tight integration between ASP.NET and the IIS7 pipeline.
**Clarification**: It's a long question but the core question is this: **why does ASP.NET do this, how can I get around it and should I?**
**Update**: I'm going to accept [Tony's answer](https://stackoverflow.com/questions/32824/why-does-httpcacheabilityprivate-suppress-etags#34004) since it's essentially correct (go Tony!). I found that if you want to emulate the HttpCacheability.Private fully you can set the cacheability to ServerAndPrivate but you also have call cache.[SetOmitVaryStar](http://msdn.microsoft.com/en-us/library/system.web.httpcachepolicy.setomitvarystar.aspx)(true) otherwise the cache will add the **Vary: \*** header to the output and you don't want that. I'll edit that into the answer when I get edit permissions (or if you see this Tony perhaps you could edit your answer to include that call?) | I think you need to use HttpCacheability.ServerAndPrivate
That should give you cache-control: private in the headers and let you set an ETag.
The documentation on that needs to be a bit better.
**Edit:** Markus found that you also have call cache.SetOmitVaryStar(true) otherwise the cache will add the Vary: \* header to the output and you don't want that. |
32,845 | <p>Is it "taboo" to programatically create system restore points? I would be doing this before I perform a software update. If there is a better method to create a restore point with just my software's files and data, please let me know.</p>
<p>I would like a means by which I can get the user back to a known working state if everything goes kaput during an update (closes/kills the update app, power goes out, user pulls the plug, etc.)</p>
<pre><code> private void CreateRestorePoint(string description)
{
ManagementScope oScope = new ManagementScope("\\\\localhost\\root\\default");
ManagementPath oPath = new ManagementPath("SystemRestore");
ObjectGetOptions oGetOp = new ObjectGetOptions();
ManagementClass oProcess = new ManagementClass(oScope, oPath, oGetOp);
ManagementBaseObject oInParams = oProcess.GetMethodParameters("CreateRestorePoint");
oInParams["Description"] = description;
oInParams["RestorePointType"] = 12; // MODIFY_SETTINGS
oInParams["EventType"] = 100;
ManagementBaseObject oOutParams = oProcess.InvokeMethod("CreateRestorePoint", oInParams, null);
}
</code></pre>
| [
{
"answer_id": 32854,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": -1,
"selected": false,
"text": "<p>I don't think a complete system restore would be a good plan. Two reasons that quickly come to mind:</p>\n\n<ul>\n<li>Was... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1490/"
] | Is it "taboo" to programatically create system restore points? I would be doing this before I perform a software update. If there is a better method to create a restore point with just my software's files and data, please let me know.
I would like a means by which I can get the user back to a known working state if everything goes kaput during an update (closes/kills the update app, power goes out, user pulls the plug, etc.)
```
private void CreateRestorePoint(string description)
{
ManagementScope oScope = new ManagementScope("\\\\localhost\\root\\default");
ManagementPath oPath = new ManagementPath("SystemRestore");
ObjectGetOptions oGetOp = new ObjectGetOptions();
ManagementClass oProcess = new ManagementClass(oScope, oPath, oGetOp);
ManagementBaseObject oInParams = oProcess.GetMethodParameters("CreateRestorePoint");
oInParams["Description"] = description;
oInParams["RestorePointType"] = 12; // MODIFY_SETTINGS
oInParams["EventType"] = 100;
ManagementBaseObject oOutParams = oProcess.InvokeMethod("CreateRestorePoint", oInParams, null);
}
``` | >
> Is it "taboo" to programatically create system restore points?
>
>
>
No. That's why the API is there; so that you can have pseudo-atomic updates of the system. |
32,877 | <p>I've got a problem where incoming SOAP messages from one particular client are being marked as invalid and rejected by our XML firewall device. It appears extra payload data is being inserted by Visual Studio; we're thinking the extra data may be causing a problem b/c we're seeing "VsDebuggerCausalityData" in these messages but not in others sent from a different client who is not having a problem. It's a starting point, anyway.</p>
<p>The question I have is how can the client remove this extra data and still run from VS? Why is VS putting it in there at all?</p>
<p>Thanks.</p>
| [
{
"answer_id": 33312,
"author": "Darryl Braaten",
"author_id": 1834,
"author_profile": "https://Stackoverflow.com/users/1834",
"pm_score": 5,
"selected": true,
"text": "<p>A quick google reveals that this should get rid of it, get them to add it to the web.config or app.config for their ... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1683/"
] | I've got a problem where incoming SOAP messages from one particular client are being marked as invalid and rejected by our XML firewall device. It appears extra payload data is being inserted by Visual Studio; we're thinking the extra data may be causing a problem b/c we're seeing "VsDebuggerCausalityData" in these messages but not in others sent from a different client who is not having a problem. It's a starting point, anyway.
The question I have is how can the client remove this extra data and still run from VS? Why is VS putting it in there at all?
Thanks. | A quick google reveals that this should get rid of it, get them to add it to the web.config or app.config for their application.
```
<configuration>
<system.diagnostics>
<switches>
<add name="Remote.Disable" value="1" />
</switches>
</system.diagnostics>
</configuration>
```
The information is debug information that the receiving service can use to help trace things back to the client. (maybe, I am guessing a little)
* I have proposed a follow up [question](https://stackoverflow.com/questions/33334/how-do-you-find-what-debug-switches-are-available-or-given-a-switch-find-out-wh) to determine were the magic switch actually comes from. |
32,897 | <p>This question would probably apply equally as well to other languages with C-like multi-line comments. Here's the problem I'm encountering. I'm working with Java code in Eclipse, and I wanted to comment out a block of code. However, there is a string that contains the character sequence "*/", and Eclipse thinks that the comment should end there, even though it is inside a string. It gives me tons of errors and fails to build.</p>
<pre><code>/*
... some Java code ...
... "... */ ..." ...
... more Java code ...
*/
</code></pre>
<p>Does the Java specification match with Eclipse's interpretation of my multi-line comment? I would like to think that Java and/or Eclipse would account for this sort of thing.</p>
| [
{
"answer_id": 32916,
"author": "Damien B",
"author_id": 3069,
"author_profile": "https://Stackoverflow.com/users/3069",
"pm_score": 4,
"selected": true,
"text": "<p>Eclipse is correct. There is no interpretation context inside a comment (no escaping, etc). See <a href=\"http://java.sun.... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This question would probably apply equally as well to other languages with C-like multi-line comments. Here's the problem I'm encountering. I'm working with Java code in Eclipse, and I wanted to comment out a block of code. However, there is a string that contains the character sequence "\*/", and Eclipse thinks that the comment should end there, even though it is inside a string. It gives me tons of errors and fails to build.
```
/*
... some Java code ...
... "... */ ..." ...
... more Java code ...
*/
```
Does the Java specification match with Eclipse's interpretation of my multi-line comment? I would like to think that Java and/or Eclipse would account for this sort of thing. | Eclipse is correct. There is no interpretation context inside a comment (no escaping, etc). See [JLS §3.7](http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48125). |
32,899 | <p>I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this:</p>
<pre><code>import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequence(unittest.TestCase):
def testsample(self):
for name, a,b in l:
print "test", name
self.assertEqual(a,b)
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?</p>
| [
{
"answer_id": 32939,
"author": "Dmitry Mukhin",
"author_id": 3448,
"author_profile": "https://Stackoverflow.com/users/3448",
"pm_score": 9,
"selected": true,
"text": "<p>This is called "parametrization".</p>\n<p>There are several tools that support this approach. E.g.:</p>\n<u... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/720/"
] | I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this:
```
import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequence(unittest.TestCase):
def testsample(self):
for name, a,b in l:
print "test", name
self.assertEqual(a,b)
if __name__ == '__main__':
unittest.main()
```
The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions? | This is called "parametrization".
There are several tools that support this approach. E.g.:
* [pytest's decorator](https://docs.pytest.org/en/latest/parametrize.html)
* [parameterized](https://github.com/wolever/parameterized)
The resulting code looks like this:
```
from parameterized import parameterized
class TestSequence(unittest.TestCase):
@parameterized.expand([
["foo", "a", "a",],
["bar", "a", "b"],
["lee", "b", "b"],
])
def test_sequence(self, name, a, b):
self.assertEqual(a,b)
```
Which will generate the tests:
```none
test_sequence_0_foo (__main__.TestSequence) ... ok
test_sequence_1_bar (__main__.TestSequence) ... FAIL
test_sequence_2_lee (__main__.TestSequence) ... ok
======================================================================
FAIL: test_sequence_1_bar (__main__.TestSequence)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/parameterized/parameterized.py", line 233, in <lambda>
standalone_func = lambda *a: func(*(a + p.args), **p.kwargs)
File "x.py", line 12, in test_sequence
self.assertEqual(a,b)
AssertionError: 'a' != 'b'
```
For historical reasons I'll leave the original answer circa 2008):
I use something like this:
```
import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequense(unittest.TestCase):
pass
def test_generator(a, b):
def test(self):
self.assertEqual(a,b)
return test
if __name__ == '__main__':
for t in l:
test_name = 'test_%s' % t[0]
test = test_generator(t[1], t[2])
setattr(TestSequense, test_name, test)
unittest.main()
``` |
32,937 | <p>In C# is there a shorthand way to write this:</p>
<pre><code>public static bool IsAllowed(int userID)
{
return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...);
}
</code></pre>
<p>Like:</p>
<pre><code>public static bool IsAllowed(int userID)
{
return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...);
}
</code></pre>
<p>I know I could also use switch, but there are probably 50 or so functions like this I have to write (porting a classic ASP site over to ASP.NET) so I'd like to keep them as short as possible.</p>
| [
{
"answer_id": 32942,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "<p>I would encapsulate the list of allowed IDs as <em>data</em> not <em>code</em>. Then it's source can be changed easily... | 2008/08/28 | [
"https://Stackoverflow.com/questions/32937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1302/"
] | In C# is there a shorthand way to write this:
```
public static bool IsAllowed(int userID)
{
return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...);
}
```
Like:
```
public static bool IsAllowed(int userID)
{
return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...);
}
```
I know I could also use switch, but there are probably 50 or so functions like this I have to write (porting a classic ASP site over to ASP.NET) so I'd like to keep them as short as possible. | How about this?
```
public static class Extensions
{
public static bool In<T>(this T testValue, params T[] values)
{
return values.Contains(testValue);
}
}
```
Usage:
```
Personnel userId = Personnel.JohnDoe;
if (userId.In(Personnel.JohnDoe, Personnel.JaneDoe))
{
// Do something
}
```
I can't claim credit for this, but I also can't remember where I saw it. So, credit to you, anonymous Internet stranger. |
33,048 | <p>Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do you test this observer with rSpec?</p>
| [
{
"answer_id": 33869,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": false,
"text": "<p>Disclaimer: I've never actually done this on a production site, but it looks like a reasonable way would be to use moc... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2569/"
] | Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do you test this observer with rSpec? | You are on the right track, but I have run into a number of frustrating unexpected message errors when using rSpec, observers, and mock objects. When I am spec testing my model, I don't want to have to handle observer behavior in my message expectations.
In your example, there isn't a really good way to spec "set\_status" on the model without knowledge of what the observer is going to do to it.
Therefore, I like to use the ["No Peeping Toms" plugin.](http://patmaddox.com/2007/11/23/better-rails-testing-decoupling-observers/) Given your code above and using the No Peeping Toms plugin, I would spec the model like this:
```
describe Person do
it "should set status correctly" do
@p = Person.new(:status => "foo")
@p.set_status("bar")
@p.save
@p.status.should eql("bar")
end
end
```
You can spec your model code without having to worry that there is an observer out there that is going to come in and clobber your value. You'd spec that separately in the person\_observer\_spec like this:
```
describe PersonObserver do
it "should clobber the status field" do
@p = mock_model(Person, :status => "foo")
@obs = PersonObserver.instance
@p.should_receive(:set_status).with("aha!")
@obs.after_save
end
end
```
If you REALLY REALLY want to test the coupled Model and Observer class, you can do it like this:
```
describe Person do
it "should register a status change with the person observer turned on" do
Person.with_observers(:person_observer) do
lambda { @p = Person.new; @p.save }.should change(@p, :status).to("aha!)
end
end
end
```
99% of the time, I'd rather spec test with the observers turned off. It's just easier that way. |
33,055 | <p>I'm new to SVN and I'd like to know what methods are available for backing up repositories in a Windows environment?</p>
| [
{
"answer_id": 33062,
"author": "Misha M",
"author_id": 3467,
"author_profile": "https://Stackoverflow.com/users/3467",
"pm_score": 2,
"selected": false,
"text": "<p>I like to just copy the entire repo directory to my backup location. That way, if something happens, you can just copy th... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3396/"
] | I'm new to SVN and I'd like to know what methods are available for backing up repositories in a Windows environment? | You could use something like (Linux):
```
svnadmin dump repositorypath | gzip > backupname.svn.gz
```
Since Windows does not support GZip it is just:
```
svnadmin dump repositorypath > backupname.svn
``` |
33,063 | <p>I have a big string (let's call it a CSV file, though it isn't actually one, it'll just be easier for now) that I have to parse in C# code.<br>
The first step of the parsing process splits the file into individual lines by just using a <code>StreamReader</code> object and calling <code>ReadLine</code> until it's through the file. However, any given line might contain a quoted (in single quotes) literal with embedded newlines. I need to find those newlines and convert them temporarily into some other kind of token or escape sequence until I've split the file into an array of lines..then I can change them back. </p>
<p>Example input data: </p>
<pre><code>1,2,10,99,'Some text without a newline', true, false, 90
2,1,11,98,'This text has an embedded newline
and continues here', true, true, 90
</code></pre>
<p>I could write all of the C# code needed to do this by using <code>string.IndexOf</code> to find the quoted sections and look within them for newlines, but I'm thinking a Regex might be a better choice (i.e. <a href="http://regex.info/blog/2006-09-15/247" rel="nofollow noreferrer">now I have two problems</a>)</p>
| [
{
"answer_id": 33074,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 0,
"selected": false,
"text": "<p><strong>EDIT:</strong> Sorry, I've misinterpreted your post. If you're looking for a regex, then here is one:</p>\n\n<pre>... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2187/"
] | I have a big string (let's call it a CSV file, though it isn't actually one, it'll just be easier for now) that I have to parse in C# code.
The first step of the parsing process splits the file into individual lines by just using a `StreamReader` object and calling `ReadLine` until it's through the file. However, any given line might contain a quoted (in single quotes) literal with embedded newlines. I need to find those newlines and convert them temporarily into some other kind of token or escape sequence until I've split the file into an array of lines..then I can change them back.
Example input data:
```
1,2,10,99,'Some text without a newline', true, false, 90
2,1,11,98,'This text has an embedded newline
and continues here', true, true, 90
```
I could write all of the C# code needed to do this by using `string.IndexOf` to find the quoted sections and look within them for newlines, but I'm thinking a Regex might be a better choice (i.e. [now I have two problems](http://regex.info/blog/2006-09-15/247)) | Since this isn't a true CSV file, does it have any sort of schema?
From your example, it looks like you have:
int, int, int, int, string , bool, bool, int
With that making up your record / object.
Assuming that your data is well formed (I don't know enough about your source to know how valid this assumption is); you could:
1. Read your line.
2. Use a state machine to parse your data.
3. If your line ends, and you're parsing a string, read the next line..and keep parsing.
I'd avoid using a regex if possible. |
33,073 | <p>How do I make <code>diff</code> ignore temporary files like <code>foo.c~</code>? Is there a configuration file that will make ignoring temporaries the default?</p>
<p>More generally: what's the best way to generate a "clean" patch off a tarball? I do this rarely enough (submitting a bug fix to an OSS project by email) that I always struggle with it...</p>
<p>EDIT: OK, the short answer is</p>
<pre><code>diff -ruN -x *~ ...
</code></pre>
<p>Is there a better answer? E.g., can this go in a configuration file?</p>
| [
{
"answer_id": 33085,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 3,
"selected": true,
"text": "<p>This doesn't strictly answer your question, but you can avoid the problem by configuring Emacs to use a specific directo... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] | How do I make `diff` ignore temporary files like `foo.c~`? Is there a configuration file that will make ignoring temporaries the default?
More generally: what's the best way to generate a "clean" patch off a tarball? I do this rarely enough (submitting a bug fix to an OSS project by email) that I always struggle with it...
EDIT: OK, the short answer is
```
diff -ruN -x *~ ...
```
Is there a better answer? E.g., can this go in a configuration file? | This doesn't strictly answer your question, but you can avoid the problem by configuring Emacs to use a specific directory to keep the backup files in. There are different implementations for Emacs or XEmacs.
In GNU Emacs
```
(defvar user-temporary-file-directory
(concat temporary-file-directory user-login-name "/"))
(make-directory user-temporary-file-directory t)
(setq backup-by-copying t)
(setq backup-directory-alist
`(("." . ,user-temporary-file-directory)
(,tramp-file-name-regexp nil)))
(setq auto-save-list-file-prefix
(concat user-temporary-file-directory ".auto-saves-"))
(setq auto-save-file-name-transforms
`((".*" ,user-temporary-file-directory t)))
```
In XEmacs
```
(require 'auto-save)
(require 'backup-dir)
(defvar user-temporary-file-directory
(concat (temp-directory) "/" (user-login-name)))
(make-directory user-temporary-file-directory t)
(setq backup-by-copying t)
(setq auto-save-directory user-temporary-file-directory)
(setq auto-save-list-file-prefix
(concat user-temporary-file-directory ".auto-saves-"))
(setq bkup-backup-directory-info
`((t ,user-temporary-file-directory full-path)))
```
You can also remove them all with a simple find command
```
find . -name “*~” -delete
```
Note that the asterisk and tilde are in double quotes to stop the shell expanding them.
By the way, these aren't strictly *temporary* files. They are a backup of the previous version of the file, so you can manually "undo" your last edit at any time in the future. |
33,080 | <p>In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window.</p>
<p>I need an auto-height for the object. The DIV starts about 300px from the top screen, and its height should make it stretch to the bottom of the browser screen. I have a max height for the container DIV, so there would have to be minimum-height for the div. I believe I can just restrict that in CSS, and use Javascript to handle the resizing of the DIV.</p>
<p>My javascript isn't nearly as good as it should be. Is there an easy script I could write that would do this for me?</p>
<p>Edit:
The DIV houses a control that does it's own overflow handling (implements its own scroll bar).</p>
| [
{
"answer_id": 33096,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": false,
"text": "<p>What should happen in the case of overflow? If you want it to just get to the bottom of the window, use absolute ... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1226/"
] | In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window.
I need an auto-height for the object. The DIV starts about 300px from the top screen, and its height should make it stretch to the bottom of the browser screen. I have a max height for the container DIV, so there would have to be minimum-height for the div. I believe I can just restrict that in CSS, and use Javascript to handle the resizing of the DIV.
My javascript isn't nearly as good as it should be. Is there an easy script I could write that would do this for me?
Edit:
The DIV houses a control that does it's own overflow handling (implements its own scroll bar). | Try this simple, specific function:
```
function resizeElementHeight(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop) + "px");
}
```
It does not depend on the current distance from the top of the body being specified (in case your 300px changes).
---
EDIT: By the way, you would want to call this on that div every time the user changed the browser's size, so you would need to wire up the event handler for that, of course. |
33,089 | <p>I'm using the <a href="http://msdn.microsoft.com/en-us/library/ms178329.aspx" rel="nofollow noreferrer">ASP.NET Login Controls</a> and <a href="http://msdn.microsoft.com/en-us/library/aa480476.aspx" rel="nofollow noreferrer">Forms Authentication</a> for membership/credentials for an ASP.NET web application. It keeps redirecting to a Login.aspx page at the root of my application that does not exist. My login page is within a folder.</p>
| [
{
"answer_id": 33092,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 1,
"selected": false,
"text": "<p>I found the answer at <a href=\"http://www.codersource.net/asp_net_forms_authentication.aspx\" rel=\"nofollow noreferrer... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | I'm using the [ASP.NET Login Controls](http://msdn.microsoft.com/en-us/library/ms178329.aspx) and [Forms Authentication](http://msdn.microsoft.com/en-us/library/aa480476.aspx) for membership/credentials for an ASP.NET web application. It keeps redirecting to a Login.aspx page at the root of my application that does not exist. My login page is within a folder. | Use the LoginUrl property for the forms item?
```
<authentication mode="Forms">
<forms defaultUrl="~/Default.aspx" loginUrl="~/login.aspx" timeout="1440" ></forms>
</authentication>
``` |
33,103 | <p>I've noticed that some sites (usually banks) suppress the ability to paste text into text fields. How is this done? I know that JavaScript can be used to swallow the keyboard shortcut for paste, but what about the right-click menu item?</p>
| [
{
"answer_id": 33130,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 4,
"selected": true,
"text": "<p>Probably using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.onpaste\" rel=\"nofollow noreferre... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1450/"
] | I've noticed that some sites (usually banks) suppress the ability to paste text into text fields. How is this done? I know that JavaScript can be used to swallow the keyboard shortcut for paste, but what about the right-click menu item? | Probably using the [`onpaste`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.onpaste) event, and either `return false` from it or use `e.preventDefault()` on the Event object.
Note that `onpaste` is *non standard*, don't rely on it for production sites, because it will not be there forever.
```js
$(document).on("paste",function(e){
console.log("paste")
e.preventDefault()
return false;
})
``` |
33,115 | <p>Does C# have the notion of private / protected inheritance, and if not, why?</p>
<p><strong>C++</strong></p>
<pre>
<code>
class Foo : private Bar {
public:
...
};
</code>
</pre>
<p><strong>C#</strong></p>
<pre>
<code>
public abstract NServlet class : private System.Web.UI.Page
{
// error "type expected"
}
</code>
</pre>
<p>I am implementing a "servlet like" concept in an .aspx page and I don't want the concrete class to have the ability to see the internals of the System.Web.UI.Page base.</p>
| [
{
"answer_id": 33128,
"author": "Chris Karcher",
"author_id": 2773,
"author_profile": "https://Stackoverflow.com/users/2773",
"pm_score": 1,
"selected": false,
"text": "<p>No, public inheritance only.</p>\n"
},
{
"answer_id": 33142,
"author": "Daren Thomas",
"author_id": ... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | Does C# have the notion of private / protected inheritance, and if not, why?
**C++**
```
class Foo : private Bar {
public:
...
};
```
**C#**
```
public abstract NServlet class : private System.Web.UI.Page
{
// error "type expected"
}
```
I am implementing a "servlet like" concept in an .aspx page and I don't want the concrete class to have the ability to see the internals of the System.Web.UI.Page base. | C# allows public inheritance only. C++ allowed all three kinds. Public inheritance implied an "IS-A" type of relationship, and private inheritance implied a "Is-Implemented-In-Terms-Of" kind of relationship. Since layering (or composition) accomplished this in an arguably simpler fashion, private inheritance was only used when absolutely required by protected members or virtual functions required it - according to Scott Meyers in Effective C++, Item 42.
My guess would be that the authors of C# did not feel this additional method of implementing one class in terms of another was necessary. |
33,150 | <p>I am working on a Customer Server Control that extends another control. There is no problem with attaching to other controls on the form.</p>
<p>in vb.net: <code>Parent.FindControl(TargetControlName)</code></p>
<p>I would like to pass a method to the control in the ASPX markup. </p>
<p>for example: <code><c:MyCustomerControl runat=server InitializeStuffCallback="InitializeStuff"></code></p>
<p>So, I tried using reflection to access the given method name from the Parent.</p>
<p>Something like (in VB)</p>
<pre class="lang-vb prettyprint-override"><code>Dim pageType As Type = Page.GetType
Dim CallbackMethodInfo As MethodInfo = pageType.GetMethod( "MethodName" )
'Also tried
sender.Parent.GetType.GetMethod("MethodName")
sender.Parent.Parent.GetType.GetMethod("MethodName")
</code></pre>
<p>The method isn't found, because it just isn't apart of the Page. Where should I be looking? I'm fairly sure this is possible because I've seen other controls do similar.</p>
<hr>
<p>I forgot to mention, my work-around is to give the control events and attaching to them in the Code-behind.</p>
| [
{
"answer_id": 33163,
"author": "Joel Martinez",
"author_id": 3433,
"author_profile": "https://Stackoverflow.com/users/3433",
"pm_score": 0,
"selected": false,
"text": "<p>Your workaround is actually the better answer. If you have code that you must run at a certain part of your control... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2017/"
] | I am working on a Customer Server Control that extends another control. There is no problem with attaching to other controls on the form.
in vb.net: `Parent.FindControl(TargetControlName)`
I would like to pass a method to the control in the ASPX markup.
for example: `<c:MyCustomerControl runat=server InitializeStuffCallback="InitializeStuff">`
So, I tried using reflection to access the given method name from the Parent.
Something like (in VB)
```vb
Dim pageType As Type = Page.GetType
Dim CallbackMethodInfo As MethodInfo = pageType.GetMethod( "MethodName" )
'Also tried
sender.Parent.GetType.GetMethod("MethodName")
sender.Parent.Parent.GetType.GetMethod("MethodName")
```
The method isn't found, because it just isn't apart of the Page. Where should I be looking? I'm fairly sure this is possible because I've seen other controls do similar.
---
I forgot to mention, my work-around is to give the control events and attaching to them in the Code-behind. | If you want to be able to pass a method in the ASPX markup, you need to use the `Browsable` attribute in your code on the event.
VB.NET
```vb
<Browsable(True)> Public Event InitializeStuffCallback
```
C#
```
[Browsable(true)]
public event EventHandler InitializeStuffCallback;
```
Reference:
[Design-Time Attributes for Components](http://msdn.microsoft.com/en-us/library/tk67c2t8.aspx) and [BrowsableAttribute Class](http://msdn.microsoft.com/en-us/library/system.componentmodel.browsableattribute.aspx)
All the events, properties, or whatever need to be in the code-behind of the control with the browsable attribute to make it so you can change it in the tag code. |
33,199 | <p>Would it be possible to print <code>Hello</code> twice using single <code>condition</code>?</p>
<pre><code>if "condition"
printf ("Hello");
else
printf("World");
</code></pre>
| [
{
"answer_id": 33202,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>if</code> statement executes one or the other of the controlled statements (both <code>printf</code> in your ... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2454/"
] | Would it be possible to print `Hello` twice using single `condition`?
```
if "condition"
printf ("Hello");
else
printf("World");
``` | ```
if ( printf("Hello") == 0 )
printf ("Hello");
else
printf ("World");
```
:-) |
33,226 | <p>Assuming such a query exists, I would greatly appreciate the help.</p>
<p>I'm trying to develop a permissions script that will grant "select" and "references" permissions on the user tables and views in a database. My hope is that executing the "grant" commands on each element in such a set will make it easier to keep permissions current when new tables and views are added to the database.</p>
| [
{
"answer_id": 33266,
"author": "Jas",
"author_id": 777,
"author_profile": "https://Stackoverflow.com/users/777",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select * from information_schema.tables\nwhere table_type = 'view'\n</code></pre>\n"
},
{
"answer_id": 33285,
... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475/"
] | Assuming such a query exists, I would greatly appreciate the help.
I'm trying to develop a permissions script that will grant "select" and "references" permissions on the user tables and views in a database. My hope is that executing the "grant" commands on each element in such a set will make it easier to keep permissions current when new tables and views are added to the database. | ```
select * from information_schema.tables
WHERE OBJECTPROPERTY(OBJECT_ID(table_name),'IsMSShipped') =0
```
Will exclude dt\_properties and system tables
add
```
where table_type = 'view'
```
if you just want the view |
33,233 | <p>Imagine you homebrew a custom gui framework that <em>doesn't</em> use windows handles (compact framework, so please don't argue with "whys"). One of the main disadvantages of developing such a framework is that you lose compatability with the winform designer.</p>
<p>So my question is to all of you who know a lot about VS customisation, would there be a clever mechanism by which one could incorperate the gui framework into the designer and get it to spit out your custom code instead of the standard windows stuff in the <code>InitialiseComponent()</code> method?</p>
| [
{
"answer_id": 33266,
"author": "Jas",
"author_id": 777,
"author_profile": "https://Stackoverflow.com/users/777",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select * from information_schema.tables\nwhere table_type = 'view'\n</code></pre>\n"
},
{
"answer_id": 33285,
... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1143/"
] | Imagine you homebrew a custom gui framework that *doesn't* use windows handles (compact framework, so please don't argue with "whys"). One of the main disadvantages of developing such a framework is that you lose compatability with the winform designer.
So my question is to all of you who know a lot about VS customisation, would there be a clever mechanism by which one could incorperate the gui framework into the designer and get it to spit out your custom code instead of the standard windows stuff in the `InitialiseComponent()` method? | ```
select * from information_schema.tables
WHERE OBJECTPROPERTY(OBJECT_ID(table_name),'IsMSShipped') =0
```
Will exclude dt\_properties and system tables
add
```
where table_type = 'view'
```
if you just want the view |
33,250 | <p>In one of my applications, I am querying active directory to get a list of all users below a given user (using the "Direct Reports" thing). So basically, given the name of the person, it is looked up in AD, then the Direct Reports are read. But then for every direct report, the tool needs to check the direct reports of the direct reports. Or, more abstract: The Tool will use a person as the root of the tree and then walk down the complete tree to get the names of all the leaves (can be several hundred)</p>
<p>Now, my concern is obviously performance, as this needs to be done quite a few times. My idea is to manually cache that (essentially just put all the names in a long string and store that somewhere and update it once a day).</p>
<p>But I just wonder if there is a more elegant way to first get the information and then cache it, possibly using something in the System.DirectoryServices Namespace?</p>
| [
{
"answer_id": 33299,
"author": "kemiller2002",
"author_id": 1942,
"author_profile": "https://Stackoverflow.com/users/1942",
"pm_score": 2,
"selected": false,
"text": "<p>Active Directory is pretty efficient at storing information and the retrieval shouldn't be that much of a performance... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | In one of my applications, I am querying active directory to get a list of all users below a given user (using the "Direct Reports" thing). So basically, given the name of the person, it is looked up in AD, then the Direct Reports are read. But then for every direct report, the tool needs to check the direct reports of the direct reports. Or, more abstract: The Tool will use a person as the root of the tree and then walk down the complete tree to get the names of all the leaves (can be several hundred)
Now, my concern is obviously performance, as this needs to be done quite a few times. My idea is to manually cache that (essentially just put all the names in a long string and store that somewhere and update it once a day).
But I just wonder if there is a more elegant way to first get the information and then cache it, possibly using something in the System.DirectoryServices Namespace? | In order to take control over the properties that you want to be cached you can call 'RefreshCache()' passing the properties that you want to hang around:
```c#
System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry();
// Push the property values from AD back to cache.
entry.RefreshCache(new string[] {"cn", "www" });
``` |
33,252 | <p>As a temporary stopgap until all the designers are in place we are currently hand-cranking a whole bunch of xml configuration files at work. One of the issues with this is file-versioning because people forget to update version numbers when updating the files (which is to be expected as humans generally suck at perfection).</p>
<p>Therefore I figure that as we store the files in Sharepoint I should be able to write a script to pull the files down from Sharepoint, get the version number and automatically enter/update the version number from Sharepoint into the file. This means when someone wants the "latest" files they can run the script and get the latest files with the version numbers correct (there is slightly more to it than this so the reason for using the script isn't just the benefit of auto-versioning).</p>
<p>Does anyone know how to get the files + version numbers from Sharepoint?</p>
| [
{
"answer_id": 33299,
"author": "kemiller2002",
"author_id": 1942,
"author_profile": "https://Stackoverflow.com/users/1942",
"pm_score": 2,
"selected": false,
"text": "<p>Active Directory is pretty efficient at storing information and the retrieval shouldn't be that much of a performance... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1143/"
] | As a temporary stopgap until all the designers are in place we are currently hand-cranking a whole bunch of xml configuration files at work. One of the issues with this is file-versioning because people forget to update version numbers when updating the files (which is to be expected as humans generally suck at perfection).
Therefore I figure that as we store the files in Sharepoint I should be able to write a script to pull the files down from Sharepoint, get the version number and automatically enter/update the version number from Sharepoint into the file. This means when someone wants the "latest" files they can run the script and get the latest files with the version numbers correct (there is slightly more to it than this so the reason for using the script isn't just the benefit of auto-versioning).
Does anyone know how to get the files + version numbers from Sharepoint? | In order to take control over the properties that you want to be cached you can call 'RefreshCache()' passing the properties that you want to hang around:
```c#
System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry();
// Push the property values from AD back to cache.
entry.RefreshCache(new string[] {"cn", "www" });
``` |
33,262 | <p>I have a complete XML document in a string and would like a <code>Document</code> object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5)</p>
<p><strong>Solution</strong> Thanks to <a href="https://stackoverflow.com/users/1322/matt-mcminn">Matt McMinn</a>, I have settled on this implementation. It has the right level of input flexibility and exception granularity for me. (It's good to know if the error came from malformed XML - <code>SAXException</code> - or just bad IO - <code>IOException</code>.)</p>
<pre><code>public static org.w3c.dom.Document loadXMLFrom(String xml)
throws org.xml.sax.SAXException, java.io.IOException {
return loadXMLFrom(new java.io.ByteArrayInputStream(xml.getBytes()));
}
public static org.w3c.dom.Document loadXMLFrom(java.io.InputStream is)
throws org.xml.sax.SAXException, java.io.IOException {
javax.xml.parsers.DocumentBuilderFactory factory =
javax.xml.parsers.DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
javax.xml.parsers.DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
}
catch (javax.xml.parsers.ParserConfigurationException ex) {
}
org.w3c.dom.Document doc = builder.parse(is);
is.close();
return doc;
}
</code></pre>
| [
{
"answer_id": 33283,
"author": "Matt McMinn",
"author_id": 1322,
"author_profile": "https://Stackoverflow.com/users/1322",
"pm_score": 7,
"selected": true,
"text": "<p>This works for me in Java 1.5 - I stripped out specific exceptions for readability.</p>\n\n<pre><code>import javax.xml.... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] | I have a complete XML document in a string and would like a `Document` object. Google turns up all sorts of garbage. What is the simplest solution? (In Java 1.5)
**Solution** Thanks to [Matt McMinn](https://stackoverflow.com/users/1322/matt-mcminn), I have settled on this implementation. It has the right level of input flexibility and exception granularity for me. (It's good to know if the error came from malformed XML - `SAXException` - or just bad IO - `IOException`.)
```
public static org.w3c.dom.Document loadXMLFrom(String xml)
throws org.xml.sax.SAXException, java.io.IOException {
return loadXMLFrom(new java.io.ByteArrayInputStream(xml.getBytes()));
}
public static org.w3c.dom.Document loadXMLFrom(java.io.InputStream is)
throws org.xml.sax.SAXException, java.io.IOException {
javax.xml.parsers.DocumentBuilderFactory factory =
javax.xml.parsers.DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
javax.xml.parsers.DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
}
catch (javax.xml.parsers.ParserConfigurationException ex) {
}
org.w3c.dom.Document doc = builder.parse(is);
is.close();
return doc;
}
``` | This works for me in Java 1.5 - I stripped out specific exceptions for readability.
```
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import java.io.ByteArrayInputStream;
public Document loadXMLFromString(String xml) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new ByteArrayInputStream(xml.getBytes()));
}
``` |
33,263 | <p>I'm using the <a href="http://msdn.microsoft.com/en-us/library/ms178329.aspx" rel="nofollow noreferrer">ASP.NET Login Controls</a> and <a href="http://msdn.microsoft.com/en-us/library/aa480476.aspx" rel="nofollow noreferrer">Forms Authentication</a> for membership/credentials for an ASP.NET web application.</p>
<p>I've got two roles:</p>
<ul>
<li>Users</li>
<li>Administrators</li>
</ul>
<p>I want pages to be viewable by four different groups:</p>
<ul>
<li>Everyone <em>(Default, Help)</em></li>
<li>Anonymous <em>(CreateUser, Login, PasswordRecovery)</em></li>
<li>Users <em>(ChangePassword, DataEntry)</em></li>
<li>Administrators <em>(Report)</em></li>
</ul>
<p>Expanding on the example in the <a href="http://www.asp.net/learn/videos/video-45.aspx" rel="nofollow noreferrer">ASP.NET HOW DO I Video Series: Membership and Roles</a>, I've put those page files into such folders:</p>
<p><img src="https://i.stack.imgur.com/Ps7sm.gif" alt="Visual Studio Solution Explorer"></p>
<p>And I used the ASP.NET Web Site Administration Tool to set up access rules for each folder.</p>
<p>It works but seems kludgy to me and it creates issues <a href="https://stackoverflow.com/questions/33089/how-do-i-use-aspnet-login-controls-when-my-loginaspx-is-not-at-the-root-of-my-a">when Login.aspx is not at the root</a> and with the <a href="https://stackoverflow.com/questions/33166/how-do-i-keep-my-loginaspx-pages-returnurl-parameter-from-overriding-my-aspnet">ReturnUrl parameter</a> of Login.aspx.</p>
<p>Is there a better way to do this? Is there perhaps a simple way I can set permissions at the page level rather than at the folder level?</p>
| [
{
"answer_id": 33283,
"author": "Matt McMinn",
"author_id": 1322,
"author_profile": "https://Stackoverflow.com/users/1322",
"pm_score": 7,
"selected": true,
"text": "<p>This works for me in Java 1.5 - I stripped out specific exceptions for readability.</p>\n\n<pre><code>import javax.xml.... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | I'm using the [ASP.NET Login Controls](http://msdn.microsoft.com/en-us/library/ms178329.aspx) and [Forms Authentication](http://msdn.microsoft.com/en-us/library/aa480476.aspx) for membership/credentials for an ASP.NET web application.
I've got two roles:
* Users
* Administrators
I want pages to be viewable by four different groups:
* Everyone *(Default, Help)*
* Anonymous *(CreateUser, Login, PasswordRecovery)*
* Users *(ChangePassword, DataEntry)*
* Administrators *(Report)*
Expanding on the example in the [ASP.NET HOW DO I Video Series: Membership and Roles](http://www.asp.net/learn/videos/video-45.aspx), I've put those page files into such folders:

And I used the ASP.NET Web Site Administration Tool to set up access rules for each folder.
It works but seems kludgy to me and it creates issues [when Login.aspx is not at the root](https://stackoverflow.com/questions/33089/how-do-i-use-aspnet-login-controls-when-my-loginaspx-is-not-at-the-root-of-my-a) and with the [ReturnUrl parameter](https://stackoverflow.com/questions/33166/how-do-i-keep-my-loginaspx-pages-returnurl-parameter-from-overriding-my-aspnet) of Login.aspx.
Is there a better way to do this? Is there perhaps a simple way I can set permissions at the page level rather than at the folder level? | This works for me in Java 1.5 - I stripped out specific exceptions for readability.
```
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import java.io.ByteArrayInputStream;
public Document loadXMLFromString(String xml) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new ByteArrayInputStream(xml.getBytes()));
}
``` |
33,265 | <p>There are two weird operators in C#:</p>
<ul>
<li>the <a href="http://msdn.microsoft.com/en-us/library/6x6y6z4d.aspx" rel="noreferrer">true operator</a></li>
<li>the <a href="http://msdn.microsoft.com/en-us/library/6292hy1k.aspx" rel="noreferrer">false operator</a></li>
</ul>
<p>If I understand this right these operators can be used in types which I want to use instead of a boolean expression and where I don't want to provide an implicit conversion to bool.</p>
<p>Let's say I have a following class:</p>
<pre><code> public class MyType
{
public readonly int Value;
public MyType(int value)
{
Value = value;
}
public static bool operator true (MyType mt)
{
return mt.Value > 0;
}
public static bool operator false (MyType mt)
{
return mt.Value < 0;
}
}
</code></pre>
<p>So I can write the following code:</p>
<pre><code> MyType mTrue = new MyType(100);
MyType mFalse = new MyType(-100);
MyType mDontKnow = new MyType(0);
if (mTrue)
{
// Do something.
}
while (mFalse)
{
// Do something else.
}
do
{
// Another code comes here.
} while (mDontKnow)
</code></pre>
<p>However for all the examples above only the true operator is executed. So what's the false operator in C# good for?</p>
<p><em>Note: More examples can be found <a href="http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/truefalseoperatorforComplex.htm" rel="noreferrer">here</a>, <a href="http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/OverloadtrueandfalseforTwoDimension.htm" rel="noreferrer">here</a> and <a href="http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/trueandfalseoperator.htm" rel="noreferrer">here</a>.</em></p>
| [
{
"answer_id": 33315,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 4,
"selected": false,
"text": "<p>The page you link to <a href=\"http://msdn.microsoft.com/en-us/library/6x6y6z4d.aspx\" rel=\"noreferrer\">http://msdn.mic... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
] | There are two weird operators in C#:
* the [true operator](http://msdn.microsoft.com/en-us/library/6x6y6z4d.aspx)
* the [false operator](http://msdn.microsoft.com/en-us/library/6292hy1k.aspx)
If I understand this right these operators can be used in types which I want to use instead of a boolean expression and where I don't want to provide an implicit conversion to bool.
Let's say I have a following class:
```
public class MyType
{
public readonly int Value;
public MyType(int value)
{
Value = value;
}
public static bool operator true (MyType mt)
{
return mt.Value > 0;
}
public static bool operator false (MyType mt)
{
return mt.Value < 0;
}
}
```
So I can write the following code:
```
MyType mTrue = new MyType(100);
MyType mFalse = new MyType(-100);
MyType mDontKnow = new MyType(0);
if (mTrue)
{
// Do something.
}
while (mFalse)
{
// Do something else.
}
do
{
// Another code comes here.
} while (mDontKnow)
```
However for all the examples above only the true operator is executed. So what's the false operator in C# good for?
*Note: More examples can be found [here](http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/truefalseoperatorforComplex.htm), [here](http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/OverloadtrueandfalseforTwoDimension.htm) and [here](http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/trueandfalseoperator.htm).* | You can use it to override the `&&` and `||` operators.
The `&&` and `||` operators can't be overridden, but if you override `|`, `&`, `true` and `false` in exactly the right way the compiler will call `|` and `&` when you write `||` and `&&`.
For example, look at this code (from <http://ayende.com/blog/1574/nhibernate-criteria-api-operator-overloading> - where I found out about this trick; [archived version](http://web.archive.org/web/20080613013350/http://www.ayende.com/Blog/archive/2006/08/04/7381.aspx) by @BiggsTRC):
```
public static AbstractCriterion operator &(AbstractCriterion lhs, AbstractCriterion rhs)
{
return new AndExpression(lhs, rhs);
}
public static AbstractCriterion operator |(AbstractCriterion lhs, AbstractCriterion rhs)
{
return new OrExpression(lhs, rhs);
}
public static bool operator false(AbstractCriterion criteria)
{
return false;
}
public static bool operator true(AbstractCriterion criteria)
{
return false;
}
```
This is obviously a side effect and not the way it's intended to be used, but it is useful. |
33,301 | <p>I have a JavaScript method that I need to run on one of my pages, in particular, the <code>onresize</code> event. </p>
<p>However, I don't see how I can set that event from my content page. I wish I could just put it on my master page, but I don't have the need for the method to be called on all pages that use that master page.</p>
<p>Any help would be appreciated.</p>
| [
{
"answer_id": 33440,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 3,
"selected": true,
"text": "<p>Place the following in your content page:</p>\n\n<pre><code><script type=\"text/javascript\">\n\n// here is a c... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1226/"
] | I have a JavaScript method that I need to run on one of my pages, in particular, the `onresize` event.
However, I don't see how I can set that event from my content page. I wish I could just put it on my master page, but I don't have the need for the method to be called on all pages that use that master page.
Any help would be appreciated. | Place the following in your content page:
```
<script type="text/javascript">
// here is a cross-browser compatible way of connecting
// handlers to events, in case you don't have one
function attachEventHandler(element, eventToHandle, eventHandler) {
if(element.attachEvent) {
element.attachEvent(eventToHandle, eventHandler);
} else if(element.addEventListener) {
element.addEventListener(eventToHandle.replace("on", ""), eventHandler, false);
} else {
element[eventToHandle] = eventHandler;
}
}
attachEventHandler(window, "onresize", function() {
// the code you want to run when the browser is resized
});
</script>
```
---
That code should give you the basic idea of what you need to do. Hopefully you are using a library that already has code to help you write up event handlers and such. |
33,334 | <p>In this <a href="https://stackoverflow.com/questions/32877/how-to-remove-vsdebuggercausalitydata-data-from-soap-message">question</a> the answer was to flip on a switch that is picked up by the debugger disabling the extraneous header that was causing the problem. The Microsoft help implies these switched are user generated and does not list any switches.</p>
<pre><code><configuration>
<system.diagnostics>
<switches>
<add name="Remote.Disable" value="1" />
</switches>
</system.diagnostics>
</configuration>
</code></pre>
<p>What I would like to know is where the value "Remote.Disable" comes from and how find out what other things can be switched on or off. Currently it is just some config magic, and I don't like magic.</p>
| [
{
"answer_id": 33677,
"author": "Kevin Dente",
"author_id": 9,
"author_profile": "https://Stackoverflow.com/users/9",
"pm_score": 1,
"selected": false,
"text": "<p>You can use Reflector to search for uses of the Switch class and its subclasss (BooleanSwitch, TraceSwitch, etc). The variou... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1834/"
] | In this [question](https://stackoverflow.com/questions/32877/how-to-remove-vsdebuggercausalitydata-data-from-soap-message) the answer was to flip on a switch that is picked up by the debugger disabling the extraneous header that was causing the problem. The Microsoft help implies these switched are user generated and does not list any switches.
```
<configuration>
<system.diagnostics>
<switches>
<add name="Remote.Disable" value="1" />
</switches>
</system.diagnostics>
</configuration>
```
What I would like to know is where the value "Remote.Disable" comes from and how find out what other things can be switched on or off. Currently it is just some config magic, and I don't like magic. | As you suspected, Remote.Disable stops the app from attaching debug info to remote requests. It's defined inside the .NET framework methods that make the SOAP request.
The basic situation is that these switches can be defined anywhere in code, you just need to create a new System.Diagnostics.BooleanSwitch with the name given and the config file can control them.
This particular one is defined in System.ComponentModel.CompModSwitches.DisableRemoteDebugging:
```
public static BooleanSwitch DisableRemoteDebugging
{
get
{
if (disableRemoteDebugging == null)
{
disableRemoteDebugging = new BooleanSwitch("Remote.Disable", "Disable remote debugging for web methods.");
}
return disableRemoteDebugging;
}
}
```
In your case it's probably being called from *System.Web.Services.Protocols.RemoteDebugger.IsClientCallOutEnabled()*, which is being called by *System.Web.Services.Protocols.WebClientProtocol.NotifyClientCallOut* which is in turn being called by the Invoke method of *System.Web.Services.Protocols.SoapHttpClientProtocol*
Unfortunately, to my knowledge, short of decompiling the framework & seaching for
```
new BooleanSwitch
```
or any of the other inheritors of the *System.Diagnostics.Switch* class,
there's no easy way to know what switches are defined. It seems to be a case of searching msdn/google/stack overflow for the specific case
In this case I just used Reflector & searched for the Remote.Disable string |
33,341 | <p>Is there a way to hide radio buttons inside a RadioButtonList control programmatically?</p>
| [
{
"answer_id": 33353,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 0,
"selected": false,
"text": "<p>If you mean with JavaScript, and if I remember correctly, you've got to dig out the ClientID properties of each <inpu... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/877/"
] | Is there a way to hide radio buttons inside a RadioButtonList control programmatically? | Under the hood, you can access the attributes of the item and assign it a CSS style.
So you should be able to then programmatically assign it by specifying:
```
RadioButtonList.Items(1).CssClass.Add("visibility", "hidden")
```
and get the job done. |
33,395 | <p>I'm using the <a href="http://msdn.microsoft.com/en-us/library/ms178329.aspx" rel="nofollow noreferrer">ASP.NET Login Controls</a> and <a href="http://msdn.microsoft.com/en-us/library/aa480476.aspx" rel="nofollow noreferrer">Forms Authentication</a> for membership/credentials for an ASP.NET web application. And I'm using a <a href="http://msdn.microsoft.com/en-us/library/yy2ykkab.aspx" rel="nofollow noreferrer">site map</a> for site navigation.</p>
<p>I have ASP.NET TreeView and Menu navigation controls populated using a SiteMapDataSource. But off-limits administrator-only pages are visible to non-administrator users.</p>
<hr>
<blockquote>
<p><strong><a href="https://stackoverflow.com/users/1574/kevin-pang">Kevin Pang</a></strong> wrote:</p>
<p>I'm not sure how this question is any
different than your <a href="https://stackoverflow.com/questions/33263/how-do-i-best-handle-role-based-permissions-using-forms-authentication-on-my-as">other question</a>…</p>
</blockquote>
<p>The other question deals with assigning and maintaining permissions.</p>
<p>This question just deals with presentation of navigation. Specifically TreeView and Menu controls with sitemap data sources.</p>
<pre><code><asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" />
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" ShowStartingNode="False" />
</code></pre>
<hr>
<blockquote>
<p><strong><a href="https://stackoverflow.com/users/2808/nicholas">Nicholas</a></strong> wrote:</p>
<p>add role="SomeRole" in the sitemap</p>
</blockquote>
<p>Does that only handle the display issue? Or are such page permissions enforced?</p>
| [
{
"answer_id": 33402,
"author": "Vin",
"author_id": 1747,
"author_profile": "https://Stackoverflow.com/users/1747",
"pm_score": 0,
"selected": false,
"text": "<p>I think Jeff Atwood talked about this in the <a href=\"http://herdingcode.com/?p=36\" rel=\"nofollow noreferrer\">Herding Code... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | I'm using the [ASP.NET Login Controls](http://msdn.microsoft.com/en-us/library/ms178329.aspx) and [Forms Authentication](http://msdn.microsoft.com/en-us/library/aa480476.aspx) for membership/credentials for an ASP.NET web application. And I'm using a [site map](http://msdn.microsoft.com/en-us/library/yy2ykkab.aspx) for site navigation.
I have ASP.NET TreeView and Menu navigation controls populated using a SiteMapDataSource. But off-limits administrator-only pages are visible to non-administrator users.
---
>
> **[Kevin Pang](https://stackoverflow.com/users/1574/kevin-pang)** wrote:
>
>
> I'm not sure how this question is any
> different than your [other question](https://stackoverflow.com/questions/33263/how-do-i-best-handle-role-based-permissions-using-forms-authentication-on-my-as)…
>
>
>
The other question deals with assigning and maintaining permissions.
This question just deals with presentation of navigation. Specifically TreeView and Menu controls with sitemap data sources.
```
<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1" />
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" ShowStartingNode="False" />
```
---
>
> **[Nicholas](https://stackoverflow.com/users/2808/nicholas)** wrote:
>
>
> add role="SomeRole" in the sitemap
>
>
>
Does that only handle the display issue? Or are such page permissions enforced? | You pretty much need to keep the same data context available throughout the lifetime of the operations you want to perform if you're ever going to be storing changes which are to be `.SubmitChanges()`'d later, as otherwise you will lose those changes.
If you're just querying stuff then it's fine to create them as needed, but then if later you want to `.SubmitChanges()` you'll have to refactor your code a lot, so you may as well adopt the pattern of effectively keeping the `datacontext` global throughout your app from the beginning.
Note the data context is *disconnected*. The connection is only made when the query data is *enumerated* (not when you first run the query, it's a 'lazy' data type so only provides data when it's needed), and then closed immediately afterwards. On `.SubmitChanges()` the connection is opened to submit the changes then closed immediately afterwards. So don't think keeping the `datacontext` around keeps a connection open, it doesn't (you can hook the `StateChange` event of the connection to confirm this for yourself, that's how I'm sure).
There is a great article over at [Rick Strahl's Blog](http://www.west-wind.com/weblog/posts/246222.aspx) which covers this topic in depth, far more than my answer here provides!! |
33,409 | <p>I am using SQL Server 2005. I have a table with a text column and I have many rows in the table where the value of this column is not null, but it is empty. Trying to compare against '' yields this response:</p>
<blockquote>
<p>The data types text and varchar are incompatible in the not equal to operator.</p>
</blockquote>
<p>Is there a special function to determine whether the value of a text column is not null but empty?</p>
| [
{
"answer_id": 33415,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 0,
"selected": false,
"text": "<p>I would test against <a href=\"http://msdn.microsoft.com/en-us/library/ms187748.aspx\" rel=\"nofollow noreferrer\">SUBSTRIN... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1214/"
] | I am using SQL Server 2005. I have a table with a text column and I have many rows in the table where the value of this column is not null, but it is empty. Trying to compare against '' yields this response:
>
> The data types text and varchar are incompatible in the not equal to operator.
>
>
>
Is there a special function to determine whether the value of a text column is not null but empty? | ```
where datalength(mytextfield)=0
``` |
33,412 | <p>After reading Jeff's blog post on <a href="http://www.codinghorror.com/blog/archives/001167.html" rel="noreferrer">Protecting Your Cookies: HttpOnly</a>. I'd like to implement HttpOnly cookies in my web application.</p>
<p>How do you tell tomcat to use http only cookies for sessions?</p>
| [
{
"answer_id": 33456,
"author": "Shabaz",
"author_id": 1827,
"author_profile": "https://Stackoverflow.com/users/1827",
"pm_score": 3,
"selected": false,
"text": "<p>For session cookies it doesn't seem to be supported in Tomcat yet. See the bug report <a href=\"https://issues.apache.org/b... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
] | After reading Jeff's blog post on [Protecting Your Cookies: HttpOnly](http://www.codinghorror.com/blog/archives/001167.html). I'd like to implement HttpOnly cookies in my web application.
How do you tell tomcat to use http only cookies for sessions? | httpOnly is supported as of Tomcat 6.0.19 and Tomcat 5.5.28.
See the [changelog](http://tomcat.apache.org/tomcat-6.0-doc/changelog.html) entry for bug 44382.
The last comment for bug [44382](https://issues.apache.org/bugzilla/show_bug.cgi?id=44382) states, "this has been applied to 5.5.x and will be included in 5.5.28 onwards." However, it does not appear that 5.5.28 has been released.
The httpOnly functionality can be enabled for all webapps in **conf/context.xml**:
```
<Context useHttpOnly="true">
...
</Context>
```
My interpretation is that it also works for an individual context by setting it on the desired ***Context*** entry in **conf/server.xml** (in the same manner as above). |
33,449 | <p>Is there a way to call out from a TSQL stored procedure or function to a webservice?</p>
| [
{
"answer_id": 33455,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 3,
"selected": false,
"text": "<p>Not in T-SQL code itself, but with SQL Server 2005 and above, they've enabled the ability to write CLR stored procedures, whi... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1874/"
] | Is there a way to call out from a TSQL stored procedure or function to a webservice? | Yes , you can create like this
```
CREATE PROCEDURE CALLWEBSERVICE(@Para1 ,@Para2)
AS
BEGIN
Declare @Object as Int;
Declare @ResponseText as Varchar(8000);
Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'get', 'http://www.webservicex.com/stockquote.asmx/GetQuote?symbol=MSFT','false'
Exec sp_OAMethod @Object, 'send'
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT
Select @ResponseText
Exec sp_OADestroy @Object
END
``` |
33,459 | <p>Is it possible to use a flash document embedded in HTML as a link?</p>
<p>I tried just wrapping the <code>object</code> element with an <code>a</code> like this:</p>
<pre><code><a href="http://whatever.com">
<object ...>
<embed ... />
</object>
</a>
</code></pre>
<p>In Internet Explorer, that made it show the location in the status bar like a link, but it doesn't do anything.</p>
<p>I just have the .swf file, so I can't add a click handler in ActionScript.</p>
| [
{
"answer_id": 33519,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 2,
"selected": true,
"text": "<p>Though the object really should respond to being wrapped in an a href tag, you could open the swf in vim and just throw in a... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2214/"
] | Is it possible to use a flash document embedded in HTML as a link?
I tried just wrapping the `object` element with an `a` like this:
```
<a href="http://whatever.com">
<object ...>
<embed ... />
</object>
</a>
```
In Internet Explorer, that made it show the location in the status bar like a link, but it doesn't do anything.
I just have the .swf file, so I can't add a click handler in ActionScript. | Though the object really should respond to being wrapped in an a href tag, you could open the swf in vim and just throw in an `_root.onPress=function(){getURL("http://yes.no/");};` or if it's AS3, something like `_root.addEventHandler(MouseEvent.PRESS, function (e:event) {getURL("http://yes.no/");});` But if editing the swf is your route, you'd likely have more success with [a tool for the purpose](http://www.buraks.com/uae/1.html). |
33,465 | <p>Working on a little side project web app...</p>
<p>I'd like to have it set up so that, when users send email to a certain account, I can kick off a PHP script that reads the email, pulls out some key info, and writes it to a database.</p>
<p>What's the best way to do this? A cron job that checks for new email?</p>
<p>The app is running on a "Dedicated-Virtual" Server at MediaTemple, so I guess I have a reasonable level of control, which should give me a range of options.</p>
<p>I'm very slowly learning the ropes (PHP, MySQL, configuring/managing the server), so your advice and insight are much appreciated.</p>
<p>Cheers,
Matt Stuehler</p>
| [
{
"answer_id": 33472,
"author": "crono",
"author_id": 1462,
"author_profile": "https://Stackoverflow.com/users/1462",
"pm_score": 0,
"selected": false,
"text": "<p>The Cronjob is the common solution to such a task. <a href=\"http://php.net/manual/en/function.imap-getmailboxes.php\" rel=\... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Working on a little side project web app...
I'd like to have it set up so that, when users send email to a certain account, I can kick off a PHP script that reads the email, pulls out some key info, and writes it to a database.
What's the best way to do this? A cron job that checks for new email?
The app is running on a "Dedicated-Virtual" Server at MediaTemple, so I guess I have a reasonable level of control, which should give me a range of options.
I'm very slowly learning the ropes (PHP, MySQL, configuring/managing the server), so your advice and insight are much appreciated.
Cheers,
Matt Stuehler | Procmail is how I do it. Here's an example where I actually process the text inside the email to archive it back to a MySQL database.
```
:0:
* ^(From).*test@example.com
{
:0 c
| php /var/www/app/process_email.php
}
``` |
33,469 | <p>So I just fixed a bug in a framework I'm developing. The pseudo-pseudocode looks like this:</p>
<pre><code>myoldObject = new MyObject { someValue = "old value" };
cache.Insert("myObjectKey", myoldObject);
myNewObject = cache.Get("myObjectKey");
myNewObject.someValue = "new value";
if(myObject.someValue != cache.Get("myObjectKey").someValue)
myObject.SaveToDatabase();
</code></pre>
<p>So, essentially, I was getting an object from the cache, and then later on comparing the original object to the cached object to see if I need to save it to the database in case it's changed. The problem arose because the original object is a reference...so changing someValue also changed the referenced cached object, so it'd never save back to the database. I fixed it by cloning the object off of the cached version, severing the reference and allowing me to compare the new object against the cached one.</p>
<p>My question is: <strong>is there a better way to do this, some pattern, that you could recommend?</strong> I can't be the only person that's done this before :)</p>
| [
{
"answer_id": 33507,
"author": "Craig Walker",
"author_id": 3488,
"author_profile": "https://Stackoverflow.com/users/3488",
"pm_score": 1,
"selected": false,
"text": "<p>I've done similar things, but I got around it by cloning too. The difference is that I had the cache do the cloning. ... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212/"
] | So I just fixed a bug in a framework I'm developing. The pseudo-pseudocode looks like this:
```
myoldObject = new MyObject { someValue = "old value" };
cache.Insert("myObjectKey", myoldObject);
myNewObject = cache.Get("myObjectKey");
myNewObject.someValue = "new value";
if(myObject.someValue != cache.Get("myObjectKey").someValue)
myObject.SaveToDatabase();
```
So, essentially, I was getting an object from the cache, and then later on comparing the original object to the cached object to see if I need to save it to the database in case it's changed. The problem arose because the original object is a reference...so changing someValue also changed the referenced cached object, so it'd never save back to the database. I fixed it by cloning the object off of the cached version, severing the reference and allowing me to compare the new object against the cached one.
My question is: **is there a better way to do this, some pattern, that you could recommend?** I can't be the only person that's done this before :) | Dirty tracking is the normal way to handle this, I think. Something like:
```
class MyObject {
public string SomeValue {
get { return _someValue; }
set {
if (value != SomeValue) {
IsDirty = true;
_someValue = value;
}
}
public bool IsDirty {
get;
private set;
}
void SaveToDatabase() {
base.SaveToDatabase();
IsDirty = false;
}
}
myoldObject = new MyObject { someValue = "old value" };
cache.Insert("myObjectKey", myoldObject);
myNewObject = cache.Get("myObjectKey");
myNewObject.someValue = "new value";
if(myNewObject.IsDirty)
myNewObject.SaveToDatabase();
``` |
33,471 | <p>Is there a way to tell subversion "update/merge unless it would cause a conflict"?</p>
<p>I know you can use <code>--dry-run</code> / <code>status -u</code> to check before running the update, but I often have others running updates and getting broken webpages because they don't notice the "C index.php" line.</p>
<p>I've also noticed that svn doesn't seem too unhappy about conflicts - it still says "updated to revision blah" and exits zero, regardless of conflicts. So I have to parse the line-by-line output to discover them. Surely there's a better way?</p>
| [
{
"answer_id": 33483,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps a better way is to use a graphical tool? Or write a script to do the update that redirects the output to a file an... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1806/"
] | Is there a way to tell subversion "update/merge unless it would cause a conflict"?
I know you can use `--dry-run` / `status -u` to check before running the update, but I often have others running updates and getting broken webpages because they don't notice the "C index.php" line.
I've also noticed that svn doesn't seem too unhappy about conflicts - it still says "updated to revision blah" and exits zero, regardless of conflicts. So I have to parse the line-by-line output to discover them. Surely there's a better way? | You can use the --accept parameter to indicate what should happen when a conflict occurs:
```
--accept ARG : specify automatic conflict resolution action
('postpone', 'base', 'mine-full', 'theirs-full',
'edit', 'launch')
```
See also the [interactive conflict resolution](http://svnbook.red-bean.com/en/1.5/svn.tour.cycle.html#svn.tour.cycle.resolve.diff) page in the svnbook |
33,475 | <p>I need to launch a server on the remote machine and retrieve the port number that the server process is lsitening on. When invoked, the server will listen on a random port and output the port number on stderr.</p>
<p>I want to automate the process of logging on to the remote machine, launching the process, and retrieving the port number. I wrote a Python script called "<code>invokejob.py</code>" that lives on the remote machine to act as a wrapper that invokes the job and then returns the port number, it looks like this:</p>
<pre><code>import re, subprocess
executable = ... # Name of executable
regex = ... # Regex to extract the port number from the output
p = subprocess.Popen(executable,
bufsize=1, # line buffered
stderr=subprocess.PIPE
)
s = p.stderr.readline()
port = re.match(regex).groups()[0]
print port
</code></pre>
<p>If I log in interactively, this script works:</p>
<pre><code>$ ssh remotehost.example.com
Last login: Thu Aug 28 17:31:18 2008 from localhost
$ ./invokejob.py
63409
$ exit
logout
Connection to remotehost.example.com closed.
</code></pre>
<p>(Note: successful logout, it did not hang).</p>
<p>However, if I try to invoke it from the command-line, it just hangs:</p>
<pre><code>$ ssh remotehost.example.com invokejob.py
</code></pre>
<p>Does anybody know why it hangs in the second case, and what I can do to avoid this? </p>
<p>Note that I need to retrieve the output of the program, so I can't just use the ssh "-f" flag or redirect standard output.</p>
| [
{
"answer_id": 33486,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n<pre><code>s = p.stderr.readline()\n</code></pre>\n</blockquote>\n\n<p>I suspect it's the above line. When ... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] | I need to launch a server on the remote machine and retrieve the port number that the server process is lsitening on. When invoked, the server will listen on a random port and output the port number on stderr.
I want to automate the process of logging on to the remote machine, launching the process, and retrieving the port number. I wrote a Python script called "`invokejob.py`" that lives on the remote machine to act as a wrapper that invokes the job and then returns the port number, it looks like this:
```
import re, subprocess
executable = ... # Name of executable
regex = ... # Regex to extract the port number from the output
p = subprocess.Popen(executable,
bufsize=1, # line buffered
stderr=subprocess.PIPE
)
s = p.stderr.readline()
port = re.match(regex).groups()[0]
print port
```
If I log in interactively, this script works:
```
$ ssh remotehost.example.com
Last login: Thu Aug 28 17:31:18 2008 from localhost
$ ./invokejob.py
63409
$ exit
logout
Connection to remotehost.example.com closed.
```
(Note: successful logout, it did not hang).
However, if I try to invoke it from the command-line, it just hangs:
```
$ ssh remotehost.example.com invokejob.py
```
Does anybody know why it hangs in the second case, and what I can do to avoid this?
Note that I need to retrieve the output of the program, so I can't just use the ssh "-f" flag or redirect standard output. | >
>
> ```
> s = p.stderr.readline()
>
> ```
>
>
I suspect it's the above line. When you invoke a command directly through ssh, you don't get your full pty (assuming Linux), and thus no stderr to read from.
When you log in interactively, stdin, stdout, and stderr are set up for you, and so your script works. |
33,529 | <p>Inspired by this CodingHorror article, "<a href="http://www.codinghorror.com/blog/archives/001167.html" rel="noreferrer">Protecting Your Cookies: HttpOnly</a>"</p>
<p>How do you set this property? Somewhere in the web config?</p>
| [
{
"answer_id": 33532,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 4,
"selected": false,
"text": "<p>With props to Rick (second comment down in the blog post mentioned), here's the <a href=\"http://msdn.microsoft.com/en-us/lib... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1842/"
] | Inspired by this CodingHorror article, "[Protecting Your Cookies: HttpOnly](http://www.codinghorror.com/blog/archives/001167.html)"
How do you set this property? Somewhere in the web config? | If you're using ASP.NET 2.0 or greater, you can turn it on in the Web.config file. In the <system.web> section, add the following line:
```
<httpCookies httpOnlyCookies="true"/>
``` |
33,534 | <p>I'm trying to extend some "base" classes in Python:</p>
<pre><code>class xlist (list):
def len(self):
return len(self)
def add(self, *args):
self.extend(args)
return None
class xint (int):
def add(self, value):
self += value
return self
x = xlist([1,2,3])
print x.len() ## >>> 3 ok
print x ## >>> [1,2,3] ok
x.add (4, 5, 6)
print x ## >>> [1,2,3,4,5,6] ok
x = xint(10)
print x ## >>> 10 ok
x.add (2)
print x ## >>> 10 # Not ok (#1)
print type(x) ## >>> <class '__main__.xint'> ok
x += 5
print type(x) ## >>> <type 'int'> # Not ok (#2)
</code></pre>
<p>It works fine in the <em>list</em> case because the <em>append</em> method modifies the object "in place", without returning it. But in the <em>int</em> case, the <em>add</em> method doesn't modify the value of the external <em>x</em> variable. I suppose that's fine in the sense that <em>self</em> is a local variable in the <em>add</em> method of the class, but this is preventing me from modifying the initial value assigned to the instance of the class.</p>
<p>Is it possible to extend a class this way or should I define a class property with the base type and map all the needed methods to this property?</p>
| [
{
"answer_id": 33556,
"author": "dwestbrook",
"author_id": 3119,
"author_profile": "https://Stackoverflow.com/users/3119",
"pm_score": 0,
"selected": false,
"text": "<p>Ints are immutable and you can't modify them in place, so you should go with option #2 (because option #1 is impossible... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/394/"
] | I'm trying to extend some "base" classes in Python:
```
class xlist (list):
def len(self):
return len(self)
def add(self, *args):
self.extend(args)
return None
class xint (int):
def add(self, value):
self += value
return self
x = xlist([1,2,3])
print x.len() ## >>> 3 ok
print x ## >>> [1,2,3] ok
x.add (4, 5, 6)
print x ## >>> [1,2,3,4,5,6] ok
x = xint(10)
print x ## >>> 10 ok
x.add (2)
print x ## >>> 10 # Not ok (#1)
print type(x) ## >>> <class '__main__.xint'> ok
x += 5
print type(x) ## >>> <type 'int'> # Not ok (#2)
```
It works fine in the *list* case because the *append* method modifies the object "in place", without returning it. But in the *int* case, the *add* method doesn't modify the value of the external *x* variable. I suppose that's fine in the sense that *self* is a local variable in the *add* method of the class, but this is preventing me from modifying the initial value assigned to the instance of the class.
Is it possible to extend a class this way or should I define a class property with the base type and map all the needed methods to this property? | `int` is a value type, so each time you do an assignment, (e.g. both instances of `+=` above), it doesn't modify the object you have on the heap, but replaces the reference with one of the result of the right hand side of the assignment (i.e. an `int`)
`list` isn't a value type, so it isn't bound by the same rules.
this page has more details on the differences: [The Python Language Reference - 3. Data model](https://docs.python.org/3/reference/datamodel.html)
IMO, yes, you should define a new class that keeps an int as an instance variable |
33,577 | <p>I want to check out all files in all subdirectories of a specified folder.</p>
<p>(And it is painful to do this using the GUI, because there is no recursive checkout option).</p>
| [
{
"answer_id": 33605,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "<pre><code>cleartool find somedir -exec \"cleartool checkout -nc \\\"%CLEARCASE_PN%\\\"\"\n</code></pre>\n\n<p>Also an article \"... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
] | I want to check out all files in all subdirectories of a specified folder.
(And it is painful to do this using the GUI, because there is no recursive checkout option). | Beware: ClearCase is File-centric, not repository centric (like SVN or CVS).
That means it is rarely a good solution to checkout all files (and it can be fairly long with ClearCase ;) )
That being said, the question is perfectly legitimate and I would like to point out another way:
open a `cleartool` session in the 'specified folder':
```
c:\MyFolder> cleartool
cleartool> co -c "Reason for massive checkout" .../*
```
does the trick too. But as the aku's answer, it does checkout *everything*: files and directories... and you may most *not need* to checkout directories!
```
cleartool find somedir -type f -exec "cleartool checkout -c \"Reason for massive checkout\" \"%CLEARCASE_PN%\""
```
would only checkout files...
Now the problem is to checkin everything that has changed. It is problematic since often *not everything* has changed, and CleaCase will trigger an error message when trying to check in an identical file. Meaning you will need 2 commands:
```
ct lsco -r -cvi -fmt "ci -nc \"%n\"\n" | ct
ct lsco -r -cvi -fmt "unco -rm %n\n" | ct
```
(with '`ct` being '`cleartool`' : type '`doskey ct=cleartool $*`' on Windows to set that alias)
Note that `ct ci -nc` will check-in with the comment used for the checkout stage.
So it is *not* a checkin without a comment (like the `-nc` option -- or "no comment" -- could make believe). |
33,590 | <p>Has anyone looked at <a href="http://developer.yahoo.com/flash/" rel="nofollow noreferrer">Yahoo's ASTRA</a>? It's fairly nifty, but I had some issues creating a custom label for a pie chart. They have an example for a line chart, which overrides an axis's series's label renderer. My solution was to override the <code>myPieChart.dataTipFunction</code>. For data that looks like:</p>
<pre><code>myPieChart.dataProvider =
[ { category: "Groceries", cost: 50 },
{ category: "Transportation", cost: 175} ]
myPieChart.dataField = "cost";
myPieChart.categoryField = "category";
</code></pre>
<p>I wrote a function like this:</p>
<pre><code>import com.yahoo.astra.fl.charts.series.*
myPieChart.dataTipFunction =
function (obj:Object, index:int, series:ISeries):String {
return obj.category + "\n$" + obj.cost;
};
</code></pre>
<p>There's ceil(2.718281828459045) problems with this:</p>
<ol>
<li><p>I'm directly calling the category and cost properties of the data provider. The names are actually configurable when setting up the chart, I'd like to maintain that flexibility.</p>
</li>
<li><p>The default data tip would show the category, the cost (without a dollar sign), and the percentage it makes up in the pie chart. So here, I've lost the percentage. I just have no idea which property of what would hold that. It might be part of the series.</p>
</li>
<li><p>I probably only need to override the <code>dataItemRenderer</code> for the cost part of the series, but I don't know how to access it. The documentation is a little ... lacking there.</p>
</li>
</ol>
<p>Normally I would just look at the default implementation of the <code>dataTipFunction</code> but it's all inside a compiled shm that's part of the components distributed from yahoo.</p>
<p>Can anyone help me complete this overridden function with percentage information and the flexibility mentioned in point 1?</p>
| [
{
"answer_id": 35019,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 3,
"selected": true,
"text": "<p>Okay... so no-one's tried Astra, or people just avoid Flash questions.</p>\n\n<p>After a lot of guess work it turns out I ne... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459/"
] | Has anyone looked at [Yahoo's ASTRA](http://developer.yahoo.com/flash/)? It's fairly nifty, but I had some issues creating a custom label for a pie chart. They have an example for a line chart, which overrides an axis's series's label renderer. My solution was to override the `myPieChart.dataTipFunction`. For data that looks like:
```
myPieChart.dataProvider =
[ { category: "Groceries", cost: 50 },
{ category: "Transportation", cost: 175} ]
myPieChart.dataField = "cost";
myPieChart.categoryField = "category";
```
I wrote a function like this:
```
import com.yahoo.astra.fl.charts.series.*
myPieChart.dataTipFunction =
function (obj:Object, index:int, series:ISeries):String {
return obj.category + "\n$" + obj.cost;
};
```
There's ceil(2.718281828459045) problems with this:
1. I'm directly calling the category and cost properties of the data provider. The names are actually configurable when setting up the chart, I'd like to maintain that flexibility.
2. The default data tip would show the category, the cost (without a dollar sign), and the percentage it makes up in the pie chart. So here, I've lost the percentage. I just have no idea which property of what would hold that. It might be part of the series.
3. I probably only need to override the `dataItemRenderer` for the cost part of the series, but I don't know how to access it. The documentation is a little ... lacking there.
Normally I would just look at the default implementation of the `dataTipFunction` but it's all inside a compiled shm that's part of the components distributed from yahoo.
Can anyone help me complete this overridden function with percentage information and the flexibility mentioned in point 1? | Okay... so no-one's tried Astra, or people just avoid Flash questions.
After a lot of guess work it turns out I needed to cast the series to a PieSeries and then work with those member functions, as the ISeries was useless on it's own.
```
myPieChart.dataTipFunction =
function (item:Object, index:int, series:ISeries):String {
var oPieSeries:PieSeries = series as PieSeries;
return oPieSeries.itemToCategory(item,index) + "\n$" +
oPieSeries.itemToData(item) + "\n" +
Number(oPieSeries.itemToPercentage(item)).toFixed(2) + "%";
};
``` |
33,594 | <p>I need to <code>ShellExecute</code> something as another user, currently I start a helper process with <code>CreateProcessAsUser</code> that calls <code>ShellExecute</code>, but that seems like too much of a hack (Wrong parent process etc.) Is there a better way to do this?</p>
<p>@PabloG: ImpersonateLoggedOnUser does not work:</p>
<pre>
HANDLE hTok;
VERIFY(LogonUser("otheruser",0,"password",LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT,&hTok));
VERIFY(ImpersonateLoggedOnUser(hTok));
ShellExecute(0,0,"calc.exe",0,0,SW_SHOW);
RevertToSelf();
CloseHandle(hTok);
</pre>
<p>will just start calc as the logged in user, not "otheruser"</p>
<p>@1800 INFORMATION: <code>CreateProcess</code>/<code>CreateProcessAsUser</code> is not the same as <code>ShellExecute</code>, with UAC on Vista, <code>CreateProcess</code> is useless when you don't have control over what program the user is executing (<code>CreateProcess</code> will return with a error if you give it a exe file with a manifest marked as requireAdmin)</p>
<p>@Brian R. Bondy: I already know this info (And don't get me wrong, its good stuff), but it is off topic (IMHO) I am asking for a <code>ShellExecuteAsUser</code>, not about starting processes as another user, I already know how to do that.</p>
| [
{
"answer_id": 33661,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 0,
"selected": false,
"text": "<p>You can wrap the ShellExecute between ImpersonateLoggedOnUser / RevertToSelf</p>\n\n<p>links: \nImpersonateLoggedOnUser: <a h... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3501/"
] | I need to `ShellExecute` something as another user, currently I start a helper process with `CreateProcessAsUser` that calls `ShellExecute`, but that seems like too much of a hack (Wrong parent process etc.) Is there a better way to do this?
@PabloG: ImpersonateLoggedOnUser does not work:
```
HANDLE hTok;
VERIFY(LogonUser("otheruser",0,"password",LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT,&hTok));
VERIFY(ImpersonateLoggedOnUser(hTok));
ShellExecute(0,0,"calc.exe",0,0,SW_SHOW);
RevertToSelf();
CloseHandle(hTok);
```
will just start calc as the logged in user, not "otheruser"
@1800 INFORMATION: `CreateProcess`/`CreateProcessAsUser` is not the same as `ShellExecute`, with UAC on Vista, `CreateProcess` is useless when you don't have control over what program the user is executing (`CreateProcess` will return with a error if you give it a exe file with a manifest marked as requireAdmin)
@Brian R. Bondy: I already know this info (And don't get me wrong, its good stuff), but it is off topic (IMHO) I am asking for a `ShellExecuteAsUser`, not about starting processes as another user, I already know how to do that. | The solution really depends on what your needs are, and can be pretty complex (Thanks fully to Windows Vista). This is probably going to be beyond your need, but this will help others that find this page via search.
1. If you do not need the process to run with a GUI and you do not require elevation
2. If the user you want to run as is already logged into a session
3. If you need to run the process with a GUI, and the user may, or may not be logged in
4. If you need to run the process with elevation
**Regarding 1:**
In windows Vista there exists something called session 0 isolation. All services run as session 0 and you are not supposed to have a GUI in session 0. The first logged on user is logged into session 1. In previous versions of windows (pre Vista), the first logged on user was also ran fully in session 0.
You can run several different processes with different usernames in the same session. You can find a good document about session 0 isolation [here](http://www.microsoft.com/whdc/system/vista/services.mspx).
Since we're dealing with option 1), you don't need a GUI. Therefore you can start your process in session 0.
You'll want a call sequence something like this:
LogonUser, ExpandEnvironmentStringsForUser, GetLogonSID, LoadUserProfile, CreateEnvironmentBlock, CreateProcessAsUser.
Example code for this can be found via any search engine, or via [Google code search](http://www.google.com/codesearch)
**Regarding 2:** If the user you'd like to run the process as is already logged in, you can simply use: WTSEnumerateSessions, and WTSQuerySessionInformation to get the session ID, and then WTSQueryUserToken to get the user token. From there you can just use the user token in the CreateProcessAsUser Win32 API.
This is a great method because you don't even need to login as the user nor know the user's username/password. I believe this is only possible via a service though running as local system account.
You can get the current session via WTSGetActiveConsoleSessionId.
**Regarding 3:**
You would follow the same steps as #1, but in addition you would use the STARTUPINFO's lpDesktop field. Set this to winsta0\Default. You will also need to try to use the OpenDesktop Win32 API and if this fails you can CreateDesktop. Before using the station and desktop handles you should use SetSecurityInfo on each of them with SE\_WINDOW\_OBJECT, and GROUP\_SECURITY\_INFORMATION | DACL\_SECURITY\_INFORMATION.
If the user in question later tries to login, he will actually see the running process.
**Regarding 4:**
This can be done as well, but it requires you to already be running an elevated process. A service running as local system account does run as elevated. I could also only get it to work by having an authenticode signed process that I wanted to start. The process you want to start also must have a manifest file associated with it with the requestedExecutionLevel level="requireAdministrator"
Other notes:
* You can set a token's session via SetTokenInformation and TokenSessionId
* You cannot change the session ID of an already running process.
* This whole process would be drastically more simple if Vista was not in the equation. |
33,685 | <p>This is a sql 2000 database that I am working with.</p>
<p>I have what I call a staging table that is a raw data dump of data, so everything is ntext or nvarchar(255). </p>
<p>I need to cast/convert all of this data into the appropriate data types (ie int, decimal, nvarchar, etc.)</p>
<p>The way I was going to do this was to iterate through all records using a while loop and attempt a CAST on each column on a single record during each iteration, after I visit a particular record I flag it as processed (bit field).</p>
<p>But how can I log the error when/if it occurs but allow the while loop to continue.</p>
<p>At first I implemented this using a TRY CATCH in a local SQL 2005 instance (to get the project going) and all was working well, but i learned today that the dev & production database that the international DBA's have set up is a SQL 2000 instance so I have to conform.</p>
<p><strong>EDIT</strong>: I am using a SSIS package to populate the staging table. I see that now I must revisit that package and implement a script component to handle the conversions. Thanks guys</p>
<p><strong>EDIT</strong>: I <em>am</em> doing this on a record by record basis, not a batch insert, so the transaction idea seems like it would be feasible but I'm not sure how to trap @@ERROR and allow the stored procedure to continue.</p>
<p><strong>EDIT</strong>: I really like <a href="https://stackoverflow.com/questions/33685/sql-2000-try-catch-like-error-handling#39161">Guy's approach</a>, I am going to implement it this way.</p>
| [
{
"answer_id": 33717,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 2,
"selected": false,
"text": "<p>What are you using to import the file? DTS has scripting abilities that can be used for data validation. If your not... | 2008/08/28 | [
"https://Stackoverflow.com/questions/33685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1950/"
] | This is a sql 2000 database that I am working with.
I have what I call a staging table that is a raw data dump of data, so everything is ntext or nvarchar(255).
I need to cast/convert all of this data into the appropriate data types (ie int, decimal, nvarchar, etc.)
The way I was going to do this was to iterate through all records using a while loop and attempt a CAST on each column on a single record during each iteration, after I visit a particular record I flag it as processed (bit field).
But how can I log the error when/if it occurs but allow the while loop to continue.
At first I implemented this using a TRY CATCH in a local SQL 2005 instance (to get the project going) and all was working well, but i learned today that the dev & production database that the international DBA's have set up is a SQL 2000 instance so I have to conform.
**EDIT**: I am using a SSIS package to populate the staging table. I see that now I must revisit that package and implement a script component to handle the conversions. Thanks guys
**EDIT**: I *am* doing this on a record by record basis, not a batch insert, so the transaction idea seems like it would be feasible but I'm not sure how to trap @@ERROR and allow the stored procedure to continue.
**EDIT**: I really like [Guy's approach](https://stackoverflow.com/questions/33685/sql-2000-try-catch-like-error-handling#39161), I am going to implement it this way. | Generally I don't like "loop through the record" solutions as they tend to be slow and you end up writing a lot of custom code.
So...
Depending on how many records are in your staging table, you could post process the data with a series of SQL statements that test the columns for correctness and mark any records that fail the test.
i.e.
```
UPDATE staging_table
SET status_code = 'FAIL_TEST_1'
WHERE status_code IS NULL
AND ISDATE(ntext_column1) = 0;
UPDATE staging_table
SET status_code = 'FAIL_TEST_2'
WHERE status_code IS NULL
AND ISNUMERIC(ntext_column2) = 0;
etc...
```
Finally
```
INSERT INTO results_table ( mydate, myprice )
SELECT ntext_column1 AS mydate, ntext_column2 AS myprice
FROM staging_table
WHERE status_code IS NULL;
DELETE FROM staging_table
WHERE status_code IS NULL;
```
And the staging table has all the errors, that you can export and report out. |
33,708 | <p>So I've got a <code>JPanel</code> implementing <code>MouseListener</code> and <code>MouseMotionListener</code>:</p>
<pre><code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DisplayArea extends JPanel implements MouseListener, MouseMotionListener {
public DisplayArea(Rectangle bounds, Display display) {
setLayout(null);
setBounds(bounds);
setOpaque(false);
setPreferredSize(new Dimension(bounds.width, bounds.height));
this.display = display;
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
if (display.getControlPanel().Antialiasing()) {
g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
}
g2.setColor(Color.white);
g2.fillRect(0, 0, getWidth(), getHeight());
}
public void mousePressed(MouseEvent event) {
System.out.println("mousePressed()");
mx1 = event.getX();
my1 = event.getY();
}
public void mouseReleased(MouseEvent event) {
System.out.println("mouseReleased()");
mx2 = event.getX();
my2 = event.getY();
int mode = display.getControlPanel().Mode();
switch (mode) {
case ControlPanel.LINE:
System.out.println("Line from " + mx1 + ", " + my1 + " to " + mx2 + ", " + my2 + ".");
}
}
public void mouseEntered(MouseEvent event) {
System.out.println("mouseEntered()");
}
public void mouseExited(MouseEvent event) {
System.out.println("mouseExited()");
}
public void mouseClicked(MouseEvent event) {
System.out.println("mouseClicked()");
}
public void mouseMoved(MouseEvent event) {
System.out.println("mouseMoved()");
}
public void mouseDragged(MouseEvent event) {
System.out.println("mouseDragged()");
}
private Display display = null;
private int mx1 = -1;
private int my1 = -1;
private int mx2 = -1;
private int my2 = -1;
}
</code></pre>
<p>The trouble is, none of these mouse functions are ever called. <code>DisplayArea</code> is created like this:</p>
<pre><code>da = new DisplayArea(new Rectangle(CONTROL_WIDTH, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT), this);
</code></pre>
<p>I am not really a Java programmer (this is part of an assignment), but I can't see anything glaringly obvious. Can someone smarter than I see anything?</p>
| [
{
"answer_id": 33715,
"author": "Shabaz",
"author_id": 1827,
"author_profile": "https://Stackoverflow.com/users/1827",
"pm_score": 5,
"selected": true,
"text": "<p>The <em>implements mouselistener, mousemotionlistener</em> just allows the displayArea class to listen to some, to be define... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | So I've got a `JPanel` implementing `MouseListener` and `MouseMotionListener`:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DisplayArea extends JPanel implements MouseListener, MouseMotionListener {
public DisplayArea(Rectangle bounds, Display display) {
setLayout(null);
setBounds(bounds);
setOpaque(false);
setPreferredSize(new Dimension(bounds.width, bounds.height));
this.display = display;
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
if (display.getControlPanel().Antialiasing()) {
g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
}
g2.setColor(Color.white);
g2.fillRect(0, 0, getWidth(), getHeight());
}
public void mousePressed(MouseEvent event) {
System.out.println("mousePressed()");
mx1 = event.getX();
my1 = event.getY();
}
public void mouseReleased(MouseEvent event) {
System.out.println("mouseReleased()");
mx2 = event.getX();
my2 = event.getY();
int mode = display.getControlPanel().Mode();
switch (mode) {
case ControlPanel.LINE:
System.out.println("Line from " + mx1 + ", " + my1 + " to " + mx2 + ", " + my2 + ".");
}
}
public void mouseEntered(MouseEvent event) {
System.out.println("mouseEntered()");
}
public void mouseExited(MouseEvent event) {
System.out.println("mouseExited()");
}
public void mouseClicked(MouseEvent event) {
System.out.println("mouseClicked()");
}
public void mouseMoved(MouseEvent event) {
System.out.println("mouseMoved()");
}
public void mouseDragged(MouseEvent event) {
System.out.println("mouseDragged()");
}
private Display display = null;
private int mx1 = -1;
private int my1 = -1;
private int mx2 = -1;
private int my2 = -1;
}
```
The trouble is, none of these mouse functions are ever called. `DisplayArea` is created like this:
```
da = new DisplayArea(new Rectangle(CONTROL_WIDTH, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT), this);
```
I am not really a Java programmer (this is part of an assignment), but I can't see anything glaringly obvious. Can someone smarter than I see anything? | The *implements mouselistener, mousemotionlistener* just allows the displayArea class to listen to some, to be defined, Swing component's mouse events. You have to explicitly define what it should be listening at. So I suppose you could add something like this to the constructor:
```
this.addMouseListener(this);
this.addMouseMotionListener(this);
``` |
33,746 | <p>At work we are being asked to create XML files to pass data to another offline application that will then create a second XML file to pass back in order to update some of our data. During the process we have been discussing with the team of the other application about the structure of the XML file. </p>
<p>The sample I came up with is essentially something like:</p>
<pre><code><INVENTORY>
<ITEM serialNumber="something" location="something" barcode="something">
<TYPE modelNumber="something" vendor="something"/>
</ITEM>
</INVENTORY>
</code></pre>
<p>The other team said that this was not industry standard and that attributes should only be used for meta data. They suggested:</p>
<pre><code><INVENTORY>
<ITEM>
<SERIALNUMBER>something</SERIALNUMBER>
<LOCATION>something</LOCATION>
<BARCODE>something</BARCODE>
<TYPE>
<MODELNUMBER>something</MODELNUMBER>
<VENDOR>something</VENDOR>
</TYPE>
</ITEM>
</INVENTORY>
</code></pre>
<p>The reason I suggested the first is that the size of the file created is much smaller. There will be roughly 80000 items that will be in the file during transfer. Their suggestion in reality turns out to be three times larger than the one I suggested. I searched for the mysterious "Industry Standard" that was mentioned, but the closest I could find was that XML attributes should only be used for meta data, but said the debate was about what was actually meta data.</p>
<p>After the long winded explanation (sorry) how do you determine what is meta data, and when designing the structure of an XML document how should you decide when to use an attribute or an element?</p>
| [
{
"answer_id": 33749,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "<p>Both methods for storing object's properties are perfectly valid. You should depart from pragmatic considerations. Try answeri... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3340/"
] | At work we are being asked to create XML files to pass data to another offline application that will then create a second XML file to pass back in order to update some of our data. During the process we have been discussing with the team of the other application about the structure of the XML file.
The sample I came up with is essentially something like:
```
<INVENTORY>
<ITEM serialNumber="something" location="something" barcode="something">
<TYPE modelNumber="something" vendor="something"/>
</ITEM>
</INVENTORY>
```
The other team said that this was not industry standard and that attributes should only be used for meta data. They suggested:
```
<INVENTORY>
<ITEM>
<SERIALNUMBER>something</SERIALNUMBER>
<LOCATION>something</LOCATION>
<BARCODE>something</BARCODE>
<TYPE>
<MODELNUMBER>something</MODELNUMBER>
<VENDOR>something</VENDOR>
</TYPE>
</ITEM>
</INVENTORY>
```
The reason I suggested the first is that the size of the file created is much smaller. There will be roughly 80000 items that will be in the file during transfer. Their suggestion in reality turns out to be three times larger than the one I suggested. I searched for the mysterious "Industry Standard" that was mentioned, but the closest I could find was that XML attributes should only be used for meta data, but said the debate was about what was actually meta data.
After the long winded explanation (sorry) how do you determine what is meta data, and when designing the structure of an XML document how should you decide when to use an attribute or an element? | I use this rule of thumb:
1. An Attribute is something that is self-contained, i.e., a color, an ID, a name.
2. An Element is something that does or could have attributes of its own or contain other elements.
So yours is close. I would have done something like:
**EDIT**: Updated the original example based on feedback below.
```
<ITEM serialNumber="something">
<BARCODE encoding="Code39">something</BARCODE>
<LOCATION>XYX</LOCATION>
<TYPE modelNumber="something">
<VENDOR>YYZ</VENDOR>
</TYPE>
</ITEM>
``` |
33,751 | <p>I would like to add the following MIME type to a site run by <code>Apache</code>:</p>
<pre><code><mime-mapping>
<extension>jnlp</extension>
<mime-type>application/x-java-jnlp-file</mime-type>
</mime-mapping>
</code></pre>
<p><strong>That is the Tomcat format.</strong></p>
<p>I'm on a shared host, so I can only create an <code>.htaccess</code> file. Would someone please specify the complete contents of such a file?</p>
| [
{
"answer_id": 33762,
"author": "Ryan Guest",
"author_id": 1811,
"author_profile": "https://Stackoverflow.com/users/1811",
"pm_score": 2,
"selected": false,
"text": "<p>You should be able to just add this line:</p>\n\n<pre><code>AddType application/x-java-jnlp-file .jnlp\n</code></pr... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] | I would like to add the following MIME type to a site run by `Apache`:
```
<mime-mapping>
<extension>jnlp</extension>
<mime-type>application/x-java-jnlp-file</mime-type>
</mime-mapping>
```
**That is the Tomcat format.**
I'm on a shared host, so I can only create an `.htaccess` file. Would someone please specify the complete contents of such a file? | ```
AddType application/x-java-jnlp-file .jnlp
```
Note that you might not actually be allowed to do that.
See also the [documentation of the AddType directive](http://HTTPd.Apache.Org/docs/trunk/mod/mod_mime.html#addtype "mod_mime - AddType") and the [.htaccess howto](http://HTTPd.Apache.Org/docs/trunk/howto/htaccess.html ".htaccess howto"). |
33,779 | <p>Does anyone know of a powershell cmdlet out there for automating task scheduler in XP/2003? If you've ever tried to work w/ schtasks you know it's pretty painful.</p>
| [
{
"answer_id": 33805,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 1,
"selected": false,
"text": "<p>You don't need PowerShell to automate the Task Scheduler, you can use the SCHTASKS command in XP.</p>\n\n<p>According to <a h... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1635/"
] | Does anyone know of a powershell cmdlet out there for automating task scheduler in XP/2003? If you've ever tried to work w/ schtasks you know it's pretty painful. | Ok, Pablo has sparked my interest in saying that the scheduler is accessible via COM.
In PowerShell you can do this:
```
$svc = new-object -com Schedule.Service
```
... and that gives you a handle to the task scheduler. You can see what members it has using:
```
$svc | get-member
```
One of its methods is NewTask, so I'd start there.
Edit: Some more info [here](http://msdn.microsoft.com/en-us/library/aa446862.aspx). It's a VBScript example but it'll give you the gist. |
33,790 | <p>I am currently using the following command to upload my site content:</p>
<pre><code>scp -r web/* user@site.com:site.com/
</code></pre>
<p>This works great except that the .htaccess file is not sent. Presumably, this is because it's hidden.</p>
<p>I have tried adding a second line to send the file explicitely:</p>
<pre><code>scp -r web/.htaccess user@site.com:site.com/.htaccess
</code></pre>
<p>This works great except now I have to enter my password twice.</p>
<p>Any thoughts on how to make this deploy with only 1 or 0 entries of my password?</p>
| [
{
"answer_id": 33791,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 4,
"selected": true,
"text": "<p>Just combine the two commands:</p>\n\n<pre><code>scp -r web/* web/.htaccess user@site.com:site.com/\n</code></pre>\n\n<p>If you... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] | I am currently using the following command to upload my site content:
```
scp -r web/* user@site.com:site.com/
```
This works great except that the .htaccess file is not sent. Presumably, this is because it's hidden.
I have tried adding a second line to send the file explicitely:
```
scp -r web/.htaccess user@site.com:site.com/.htaccess
```
This works great except now I have to enter my password twice.
Any thoughts on how to make this deploy with only 1 or 0 entries of my password? | Just combine the two commands:
```
scp -r web/* web/.htaccess user@site.com:site.com/
```
If you want 0 entries of your password you can set up [public key authentication](http://sial.org/howto/openssh/publickey-auth/) for ssh/scp. |
33,813 | <p>I noticed that many people here use <a href="http://macromates.com/" rel="nofollow noreferrer">TextMate</a> for coding on OS X. I've recently started using it, and although I like its minimalistic interface, it makes it harder to stumble upon cool features if you don't know what you're looking for.</p>
<p>So, what feature have you found most helpful for coding (mainly in Python)? Are there any third-party bundles I should know about, besides what's included?</p>
| [
{
"answer_id": 33819,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "<p>The ease of snippet creation.</p>\n\n<p>It's trivial to create new snippets that can accomplish a lot using replacemen... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3002/"
] | I noticed that many people here use [TextMate](http://macromates.com/) for coding on OS X. I've recently started using it, and although I like its minimalistic interface, it makes it harder to stumble upon cool features if you don't know what you're looking for.
So, what feature have you found most helpful for coding (mainly in Python)? Are there any third-party bundles I should know about, besides what's included? | Don't neglect the 'mate' command line tool. You can use it to pipe output into TextMate, so if you do the following...
```
diff file1.py file2.py | mate
```
...it will not only open in TextMate, but it is smart enough to know that you're looking at a diff and highlight lines on screen.
TextMate's SVN integration is great; it also seems to have bundles for some other version control systems as well.
Add GetBundle to browse the bundle repository. I found the jQuery bundle through it and it's very handy.
As others have mentioned, rolling your own bundle for frequently used snippets is very helpful. If you have some snippets that are specific to a project or framework, you might want to prefix all of them with a common letter to keep the namespace tidy. |
33,814 | <p>I'm writing a PHP script that involves scraping web pages. Currently, the script analyzes the page line by line, but it breaks if there is a tag that spans multiple lines, like </p>
<pre><code><img src="example.jpg"
alt="example">
</code></pre>
<p>If worse comes to worst, I could possibly preprocess the page by removing all line breaks, then re-inserting them at the closest <code>></code>, but this seems like a kludge.</p>
<p>Ideally, I'd be able to detect a tag that spans lines, conjoin only those to lines, and continue processing.<br>
So what's the best method to detect this?</p>
| [
{
"answer_id": 33835,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 1,
"selected": false,
"text": "<p>Well, this doesn't answer the question and is more of an opinion, but...</p>\n\n<p>I think that the best scraping strateg... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1569/"
] | I'm writing a PHP script that involves scraping web pages. Currently, the script analyzes the page line by line, but it breaks if there is a tag that spans multiple lines, like
```
<img src="example.jpg"
alt="example">
```
If worse comes to worst, I could possibly preprocess the page by removing all line breaks, then re-inserting them at the closest `>`, but this seems like a kludge.
Ideally, I'd be able to detect a tag that spans lines, conjoin only those to lines, and continue processing.
So what's the best method to detect this? | Perhaps for future projects I'll use a parsing library, but that's kind of aside from the question at hand. This is my current solution. `rstrpos` is strpos, but from the reverse direction. Example use:
```
for($i=0; $i<count($lines); $i++)
{
$line = handle_mulitline_tags(&$i, $line, $lines);
}
```
And here's that implementation:
```
function rstrpos($string, $charToFind, $relativePos)
{
$searchPos = $relativePos;
$searchChar = '';
while (($searchChar != $charToFind)&&($searchPos>-1))
{
$newPos = $searchPos-1;
$searchChar = substr($string,$newPos,strlen($charToFind));
$searchPos = $newPos;
}
if (!empty($searchChar))
{
return $searchPos;
return TRUE;
}
else
{
return FALSE;
}
}
function handle_multiline_tags(&$i, $line, $lines)
{
//if a tag is opened but not closed before a line break,
$open = rstrpos($line, '<', strlen($line));
$close = rstrpos($line, '>', strlen($line));
if(($open > $close)&&($open > -1)&&($close > -1))
{
$i++;
return trim($line).trim(handle_multiline_tags(&$i, $lines[$i], $lines));
}
else
{
return trim($line);
}
}
```
This could probably be optimized in some way, but for my purposes, it's sufficient. |
33,822 | <p>Every time I turn on my company-owned development machine, I have to kill 10+ processes using the Task Manager or any other process management app just to get decent performance out of my IDE. Yes, these are processes from programs that my company installs on my machine for security and compliance. What I'd like to do is have a .bat file or script of some kind with which I can kill the processes in question. </p>
<p>Does anybody know how to do this?</p>
| [
{
"answer_id": 33826,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 2,
"selected": false,
"text": "<p>Download <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896683.aspx\" rel=\"nofollow noreferrer\">PSKill</a>. Wri... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3030/"
] | Every time I turn on my company-owned development machine, I have to kill 10+ processes using the Task Manager or any other process management app just to get decent performance out of my IDE. Yes, these are processes from programs that my company installs on my machine for security and compliance. What I'd like to do is have a .bat file or script of some kind with which I can kill the processes in question.
Does anybody know how to do this? | You can do this with '**taskkill**'.
With the /IM parameter, you can specify image names.
Example:
```
taskkill /im somecorporateprocess.exe
```
You can also do this to '**force**' kill:
Example:
```
taskkill /f /im somecorporateprocess.exe
```
Just add one line per process you want to kill, save it as a .bat file, and add in your startup directory. Problem solved!
If this is a legacy system, [PsKill](http://technet.microsoft.com/en-us/sysinternals/bb896683.aspx) will do the same. |
33,836 | <p>This is a follow on question to "<a href="https://stackoverflow.com/questions/33778/how-do-i-delete-1-file-from-a-revision-in-svn">How do I delete 1 file from a revision in SVN?</a>" but because it probably has a very different answer and I believe that others would benefit from knowing the answer. (I don't know the answer yet.)</p>
<p>The previous question was answered and I discovered that it is not possible to remove a revision from SVN. The second best solution was to remove the file from SVN, commit and then add the file back and commit again.</p>
<p>I now want to make sure that the original file's revision history has gone. So I am hoping that the answer to the question "<strong>How can I find the revision history of the file that was deleted and then resubmitted to SVN?</strong>" is that you can't.</p>
| [
{
"answer_id": 33846,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 1,
"selected": false,
"text": "<p>I would have said you can't - you have created a new file and thus revision tree in the eyes of SVN.</p>\n\n<p>It may ... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | This is a follow on question to "[How do I delete 1 file from a revision in SVN?](https://stackoverflow.com/questions/33778/how-do-i-delete-1-file-from-a-revision-in-svn)" but because it probably has a very different answer and I believe that others would benefit from knowing the answer. (I don't know the answer yet.)
The previous question was answered and I discovered that it is not possible to remove a revision from SVN. The second best solution was to remove the file from SVN, commit and then add the file back and commit again.
I now want to make sure that the original file's revision history has gone. So I am hoping that the answer to the question "**How can I find the revision history of the file that was deleted and then resubmitted to SVN?**" is that you can't. | With a simple
```
svn log -v [folder]
```
you can browse quickly the adding and deletion.
```
------------------------------------------------------------------------
r14 | kame | 2008-08-29 04:23:43 +0200 (ven., 29 aoû2008) | 1 line
Chemins modifié :
A /a.txt
Readded a
------------------------------------------------------------------------
r13 | kame | 2008-08-29 04:23:24 +0200 (ven., 29 aoû2008) | 1 line
Chemins modifié :
D /a.txt
Delete a
------------------------------------------------------------------------
r12 | kame | 2008-08-29 04:23:06 +0200 (ven., 29 aoû2008) | 1 line
Chemins modifié :
A /a.txt
```
svn log won't show the file, svn diff will pretend that the old revision does not exist, but a svn checkout targeting the old revision will happily give you the old file. |
33,837 | <p>I have a page where there is a column and a content div, somewhat like this:</p>
<pre><code><div id="container">
<div id="content">blahblahblah</div>
<div id="column"> </div>
</div>
</code></pre>
<p>With some styling I have an image that is split between the column and the content but needs to maintain the same vertical positioning so that it lines up.</p>
<p>Styling is similar to this:</p>
<pre class="lang-css prettyprint-override"><code>#column
{
width:150px;
height:450px;
left:-150px;
bottom:-140px;
background:url(../images/image.png) no-repeat;
position:absolute;
z-index:1;
}
#container
{
background:transparent url(../images/container.png) no-repeat scroll left bottom;
position:relative;
width:100px;
}
</code></pre>
<p>This works great when content in <code>#content</code> is dynamically loaded before rendering. This also works great in firefox always. However, in IE6 and IE7 if I use javascript to change the content (and thus height) of <code>#content</code>, the images no longer line up (<code>#column</code> doesn't move). If I use IE Developer Bar to just update the div (say add position:absolute manually) the image jumps down and lines up again.</p>
<p>Is there something I am missing here?</p>
<p>@Ricky - Hmm, that means in this case there is no solution I think. At its best there will be a jaggedy matchup afterwards but as my content expands and contracts etc. hiding/showing doesn't work out to be practical. Still thanks for answering with the best solution.</p>
| [
{
"answer_id": 33854,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 3,
"selected": true,
"text": "<p>Its a bug in the rendering engine. I run into it all the time. One potential way to solve it is to hide and show the div whenev... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | I have a page where there is a column and a content div, somewhat like this:
```
<div id="container">
<div id="content">blahblahblah</div>
<div id="column"> </div>
</div>
```
With some styling I have an image that is split between the column and the content but needs to maintain the same vertical positioning so that it lines up.
Styling is similar to this:
```css
#column
{
width:150px;
height:450px;
left:-150px;
bottom:-140px;
background:url(../images/image.png) no-repeat;
position:absolute;
z-index:1;
}
#container
{
background:transparent url(../images/container.png) no-repeat scroll left bottom;
position:relative;
width:100px;
}
```
This works great when content in `#content` is dynamically loaded before rendering. This also works great in firefox always. However, in IE6 and IE7 if I use javascript to change the content (and thus height) of `#content`, the images no longer line up (`#column` doesn't move). If I use IE Developer Bar to just update the div (say add position:absolute manually) the image jumps down and lines up again.
Is there something I am missing here?
@Ricky - Hmm, that means in this case there is no solution I think. At its best there will be a jaggedy matchup afterwards but as my content expands and contracts etc. hiding/showing doesn't work out to be practical. Still thanks for answering with the best solution. | Its a bug in the rendering engine. I run into it all the time. One potential way to solve it is to hide and show the div whenever you change the content (that in turn changes the height):
```
var divCol = document.getElementById('column');
divCol.style.display = 'none';
divCol.style.display = 'block';
```
Hopefully this happens fast enough that it isn't noticeable :) |
33,852 | <p>Most of time we represent concepts which can never be less than 0. For example to declare length, we write:</p>
<pre><code>int length;
</code></pre>
<p>The name expresses its purpose well but you can assign negative values to it. It seems that for some situations, you can represent your intent more clearly by writing it this way instead:</p>
<pre><code>uint length;
</code></pre>
<p>Some disadvantages that I can think of:</p>
<ul>
<li>unsigned types (uint, ulong, ushort) are not CLS compliant so you can't use it with other languages that don't support this</li>
<li>.Net classes use signed types most of the time so you have to cast</li>
</ul>
<p>Thoughts?</p>
| [
{
"answer_id": 33857,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 3,
"selected": false,
"text": "<p>If you decrement a signed number with a value of 0, it becomes negative and you can easily test for this. If you decrement an ... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/718/"
] | Most of time we represent concepts which can never be less than 0. For example to declare length, we write:
```
int length;
```
The name expresses its purpose well but you can assign negative values to it. It seems that for some situations, you can represent your intent more clearly by writing it this way instead:
```
uint length;
```
Some disadvantages that I can think of:
* unsigned types (uint, ulong, ushort) are not CLS compliant so you can't use it with other languages that don't support this
* .Net classes use signed types most of the time so you have to cast
Thoughts? | “When in Rome, do as the Romans do.”
While there is theoretically an advantage in using unsigned values where applicable because it makes the code more expressive, this is simply not done in C#. I'm not sure why the developers initially didn't design the interfaces to handle `uints` and make the type CLS compliant but now the train has left the station.
Since consistency is generally important I'd advise taking the C# road and using `int`s. |
33,860 | <p>In Ruby on Rails, I'm attempting to update the <code>innerHTML</code> of a div tag using the <code>form_remote_tag</code> helper. This update happens whenever an associated select tag receives an onchange event. The problem is, <code><select onchange="this.form.submit();"></code>; doesn't work. Nor does <code>document.forms[0].submit()</code>. The only way to get the onsubmit code generated in the form_remote_tag to execute is to create a hidden submit button, and invoke the click method on the button from the select tag. Here's a working ERb partial example.</p>
<pre><code><% form_remote_tag :url => product_path, :update => 'content', :method => 'get' do -%>
<% content_tag :div, :id => 'content' do -%>
<%= select_tag :update, options_for_select([["foo", 1], ["bar", 2]]), :onchange => "this.form.commit.click" %>
<%= submit_tag 'submit_button', :style => "display: none" %>
<% end %>
<% end %>
</code></pre>
<p>What I want to do is something like this, but it doesn't work.</p>
<pre><code><% form_remote_tag :url => product_path, :update => 'content', :method => 'get' do -%>
<% content_tag :div, :id => 'content' do -%>
# the following line does not work
<%= select_tag :update, options_for_select([["foo", 1], ["bar", 2]]), :onchange => "this.form.onsubmit()" %>
<% end %>
<% end %>
</code></pre>
<p>So, is there any way to remove the invisible submit button for this use case?</p>
<p>There seems to be some confusion. So, let me explain. The basic problem is that <code>submit()</code> doesn't call the <code>onsubmit()</code> code rendered into the form.</p>
<p>The actual HTML form that Rails renders from this ERb looks like this:</p>
<pre><code><form action="/products/1" method="post" onsubmit="new Ajax.Updater('content', '/products/1', {asynchronous:true, evalScripts:true, method:'get', parameters:Form.serialize(this)}); return false;">
<div style="margin:0;padding:0">
<input name="authenticity_token" type="hidden" value="4eacf78eb87e9262a0b631a8a6e417e9a5957cab" />
</div>
<div id="content">
<select id="update" name="update" onchange="this.form.commit.click">
<option value="1">foo</option>
<option value="2">bar</option>
</select>
<input name="commit" style="display: none" type="submit" value="submit_button" />
</div>
</form>
</code></pre>
<p>I want to axe the invisible submit button, but using a straight form.submit appears to not work. So, I need some way to call the form's onsubmit event code.</p>
<p>Update: Orion Edwards solution would work if there wasn't a <code>return(false);</code> generated by Rails. I'm not sure which is worse though, sending a phantom click to an invisible submit button or calling eval on the <code>getAttribute('onsubmit')</code> call after removing the return call with a javascript string replacement! </p>
| [
{
"answer_id": 33879,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>give your form an <code>id</code>.</p>\n\n<p>then</p>\n\n<pre><code>document.getElementById('formid').submit();\n</code></... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3499/"
] | In Ruby on Rails, I'm attempting to update the `innerHTML` of a div tag using the `form_remote_tag` helper. This update happens whenever an associated select tag receives an onchange event. The problem is, `<select onchange="this.form.submit();">`; doesn't work. Nor does `document.forms[0].submit()`. The only way to get the onsubmit code generated in the form\_remote\_tag to execute is to create a hidden submit button, and invoke the click method on the button from the select tag. Here's a working ERb partial example.
```
<% form_remote_tag :url => product_path, :update => 'content', :method => 'get' do -%>
<% content_tag :div, :id => 'content' do -%>
<%= select_tag :update, options_for_select([["foo", 1], ["bar", 2]]), :onchange => "this.form.commit.click" %>
<%= submit_tag 'submit_button', :style => "display: none" %>
<% end %>
<% end %>
```
What I want to do is something like this, but it doesn't work.
```
<% form_remote_tag :url => product_path, :update => 'content', :method => 'get' do -%>
<% content_tag :div, :id => 'content' do -%>
# the following line does not work
<%= select_tag :update, options_for_select([["foo", 1], ["bar", 2]]), :onchange => "this.form.onsubmit()" %>
<% end %>
<% end %>
```
So, is there any way to remove the invisible submit button for this use case?
There seems to be some confusion. So, let me explain. The basic problem is that `submit()` doesn't call the `onsubmit()` code rendered into the form.
The actual HTML form that Rails renders from this ERb looks like this:
```
<form action="/products/1" method="post" onsubmit="new Ajax.Updater('content', '/products/1', {asynchronous:true, evalScripts:true, method:'get', parameters:Form.serialize(this)}); return false;">
<div style="margin:0;padding:0">
<input name="authenticity_token" type="hidden" value="4eacf78eb87e9262a0b631a8a6e417e9a5957cab" />
</div>
<div id="content">
<select id="update" name="update" onchange="this.form.commit.click">
<option value="1">foo</option>
<option value="2">bar</option>
</select>
<input name="commit" style="display: none" type="submit" value="submit_button" />
</div>
</form>
```
I want to axe the invisible submit button, but using a straight form.submit appears to not work. So, I need some way to call the form's onsubmit event code.
Update: Orion Edwards solution would work if there wasn't a `return(false);` generated by Rails. I'm not sure which is worse though, sending a phantom click to an invisible submit button or calling eval on the `getAttribute('onsubmit')` call after removing the return call with a javascript string replacement! | If you didn't actually want to submit the form, but just invoke whatever code happened to be in the onsubmit, you could possibly do this: (untested)
```
var code = document.getElementById('formId').getAttribute('onsubmit');
eval(code);
``` |
33,881 | <p>I always run into the same problem when creating web pages. When I add a font that is larger then about 16-18px it looks terrible. Its jagged, and pixelated. I have tried using different fonts and weights, however I haven't had much luck there. </p>
<p>Note: Its only in windows that it is like this. Mainly in Opera and FF also in IE7 but not quite as bad. In Linux the font looks good. I haven't looked at a Mac.</p>
<p>What do you guys do to fix this? if anything. I noticed that the titles here on SO are also pretty jagged but they are just small enough not to look bad. </p>
| [
{
"answer_id": 33885,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 0,
"selected": false,
"text": "<p>Enabling anti-aliasing should solve the display problem. </p>\n"
},
{
"answer_id": 33886,
"author": "tra... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1925/"
] | I always run into the same problem when creating web pages. When I add a font that is larger then about 16-18px it looks terrible. Its jagged, and pixelated. I have tried using different fonts and weights, however I haven't had much luck there.
Note: Its only in windows that it is like this. Mainly in Opera and FF also in IE7 but not quite as bad. In Linux the font looks good. I haven't looked at a Mac.
What do you guys do to fix this? if anything. I noticed that the titles here on SO are also pretty jagged but they are just small enough not to look bad. | There is nothing you can do to force the user to change the way that their operating system renders fonts. If it is that big a deal to you then you can replace the large headings with images, this allows you to control exactly how the font is rendered (and ensures that the heading looks exactly as you wish, even if the user doesnt have your suggested font installed).
If you do this make sure that you provide an alternative text representation for those who do not see images. I tend to use CSS to show a background image, and hide the contents of the heading. Like this.
```
<style>
h1
{
height: 32px;
width: 100px;
background: url("path/to/image")
}
h1 span
{
display: none;
}
</style>
<h1>
<span>
Heading Text
<span>
</h1>
```
To be honest this does seem like overkill if it is on all large text. And be aware that it will increase the amount of data that your clients need to download. However for a large heading this method can lead to something that looks nicer than OS rendered text. |
33,893 | <p>In my (PHP) web app, I have a part of my site that keeps a history of recent searches. The most recent queries get shown in a side box. If the query text is too long, I truncate it and show ellipses. Eg: "My very long query is..."</p>
<p>Currently, I truncate after a certain number of characters. Since the font is not monotype, a query of all I's is more narrow than a query of all W's. I'd like them to all be about the same width prior to the ellipses. Is there a way to get the approximate width of the resulting string so that the ellipses for any given string will occur in about the same number of pixels from the beginning? Does CSS have a way? Does PHP? Would this be better handled by JavaScript?</p>
| [
{
"answer_id": 33899,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Does CSS have a way?</p>\n</blockquote>\n\n<p>No</p>\n\n<blockquote>\n <p>Does PHP?</p>\n</blockquote... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/356/"
] | In my (PHP) web app, I have a part of my site that keeps a history of recent searches. The most recent queries get shown in a side box. If the query text is too long, I truncate it and show ellipses. Eg: "My very long query is..."
Currently, I truncate after a certain number of characters. Since the font is not monotype, a query of all I's is more narrow than a query of all W's. I'd like them to all be about the same width prior to the ellipses. Is there a way to get the approximate width of the resulting string so that the ellipses for any given string will occur in about the same number of pixels from the beginning? Does CSS have a way? Does PHP? Would this be better handled by JavaScript? | Here's another take on it and you don't have to live without the ellipsis!
```
<html>
<head>
<style>
div.sidebox {
width: 25%;
}
div.sidebox div.qrytxt {
height: 1em;
line-height: 1em;
overflow: hidden;
}
div.sidebox div.qrytxt span.ellipsis {
float: right;
}
</style>
</head>
<body>
<div class="sidebox">
<div class="qrytxt">
<span class="ellipsis">…</span>
Some long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end.
</div>
<div class="qrytxt">
<span class="ellipsis">…</span>
Some more long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end.
</div>
<div class="qrytxt">
<span class="ellipsis">…</span>
Short text. Fail!
</div>
</body>
</html>
```
There is one flaw with this, if the text is short enough to be fully displayed, the ellipses will still be displayed as well.
[EDIT: 6/26/2009]
At the suggestion of Power-Coder I have revised this a little. There are really only two changes, the addition of the `doctype` (see notes below) and the addition of the `display: inline-block` attribute on the `.qrytxt` DIV. Here is what it looks like now...
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style>
div.sidebox
{
width: 25%;
}
div.sidebox div.qrytxt
{
height: 1em;
line-height: 1em;
overflow: hidden;
display: inline-block;
}
div.sidebox div.qrytxt span.ellipsis
{
float: right;
}
</style>
</head>
<body>
<div class="sidebox">
<div class="qrytxt">
<span class="ellipsis">…</span>
Some long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end.
</div>
<div class="qrytxt">
<span class="ellipsis">…</span>
Some more long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end.
</div>
<div class="qrytxt">
<span class="ellipsis">…</span>
Short text. FTW
</div>
</div>
</body>
</html>
```
Notes:
* Viewed in IE 8.0, Opera 9, FF 3
* A `doctype` is required for IE to get the `display: inline-block` to work correctly.
* If the `.qrytxt` DIV's overflow occurs on a long word, there is going to be a wide gap between the ellipsis and the last visible word. You can see this by viewing the example and resizing your browser width in small increments. (this probably existed in the original example as well, I just may have not noticed it then)
So again, an imperfect CSS-only solution. Javascript may be the only thing that can get the effect perfect.
[EDIT: 6/27/2009]
Here is another alternative which uses browser specific extensions.
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style>
div.sidebox
{
width: 26%;
}
div.sidebox div.qrytxt
{
height: 1em;
line-height: 1em;
overflow: hidden;
text-overflow:ellipsis;
-o-text-overflow:ellipsis;
-ms-text-overflow:ellipsis;
-moz-binding:url(ellipsis-xbl.xml#ellipsis);
white-space:nowrap;
}
</style>
</head>
<body>
<div class="sidebox">
<div class="qrytxt">
Some long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end.
</div>
<div class="qrytxt">
Some more long text which will arbitrarily be cut off at whatever word fits best but will have an ellipsis at the end.
</div>
<div class="qrytxt">
Short text. FTW
</div>
</div>
</body>
</html>
```
Note that in order for the above example to work, you must create the xml file referenced by the -moz-binding rule, ***ellipsis-xbl.xml***. It's should contain the following xml:
```
<?xml version="1.0" encoding="UTF-8"?>
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:xbl="http://www.mozilla.org/xbl" xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<binding id="ellipsis">
<content>
<xul:window>
<xul:description crop="end" xbl:inherits="value=xbl:text"><children/></xul:description>
</xul:window>
</content>
</binding>
</bindings>
``` |
33,923 | <p>Whilst starting to learn lisp, I've come across the term <em>tail-recursive</em>. What does it mean exactly?</p>
| [
{
"answer_id": 33924,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 4,
"selected": false,
"text": "<p>I'm not a Lisp programmer, but I think <a href=\"http://en.wikipedia.org/wiki/Tail_recursion\" rel=\"noreferrer\">this... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2045/"
] | Whilst starting to learn lisp, I've come across the term *tail-recursive*. What does it mean exactly? | Consider a simple function that adds the first N natural numbers. (e.g. `sum(5) = 0 + 1 + 2 + 3 + 4 + 5 = 15`).
Here is a simple JavaScript implementation that uses recursion:
```js
function recsum(x) {
if (x === 0) {
return 0;
} else {
return x + recsum(x - 1);
}
}
```
If you called `recsum(5)`, this is what the JavaScript interpreter would evaluate:
```js
recsum(5)
5 + recsum(4)
5 + (4 + recsum(3))
5 + (4 + (3 + recsum(2)))
5 + (4 + (3 + (2 + recsum(1))))
5 + (4 + (3 + (2 + (1 + recsum(0)))))
5 + (4 + (3 + (2 + (1 + 0))))
5 + (4 + (3 + (2 + 1)))
5 + (4 + (3 + 3))
5 + (4 + 6)
5 + 10
15
```
Note how every recursive call has to complete before the JavaScript interpreter begins to actually do the work of calculating the sum.
Here's a tail-recursive version of the same function:
```js
function tailrecsum(x, running_total = 0) {
if (x === 0) {
return running_total;
} else {
return tailrecsum(x - 1, running_total + x);
}
}
```
Here's the sequence of events that would occur if you called `tailrecsum(5)`, (which would effectively be `tailrecsum(5, 0)`, because of the default second argument).
```js
tailrecsum(5, 0)
tailrecsum(4, 5)
tailrecsum(3, 9)
tailrecsum(2, 12)
tailrecsum(1, 14)
tailrecsum(0, 15)
15
```
In the tail-recursive case, with each evaluation of the recursive call, the `running_total` is updated.
*Note: The original answer used examples from Python. These have been changed to JavaScript, since Python interpreters don't support [tail call optimization](https://stackoverflow.com/questions/310974/what-is-tail-call-optimization). However, while tail call optimization is [part of the ECMAScript 2015 spec](https://www.ecma-international.org/ecma-262/6.0/#sec-tail-position-calls), most JavaScript interpreters [don't support it](https://kangax.github.io/compat-table/es6/#test-proper_tail_calls_(tail_call_optimisation)).* |
33,933 | <p>I have the following <code>textarea</code> in a <code>table</code>:</p>
<pre><code><table width="300"><tr><td>
<textarea style="width:100%">
longstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstring
</textarea>
</td></tr></table>
</code></pre>
<p>With a long string in the textarea, the textarea stretches out to accommodate it in one line in IE7, but retains its 300px width in other browsers.</p>
<p>Any ideas as to how to fix this in IE?</p>
| [
{
"answer_id": 33936,
"author": "Jiaaro",
"author_id": 2908,
"author_profile": "https://Stackoverflow.com/users/2908",
"pm_score": 0,
"selected": false,
"text": "<p>did you try...</p>\n\n<p><code>overflow: hidden;</code></p>\n\n<p>??</p>\n\n<p>I'm not sure if it should be in the table of... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2749/"
] | I have the following `textarea` in a `table`:
```
<table width="300"><tr><td>
<textarea style="width:100%">
longstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstring
</textarea>
</td></tr></table>
```
With a long string in the textarea, the textarea stretches out to accommodate it in one line in IE7, but retains its 300px width in other browsers.
Any ideas as to how to fix this in IE? | Apply the width to the `td`, not the `table`.
EDIT: @Emmett - the width could just as easily be applied via CSS.
```css
td {
width: 300px;
}
```
produces the desired result. Or, if you're using jQuery, you could add the width through script:
```
$('textarea[width=100%]').parent('td').css('width', '300px');
```
Point being, there's more than one way to apply a width to a table cell, if development constraints prevent you from applying it directly. |
33,956 | <p>Assume that I have a field called <em>price</em> for the documents in Solr and I have that field faceted. I want to get the facets as ranges of values (eg: 0-100, 100-500, 500-1000, etc). How to do it?</p>
<p>I can specify the ranges beforehand, but I also want to know whether it is possible to calculate the ranges (say for 5 values) automatically based on the values in the documents?</p>
| [
{
"answer_id": 34027,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 2,
"selected": false,
"text": "<p>There may well be a better Solr-specific answer, but I work with straight Lucene, and since you're not getting much tract... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | Assume that I have a field called *price* for the documents in Solr and I have that field faceted. I want to get the facets as ranges of values (eg: 0-100, 100-500, 500-1000, etc). How to do it?
I can specify the ranges beforehand, but I also want to know whether it is possible to calculate the ranges (say for 5 values) automatically based on the values in the documents? | To answer your first question, you can get facet ranges by using the the generic facet query support. [Here](http://wiki.apache.org/solr/SimpleFacetParameters#head-1da3ab3995bc4abcdce8e0f04be7355ba19e9b2c)'s an example:
```
http://localhost:8983/solr/select?q=video&rows=0&facet=true&facet.query=price:[*+TO+500]&facet.query=price:[500+TO+*]
```
As for your second question (automatically suggesting facet ranges), that's not yet implemented. Some argue that this kind of querying would be best implemented on your application rather that letting Solr "guess" the best facet ranges.
Here are some discussions on the topic:
* (Archived) <https://web.archive.org/web/20100416235126/http://old.nabble.com/Re:-faceted-browsing-p3753053.html>
* (Archived) <https://web.archive.org/web/20090430160232/http://www.nabble.com/Re:-Sorting-p6803791.html>
* (Archived) <https://web.archive.org/web/20090504020754/http://www.nabble.com/Dynamically-calculated-range-facet-td11314725.html> |
33,969 | <p>We're experimenting with various ways to throttle user actions in a <strong>given time period</strong>:</p>
<ul>
<li>Limit question/answer posts</li>
<li>Limit edits</li>
<li>Limit feed retrievals</li>
</ul>
<p>For the time being, we're using the Cache to simply insert a record of user activity - if that record exists if/when the user does the same activity, we throttle.</p>
<p>Using the Cache automatically gives us stale data cleaning and sliding activity windows of users, but how it will scale could be a problem.</p>
<p>What are some other ways of ensuring that requests/user actions can be effectively throttled (emphasis on stability)?</p>
| [
{
"answer_id": 291390,
"author": "Rob Kraft",
"author_id": 37749,
"author_profile": "https://Stackoverflow.com/users/37749",
"pm_score": 4,
"selected": false,
"text": "<p>We use the technique borrowed from this URL <a href=\"http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx\"... | 2008/08/29 | [
"https://Stackoverflow.com/questions/33969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3/"
] | We're experimenting with various ways to throttle user actions in a **given time period**:
* Limit question/answer posts
* Limit edits
* Limit feed retrievals
For the time being, we're using the Cache to simply insert a record of user activity - if that record exists if/when the user does the same activity, we throttle.
Using the Cache automatically gives us stale data cleaning and sliding activity windows of users, but how it will scale could be a problem.
What are some other ways of ensuring that requests/user actions can be effectively throttled (emphasis on stability)? | Here's a generic version of what we've been using on Stack Overflow for the past year:
```
/// <summary>
/// Decorates any MVC route that needs to have client requests limited by time.
/// </summary>
/// <remarks>
/// Uses the current System.Web.Caching.Cache to store each client request to the decorated route.
/// </remarks>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ThrottleAttribute : ActionFilterAttribute
{
/// <summary>
/// A unique name for this Throttle.
/// </summary>
/// <remarks>
/// We'll be inserting a Cache record based on this name and client IP, e.g. "Name-192.168.0.1"
/// </remarks>
public string Name { get; set; }
/// <summary>
/// The number of seconds clients must wait before executing this decorated route again.
/// </summary>
public int Seconds { get; set; }
/// <summary>
/// A text message that will be sent to the client upon throttling. You can include the token {n} to
/// show this.Seconds in the message, e.g. "Wait {n} seconds before trying again".
/// </summary>
public string Message { get; set; }
public override void OnActionExecuting(ActionExecutingContext c)
{
var key = string.Concat(Name, "-", c.HttpContext.Request.UserHostAddress);
var allowExecute = false;
if (HttpRuntime.Cache[key] == null)
{
HttpRuntime.Cache.Add(key,
true, // is this the smallest data we can have?
null, // no dependencies
DateTime.Now.AddSeconds(Seconds), // absolute expiration
Cache.NoSlidingExpiration,
CacheItemPriority.Low,
null); // no callback
allowExecute = true;
}
if (!allowExecute)
{
if (String.IsNullOrEmpty(Message))
Message = "You may only perform this action every {n} seconds.";
c.Result = new ContentResult { Content = Message.Replace("{n}", Seconds.ToString()) };
// see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
c.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
}
}
}
```
Sample usage:
```
[Throttle(Name="TestThrottle", Message = "You must wait {n} seconds before accessing this url again.", Seconds = 5)]
public ActionResult TestThrottle()
{
return Content("TestThrottle executed");
}
```
The ASP.NET Cache works like a champ here - by using it, you get automatic clean-up of your throttle entries. And with our growing traffic, we're not seeing that this is an issue on the server.
Feel free to give feedback on this method; when we make Stack Overflow better, you get your [Ewok fix](https://stackoverflow.blog/2009/05/31/the-stack-overflow-trilogy/) even faster :) |
34,065 | <p>Given the key for some registry value (e.g. HKEY_LOCAL_MACHINE\blah\blah\blah\foo) how can I:</p>
<ol>
<li>Safely determine that such a key exists.</li>
<li>Programmatically (i.e. with code) get its value.</li>
</ol>
<p>I have absolutely no intention of writing anything back to the registry (for the duration of my career if I can help it). So we can skip the lecture about every molecule in my body exploding at the speed of light if I write to the registry incorrectly. </p>
<p>Prefer answers in C++, but mostly just need to know what the special Windows API incantation to get at the value is.</p>
| [
{
"answer_id": 34067,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms724911%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">RegQueryValueEx</a>... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3551/"
] | Given the key for some registry value (e.g. HKEY\_LOCAL\_MACHINE\blah\blah\blah\foo) how can I:
1. Safely determine that such a key exists.
2. Programmatically (i.e. with code) get its value.
I have absolutely no intention of writing anything back to the registry (for the duration of my career if I can help it). So we can skip the lecture about every molecule in my body exploding at the speed of light if I write to the registry incorrectly.
Prefer answers in C++, but mostly just need to know what the special Windows API incantation to get at the value is. | **Here is some pseudo-code to retrieve the following:**
1. If a registry key exists
2. What the default value is for that registry key
3. What a string value is
4. What a DWORD value is
**Example code:**
Include the library dependency: Advapi32.lib
```
HKEY hKey;
LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &hKey);
bool bExistsAndSuccess (lRes == ERROR_SUCCESS);
bool bDoesNotExistsSpecifically (lRes == ERROR_FILE_NOT_FOUND);
std::wstring strValueOfBinDir;
std::wstring strKeyDefaultValue;
GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad");
GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad");
LONG GetDWORDRegKey(HKEY hKey, const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue)
{
nValue = nDefaultValue;
DWORD dwBufferSize(sizeof(DWORD));
DWORD nResult(0);
LONG nError = ::RegQueryValueExW(hKey,
strValueName.c_str(),
0,
NULL,
reinterpret_cast<LPBYTE>(&nResult),
&dwBufferSize);
if (ERROR_SUCCESS == nError)
{
nValue = nResult;
}
return nError;
}
LONG GetBoolRegKey(HKEY hKey, const std::wstring &strValueName, bool &bValue, bool bDefaultValue)
{
DWORD nDefValue((bDefaultValue) ? 1 : 0);
DWORD nResult(nDefValue);
LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue);
if (ERROR_SUCCESS == nError)
{
bValue = (nResult != 0) ? true : false;
}
return nError;
}
LONG GetStringRegKey(HKEY hKey, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue)
{
strValue = strDefaultValue;
WCHAR szBuffer[512];
DWORD dwBufferSize = sizeof(szBuffer);
ULONG nError;
nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize);
if (ERROR_SUCCESS == nError)
{
strValue = szBuffer;
}
return nError;
}
``` |
34,079 | <p>What's the best way to specify a proxy with username and password for an http connection in python?</p>
| [
{
"answer_id": 34116,
"author": "bernhardrusch",
"author_id": 3056,
"author_profile": "https://Stackoverflow.com/users/3056",
"pm_score": 6,
"selected": false,
"text": "<p>This works for me: </p>\n\n<pre><code>import urllib2\n\nproxy = urllib2.ProxyHandler({'http': 'http://\nusername:pa... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3573/"
] | What's the best way to specify a proxy with username and password for an http connection in python? | Use this:
```
import requests
proxies = {"http":"http://username:password@proxy_ip:proxy_port"}
r = requests.get("http://www.example.com/", proxies=proxies)
print(r.content)
```
I think it's much simpler than using `urllib`. I don't understand why people love using `urllib` so much. |
34,087 | <pre><code><xsl:for-each select="./node [position() &lt;= (count(*) div 2)]">
<li>foo</li>
</xsl:for-each>
<xsl:for-each select="./node [count(*) div 2 &lt; position()]">
<li>bar</li>
</xsl:for-each>
</code></pre>
<p>My list has 12 nodes, but the second list is always 8 and the first is always 4. What's wrong with my selects?</p>
| [
{
"answer_id": 34111,
"author": "A. Rex",
"author_id": 3508,
"author_profile": "https://Stackoverflow.com/users/3508",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not at all sure, but it seems to me that <code>count(*)</code> is not doing what you think it is. That counts the numb... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1786/"
] | ```
<xsl:for-each select="./node [position() <= (count(*) div 2)]">
<li>foo</li>
</xsl:for-each>
<xsl:for-each select="./node [count(*) div 2 < position()]">
<li>bar</li>
</xsl:for-each>
```
My list has 12 nodes, but the second list is always 8 and the first is always 4. What's wrong with my selects? | When you do `count(*)`, the current node is the `node` element being processed. You want either `count(current()/node)` or `last()` (preferable), or just calculate the midpoint to a variable for better performance and clearer code:
```
<xsl:variable name="nodes" select="node"/>
<xsl:variable name="mid" select="count($nodes) div 2"/>
<xsl:for-each select="$nodes[position() <= $mid]">
<li>foo</li>
</xsl:for-each>
<xsl:for-each select="$nodes[$mid < position()]">
<li>bar</li>
</xsl:for-each>
``` |
34,093 | <p>I want to apply an XSLT Stylesheet to an XML Document using C# and write the output to a File.</p>
| [
{
"answer_id": 34095,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 9,
"selected": true,
"text": "<p>I found a possible answer here: <a href=\"http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Artic... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] | I want to apply an XSLT Stylesheet to an XML Document using C# and write the output to a File. | I found a possible answer here: <http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63>
From the article:
```
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;
```
**Edit:**
But my trusty compiler says, `XslTransform` is obsolete: Use `XslCompiledTransform` instead:
```
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);
``` |
34,125 | <p>It seems to me that it would work perfectly well to do tail-recursion optimization in both C and C++, yet while debugging I never seem to see a frame stack that indicates this optimization. That is kind of good, because the stack tells me how deep the recursion is. However, the optimization would be kind of nice as well.</p>
<p>Do any C++ compilers do this optimization? Why? Why not?</p>
<p>How do I go about telling the compiler to do it?</p>
<ul>
<li>For MSVC: <code>/O2</code> or <code>/Ox</code></li>
<li>For GCC: <code>-O2</code> or <code>-O3</code></li>
</ul>
<p>How about checking if the compiler has done this in a certain case?</p>
<ul>
<li>For MSVC, enable PDB output to be able to trace the code, then inspect the code</li>
<li>For GCC..?</li>
</ul>
<p>I'd still take suggestions for how to determine if a certain function is optimized like this by the compiler (even though I find it reassuring that Konrad tells me to assume it)</p>
<p>It is always possible to check if the compiler does this at all by making an infinite recursion and checking if it results in an infinite loop or a stack overflow (I did this with GCC and found out that <code>-O2</code> is sufficient), but I want to be able to check a certain function that I know will terminate anyway. I'd love to have an easy way of checking this :)</p>
<hr>
<p>After some testing, I discovered that destructors ruin the possibility of making this optimization. It can sometimes be worth it to change the scoping of certain variables and temporaries to make sure they go out of scope before the return-statement starts.</p>
<p>If any destructor needs to be run after the tail-call, the tail-call optimization can not be done.</p>
| [
{
"answer_id": 34129,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 8,
"selected": true,
"text": "<p><strong>All current mainstream compilers perform tail call optimisation</strong> fairly well (and have done for more... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2971/"
] | It seems to me that it would work perfectly well to do tail-recursion optimization in both C and C++, yet while debugging I never seem to see a frame stack that indicates this optimization. That is kind of good, because the stack tells me how deep the recursion is. However, the optimization would be kind of nice as well.
Do any C++ compilers do this optimization? Why? Why not?
How do I go about telling the compiler to do it?
* For MSVC: `/O2` or `/Ox`
* For GCC: `-O2` or `-O3`
How about checking if the compiler has done this in a certain case?
* For MSVC, enable PDB output to be able to trace the code, then inspect the code
* For GCC..?
I'd still take suggestions for how to determine if a certain function is optimized like this by the compiler (even though I find it reassuring that Konrad tells me to assume it)
It is always possible to check if the compiler does this at all by making an infinite recursion and checking if it results in an infinite loop or a stack overflow (I did this with GCC and found out that `-O2` is sufficient), but I want to be able to check a certain function that I know will terminate anyway. I'd love to have an easy way of checking this :)
---
After some testing, I discovered that destructors ruin the possibility of making this optimization. It can sometimes be worth it to change the scoping of certain variables and temporaries to make sure they go out of scope before the return-statement starts.
If any destructor needs to be run after the tail-call, the tail-call optimization can not be done. | **All current mainstream compilers perform tail call optimisation** fairly well (and have done for more than a decade), [even for mutually recursive calls](https://godbolt.org/g/TjqTHV) such as:
```
int bar(int, int);
int foo(int n, int acc) {
return (n == 0) ? acc : bar(n - 1, acc + 2);
}
int bar(int n, int acc) {
return (n == 0) ? acc : foo(n - 1, acc + 1);
}
```
Letting the compiler do the optimisation is straightforward: Just switch on optimisation for speed:
* For MSVC, use `/O2` or `/Ox`.
* For GCC, Clang and ICC, use `-O3`
An easy way to check if the compiler did the optimisation is to perform a call that would otherwise result in a stack overflow — or looking at the assembly output.
As an interesting historical note, tail call optimisation for C was added to the GCC in the course of a [diploma thesis](http://www.complang.tuwien.ac.at/schani/diplarb.ps) by Mark Probst. The thesis describes some interesting caveats in the implementation. It's worth reading. |
34,126 | <p>I see 2 main ways to set events in JavaScript:</p>
<ol>
<li><p>Add an event directly inside the tag like this:</p>
<p><code><a href="" onclick="doFoo()">do foo</a></code></p></li>
<li><p>Set them by JavaScript like this:</p>
<p><code><a id="bar" href="">do bar</a></code></p></li>
</ol>
<p>and add an event in a <code><script></code> section inside the <code><head></code> section or in an external JavaScript file, like that if you're using <strong>prototypeJS</strong>:</p>
<pre><code>Event.observe(window, 'load', function() {
$('bar').observe('click', doBar);
}
</code></pre>
<p>I think the first method is easier to read and maintain (because the JavaScript action is directly bound to the link) but it's not so clean (because users can click on the link even if the page is not fully loaded, which may cause JavaScript errors in some cases).</p>
<p>The second method is cleaner (actions are added when the page is fully loaded) but it's more difficult to know that an action is linked to the tag.</p>
<p>Which method is the best?</p>
<p>A killer answer will be fully appreciated!</p>
| [
{
"answer_id": 34130,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 0,
"selected": false,
"text": "<p>Libraries like YUI and jQuery provide methods to add events only once the DOM is ready, which can be before window.onload. ... | 2008/08/29 | [
"https://Stackoverflow.com/questions/34126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3122/"
] | I see 2 main ways to set events in JavaScript:
1. Add an event directly inside the tag like this:
`<a href="" onclick="doFoo()">do foo</a>`
2. Set them by JavaScript like this:
`<a id="bar" href="">do bar</a>`
and add an event in a `<script>` section inside the `<head>` section or in an external JavaScript file, like that if you're using **prototypeJS**:
```
Event.observe(window, 'load', function() {
$('bar').observe('click', doBar);
}
```
I think the first method is easier to read and maintain (because the JavaScript action is directly bound to the link) but it's not so clean (because users can click on the link even if the page is not fully loaded, which may cause JavaScript errors in some cases).
The second method is cleaner (actions are added when the page is fully loaded) but it's more difficult to know that an action is linked to the tag.
Which method is the best?
A killer answer will be fully appreciated! | In my experience, there are two major points to this:
1) The most important thing is to be consistent. I don't think either of the two methods is necessarily easier to read, as long as you stick to it. I only get confused when both methods are used in a project (or even worse on the same page) because then I have to start searching for the calls and don't immediately know where to look.
2) The second kind, i.e. `Event.observe()` has advantages when the same or a very similar action is taken on multiple events because this becomes obvious when all those calls are in the same place. Also, as Konrad pointed out, in some cases this can be handled with a single call. |