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 |
|---|---|---|---|---|---|---|
145,291 | <p>Can you have smart behavior for the home key in Emacs? By smart I mean that instead of going to the character number 0, it should go to the first non-blank character, and go to 0 on a second pressing, and back to the first non-blank in a third and so on.
Having smart end would be nice as well.</p>
| [
{
"answer_id": 145359,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 7,
"selected": true,
"text": "<pre><code>(defun smart-beginning-of-line ()\n \"Move point to first non-whitespace character or beginning-of-line.\n\nMove poin... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] | Can you have smart behavior for the home key in Emacs? By smart I mean that instead of going to the character number 0, it should go to the first non-blank character, and go to 0 on a second pressing, and back to the first non-blank in a third and so on.
Having smart end would be nice as well. | ```
(defun smart-beginning-of-line ()
"Move point to first non-whitespace character or beginning-of-line.
Move point to the first non-whitespace character on this line.
If point was already at that position, move point to beginning of line."
(interactive "^") ; Use (interactive) in Emacs 22 or older
(let ((oldpos (point)))
(back-to-indentation)
(and (= oldpos (point))
(beginning-of-line))))
(global-set-key [home] 'smart-beginning-of-line)
```
I'm not quite sure what smart end would do. Do you normally have a lot of trailing whitespace?
**Note:** The major difference between this function and Robert Vuković's is that his always moves to the first non-blank character on the first keypress, even if the cursor was already there. Mine would move to column 0 in that case.
Also, he used `(beginning-of-line-text)` where I used `(back-to-indentation)`. Those are very similar, but there are some differences between them. `(back-to-indentation)` always moves to the first non-whitespace character on a line. `(beginning-of-line-text)` sometimes moves past non-whitespace characters that it considers insignificant. For instance, on a comment-only line, it moves to the first character of the comment's text, not the comment marker. But either function could be used in either of our answers, depending on which behavior you prefer. |
145,335 | <p>I know how to lighten the colors for certain commands, however I'd like to lighten the standard ansi colors across all commands.</p>
| [
{
"answer_id": 145421,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 0,
"selected": false,
"text": "<p>A simple solution would be to turn up your monitor brightness :)</p>\n\n<p>More seriously, see the RESOURCES section... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3624/"
] | I know how to lighten the colors for certain commands, however I'd like to lighten the standard ansi colors across all commands. | I found instructions for doing it for Xterm and aterm here:
<http://gentoo-wiki.com/TIP_Linux_Colors_in_Aterm/rxvt>
From those I was able to get brighter colors by adding:
```
rxvt*background: #000000
rxvt*foreground: #7f7f7f
rxvt*color0: #000000
rxvt*color1: #9e1828
rxvt*color2: #aece92
rxvt*color3: #968a38
rxvt*color4: #414171
rxvt*color5: #963c59
rxvt*color6: #418179
rxvt*color7: #bebebe
rxvt*color8: #666666
rxvt*color9: #cf6171
rxvt*color10: #c5f779
rxvt*color11: #fff796
rxvt*color12: #4186be
rxvt*color13: #cf9ebe
rxvt*color14: #71bebe
rxvt*color15: #ffffff
```
to the bottom of my `~/.Xdefaults` file |
145,337 | <ol>
<li>What is the most efficient way to check if an array is <strong>a flat array
of primitive values</strong> or if it is a <strong>multidimensional array</strong>?</li>
<li>Is there any way to do this without actually looping through an
array and running <code>is_array()</code> on each of its elements?</li>
</ol>
| [
{
"answer_id": 145342,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>You could look check <code>is_array()</code> on the first element, under the assumption that if the first element of a... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] | 1. What is the most efficient way to check if an array is **a flat array
of primitive values** or if it is a **multidimensional array**?
2. Is there any way to do this without actually looping through an
array and running `is_array()` on each of its elements? | The short answer is no you can't do it without at least looping implicitly if the 'second dimension' could be anywhere. If it has to be in the first item, you'd just do
```
is_array($arr[0]);
```
But, the most efficient general way I could find is to use a foreach loop on the array, shortcircuiting whenever a hit is found (at least the implicit loop is better than the straight for()):
```
$ more multi.php
<?php
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
$c = array(1 => 'a',2 => 'b','foo' => array(1,array(2)));
function is_multi($a) {
$rv = array_filter($a,'is_array');
if(count($rv)>0) return true;
return false;
}
function is_multi2($a) {
foreach ($a as $v) {
if (is_array($v)) return true;
}
return false;
}
function is_multi3($a) {
$c = count($a);
for ($i=0;$i<$c;$i++) {
if (is_array($a[$i])) return true;
}
return false;
}
$iters = 500000;
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi($a);
is_multi($b);
is_multi($c);
}
$end = microtime(true);
echo "is_multi took ".($end-$time)." seconds in $iters times\n";
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi2($a);
is_multi2($b);
is_multi2($c);
}
$end = microtime(true);
echo "is_multi2 took ".($end-$time)." seconds in $iters times\n";
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi3($a);
is_multi3($b);
is_multi3($c);
}
$end = microtime(true);
echo "is_multi3 took ".($end-$time)." seconds in $iters times\n";
?>
$ php multi.php
is_multi took 7.53565130424 seconds in 500000 times
is_multi2 took 4.56964588165 seconds in 500000 times
is_multi3 took 9.01706600189 seconds in 500000 times
```
Implicit looping, but we can't shortcircuit as soon as a match is found...
```
$ more multi.php
<?php
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
function is_multi($a) {
$rv = array_filter($a,'is_array');
if(count($rv)>0) return true;
return false;
}
var_dump(is_multi($a));
var_dump(is_multi($b));
?>
$ php multi.php
bool(true)
bool(false)
``` |
145,376 | <p>Would it be possible to write a class that is virtually indistinguishable from an actual PHP array by implementing all the necessary SPL interfaces? Are they missing anything that would be critical?</p>
<p>I'd like to build a more advanced Array object, but I want to make sure I wouldn't break an existing app that uses arrays everywhere if I substituted them with a custom Array class.</p>
| [
{
"answer_id": 145428,
"author": "Bob Fanger",
"author_id": 19165,
"author_profile": "https://Stackoverflow.com/users/19165",
"pm_score": 4,
"selected": true,
"text": "<p>The only problems i can think of are the gettype() and the is_array() functions.\nCheck your code for</p>\n\n<pre><co... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] | Would it be possible to write a class that is virtually indistinguishable from an actual PHP array by implementing all the necessary SPL interfaces? Are they missing anything that would be critical?
I'd like to build a more advanced Array object, but I want to make sure I wouldn't break an existing app that uses arrays everywhere if I substituted them with a custom Array class. | The only problems i can think of are the gettype() and the is\_array() functions.
Check your code for
```
gettype($FakeArray) == 'array'
is_array($FakeArray)
```
Because although you can use the object just like an array, it will still be identified as an object. |
145,480 | <p>Checking the HTML source of a question I see for instance:</p>
<pre><code><a id="comments-link-xxxxx" class="comments-link">add comment</a><noscript>&nbsp;JavaScript is needed to access comments.</noscript>
</code></pre>
<p>And then in the javascript source:</p>
<pre><code>// Setup our click events..
$().ready(function() {
$("a[id^='comments-link-']").click(function() { comments.show($(this).attr("id").substr("comments-link-".length)); });
});
</code></pre>
<p>It seems that all the user click events are binded this way.</p>
<p>The downsides of this approach are obvious for people browsing the site with no javascript but, what are the advantages of adding events dynamically whith javascript over declaring them directly?</p>
| [
{
"answer_id": 145486,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": -1,
"selected": false,
"text": "<p>The only advantage I see is a reduction of the page size, and thus a lower bandwith need.</p>\n\n<p>Edit: As I'm being dow... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4264/"
] | Checking the HTML source of a question I see for instance:
```
<a id="comments-link-xxxxx" class="comments-link">add comment</a><noscript> JavaScript is needed to access comments.</noscript>
```
And then in the javascript source:
```
// Setup our click events..
$().ready(function() {
$("a[id^='comments-link-']").click(function() { comments.show($(this).attr("id").substr("comments-link-".length)); });
});
```
It seems that all the user click events are binded this way.
The downsides of this approach are obvious for people browsing the site with no javascript but, what are the advantages of adding events dynamically whith javascript over declaring them directly? | * You don't have to type the same string over and over again in the HTML (which if nothing else would increase the number of typos to debug)
* You can hand over the HTML/CSS to a designer who need not have any javascript skills
* You have programmatic control over what callbacks are called and when
* It's more elegant because it fits the conceptual separation between layout and behaviour
* It's easier to modify and refactor
On the last point, imagine if you wanted to add a "show comments" icon somewhere else in the template. It'd be very easy to bind the same callback to the icon. |
145,552 | <p>I basically want to do this:</p>
<pre><code>grep 'example.com' www_log > example.com.YYYY-MM-DD-H:i:S.log
</code></pre>
<p>...with of course the filename being <b>example.com.2008-09-27-11:21:30.log</b></p>
<p>I'd then put this in crontab to run daily.</p>
| [
{
"answer_id": 145554,
"author": "Michael Ridley",
"author_id": 4838,
"author_profile": "https://Stackoverflow.com/users/4838",
"pm_score": 4,
"selected": true,
"text": "<p>The verbose method:</p>\n\n<pre><code>grep 'example.com' www_log > `date +example.com.%Y-%m-%d-%H:%M:%S.log`\n</... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I basically want to do this:
```
grep 'example.com' www_log > example.com.YYYY-MM-DD-H:i:S.log
```
...with of course the filename being **example.com.2008-09-27-11:21:30.log**
I'd then put this in crontab to run daily. | The verbose method:
```
grep 'example.com' www_log > `date +example.com.%Y-%m-%d-%H:%M:%S.log`
```
The terse method:
```
grep 'example.com' www_log > `date +example.com.%F-%T.log`
``` |
145,563 | <p>Suppose we have a vector/array in C++ and we wish to count which of these N elements has maximum repetitive occurrences and output the highest count. Which algorithm is best suited for this job.</p>
<p>example:</p>
<pre><code>int a = { 2, 456, 34, 3456, 2, 435, 2, 456, 2}
</code></pre>
<p>the output is 4 because 2 occurs 4 times. That is the maximum number of times 2 occurs.</p>
| [
{
"answer_id": 145576,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 5,
"selected": true,
"text": "<p>Sort the array and then do a quick pass to count each number. The algorithm has O(N*logN) complexity.</p>\n\n<p>Alt... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8786/"
] | Suppose we have a vector/array in C++ and we wish to count which of these N elements has maximum repetitive occurrences and output the highest count. Which algorithm is best suited for this job.
example:
```
int a = { 2, 456, 34, 3456, 2, 435, 2, 456, 2}
```
the output is 4 because 2 occurs 4 times. That is the maximum number of times 2 occurs. | Sort the array and then do a quick pass to count each number. The algorithm has O(N\*logN) complexity.
Alternatively, create a hash table, using the number as the key. Store in the hashtable a counter for each element you've keyed. You'll be able to count all elements in one pass; however, the complexity of the algorithm now depends on the complexity of your hasing function. |
145,607 | <p>I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.</p>
<p>The implementation can be in c# or python.</p>
<p>Thanks.</p>
| [
{
"answer_id": 145609,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 5,
"selected": false,
"text": "<p>Look at <a href=\"http://docs.python.org/lib/module-difflib.html\" rel=\"noreferrer\">difflib</a>. (Python)</p>\n\... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] | I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implement, but it's not.
The implementation can be in c# or python.
Thanks. | In Python, there is [difflib](https://docs.python.org/3/library/difflib.html), as also others have suggested.
`difflib` offers the [SequenceMatcher](https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher) class, which can be used to give you a similarity ratio. Example function:
```
def text_compare(text1, text2, isjunk=None):
return difflib.SequenceMatcher(isjunk, text1, text2).ratio()
``` |
145,617 | <p>The case goes as following:
You have a Boolean property called FullScreenEnabled. You enter some method, and the code within this method is executed iff FullScreenEnabled is true. Which of the 2 approaches below do you use in your everyday programming:</p>
<pre><code> private bool FullScreenEnabled { get; set; }
// Check if FullScreenEnabled is false and return;
private void Case1()
{
if (FullScreenEnabled == false)
{
return;
}
// code to be executed goes here!
}
// Surround the code by an if statement.
private void Case2()
{
if (FullScreenEnabled)
{
// code to be executed goes here!
}
}
</code></pre>
| [
{
"answer_id": 145622,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 0,
"selected": false,
"text": "<p>Neither approach was posted. You should read the <a href=\"https://stackoverflow.com/editing-help\">editing help</a>... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/113670/"
] | The case goes as following:
You have a Boolean property called FullScreenEnabled. You enter some method, and the code within this method is executed iff FullScreenEnabled is true. Which of the 2 approaches below do you use in your everyday programming:
```
private bool FullScreenEnabled { get; set; }
// Check if FullScreenEnabled is false and return;
private void Case1()
{
if (FullScreenEnabled == false)
{
return;
}
// code to be executed goes here!
}
// Surround the code by an if statement.
private void Case2()
{
if (FullScreenEnabled)
{
// code to be executed goes here!
}
}
``` | ```
private void MyMethod(bool arg){
if(arg)
return;
//do stuff
};
```
(for voting) |
145,701 | <p>Could anyone show me a sample about how to use these two commands in Windbg please? I read the document in debugger.chm, but confused. I did search in Google and MSDN, but not find an easy to learn sample.</p>
| [
{
"answer_id": 145782,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "<p>Think in terms of function levels as per the following pseudo-code:</p>\n\n<pre><code> 1 x = 0\n 2 y = 0\n 3 call ... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Could anyone show me a sample about how to use these two commands in Windbg please? I read the document in debugger.chm, but confused. I did search in Google and MSDN, but not find an easy to learn sample. | Think in terms of function levels as per the following pseudo-code:
```
1 x = 0
2 y = 0
3 call 8
4 x = 5
5 y = 7
6 call 8
7 halt
8 print x
9 print y
10 call 12
11 return
12 print x + y
13 print x * y
14 return
```
The commands are basically "run until an event occurs". The event causes the debugger to break (stop execution and await your command).
The "`gu`" command runs until it goes up to the next highest stack level. If you're on lines 8, 9, 10 or 11, you'll end up at 4 or 7 depending on which "`call 8`" has called that code. If you're on lines 12, 13 or 14, you'll break at 11.
Think of this as running until you've moved up the stack. Note that if you first go down, you'll have to come up twice.
The "`pc`" command runs until the next call so, if you're on line 1, it will break at line 3. This is sort of opposite to "`gu`" since it halts when you're trying to go **down** a stack level. |
145,765 | <p>I've a fairly huge .gdbinit (hence not copied here) in my home directory.</p>
<p>Now if I want to debug code inside Xcode I get this error: </p>
<pre><code>Failed to load debugging library at:
/Developer/Applications/Xcode.app/Contents/PlugIns/GDBMIDebugging.xcplugin/Contents/Resources/PBGDBIntrospectionSupport.A.dylib
Custom data formatters are disabled.
Error message was:
0x1005c5 "dlopen(/Developer/Applications/Xcode.app/Contents/PlugIns/GDBMIDebugging.xcplugin/Contents/Resources/PBGDBIntrospectionSupport.A.dylib, 16): image not found"
</code></pre>
<p>Actually - as posted below - the debugging still works in Xcode but the Data Formatters breaks. Moving out .gdbinit OR disabling Data Formatters does get gdb in Xcode back in a working state but it's obviously a pain (Including Data Formatters, in the first case)</p>
<p>Any idea as to which settings in gdbinit could cause this error in Xcode ?</p>
<p>Note from Reply: It's seems (from a google search) that this error might happen when linking against the wxWidgets library. Something that I'm not doing here.</p>
<p>Note: if needed I can provide a copy of my (long) .gdbinit</p>
<p>WIP: I will have a look in details at my .gdbinit to see if I can narrow down the issue</p>
| [
{
"answer_id": 151368,
"author": "Mike G.",
"author_id": 18901,
"author_profile": "https://Stackoverflow.com/users/18901",
"pm_score": 0,
"selected": false,
"text": "<p>Strange... Looking around my Mac, I see that library just fine, and it looks sane.</p>\n\n<p>Have you tried using dtra... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18835/"
] | I've a fairly huge .gdbinit (hence not copied here) in my home directory.
Now if I want to debug code inside Xcode I get this error:
```
Failed to load debugging library at:
/Developer/Applications/Xcode.app/Contents/PlugIns/GDBMIDebugging.xcplugin/Contents/Resources/PBGDBIntrospectionSupport.A.dylib
Custom data formatters are disabled.
Error message was:
0x1005c5 "dlopen(/Developer/Applications/Xcode.app/Contents/PlugIns/GDBMIDebugging.xcplugin/Contents/Resources/PBGDBIntrospectionSupport.A.dylib, 16): image not found"
```
Actually - as posted below - the debugging still works in Xcode but the Data Formatters breaks. Moving out .gdbinit OR disabling Data Formatters does get gdb in Xcode back in a working state but it's obviously a pain (Including Data Formatters, in the first case)
Any idea as to which settings in gdbinit could cause this error in Xcode ?
Note from Reply: It's seems (from a google search) that this error might happen when linking against the wxWidgets library. Something that I'm not doing here.
Note: if needed I can provide a copy of my (long) .gdbinit
WIP: I will have a look in details at my .gdbinit to see if I can narrow down the issue | My "short" answer:
------------------
---
You may have noticed this already, but just in case:
First of all, even when you see that error, (assuming that you click past it and continue), then you should **still be able to use 99% of the debugging features** in Xcode. In other words, that error means that only a very small, specific portion of the debugger is "broken" for a given debugging session. It does ***not*** mean that debugging is completely down and/or impossible for the given program-execution.
Given the above fact, if you simply want to get rid of the error and do not care whether Custom Data Formatters are working or not, then REMOVE the check-mark next to the following menu item:
* Run -> Variables View -> Enable Data Formatters
My "long" answer:
-----------------
---
The developers in my office had been experiencing this very same Xcode error for quite a while until someone discovered that some third party libraries were the cause.
In our case, this error was happening only for projects using wxWidgets. I am not meaning to imply that usage of wxWidgets is the only possible cause. I am only trying to put forth more information that might lead to the right solution for your case.
Also of interest: we (in my office) were getting this error without any use or presence of any .gdbinit file whatsoever.
It turns out that the "property" of wxWidgets that made it trigger this error was related to a "custom/generic" implementation of "dlopen." Prior to Mac OS X 10.3,
dlopen was not provided within the operating system, so apparently some libraries coded their own versions. When such libraries are being used, then apparently the dlopen call that tries to open PBGDBIntrospectionSupport.A.dylib can fail.
[Read through the comments on this sourceforge patch submission to learn even further details about dlopen in 10.3 and beyond.](http://sourceforge.net/tracker/index.php?func=detail&aid=1896410&group_id=9863&atid=309863)
Also, here is another related link:
[Message on the Xcode users mailing list about PBGDBIntrospectionSupport and Custom Data Formatters](http://lists.apple.com/archives/Xcode-users/2008/Mar/msg00240.html) |
145,770 | <p>There is a webpage loaded in the firefox sidebar and another webpage loaded in the main document. Now, how do I ask access the main document object through the Firefox sidebar? An example to do this through Javascript code in the firefox sidebar document to access the main document would be helpful.</p>
<p>Thanks for the answers. I have to refine my question however. The main window has some webpage loaded and the sidebar has a webpage. I want the sidebar window to know what text the user has selected on the main window when a link on the sidebar window is clicked. I know how to get the selected text from a window. Only that the sidebar element adds complexity to the problem that I am not able to surpass.</p>
<p>@PConory:</p>
<p>I like your answer, but when I try it there is an error:</p>
<blockquote>
<p>Error: Permission denied to create wrapper for object of class
UnnamedClass.</p>
</blockquote>
<p>Thanks.</p>
| [
{
"answer_id": 145791,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 1,
"selected": false,
"text": "<p>Accessing the main window from a sidebar is much trickier than going back the other way.</p>\n\n<p>The DOM tree you'll ne... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6488/"
] | There is a webpage loaded in the firefox sidebar and another webpage loaded in the main document. Now, how do I ask access the main document object through the Firefox sidebar? An example to do this through Javascript code in the firefox sidebar document to access the main document would be helpful.
Thanks for the answers. I have to refine my question however. The main window has some webpage loaded and the sidebar has a webpage. I want the sidebar window to know what text the user has selected on the main window when a link on the sidebar window is clicked. I know how to get the selected text from a window. Only that the sidebar element adds complexity to the problem that I am not able to surpass.
@PConory:
I like your answer, but when I try it there is an error:
>
> Error: Permission denied to create wrapper for object of class
> UnnamedClass.
>
>
>
Thanks. | As far as I can tell, you are actually loading a web site in the sidebar (checked the 'Load this bookmark in Sidebar'). If this is the case, AND if the sidebar is opening the main window page. You can use the window.postMessage to communicate between them. But like I said, the sidebar page has to open the main page because you need the window reference in order to post the message.
sidebar.js
```
var newwin = window.open('http://otherpage')
newwin.onload = function()
{
newwin.postMessage('Hey newwin', 'http://sidebar');
};
mainpage.js
window.addEventListener('message',function(e)
{
if(message.origin == 'http://sidebar')
alert('message from sidebar');
},false);
```
Using this you still do not have access to the document, but can communicate between them and script out any changes you want to do.
EDIT: Putting some more thought into it, if you opened the window from the side bar, you would have the DOM for it. var newwin = window.open('blah'); newwin.document making the hole postMessage thing pretty pointless. |
145,803 | <p>I have a little dilemma on how to set up my visual studio builds for multi-targeting.</p>
<p>Background: c# .NET v2.0 with p/invoking into 3rd party 32 bit DLL's, SQL compact v3.5 SP1, with a Setup project.
Right now, the platform target is set to x86 so it can be run on Windows x64.</p>
<p>The 3rd party company has just released 64 bit versions of their DLL's and I want to build a dedicated 64bit program.</p>
<p>This raises some questions which I haven't got the answers to yet.
I want to have the exact same code base.
I must build with references to either the 32bit set of DLL's or 64bit DLL's.
(Both 3rd party and SQL Server Compact)</p>
<p>Can this be solved with 2 new sets of configurations (Debug64 and Release64) ?</p>
<p>Must I create 2 separate setup projects(std. visual studio projects, no Wix or any other utility), or can this be solved within the same .msi?</p>
<p>Any ideas and/or recommendations would be welcomed.</p>
| [
{
"answer_id": 145820,
"author": "mrpbody",
"author_id": 3849,
"author_profile": "https://Stackoverflow.com/users/3849",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure of the total answer to your question - but thought I would point out a comment in the Additional Information sec... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584/"
] | I have a little dilemma on how to set up my visual studio builds for multi-targeting.
Background: c# .NET v2.0 with p/invoking into 3rd party 32 bit DLL's, SQL compact v3.5 SP1, with a Setup project.
Right now, the platform target is set to x86 so it can be run on Windows x64.
The 3rd party company has just released 64 bit versions of their DLL's and I want to build a dedicated 64bit program.
This raises some questions which I haven't got the answers to yet.
I want to have the exact same code base.
I must build with references to either the 32bit set of DLL's or 64bit DLL's.
(Both 3rd party and SQL Server Compact)
Can this be solved with 2 new sets of configurations (Debug64 and Release64) ?
Must I create 2 separate setup projects(std. visual studio projects, no Wix or any other utility), or can this be solved within the same .msi?
Any ideas and/or recommendations would be welcomed. | Yes, you can target both x86 and x64 with the same code base in the same project. In general, things will Just Work if you create the right solution configurations in VS.NET (although P/Invoke to entirely unmanaged DLLs will most likely require some conditional code): the items that I found to require special attention are:
* References to outside managed assemblies with the same name but their own specific bitness (this also applies to COM interop assemblies)
* The MSI package (which, as has already been noted, will need to target either x86 or x64)
* Any custom .NET Installer Class-based actions in your MSI package
The assembly reference issue can't be solved entirely within VS.NET, as it will only allow you to add a reference with a given name to a project once. To work around this, edit your project file manually (in VS, right-click your project file in the Solution Explorer, select Unload Project, then right-click again and select Edit). After adding a reference to, say, the x86 version of an assembly, your project file will contain something like:
```
<Reference Include="Filename, ..., processorArchitecture=x86">
<HintPath>C:\path\to\x86\DLL</HintPath>
</Reference>
```
Wrap that Reference tag inside an ItemGroup tag indicating the solution configuration it applies to, e.g:
```
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<Reference ...>....</Reference>
</ItemGroup>
```
Then, copy and paste the entire ItemGroup tag, and edit it to contain the details of your 64-bit DLL, e.g.:
```
<ItemGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
<Reference Include="Filename, ..., processorArchitecture=AMD64">
<HintPath>C:\path\to\x64\DLL</HintPath>
</Reference>
</ItemGroup>
```
After reloading your project in VS.NET, the Assembly Reference dialog will be a bit confused by these changes, and you may encounter some warnings about assemblies with the wrong target processor, but all your builds will work just fine.
Solving the MSI issue is up next, and unfortunately this *will* require a non-VS.NET tool: I prefer Caphyon's [Advanced Installer](http://www.advancedinstaller.com/) for that purpose, as it pulls off the basic trick involved (create a common MSI, as well as 32-bit and 64-bit specific MSIs, and use an .EXE setup launcher to extract the right version and do the required fixups at runtime) very, very well.
You can probably achieve the same results using other tools or the [Windows Installer XML (WiX) toolset](http://wix.sourceforge.net/), but Advanced Installer makes things so easy (and is quite affordable at that) that I've never really looked at alternatives.
One thing you *may* still require WiX for though, even when using Advanced Installer, is for your .NET Installer Class custom actions. Although it's trivial to specify certain actions that should only run on certain platforms (using the VersionNT64 and NOT VersionNT64 execution conditions, respectively), the built-in AI custom actions will be executed using the 32-bit Framework, even on 64-bit machines.
This may be fixed in a future release, but for now (or when using a different tool to create your MSIs that has the same issue), you can use WiX 3.0's managed custom action support to create action DLLs with the proper bitness that will be executed using the corresponding Framework.
---
Edit: as of version 8.1.2, Advanced Installer correctly supports 64-bit custom actions. Since my original answer, its price has increased quite a bit, unfortunately, even though it's still extremely good value when compared to InstallShield and its ilk...
---
Edit: If your DLLs are registered in the GAC, you can also use the standard reference tags this way (SQLite as an example):
```
<ItemGroup Condition="'$(Platform)' == 'x86'">
<Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=x86" />
</ItemGroup>
<ItemGroup Condition="'$(Platform)' == 'x64'">
<Reference Include="System.Data.SQLite, Version=1.0.80.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=AMD64" />
</ItemGroup>
```
The condition is also reduced down to all build types, release or debug, and just specifies the processor architecture. |
145,814 | <p>Following techniques from 'Modern C++ Design', I am implementing a persistence library with various compile-time optimisations. I would like the ability to dispatch a function to a templated member variable if that variable derives from a given class:</p>
<pre><code>template<class T, template <class> class Manager = DefaultManager> class Data
{
private:
T *data_;
public:
void Dispatch()
{
if(SUPERSUBCLASS(Container, T))
{
data_->IKnowThisIsHere();
}
else
{
Manager<T>::SomeGenericFunction(data_);
}
}
}
</code></pre>
<p>Where SUPERSUBCLASS is a compile-time macro to determine object inheritance. Of course, this fails in all cases where T does to inherit from Container (or T is an intrinsic type etc etc) because the compiler rightly complains that IKnowThisIsHere() is not a data member, even though this code path will never be followed, as shown here after preprocessing with T = int:</p>
<pre><code>private:
int *data_;
public:
void Dispatch()
{
if(false)
{
data_->IKnowThisIsHere();
</code></pre>
<p>Compiler clearly complains at this code, even though it will never get executed. A suggestion of using a dynamic_cast also does not work, as again a type conversion is attempted at compile time that is not possible (for example with T=double, std::string):</p>
<pre><code>void Dispatch()
{
if(false)
{
dynamic_cast<Container*>(data_)->IKnowThisIsHere();
error: cannot dynamic_cast '((const Data<double, DefaultManager>*)this)->Data<double, DefaultManager>::data_' (of type 'double* const') to type 'class Container*' (source is not a pointer to class)
error: cannot dynamic_cast '((const Data<std::string, DefaultManager>*)this)->Da<sttad::string, DefaultManager>::data_' (of type 'struct std::string* const') to type 'class Container*' (source type is not polymorphic)
</code></pre>
<p>I really need to emulate (or indeed persuade!) having the compiler emit one set of code if T does inherit from Container, and another if it does not.</p>
<p>Any suggestions?</p>
| [
{
"answer_id": 145816,
"author": "David Pierre",
"author_id": 18296,
"author_profile": "https://Stackoverflow.com/users/18296",
"pm_score": 1,
"selected": false,
"text": "<p>Boost traits has something for that : <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/type_traits/doc/html/boo... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23167/"
] | Following techniques from 'Modern C++ Design', I am implementing a persistence library with various compile-time optimisations. I would like the ability to dispatch a function to a templated member variable if that variable derives from a given class:
```
template<class T, template <class> class Manager = DefaultManager> class Data
{
private:
T *data_;
public:
void Dispatch()
{
if(SUPERSUBCLASS(Container, T))
{
data_->IKnowThisIsHere();
}
else
{
Manager<T>::SomeGenericFunction(data_);
}
}
}
```
Where SUPERSUBCLASS is a compile-time macro to determine object inheritance. Of course, this fails in all cases where T does to inherit from Container (or T is an intrinsic type etc etc) because the compiler rightly complains that IKnowThisIsHere() is not a data member, even though this code path will never be followed, as shown here after preprocessing with T = int:
```
private:
int *data_;
public:
void Dispatch()
{
if(false)
{
data_->IKnowThisIsHere();
```
Compiler clearly complains at this code, even though it will never get executed. A suggestion of using a dynamic\_cast also does not work, as again a type conversion is attempted at compile time that is not possible (for example with T=double, std::string):
```
void Dispatch()
{
if(false)
{
dynamic_cast<Container*>(data_)->IKnowThisIsHere();
error: cannot dynamic_cast '((const Data<double, DefaultManager>*)this)->Data<double, DefaultManager>::data_' (of type 'double* const') to type 'class Container*' (source is not a pointer to class)
error: cannot dynamic_cast '((const Data<std::string, DefaultManager>*)this)->Da<sttad::string, DefaultManager>::data_' (of type 'struct std::string* const') to type 'class Container*' (source type is not polymorphic)
```
I really need to emulate (or indeed persuade!) having the compiler emit one set of code if T does inherit from Container, and another if it does not.
Any suggestions? | Overloading can be useful to implement compile-time dispatching, as proposed by *Alexandrescu* in his book "Modern C++ Design".
You can use a class like this to transform at compile time a boolean or integer into a type:
```
template <bool n>
struct int2type
{ enum { value = n}; };
```
The following source code shows a possible application:
```
#include <iostream>
#define MACRO() true // <- macro used to dispatch
template <bool n>
struct int2type
{ enum { value = n }; };
void method(int2type<false>)
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
void method(int2type<true>)
{ std::cout << __PRETTY_FUNCTION__ << std::endl; }
int
main(int argc, char *argv[])
{
// MACRO() determines which function to call
//
method( int2type<MACRO()>());
return 0;
}
```
Of course what really makes the job is the MACRO() or a better implementation as a metafunction |
145,838 | <p>What is the advantages/disadvantages of using inline functions in C++? I see that it only increases performance for the code that the compiler outputs, but with today's optimized compilers, fast CPUs, huge memory etc. (not like in the 1980< where memory was scarce and everything had to fit in 100KB of memory) what advantages do they really have today?</p>
| [
{
"answer_id": 145841,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 8,
"selected": true,
"text": "<p>Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the ... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22040/"
] | What is the advantages/disadvantages of using inline functions in C++? I see that it only increases performance for the code that the compiler outputs, but with today's optimized compilers, fast CPUs, huge memory etc. (not like in the 1980< where memory was scarce and everything had to fit in 100KB of memory) what advantages do they really have today? | Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger.
Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough for some people.
Marking something inline does not give you a guarantee that it will be inline. It's just a suggestion to the compiler. Sometimes it's not possible such as when you have a virtual function, or when there is recursion involved. And sometimes the compiler just chooses not to use it.
I could see a situation like this making a detectable difference:
```
inline int aplusb_pow2(int a, int b) {
return (a + b)*(a + b) ;
}
for(int a = 0; a < 900000; ++a)
for(int b = 0; b < 900000; ++b)
aplusb_pow2(a, b);
``` |
145,856 | <p>I have an array of integers:</p>
<pre><code>int[] number = new int[] { 2,3,6,7 };
</code></pre>
<p>What is the easiest way of converting these into a single string where the numbers are separated by a character (like: <code>"2,3,6,7"</code>)?</p>
<p>I'm using C# and .NET 3.5.</p>
| [
{
"answer_id": 145864,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 8,
"selected": true,
"text": "<pre><code>var ints = new int[] {1, 2, 3, 4, 5};\nvar result = string.Join(",", ints.Select(x => x.ToString()).ToArr... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/298/"
] | I have an array of integers:
```
int[] number = new int[] { 2,3,6,7 };
```
What is the easiest way of converting these into a single string where the numbers are separated by a character (like: `"2,3,6,7"`)?
I'm using C# and .NET 3.5. | ```
var ints = new int[] {1, 2, 3, 4, 5};
var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());
Console.WriteLine(result); // prints "1,2,3,4,5"
```
As of (at least) .NET 4.5,
```
var result = string.Join(",", ints.Select(x => x.ToString()).ToArray());
```
is equivalent to:
```
var result = string.Join(",", ints);
```
I see several solutions advertise usage of StringBuilder. Someone complains that the Join method should take an IEnumerable argument.
I'm going to disappoint you :) String.Join requires an array for a single reason - performance. The Join method needs to know the size of the data to effectively preallocate the necessary amount of memory.
Here is a part of the internal implementation of String.Join method:
```
// length computed from length of items in input array and length of separator
string str = FastAllocateString(length);
fixed (char* chRef = &str.m_firstChar) // note than we use direct memory access here
{
UnSafeCharBuffer buffer = new UnSafeCharBuffer(chRef, length);
buffer.AppendString(value[startIndex]);
for (int j = startIndex + 1; j <= num2; j++)
{
buffer.AppendString(separator);
buffer.AppendString(value[j]);
}
}
``` |
145,900 | <p>I have an install that upgrades a previous version of an app if it exits. I'd like to skip certain actions when the install is upgrade mode. How can I determine if the install is running in upgrade mode vs. first time install mode?</p>
<p>I'm using Wise Installer, but I don't think that matters. I'm assuming that Windows Installer has a property that is set when the installer is in upgrade mode. I just can't seem to find it. If the property exists, I'm assuming I could use it in a conditional statement.</p>
| [
{
"answer_id": 145962,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": -1,
"selected": false,
"text": "<p>I am not sure I understood your question.<br>\nIf you are writting the install script yourself, the best way, on Window... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22984/"
] | I have an install that upgrades a previous version of an app if it exits. I'd like to skip certain actions when the install is upgrade mode. How can I determine if the install is running in upgrade mode vs. first time install mode?
I'm using Wise Installer, but I don't think that matters. I'm assuming that Windows Installer has a property that is set when the installer is in upgrade mode. I just can't seem to find it. If the property exists, I'm assuming I could use it in a conditional statement. | Can you elaborate what kind of tools are you using to create this installer?
I use Windows Installer XML([WIX](http://wix.sourceforge.net/)). In WIX you could do something like this:
```
<!-- Property definitions -->
<?define SkuName = "MyCoolApp"?>
<?define ProductName="My Cool Application"?>
<?define Manufacturer="Acme Inc."?>
<?define Copyright="Copyright © Acme Inc. All rights reserved."?>
<?define ProductVersion="1.1.0.0"?>
<?define RTMProductVersion="1.0.0.0" ?>
<?define UpgradeCode="{EF9D543D-9BDA-47F9-A6B4-D1845A2EBD49}"?>
<?define ProductCode="{27EA5747-9CE3-3F83-96C3-B2F5212CD1A6}"?>
<?define Language="1033"?>
<?define CodePage="1252"?>
<?define InstallerVersion="200"?>
```
And define upgrade options:
```
<Upgrade Id="$(var.UpgradeCode)">
<UpgradeVersion Minimum="$(var.ProductVersion)"
IncludeMinimum="no"
OnlyDetect="yes"
Language="$(var.Language)"
Property="NEWPRODUCTFOUND" />
<UpgradeVersion Minimum="$(var.RTMProductVersion)"
IncludeMinimum="yes"
Maximum="$(var.ProductVersion)"
IgnoreRemoveFailure="no"
IncludeMaximum="no"
Language="$(var.Language)"
Property="OLDIEFOUND" />
</Upgrade>
```
Then further you could use `OLDIEFOUND` and `NEWPRODUCTFOUND` properties depending on what you want to do:
```
<!-- Define custom actions -->
<CustomAction Id="ActivateProduct"
Directory='MyCoolAppFolder'
ExeCommand='"[MyCoolAppFolder]activateme.exe"'
Return='asyncNoWait'
Execute='deferred'/>
<CustomAction Id="NoUpgrade4U"
Error="A newer version of MyCoolApp is already installed."/>
```
The above defined actions have to be define in `InstallExcecuteSequence`
```
<InstallExecuteSequence>
<Custom Action="NoUpgrade4U"
After="FindRelatedProducts">NEWPRODUCTFOUND</Custom>
<Custom Action="ActivateProduct"
OnExit='success'>NOT OLDIEFOUND</Custom>
</InstallExecuteSequence>
``` |
145,922 | <p>I've managed to get a memory 'leak' in a java application I'm developing. When running my JUnit test suite I randomly get out of memory exceptions (java.lang.OutOfMemoryError).</p>
<p>What tools can I use to examine the heap of my java application to see what's using up all my heap so that I can work out what's keeping references to objects which should be able to be garbage collected.</p>
| [
{
"answer_id": 145925,
"author": "Free Wildebeest",
"author_id": 1849,
"author_profile": "https://Stackoverflow.com/users/1849",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using a system which supports GTK you could try using <a href=\"http://www.khelekore.org/jmp/\" rel=\"n... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1849/"
] | I've managed to get a memory 'leak' in a java application I'm developing. When running my JUnit test suite I randomly get out of memory exceptions (java.lang.OutOfMemoryError).
What tools can I use to examine the heap of my java application to see what's using up all my heap so that I can work out what's keeping references to objects which should be able to be garbage collected. | VisualVM is included in the most recent releases of Java. You can use this to create a heap dump, and look at the objects in it.
Alternatively, you can also create a heapdump commandine using jmap (in your jdk/bin dir):
```
jmap -dump:format=b,file=heap.bin <pid>
```
You can even use this to get a quick histogram of all objects
```
jmap -histo <pid>
```
I can recommend Eclipse Memory Analyzer (<http://eclipse.org/mat>) for advanced analysis of heap dumps. It lets you find out exactly why a certain object or set of objects is alive. Here's a blog entry showing you what Memory Analyzer can do: <http://dev.eclipse.org/blogs/memoryanalyzer/2008/05/27/automated-heap-dump-analysis-finding-memory-leaks-with-one-click/> |
145,969 | <p>I've got a sections table, and an items table.</p>
<p>The problem is each item may be in one or more sections, so a simple 'section_id' for each item won't work, and sql doesn't have a way to store arrays where I can do say "WHERE 5 in section_ids"...</p>
<p>I've considered storing the list of ids as a comma separated string, the problem is I see no way to then check if an item is in a given section from the sql query. The only option I see here is to select the entire table, and parse the strings in php. Needless to say that with 1000's of items this isn't a good idea.</p>
<p>Is there a better way to 'link' an item with multiple sections, and be able to easily select all items for a given section id?</p>
| [
{
"answer_id": 145985,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 0,
"selected": false,
"text": "<p>You need a third table itemsPerSection with a primary key composed of both itemid and sectionid, this way you can hav... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6266/"
] | I've got a sections table, and an items table.
The problem is each item may be in one or more sections, so a simple 'section\_id' for each item won't work, and sql doesn't have a way to store arrays where I can do say "WHERE 5 in section\_ids"...
I've considered storing the list of ids as a comma separated string, the problem is I see no way to then check if an item is in a given section from the sql query. The only option I see here is to select the entire table, and parse the strings in php. Needless to say that with 1000's of items this isn't a good idea.
Is there a better way to 'link' an item with multiple sections, and be able to easily select all items for a given section id? | You need an intermediate lookup table:
```
CREATE TABLE item_in_section (item_id int, section_id int)
```
(I'm guessing about your key types, use whatever ones are appropriate).
To find items in a section:
```
SELECT item.* from item, item_in_section WHERE item_in_section.item_id = item.item_id AND item_in_section.section_id = X GROUP BY item_id
```
To find sections an item belongs to
```
SELECT section.* from section, item_in_section WHERE item_in_section.section_id = section.section_id AND item_in_section.item_id = Y GROUP BY section_id
``` |
145,972 | <p>I need to setup LookAndFeel Files in JDK 1.6.
I have two files:</p>
<ol>
<li><p>napkinlaf-swingset2.jar</p></li>
<li><p>napkinlaf.jar</p></li>
</ol>
<p>How can I set this up and use it?</p>
<p>I would like a GTK look and feel OR Qt look and feel, Are they available?</p>
| [
{
"answer_id": 145996,
"author": "Tom",
"author_id": 22850,
"author_profile": "https://Stackoverflow.com/users/22850",
"pm_score": 3,
"selected": false,
"text": "<p>This page explains how the work with Look&Feels:\n<a href=\"http://java.sun.com/docs/books/tutorial/uiswing/lookandfeel... | 2008/09/28 | [
"https://Stackoverflow.com/questions/145972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22634/"
] | I need to setup LookAndFeel Files in JDK 1.6.
I have two files:
1. napkinlaf-swingset2.jar
2. napkinlaf.jar
How can I set this up and use it?
I would like a GTK look and feel OR Qt look and feel, Are they available? | The class name for Naplin is `net.sourceforge.napkinlaf.NapkinLookAndFeel`. So to set it as default on the command line, use:
```
java -Dswing.defaultlaf=net.sourceforge.napkinlaf.NapkinLookAndFeel
```
To install it add `napkinlaf.jar` to the `lib/ext` direction and the lines:
```
swing.installedlafs=napkin
swing.installedlaf.napkin.name=Napkin
swing.installedlaf.napkin.class=net.sourceforge.napkinlaf.NapkinLookAndFeel
```
to `lib/swing.properties` within your Java installation (you'll probably have to create the file).
See the [Napkin wiki page](http://wiki.java.net/bin/view/Projects/NapkinLAF) |
146,081 | <p>I'm writing an interactive function that I'd like to have remember the last argument the user supplied and use it as the default. </p>
<pre><code>(defun run-rake (param)
(interactive "sTask: ")
(shell-command (format "rake %s" task)))
</code></pre>
<p>The first time the function is invoked I want it to remember the argument the user supplied so that the next time they invoke the function they can just press enter and it will use the value they supplied the previous time.</p>
<p>I can't seem to find this in the documentation - how do you do this in elisp?</p>
| [
{
"answer_id": 146139,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 0,
"selected": false,
"text": "<p>I figured out how to do this manually using a defvar (global), but this feels like the kind of thing that should al... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19784/"
] | I'm writing an interactive function that I'd like to have remember the last argument the user supplied and use it as the default.
```
(defun run-rake (param)
(interactive "sTask: ")
(shell-command (format "rake %s" task)))
```
The first time the function is invoked I want it to remember the argument the user supplied so that the next time they invoke the function they can just press enter and it will use the value they supplied the previous time.
I can't seem to find this in the documentation - how do you do this in elisp? | You can see how the `compile` command does this. Bring up the help text for the compile command with `C-h f compile`, move the cursor over the name of the file that contains the function, then hit `RETURN`. This will bring up the source file for `compile`.
Basically, there's a dynamic/global variable `compile-command` that holds the last compile command. Emacs is a single-user, single-threaded system, so there's really no need for much more. Also keep in mind that Elisp is a very old school Lisp, and variables have dynamic (call stack), not lexical, scope. In this kind of system it is natural to:
```
(let ((compile-command "gcc -o foo foo.c frobnicate.c"))
...
(compile)
...)
```
Speaking of the `compile` command, have you tried using it instead of your own `run-rake` function? |
146,106 | <p>This question is about organizing the actual CSS directives themselves within a .css file. When developing a new page or set of pages, I usually just add directives by hand to the .css file, trying to refactor when I can. After some time, I have hundreds (or thousands) of lines and it can get difficult to find what I need when tweaking the layout.</p>
<p>Does anyone have advice for how to organize the directives?</p>
<ul>
<li>Should I try to organize top-down, mimicking the DOM?</li>
<li>Should I organize functionally, putting directives for elements that support the same parts of the UI together?</li>
<li>Should I just sort everything alphabetically by selector?</li>
<li>Some combination of these approaches?</li>
</ul>
<p>Also, is there a limit to how much CSS I should keep in one file before it might be a good idea to break it off into separate files? Say, 1000 lines? Or is it always a good idea to keep the whole thing in one place?</p>
<p>Related Question: <a href="http://web.archive.org/web/20170119044450/http://stackoverflow.com:80/questions/72911/whats-the-best-way-to-organize-css-rules" rel="noreferrer">What's the best way to organize CSS rules?</a></p>
| [
{
"answer_id": 146115,
"author": "Nick Sergeant",
"author_id": 22468,
"author_profile": "https://Stackoverflow.com/users/22468",
"pm_score": 2,
"selected": false,
"text": "<p>I've tried a bunch of different strategies, and I always come back to this style:</p>\n\n<pre><code>.class {borde... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
] | This question is about organizing the actual CSS directives themselves within a .css file. When developing a new page or set of pages, I usually just add directives by hand to the .css file, trying to refactor when I can. After some time, I have hundreds (or thousands) of lines and it can get difficult to find what I need when tweaking the layout.
Does anyone have advice for how to organize the directives?
* Should I try to organize top-down, mimicking the DOM?
* Should I organize functionally, putting directives for elements that support the same parts of the UI together?
* Should I just sort everything alphabetically by selector?
* Some combination of these approaches?
Also, is there a limit to how much CSS I should keep in one file before it might be a good idea to break it off into separate files? Say, 1000 lines? Or is it always a good idea to keep the whole thing in one place?
Related Question: [What's the best way to organize CSS rules?](http://web.archive.org/web/20170119044450/http://stackoverflow.com:80/questions/72911/whats-the-best-way-to-organize-css-rules) | Have a look at these three slideshare presentations to start:
* [Beautiful Maintainable CSS](http://www.slideshare.net/lachlanhardy/beautiful-maintainable-css)
* [Maintainable CSS](http://www.slideshare.net/stephenhay/maintainable-css-presentation)
* [Efficient, maintainable, modular CSS](http://www.slideshare.net/maxdesign/efficient-maintainable-css-presentation)
Firstly, and most importantly, document your CSS. Whatever method you use to organize your CSS, be consistent and document it. Describe at the top of each file what is in that file, perhaps providing a table of contents, perhaps referencing easy to search for unique tags so you jump to those sections easily in your editor.
If you want to split up your CSS into multiple files, by all means do so. Oli already mentioned that the extra HTTP requests can be expensive, but you can have the best of both worlds. Use a build script of some sort to publish your well-documented, modular CSS to a compressed, single CSS file. The [YUI Compressor](https://yui.github.io/yuicompressor/) can help with the compression.
In contrast with what others have said so far, I prefer to write each property on a separate line, and use indentation to group related rules. E.g. following Oli's example:
```css
#content {
/* css */
}
#content div {
/* css */
}
#content span {
/* css */
}
#content etc {
/* css */
}
#header {
/* css */
}
#header etc {
/* css */
}
```
That makes it easy to follow the file structure, especially with enough whitespace and clearly marked comments between groups, (though not as easy to skim through quickly) and easy to edit (since you don't have to wade through single long lines of CSS for each rule).
Understand and use the [cascade](http://reference.sitepoint.com/css/cascade) and [specificity](http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html) (so sorting your selectors alphabetically is right out).
Whether I split up my CSS into multiple files, and in what files depends on the size and complexity of the site and the CSS. I always at least have a [`reset.css`](https://meyerweb.com/eric/tools/css/reset/). That tends to be accompanied by `layout.css` for general page layout, `nav.css` if the site navigation menus get a little complicated and `forms.css` if I've got plenty of CSS to style my forms. Other than that I'm still figuring it out myself too. I might have `colors.css` and `type.css/fonts.css` to split off the colors/graphics and typography, `base.css` to provide a complete base style for all HTML tags... |
146,134 | <p>I need a robust and simple way to remove illegal path and file characters from a simple string. I've used the below code but it doesn't seem to do anything, what am I missing?</p>
<pre><code>using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string illegal = "\"M<>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?";
illegal = illegal.Trim(Path.GetInvalidFileNameChars());
illegal = illegal.Trim(Path.GetInvalidPathChars());
Console.WriteLine(illegal);
Console.ReadLine();
}
}
}
</code></pre>
| [
{
"answer_id": 146141,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 4,
"selected": false,
"text": "<p>For starters, <a href=\"http://msdn.microsoft.com/en-us/library/system.string.trim.aspx\" rel=\"nofollow noreferrer\">Tr... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
] | I need a robust and simple way to remove illegal path and file characters from a simple string. I've used the below code but it doesn't seem to do anything, what am I missing?
```
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string illegal = "\"M<>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?";
illegal = illegal.Trim(Path.GetInvalidFileNameChars());
illegal = illegal.Trim(Path.GetInvalidPathChars());
Console.WriteLine(illegal);
Console.ReadLine();
}
}
}
``` | Try something like this instead;
```
string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
foreach (char c in invalid)
{
illegal = illegal.Replace(c.ToString(), "");
}
```
But I have to agree with the comments, I'd probably try to deal with the source of the illegal paths, rather than try to mangle an illegal path into a legitimate but probably unintended one.
Edit: Or a potentially 'better' solution, using Regex's.
```
string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
illegal = r.Replace(illegal, "");
```
Still, the question begs to be asked, why you're doing this in the first place. |
146,140 | <p>I have an OpenGL RGBA texture and I blit another RGBA texture onto it using a framebuffer object. The problem is that if I use the usual blend functions with
<code>glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA),</code>
the resulting blit causes the destination texture alpha to change, making it slightly transparent for places where alpha previously was 1. I would like the destination surface alpha never to change, but otherwise the effect on RGB values should be exactly like with <code>GL_SRC_ALPHA</code> and <code>GL_ONE_MINUS_SRC_ALPHA</code>. So the blend factor functions should be (As,As,As,0) and (1-As,1-As,1-As,1). How can I achieve that?</p>
| [
{
"answer_id": 146151,
"author": "Jay Conrod",
"author_id": 1891,
"author_profile": "https://Stackoverflow.com/users/1891",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you could use <a href=\"http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/colormask.html\"... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have an OpenGL RGBA texture and I blit another RGBA texture onto it using a framebuffer object. The problem is that if I use the usual blend functions with
`glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA),`
the resulting blit causes the destination texture alpha to change, making it slightly transparent for places where alpha previously was 1. I would like the destination surface alpha never to change, but otherwise the effect on RGB values should be exactly like with `GL_SRC_ALPHA` and `GL_ONE_MINUS_SRC_ALPHA`. So the blend factor functions should be (As,As,As,0) and (1-As,1-As,1-As,1). How can I achieve that? | You can set the blend-modes for RGB and alpha to different equations:
```
void glBlendFuncSeparate(
GLenum srcRGB,
GLenum dstRGB,
GLenum srcAlpha,
GLenum dstAlpha);
```
In your case you want to use the following enums:
```
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
```
Note that you may have to import the glBlendFuncSeparate function as an extension. It's safe to do so though. The function is around for a very long time. It's part of OpenGL 1.4
Another way to do the same is to disable writing to the alpha-channel using glColorMask:
```
void glColorMask( GLboolean red,
GLboolean green,
GLboolean blue,
GLboolean alpha )
```
It **could** be a lot slower than glBlendFuncSeparate because OpenGL-drivers optimize the most commonly used functions and glColorMask is one of the rarely used OpenGL-functions.
If you're unlucky you may even end up with software-rendering emulation by calling oddball functions :-) |
146,146 | <p>This is what my browser sent, when logging into some site:</p>
<pre>
POST http://www.some.site/login.php HTTP/1.0
User-Agent: Opera/8.26 (X2000; Linux i686; Z; en)
Host: www.some.site
Accept: text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1
Accept-Language: en-US,en;q=0.9
Accept-Charset: iso-8859-1, utf-8, utf-16, *;q=0.1
Accept-Encoding: deflate, gzip, x-gzip, identity, *;q=0
Referer: http://www.some.site/
Proxy-Connection: close
Content-Length: 123
Content-Type: application/x-www-form-urlencoded
lots_of_stuff=here&e2ad811=<b>my_login_name</b>&e327696=<b>my_password</b>&lots_of_stuff=here
</pre>
<p>Can I state that anyone can sniff my login name and password for that site?
Maybe just on my LAN?
<br/>
If so (even only on LAN ) then I'm shocked. I thought using</p>
<pre><input type="password"></pre>
<p>did something more than make all characters look like ' * '</p>
<p>p.s. If it matters I played with netcat (on linux) and made connection<br/>
browser <=> netcat (loged here) <=> proxy <=> remote_site</p>
| [
{
"answer_id": 146149,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, your credentials are passed in cleartext, anyone who can hear your network traffic can sniff them.</p>\n"
... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15453/"
] | This is what my browser sent, when logging into some site:
```
POST http://www.some.site/login.php HTTP/1.0
User-Agent: Opera/8.26 (X2000; Linux i686; Z; en)
Host: www.some.site
Accept: text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1
Accept-Language: en-US,en;q=0.9
Accept-Charset: iso-8859-1, utf-8, utf-16, *;q=0.1
Accept-Encoding: deflate, gzip, x-gzip, identity, *;q=0
Referer: http://www.some.site/
Proxy-Connection: close
Content-Length: 123
Content-Type: application/x-www-form-urlencoded
lots_of_stuff=here&e2ad811=**my\_login\_name**&e327696=**my\_password**&lots_of_stuff=here
```
Can I state that anyone can sniff my login name and password for that site?
Maybe just on my LAN?
If so (even only on LAN ) then I'm shocked. I thought using
```
<input type="password">
```
did something more than make all characters look like ' \* '
p.s. If it matters I played with netcat (on linux) and made connection
browser <=> netcat (loged here) <=> proxy <=> remote\_site | Every data sent trought a http connection can be seen by someone in your route to the server (man in the middle attack).
type="password" only hides the character on-screen, and even other programs on your computer can read the data.
The only way to protect the data is to send it trought SSL (HTTPS instead of HTTP) |
146,159 | <p>From time to time I read that Fortran is or can be faster then C for heavy calculations. Is that really true? I must admit that I hardly know Fortran, but the Fortran code I have seen so far did not show that the language has features that C doesn't have.</p>
<p>If it is true, please tell me why. Please don't tell me what languages or libs are good for number crunching, I don't intend to write an app or lib to do that, I'm just curious.</p>
| [
{
"answer_id": 146172,
"author": "Kluge",
"author_id": 8752,
"author_profile": "https://Stackoverflow.com/users/8752",
"pm_score": 4,
"selected": false,
"text": "<p>Any speed differences between Fortran and C will be more a function of compiler optimizations and the underlying math libra... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18687/"
] | From time to time I read that Fortran is or can be faster then C for heavy calculations. Is that really true? I must admit that I hardly know Fortran, but the Fortran code I have seen so far did not show that the language has features that C doesn't have.
If it is true, please tell me why. Please don't tell me what languages or libs are good for number crunching, I don't intend to write an app or lib to do that, I'm just curious. | The languages have similar feature-sets. The performance difference comes from the fact that Fortran says aliasing is not allowed, unless an EQUIVALENCE statement is used. Any code that has aliasing is not valid Fortran, but it is up to the programmer and not the compiler to detect these errors. Thus Fortran compilers ignore possible aliasing of memory pointers and allow them to generate more efficient code. Take a look at this little example in C:
```
void transform (float *output, float const * input, float const * matrix, int *n)
{
int i;
for (i=0; i<*n; i++)
{
float x = input[i*2+0];
float y = input[i*2+1];
output[i*2+0] = matrix[0] * x + matrix[1] * y;
output[i*2+1] = matrix[2] * x + matrix[3] * y;
}
}
```
This function would run slower than the Fortran counterpart after optimization. Why so? If you write values into the output array, you may change the values of matrix. After all, the pointers could overlap and point to the same chunk of memory (including the `int` pointer!). The C compiler is forced to reload the four matrix values from memory for all computations.
In Fortran the compiler can load the matrix values once and store them in registers. It can do so because the Fortran compiler assumes pointers/arrays do not overlap in memory.
Fortunately, the [`restrict`](https://en.wikipedia.org/wiki/Restrict) keyword and strict-aliasing have been introduced to the C99 standard to address this problem. It's well supported in most C++ compilers these days as well. The keyword allows you to give the compiler a hint that the programmer promises that a pointer does not alias with any other pointer. The strict-aliasing means that the programmer promises that pointers of different type will never overlap, for example a `double*` will not overlap with an `int*` (with the specific exception that `char*` and `void*` can overlap with anything).
If you use them you will get the same speed from C and Fortran. However, the ability to use the `restrict` keyword only with performance critical functions means that C (and C++) programs are much safer and easier to write. For example, consider the invalid Fortran code: `CALL TRANSFORM(A(1, 30), A(2, 31), A(3, 32), 30)`, which most Fortran compilers will happily compile without any warning but introduces a bug that only shows up on some compilers, on some hardware and with some optimization options. |
146,204 | <p>Are there any dictionary classes in the .NET base class library which allow duplicate keys to be used? The only solution I've found is to create, for example, a class like:</p>
<pre><code>Dictionary<string, List<object>>
</code></pre>
<p>But this is quite irritating to actually use. In Java, I believe a MultiMap accomplishes this, but cannot find an analog in .NET.</p>
| [
{
"answer_id": 146213,
"author": "MADMap",
"author_id": 17558,
"author_profile": "https://Stackoverflow.com/users/17558",
"pm_score": 4,
"selected": false,
"text": "<p>I think something like <code>List<KeyValuePair<object, object>></code> would do the Job.</p>\n"
},
{
... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Are there any dictionary classes in the .NET base class library which allow duplicate keys to be used? The only solution I've found is to create, for example, a class like:
```
Dictionary<string, List<object>>
```
But this is quite irritating to actually use. In Java, I believe a MultiMap accomplishes this, but cannot find an analog in .NET. | If you're using .NET 3.5, use the [`Lookup`](http://msdn.microsoft.com/en-us/library/bb460184.aspx) class.
EDIT: You generally create a `Lookup` using [`Enumerable.ToLookup`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.tolookup.aspx). This does assume that you don't need to change it afterwards - but I typically find that's good enough.
If that *doesn't* work for you, I don't think there's anything in the framework which will help - and using the dictionary is as good as it gets :( |
146,212 | <p>I have a table of "items", and a table of "itemkeywords".
When a user searches for a keyword, I want to give him one page of results plus the total number of results.</p>
<p>What I'm doing currently is (for a user that searches "a b c": </p>
<pre><code>SELECT DISTINCT {fields I want} FROM itemkeywords JOIN items
WHERE (keyword = 'a' or keyword='b' or keyword='c'
ORDER BY "my magic criteria"
LIMIT 20.10
</code></pre>
<p>and then I do the same query with a count</p>
<pre><code>SELECT COUNT(*) FROM itemkeywords JOIN items
WHERE (keyword = 'a' or keyword='b' or keyword='c'
</code></pre>
<p>This may get to get a fairly large table, and I consider this solution suck enormously...<br>
But I can't think of anything much better.</p>
<p>The obvious alternative to avoid hitting MySQL twice , which is doing the first query only, without the LIMIT clause, and then navigating to the correct record to show the corresponding page, and then to the end of the recordset in order to count the result seems even worse...</p>
<p>Any ideas?</p>
<p>NOTE: I'm using ASP.Net and MySQL, not PHP</p>
| [
{
"answer_id": 146229,
"author": "ysth",
"author_id": 17389,
"author_profile": "https://Stackoverflow.com/users/17389",
"pm_score": 4,
"selected": true,
"text": "<p>Add SQL_CALC_FOUND_ROWS after the select in your limited select, then do a \"SELECT FOUND_ROWS()\" after the first select i... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] | I have a table of "items", and a table of "itemkeywords".
When a user searches for a keyword, I want to give him one page of results plus the total number of results.
What I'm doing currently is (for a user that searches "a b c":
```
SELECT DISTINCT {fields I want} FROM itemkeywords JOIN items
WHERE (keyword = 'a' or keyword='b' or keyword='c'
ORDER BY "my magic criteria"
LIMIT 20.10
```
and then I do the same query with a count
```
SELECT COUNT(*) FROM itemkeywords JOIN items
WHERE (keyword = 'a' or keyword='b' or keyword='c'
```
This may get to get a fairly large table, and I consider this solution suck enormously...
But I can't think of anything much better.
The obvious alternative to avoid hitting MySQL twice , which is doing the first query only, without the LIMIT clause, and then navigating to the correct record to show the corresponding page, and then to the end of the recordset in order to count the result seems even worse...
Any ideas?
NOTE: I'm using ASP.Net and MySQL, not PHP | Add SQL\_CALC\_FOUND\_ROWS after the select in your limited select, then do a "SELECT FOUND\_ROWS()" after the first select is finished.
Example:
```
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
-> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();
``` |
146,269 | <p>I need to change the DataTemplate for items in a ListBox depending on whether the item is selected or not (displaying different/more information when selected).</p>
<p>I don't get a GotFocus/LostFocus event on the top-most element in the DataTemplate (a StackPanel) when clicking the ListBox item in question (only through tabbing), and I'm out of ideas.</p>
| [
{
"answer_id": 146423,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 9,
"selected": true,
"text": "<p>The easiest way to do this is to supply a template for the \"ItemContainerStyle\" and NOT the \"ItemTemplate\" property. I... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23222/"
] | I need to change the DataTemplate for items in a ListBox depending on whether the item is selected or not (displaying different/more information when selected).
I don't get a GotFocus/LostFocus event on the top-most element in the DataTemplate (a StackPanel) when clicking the ListBox item in question (only through tabbing), and I'm out of ideas. | The easiest way to do this is to supply a template for the "ItemContainerStyle" and NOT the "ItemTemplate" property. In the code below I create 2 data templates: one for the "unselected" and one for the "selected" states. I then create a template for the "ItemContainerStyle" which is the actual "ListBoxItem" that contains the item. I set the default "ContentTemplate" to the "Unselected" state, and then supply a trigger that swaps out the template when the "IsSelected" property is true. (Note: I am setting the "ItemsSource" property in the code behind to a list of strings for simplicity)
```
<Window.Resources>
<DataTemplate x:Key="ItemTemplate">
<TextBlock Text="{Binding}" Foreground="Red" />
</DataTemplate>
<DataTemplate x:Key="SelectedTemplate">
<TextBlock Text="{Binding}" Foreground="White" />
</DataTemplate>
<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
<Setter Property="ContentTemplate" Value="{StaticResource ItemTemplate}" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<ListBox x:Name="lstItems" ItemContainerStyle="{StaticResource ContainerStyle}" />
``` |
146,271 | <p><strong>EDIT: This question is more about language engineering than C++ itself. I used C++ as an example to show what I wanted, mostly because I use it daily. I didn't want to know how it works on C++ but open a discussion on how it <em>could</em> be done.</strong></p>
<p>That's not the way it works right now, that's the way I <em>wish</em> it could be done, and that would break C compability for sure, but that's what I think extern "C" is all about.</p>
<p>I mean, in every function or method that you declare right now you have to explicit write that the object will be sent by reference prefixing the reference operator on it. I wish that every non-POD type would be automatically sent by reference, because I use that a lot, actually for every object that is more than 32 bits in size, and that's almost every class of mine.</p>
<p>Let's exemplify how it's right now, assume <em>a</em>, <em>b</em> and <em>c</em> to be classes:</p>
<pre>
class example {
public:
int just_use_a(const a &object);
int use_and_mess_with_b(b &object);
void do_nothing_on_c(c object);
};
</pre>
<p>Now what I wish:</p>
<pre>
class example {
public:
int just_use_a(const a object);
int use_and_mess_with_b(b object);
extern "C" void do_nothing_on_c(c object);
};
</pre>
<p>Now, do_nothing_on_c() could behave just like it is today.</p>
<p>That would be interesting at least for me, feels much more clear, and also if you <em>know</em> every non-POD parameter is coming by reference I believe the mistakes would be the same that if you had to explicit declare it.</p>
<p>Another point of view for this change, from someone coming from C, the reference operator seems to me a way to get the variable <em>address</em>, that's the way I used for getting pointers. I mean, it is the same operator but with different semantic on different contexts, doesn't that feel a little bit wrong for you too?</p>
| [
{
"answer_id": 146285,
"author": "user7545",
"author_id": 7545,
"author_profile": "https://Stackoverflow.com/users/7545",
"pm_score": 1,
"selected": false,
"text": "<p>I honestly think that this whole passing by value/passing by reference idea in C++ is misleading. <em>Everything</em> i... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18623/"
] | **EDIT: This question is more about language engineering than C++ itself. I used C++ as an example to show what I wanted, mostly because I use it daily. I didn't want to know how it works on C++ but open a discussion on how it *could* be done.**
That's not the way it works right now, that's the way I *wish* it could be done, and that would break C compability for sure, but that's what I think extern "C" is all about.
I mean, in every function or method that you declare right now you have to explicit write that the object will be sent by reference prefixing the reference operator on it. I wish that every non-POD type would be automatically sent by reference, because I use that a lot, actually for every object that is more than 32 bits in size, and that's almost every class of mine.
Let's exemplify how it's right now, assume *a*, *b* and *c* to be classes:
```
class example {
public:
int just_use_a(const a &object);
int use_and_mess_with_b(b &object);
void do_nothing_on_c(c object);
};
```
Now what I wish:
```
class example {
public:
int just_use_a(const a object);
int use_and_mess_with_b(b object);
extern "C" void do_nothing_on_c(c object);
};
```
Now, do\_nothing\_on\_c() could behave just like it is today.
That would be interesting at least for me, feels much more clear, and also if you *know* every non-POD parameter is coming by reference I believe the mistakes would be the same that if you had to explicit declare it.
Another point of view for this change, from someone coming from C, the reference operator seems to me a way to get the variable *address*, that's the way I used for getting pointers. I mean, it is the same operator but with different semantic on different contexts, doesn't that feel a little bit wrong for you too? | I guess you're missing the point of C++, and C++ semantics. You missed the fact **C++ is correct in passing (almost) everything by value, because it's the way it's done in C. Always**. But not only in C, as I'll show you below...
Parameters Semantics on C
-------------------------
In C, everything is passed by value. "primitives" and "PODs" are passed by copying their value. Modify them in your function, and the original won't be modified. Still, the cost of copying some PODs could be non-trivial.
When you use the pointer notation (the \* ), you're not passing by reference. You're passing a copy of the address. Which is more or less the same, with but one subtle difference:
```
typedef struct { int value ; } P ;
/* p is a pointer to P */
void doSomethingElse(P * p)
{
p->value = 32 ;
p = malloc(sizeof(P)) ; /* Don't bother with the leak */
p->value = 45 ;
}
void doSomething()
{
P * p = malloc(sizeof(P)) ;
p->value = 25 ;
doSomethingElse(p) ;
int i = p->value ;
/* Value of p ? 25 ? 32 ? 42 ? */
}
```
The final value of p->value is 32. Because p was passed by copying the value of the address. So the original p was not modified (and the new one was leaked).
Parameters Semantics on Java and C Sharp
----------------------------------------
It can be surprising for some, but in Java, everything is copied by value, too. The C example above would give exactly the same results in Java. This is almost what you want, but you would not be able to pass primitive "by reference/pointer" as easily as in C.
In C#, they added the "ref" keyword. It works more or less like the reference in C++. The point is, on C#, you have to mention it both on the function declaration, and on each and every call. I guess this is not what you want, again.
Parameters Semantics on C++
---------------------------
In C++, almost everything is passed by copying the value. When you're using nothing but the type of the symbol, you're copying the symbol (like it is done in C). This is why, when you're using the \*, you're passing a copy of the address of the symbol.
But when you're using the &, then assume you are passing the real object (be it struct, int, pointer, whatever): The reference.
It is easy to mistake it as syntaxic sugar (i.e., behind the scenes, it works like a pointer, and the generated code is the same used for a pointer). But...
The truth is that the reference is more than syntaxic sugar.
* Unlike pointers, it authorizes manipulating the object as if on stack.
* Unline pointers, when associatied with the const keyword, it authorizes implicit promotion from one type to another (through constructors, mainly).
* Unlike pointers, the symbol is not supposed to be NULL/invalid.
* Unlike the "by-copy", you are not spending useless time copying the object
* Unlike the "by-copy", you can use it as an [out] parameter
* Unlike the "by-copy", you can use the full range of OOP in C++ (i.e. you pass a full object to a function waiting an interface).
So, references has the best of both worlds.
Let's see the C example, but with a C++ variation on the doSomethingElse function:
```
struct P { int value ; } ;
// p is a reference to a pointer to P
void doSomethingElse(P * & p)
{
p->value = 32 ;
p = (P *) malloc(sizeof(P)) ; // Don't bother with the leak
p->value = 45 ;
}
void doSomething()
{
P * p = (P *) malloc(sizeof(P)) ;
p->value = 25 ;
doSomethingElse(p) ;
int i = p->value ;
// Value of p ? 25 ? 32 ? 42 ?
}
```
The result is 42, and the old p was leaked, replaced by the new p. Because, unlike C code, we're not passing a copy of the pointer, but the reference to the pointer, that is, the pointer itself.
When working with C++, the above example must be cristal clear. If it is not, then you're missing something.
Conclusion
----------
**C++ is pass-by-copy/value because it is the way everything works, be it in C, in C# or in Java (even in JavaScript... :-p ...). And like C#, C++ has a reference operator/keyword, *as a bonus*.**
Now, as far as I understand it, you are perhaps doing what I call half-jockingly **C+**, that is, C with some limited C++ features.
Perhaps your solution is using typedefs (it will enrage your C++ colleagues, though, to see the code polluted by useless typedefs...), but doing this will only obfuscate the fact you're really missing C++ there.
As said in another post, you should change your mindset from C development (of whatever) to C++ development, or you should perhaps move to another language. But do not keep programing the C way with C++ features, because by consciously ignoring/obfuscating the power of the idioms you use, you'll produce suboptimal code.
Note: And do not pass by copy anything else than primitives. You'll castrate your function from its OO capacity, and in C++, this is not what you want.
Edit
----
*The question was* somewhat *modified (see <https://stackoverflow.com/revisions/146271/list> ). I let my original answer, and answer the new questions below.*
**What you think about default pass-by-reference semantics on C++?** Like you said, it would break compatibility, and you'll have different pass-by for primitives (i.e. built-in types, which would still be passed by copy) and structs/objects (which would be passed as references). You would have to add another operator to mean "pass-by-value" (the extern "C" is quite awful and already used for something else quite different). No, I really like the way it is done today in C++.
**[...] the reference operator seems to me a way to get the variable address, that's the way I used for getting pointers. I mean, it is the same operator but with different semantic on different contexts, doesn't that feel a little bit wrong for you too?** Yes and no. Operator >> changed its semantic when used with C++ streams, too. Then, you can use operator += to replace strcat. I guess the operator & got used because its signification as "opposite of pointer", and because they did not want to use yet another symbol (ASCII is limited, and the scope operator :: as well as pointer -> shows that few other symbols are usable). But now, if & bothers you, && will really unnerve you, as they added an unary && in C++0x (a kind of super-reference...). I've yet to digest it myself... |
146,275 | <p>I have a templated class defined (in part) as</p>
<pre><code>template <class T> MyClass
{
public:
void DoSomething(){}
};
</code></pre>
<p>If I want to call DoSomething from another class, but be able to do this for multiple 'T' types in the same place, I am stuck for an idea as method functions pointers are uniquely constrained to the class type. Of course, each MyClass is a different type, so I can not store function pointers to MyClassDoSomething() in a 'polymorphic' way.</p>
<p>My use-case is I want to store, in a holding class, a vector of function pointers to 'DoSomething' such that I can issue a call to all stored classes from one place.</p>
<p>Has anyone any suggestions?</p>
| [
{
"answer_id": 146309,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 5,
"selected": true,
"text": "<p>Ok, so the functor solution doesn't work as you need. Perhaps you should have your template class inherit from a comm... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23167/"
] | I have a templated class defined (in part) as
```
template <class T> MyClass
{
public:
void DoSomething(){}
};
```
If I want to call DoSomething from another class, but be able to do this for multiple 'T' types in the same place, I am stuck for an idea as method functions pointers are uniquely constrained to the class type. Of course, each MyClass is a different type, so I can not store function pointers to MyClassDoSomething() in a 'polymorphic' way.
My use-case is I want to store, in a holding class, a vector of function pointers to 'DoSomething' such that I can issue a call to all stored classes from one place.
Has anyone any suggestions? | Ok, so the functor solution doesn't work as you need. Perhaps you should have your template class inherit from a common base "Interface" class. And then you use a vector of those.
Something like this:
```
class Base {
public:
virtual ~Base(){}
virtual void DoSomething() = 0;
}
template <class T> class MyClass : public Base {
public:
void DoSomething(){}
};
std::vector<Base *> objects;
objects.push_back(new MyClass<int>);
objects.push_back(new MyClass<char>);
``` |
146,291 | <p>I have a problem with <strong>scandir()</strong>: The manpage contains this as prototype:</p>
<pre><code>int scandir(const char *dir, struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **, const struct dirent **));
</code></pre>
<p>Therefore I have this:</p>
<pre><code>static inline int
RubyCompare(const struct dirent **a,
const struct dirent **b)
{
return(strcmp((*a)->d_name, (*b)->d_name));
}
</code></pre>
<p>And here's the call:</p>
<pre><code>num = scandir(buf, &entries, NULL, RubyCompare);
</code></pre>
<p>Finally the compiler says this:</p>
<pre><code>warning: passing argument 4 of ‘scandir’ from incompatible pointer type
</code></pre>
<p>Compiler is <strong>gcc-4.3.2</strong>, my CFLAGS are following: </p>
<pre><code>-Wall -Wpointer-arith -Wstrict-prototypes -Wunused -Wshadow -std=gnu99
</code></pre>
<p>What is the meaning of this warning? The declaration of RubyCompare looks correct for me and besides the warning the code works completely.</p>
| [
{
"answer_id": 146310,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 1,
"selected": false,
"text": "<p>You're giving it a pointer to an inline function? That doesn't make sense, actually I wonder that it even compiles with... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18179/"
] | I have a problem with **scandir()**: The manpage contains this as prototype:
```
int scandir(const char *dir, struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **, const struct dirent **));
```
Therefore I have this:
```
static inline int
RubyCompare(const struct dirent **a,
const struct dirent **b)
{
return(strcmp((*a)->d_name, (*b)->d_name));
}
```
And here's the call:
```
num = scandir(buf, &entries, NULL, RubyCompare);
```
Finally the compiler says this:
```
warning: passing argument 4 of ‘scandir’ from incompatible pointer type
```
Compiler is **gcc-4.3.2**, my CFLAGS are following:
```
-Wall -Wpointer-arith -Wstrict-prototypes -Wunused -Wshadow -std=gnu99
```
What is the meaning of this warning? The declaration of RubyCompare looks correct for me and besides the warning the code works completely. | Actually, there's no such constraint that you can't pass a pointer to an inline function. The inline keyword serves only as a hint to the compiler to inline calls when it can.
The problem is that the manpage for scandir() is a little misleading. The prototype in for the 4th parameter is actually int (\*cmp)(const void \*, const void \*).
Therefore you need to change the code like so:
```
static inline int RubyCompare(const void *a, const void *b)
{
return(strcmp((*(struct dirent **)a)->d_name,
(*(struct dirent **)b)->d_name));
}
```
I'm not actually sure why you're writing this function, though, because you can use the provided alphasort compare function:
```
num = scandir(buf, &entries, NULL, alphasort);
``` |
146,311 | <p>It says in <a href="http://www.ibm.com/developerworks/java/library/j-jtp04223.html" rel="nofollow noreferrer">this article</a> that: </p>
<blockquote>
<p>Making a class final because it is immutable is a good reason to do so.</p>
</blockquote>
<p>I'm a bit puzzled by this... I understand that immutability is a good thing from the POV of thread-safety and simplicity, but it seems that these concerns are somewhat orthogonal to extensibility. So, why is immutability a good reason for making a class final?</p>
| [
{
"answer_id": 146318,
"author": "cynicalman",
"author_id": 410,
"author_profile": "https://Stackoverflow.com/users/410",
"pm_score": 3,
"selected": false,
"text": "<p>Because if the class is final you can't extend it and make it mutable.</p>\n\n<p>Even if you make the fields final, that... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] | It says in [this article](http://www.ibm.com/developerworks/java/library/j-jtp04223.html) that:
>
> Making a class final because it is immutable is a good reason to do so.
>
>
>
I'm a bit puzzled by this... I understand that immutability is a good thing from the POV of thread-safety and simplicity, but it seems that these concerns are somewhat orthogonal to extensibility. So, why is immutability a good reason for making a class final? | The explanation for this is given in the book 'Effective Java'
Consider `BigDecimal` and `BigInteger` classes in Java .
It was not widely understood that immutable classes had to be effectively final
when `BigInteger` and `BigDecimal` were written, so all of their methods may be
overridden. Unfortunately, this could not be corrected after the fact while preserving backward compatibility.
**If you write a class whose security depends on the immutability of a BigInteger or BigDecimal argument from an un-trusted client, you must check to see that the argument is a “real” BigInteger or BigDecimal, rather than an instance of an un trusted subclass. If it is the latter, you must defensively copy it under the assumption that it might be mutable.**
```
public static BigInteger safeInstance(BigInteger val) {
if (val.getClass() != BigInteger.class)
return new BigInteger(val.toByteArray());
return val;
}
```
If you allow sub classing, it might break the "purity" of the immutable object. |
146,316 | <p>What number of classes do you think is ideal per one namespace "branch"? At which point would one decide to break one namespace into multiple ones? Let's not discuss the logical grouping of classes (assume they are logically grouped properly), I am, at this point, focused on the maintainable vs. not maintainable number of classes.</p>
| [
{
"answer_id": 146323,
"author": "cynicalman",
"author_id": 410,
"author_profile": "https://Stackoverflow.com/users/410",
"pm_score": 3,
"selected": false,
"text": "<p>With modern IDEs and other dev tools, I would say that if all the classes belong in a namespace, then there is no arbitr... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15497/"
] | What number of classes do you think is ideal per one namespace "branch"? At which point would one decide to break one namespace into multiple ones? Let's not discuss the logical grouping of classes (assume they are logically grouped properly), I am, at this point, focused on the maintainable vs. not maintainable number of classes. | "42? No, it doesn't work..."
Ok, let's put our programming prowess to work and see what is Microsoft's opinion:
```
# IronPython
import System
exported_types = [
(t.Namespace, t.Name)
for t in System.Int32().GetType().Assembly.GetExportedTypes()]
import itertools
get_ns = lambda (ns, typename): ns
sorted_exported_types = sorted(exported_types, key=get_ns)
counts_per_ns = dict(
(ns, len(list(typenames)))
for ns, typenames
in itertools.groupby(sorted_exported_types, get_ns))
counts = sorted(counts_per_ns.values())
print 'Min:', counts[0]
print 'Max:', counts[-1]
print 'Avg:', sum(counts) / len(counts)
print 'Med:',
if len(counts) % 2:
print counts[len(counts) / 2]
else: # ignoring len == 1 case
print (counts[len(counts) / 2 - 1] + counts[len(counts) / 2]) / 2
```
And this gives us the following statistics on number of types per namespace:
```
C:\tools\nspop>ipy nspop.py
Min: 1
Max: 173
Avg: 27
Med: 15
``` |
146,354 | <p>I'd like to automatically change my database connection settings on a per-vhost basis, so that I don't have to edit any PHP code as it moves from staging to live and yet access different databases. This is on a single dedicated server.</p>
<p>So I was wondering, can I set a PHP variable or constant in httpd.conf as part of the vhost definition that the site can then use to point itself to a testing database automatically?</p>
<pre><code>$database = 'live';
if (some staging environment variable is true) {
$database = 'testing'; // and not live
}
</code></pre>
<p>If this isn't possible, I guess in this case I can safely examine the hostname I'm running on to tell, but I'd like something a little less fragile</p>
<p>Hope this makes sense</p>
<p>many thanks</p>
<p>Ian</p>
| [
{
"answer_id": 146380,
"author": "JW.",
"author_id": 4321,
"author_profile": "https://Stackoverflow.com/users/4321",
"pm_score": 6,
"selected": false,
"text": "<p>Yep...you can do this:</p>\n\n<pre><code>SetEnv DATABASE_NAME testing\n</code></pre>\n\n<p>and then in PHP:</p>\n\n<pre><code... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137/"
] | I'd like to automatically change my database connection settings on a per-vhost basis, so that I don't have to edit any PHP code as it moves from staging to live and yet access different databases. This is on a single dedicated server.
So I was wondering, can I set a PHP variable or constant in httpd.conf as part of the vhost definition that the site can then use to point itself to a testing database automatically?
```
$database = 'live';
if (some staging environment variable is true) {
$database = 'testing'; // and not live
}
```
If this isn't possible, I guess in this case I can safely examine the hostname I'm running on to tell, but I'd like something a little less fragile
Hope this makes sense
many thanks
Ian | Did you tried to use the .htaccess file? You could override the php.ini values using it.
Just put the .htaccess file into your htdocs directory:
```
php_value name value
```
Futher information:
* <https://php.net/manual/en/configuration.changes.php>
* <https://php.net/manual/en/ini.php> |
146,358 | <p>I'm using .NET 3.5. I have two string arrays, which may share one or more values:</p>
<pre><code>string[] list1 = new string[] { "apple", "orange", "banana" };
string[] list2 = new string[] { "banana", "pear", "grape" };
</code></pre>
<p>I'd like a way to merge them into one array with no duplicate values:</p>
<pre><code>{ "apple", "orange", "banana", "pear", "grape" }
</code></pre>
<p>I can do this with LINQ:</p>
<pre><code>string[] result = list1.Concat(list2).Distinct().ToArray();
</code></pre>
<p>but I imagine that's not very efficient for large arrays.</p>
<p>Is there a better way?</p>
| [
{
"answer_id": 146379,
"author": "petr k.",
"author_id": 15497,
"author_profile": "https://Stackoverflow.com/users/15497",
"pm_score": 1,
"selected": false,
"text": "<p>Probably creating a hashtable with your values as keys (only adding those not already present) and then converting the ... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5142/"
] | I'm using .NET 3.5. I have two string arrays, which may share one or more values:
```
string[] list1 = new string[] { "apple", "orange", "banana" };
string[] list2 = new string[] { "banana", "pear", "grape" };
```
I'd like a way to merge them into one array with no duplicate values:
```
{ "apple", "orange", "banana", "pear", "grape" }
```
I can do this with LINQ:
```
string[] result = list1.Concat(list2).Distinct().ToArray();
```
but I imagine that's not very efficient for large arrays.
Is there a better way? | ```
string[] result = list1.Union(list2).ToArray();
```
from [msdn](http://msdn.microsoft.com/en-us/library/bb341731.aspx): "This method excludes duplicates from the return set. This is different behavior to the Concat(TSource) method, which returns all the elements in the input sequences including duplicates." |
146,359 | <p>I am trying to figure out this:</p>
<pre><code>c = 1
def f(n):
print c + n
def g(n):
c = c + n
f(1) # => 2
g(1) # => UnboundLocalError: local variable 'c' referenced before assignment
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 146365,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 7,
"selected": true,
"text": "<p>Within a function, variables that are assigned to are treated as local variables by default. To assign to global variab... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/462204/"
] | I am trying to figure out this:
```
c = 1
def f(n):
print c + n
def g(n):
c = c + n
f(1) # => 2
g(1) # => UnboundLocalError: local variable 'c' referenced before assignment
```
Thanks! | Within a function, variables that are assigned to are treated as local variables by default. To assign to global variables, use the [`global`](https://docs.python.org/3/reference/simple_stmts.html#the-global-statement) statement:
```
def g(n):
global c
c = c + n
```
This is one of the quirky areas of Python that has never really sat well with me. |
146,367 | <p>I have an asp.net mvc application with a route similar to:</p>
<pre><code>routes.MapRoute("Blog",
"{controller}/{action}/{year}/{month}/{day}/{friendlyName}",
new { controller = "Blog", action = "Index", id = "", friendlyName="" },
new { controller = @"[^\.]*",
year = @"\d{4}",
month = @"\d{2}",
day = @"\d{2}" }
);
</code></pre>
<p>My controller action method signature looks like:</p>
<pre><code>public ActionResult Detail(int year, int month, int day, string friendlyName)
{ // Implementation... }
</code></pre>
<p>In my view, I'm doing something like:</p>
<pre><code><%= Html.ActionLink<BlogController>(item => item.Detail(blog.PostedOn.Year, blog.PostedOn.Month, blog.PostedOn.Day, blog.Slug), blog.Title) %>
</code></pre>
<p>While the url that is generated with ActionLink works, it uses query string variables rather than URL rewriting. </p>
<p>For example, it would produce /blog/detail/my-slug?year=2008&month=7&day=5 instead of /blog/detail/2008/07/05/my-slug</p>
<p>Is there a way to get the generic version of ActionLink to properly pad the integer values so that the url comes out as expected?</p>
<p>Thanks</p>
<p>Jim</p>
| [
{
"answer_id": 146404,
"author": "Gilligan",
"author_id": 12356,
"author_profile": "https://Stackoverflow.com/users/12356",
"pm_score": 3,
"selected": true,
"text": "<p>I would suggest formatting the Year, Month, and Day as Strings instead. \nThink about this: Will you be doing any math ... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3085/"
] | I have an asp.net mvc application with a route similar to:
```
routes.MapRoute("Blog",
"{controller}/{action}/{year}/{month}/{day}/{friendlyName}",
new { controller = "Blog", action = "Index", id = "", friendlyName="" },
new { controller = @"[^\.]*",
year = @"\d{4}",
month = @"\d{2}",
day = @"\d{2}" }
);
```
My controller action method signature looks like:
```
public ActionResult Detail(int year, int month, int day, string friendlyName)
{ // Implementation... }
```
In my view, I'm doing something like:
```
<%= Html.ActionLink<BlogController>(item => item.Detail(blog.PostedOn.Year, blog.PostedOn.Month, blog.PostedOn.Day, blog.Slug), blog.Title) %>
```
While the url that is generated with ActionLink works, it uses query string variables rather than URL rewriting.
For example, it would produce /blog/detail/my-slug?year=2008&month=7&day=5 instead of /blog/detail/2008/07/05/my-slug
Is there a way to get the generic version of ActionLink to properly pad the integer values so that the url comes out as expected?
Thanks
Jim | I would suggest formatting the Year, Month, and Day as Strings instead.
Think about this: Will you be doing any math on these "integers"? Probably not, so there really is no point for making them integers.
Once you have them as Strings you can force the leading zero format. |
146,385 | <p>I am trying to call a webservice using ssl.
How do i get the relevant server cert so that i can import it into my truststore?
I know about the use of property com.ibm.ssl.enableSignerExchangePrompt from a main method but i would add the server cert to my truststore manually.</p>
<p>I dont want this property set in any of my servlets</p>
<p>Any help is greatly appreciated
Thanks
Damien</p>
| [
{
"answer_id": 146450,
"author": "Max Stewart",
"author_id": 18338,
"author_profile": "https://Stackoverflow.com/users/18338",
"pm_score": 0,
"selected": false,
"text": "<p>If you browse to the site in your web browser you can look at the security info by hitting the little padlock icon ... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11612/"
] | I am trying to call a webservice using ssl.
How do i get the relevant server cert so that i can import it into my truststore?
I know about the use of property com.ibm.ssl.enableSignerExchangePrompt from a main method but i would add the server cert to my truststore manually.
I dont want this property set in any of my servlets
Any help is greatly appreciated
Thanks
Damien | you can programmatically do this with Java by implementing your own X509TrustManager.
```
public class dummyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
//do nothing
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// do nothing
}
public X509Certificate[] getAcceptedIssuers() {
//just return an empty issuer
return new X509Certificate[0];
}
}
```
Then you can use this trust manager to create a SSL sockect
```
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, new TrustManager[] { new dummyTrustManager() },
new java.security.SecureRandom());
SSLSocketFactory factory = context.getSocketFactory();
InetAddress addr = InetAddress.getByName(host_);
SSLSocket sock = (SSLSocket)factory.createSocket(addr, port_);
```
Then with that socket you can just extract the server certificate (an put import it
in the trusted keystore)
```
SSLSession session = sock.getSession();
Certificate[] certchain = session.getPeerCertificates();
``` |
146,387 | <p>I'd like to get <strong>uniform distribution</strong> in range [0.0, 1.0)</p>
<p>If possible, please let the implementation make use of random bytes from <strong>/dev/urandom.</strong></p>
<p>It would also be nice if your solution was <strong>thread-safe</strong>. If you're not sure, please indicate that.</p>
<p>See <a href="https://stackoverflow.com/questions/146387#149814">some solution</a> I thought about after reading other answers.</p>
| [
{
"answer_id": 146410,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#include <stdlib.h>\nprintf(\"%f\\n\", drand48());\n</code></pre>\n\n<h2>/dev/random:</h2>\n\n<pre><code>doub... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403/"
] | I'd like to get **uniform distribution** in range [0.0, 1.0)
If possible, please let the implementation make use of random bytes from **/dev/urandom.**
It would also be nice if your solution was **thread-safe**. If you're not sure, please indicate that.
See [some solution](https://stackoverflow.com/questions/146387#149814) I thought about after reading other answers. | This seems to be pretty good way:
````
unsigned short int r1, r2, r3;
// let r1, r2 and r3 hold random values
double result = ldexp(r1, -48) + ldexp(r2, -32) + ldexp(r3, -16);
````
This is based on NetBSD's drand48 implementation. |
146,390 | <p>In python you can use a tuple in a formatted print statement and the tuple values are used at the indicated positions in the formatted string. For example:</p>
<pre><code>>>> a = (1,"Hello",7.2)
>>> print "these are the values %d, %s, %f" % a
these are the values 1, Hello, 7.200000
</code></pre>
<p>Is there some way to use any array or collection in a java printf statement in a similar way?</p>
<p>I've looked at the <a href="http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#syntax" rel="nofollow noreferrer">documentation</a> and it appears to have built in support for some types like Calendar, but I don't see anything for collections. </p>
<p>If this isn't provided in java, is there any java idiom that would be used in a case like this where you are populating collections and then printing the values from many collections using one format string (other than just nested looping)?</p>
| [
{
"answer_id": 146408,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 5,
"selected": true,
"text": "<p>printf will have a declaration along the lines of:</p>\n\n<pre><code>public PrintString printf(String format... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4138/"
] | In python you can use a tuple in a formatted print statement and the tuple values are used at the indicated positions in the formatted string. For example:
```
>>> a = (1,"Hello",7.2)
>>> print "these are the values %d, %s, %f" % a
these are the values 1, Hello, 7.200000
```
Is there some way to use any array or collection in a java printf statement in a similar way?
I've looked at the [documentation](http://java.sun.com/javase/6/docs/api/java/util/Formatter.html#syntax) and it appears to have built in support for some types like Calendar, but I don't see anything for collections.
If this isn't provided in java, is there any java idiom that would be used in a case like this where you are populating collections and then printing the values from many collections using one format string (other than just nested looping)? | printf will have a declaration along the lines of:
```
public PrintString printf(String format, Object... args);
```
... means much the same as `[]`. The difference is `...` allows the caller to omit explicitly creating an array. So consider:
```
out.printf("%s:%s", a, b);
```
That is the equivalent of:
```
out.printf("%s:%s", new Object[] { a, b });
```
So, getting back to your question, for an array, you can just write:
```
out.printf("%s:%s", things);
```
For a collection:
```
out.printf("%s:%s", things.toArray());
``` |
146,435 | <p>I have a file temp.txt, that I want to sort with the <code>sort</code> command in bash.</p>
<p>I want the sorted results to replace the original file.</p>
<p>This doesn't work for example (I get an empty file):</p>
<pre><code>sortx temp.txt > temp.txt
</code></pre>
<p>Can this be done in one line without resorting to copying to temporary files?</p>
<hr>
<p>EDIT: The <code>-o</code> option is very cool for <code>sort</code>. I used <code>sort</code> in my question as an example. I run into the same problem with other commands:</p>
<pre><code>uniq temp.txt > temp.txt.
</code></pre>
<p>Is there a better general solution?</p>
| [
{
"answer_id": 146441,
"author": "slim",
"author_id": 7512,
"author_profile": "https://Stackoverflow.com/users/7512",
"pm_score": 2,
"selected": false,
"text": "<p>Read up on the non-interactive editor, <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ex.html\" rel=\"n... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/814/"
] | I have a file temp.txt, that I want to sort with the `sort` command in bash.
I want the sorted results to replace the original file.
This doesn't work for example (I get an empty file):
```
sortx temp.txt > temp.txt
```
Can this be done in one line without resorting to copying to temporary files?
---
EDIT: The `-o` option is very cool for `sort`. I used `sort` in my question as an example. I run into the same problem with other commands:
```
uniq temp.txt > temp.txt.
```
Is there a better general solution? | ```
sort temp.txt -o temp.txt
``` |
146,439 | <p>Here's the idea, I'd like to make a service? that will look for a certain program starting up and dissallow it unless certain conditions are met. </p>
<p>Let's say I have a game I want to stop myself from playing during the week. So if I start it up on any day other than Friday/Saturday/Sunday, it will intercept and cancel. Is this possible with C#?</p>
<p>Main thing I am looking for is how to catch a program starting up, rest should be easy.</p>
| [
{
"answer_id": 146444,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure if you can catch it starting up, but you could try to look for the program in the list of windows (was ... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21691/"
] | Here's the idea, I'd like to make a service? that will look for a certain program starting up and dissallow it unless certain conditions are met.
Let's say I have a game I want to stop myself from playing during the week. So if I start it up on any day other than Friday/Saturday/Sunday, it will intercept and cancel. Is this possible with C#?
Main thing I am looking for is how to catch a program starting up, rest should be easy. | Well, you can definitely determine which programs are running by looking for the process names you want (GetProcessesByName()) and killing them.
```
Process[] processes = Process.GetProcessesByName(processName);
foreach(Process process in processes)
{
process.Kill();
}
```
You could just have a list of them you didn't want to run, do the time check (or whatever criteria was to be met) and then walk the list. I did something like this once for a test and it works well enough. |
146,522 | <p>I’ve got a brand new Django project. I’ve added one minimal view function to <code>views.py</code>, and one URL pattern to <code>urls.py</code>, passing the view by function reference instead of a string:</p>
<pre><code># urls.py
# -------
# coding=utf-8
from django.conf.urls.defaults import *
from myapp import views
urlpatterns = patterns('',
url(r'^myview/$', views.myview),
)
# views.py
----------
# coding=utf-8
from django.http import HttpResponse
def myview(request):
return HttpResponse('MYVIEW LOL', content_type="text/plain")
</code></pre>
<p>I’m trying to use <code>reverse()</code> to get the URL, by passing it a function reference. But I’m not getting a match, despite confirming that the view function I’m passing to reverse is the exact same view function I put in the URL pattern:</p>
<pre><code>>>> from django.core.urlresolvers import reverse
>>> import urls
>>> from myapp import views
>>> urls.urlpatterns[0].callback is views.myview
True
>>> reverse(views.myview)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 254, in reverse
*args, **kwargs)))
File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 243, in reverse
"arguments '%s' not found." % (lookup_view, args, kwargs))
NoReverseMatch: Reverse for '<function myview at 0x6fe6b0>' with arguments '()' and keyword arguments '{}' not found.
</code></pre>
<p>As far as I can tell from the documentation, function references should be fine in both the URL pattern and <code>reverse()</code>.</p>
<ul>
<li><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#passing-callable-objects-instead-of-strings" rel="noreferrer">URL patterns with function references</a></li>
<li><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#reverse" rel="noreferrer"><code>reverse</code> with function references</a></li>
</ul>
<p>I’m using the Django trunk, revision 9092.</p>
| [
{
"answer_id": 146524,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": true,
"text": "<p>Got it!! The problem is that some of the imports are of <code>myproject.myapp.views</code>, and some are just of <co... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20578/"
] | I’ve got a brand new Django project. I’ve added one minimal view function to `views.py`, and one URL pattern to `urls.py`, passing the view by function reference instead of a string:
```
# urls.py
# -------
# coding=utf-8
from django.conf.urls.defaults import *
from myapp import views
urlpatterns = patterns('',
url(r'^myview/$', views.myview),
)
# views.py
----------
# coding=utf-8
from django.http import HttpResponse
def myview(request):
return HttpResponse('MYVIEW LOL', content_type="text/plain")
```
I’m trying to use `reverse()` to get the URL, by passing it a function reference. But I’m not getting a match, despite confirming that the view function I’m passing to reverse is the exact same view function I put in the URL pattern:
```
>>> from django.core.urlresolvers import reverse
>>> import urls
>>> from myapp import views
>>> urls.urlpatterns[0].callback is views.myview
True
>>> reverse(views.myview)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 254, in reverse
*args, **kwargs)))
File "/Library/Python/2.5/site-packages/django/core/urlresolvers.py", line 243, in reverse
"arguments '%s' not found." % (lookup_view, args, kwargs))
NoReverseMatch: Reverse for '<function myview at 0x6fe6b0>' with arguments '()' and keyword arguments '{}' not found.
```
As far as I can tell from the documentation, function references should be fine in both the URL pattern and `reverse()`.
* [URL patterns with function references](http://docs.djangoproject.com/en/dev/topics/http/urls/#passing-callable-objects-instead-of-strings)
* [`reverse` with function references](http://docs.djangoproject.com/en/dev/topics/http/urls/?from=olddocs#reverse)
I’m using the Django trunk, revision 9092. | Got it!! The problem is that some of the imports are of `myproject.myapp.views`, and some are just of `myapp.views`. This is confusing the Python module system enough that it no longer detects the functions as the same object. This is because your main `settings.py` probably has a line like:
```
ROOT_URLCONF = `myproject.urls`
```
To solve this, try using the full import in your shell session:
```
>>> from django.core.urlresolvers import reverse
>>> from myproject.myapp import views
>>> reverse(views.myview)
'/myview/'
```
Here's a log of the debugging session, for any interested future readers:
```
>>> from django.core import urlresolvers
>>> from myapp import myview
>>> urlresolvers.get_resolver (None).reverse_dict
{None: ([(u'myview/', [])], 'myview/$'), <function myview at 0x845d17c>: ([(u'myview/', [])], 'myview/$')}
>>> v1 = urlresolvers.get_resolver (None).reverse_dict.items ()[1][0]
>>> reverse(v1)
'/myview/'
>>> v1 is myview
False
>>> v1.__module__
'testproject.myapp.views'
>>> myview.__module__
'myapp.views'
```
What happens if you change the URL match to be `r'^myview/$'`?
---
Have you tried it with the view name? Something like `reverse ('myapp.myview')`?
Is `urls.py` the root URLconf, or in the `myapp` application? There needs to be a full path from the root to a view for it to be resolved. If that's `myproject/myapp/urls.py`, then in `myproject/urls.py` you'll need code like this:
```
from django.conf.urls.defaults import patterns
urlpatterns = patterns ('',
(r'^/', 'myapp.urls'),
)
``` |
146,531 | <p>I have a SQL table with news stories and Unix timestamps. I'd like to only keep the 50 newest stories. How would I write an SQL statement to delete any amount of older stories?</p>
| [
{
"answer_id": 146535,
"author": "Davide Vosti",
"author_id": 1812,
"author_profile": "https://Stackoverflow.com/users/1812",
"pm_score": 3,
"selected": false,
"text": "<p>Blockquote</p>\n\n<pre><code>delete from table where id not in (\n select id from table \n order by id desc \n... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6305/"
] | I have a SQL table with news stories and Unix timestamps. I'd like to only keep the 50 newest stories. How would I write an SQL statement to delete any amount of older stories? | I ended up using two queries since MySQL5 doesn't yet support LIMIT's in subqueries
```
SELECT unixTime FROM entries ORDER BY unixTime DESC LIMIT 49, 1;
DELETE FROM entries WHERE unixTime < $sqlResult;
``` |
146,557 | <p>I was reading a question about the Python <em>global</em> statement ( <a href="https://stackoverflow.com/questions/146359/python-scope">"Python scope"</a> ) and I was remembering about how often I used this statement when I was a Python beginner (I used <em>global</em> a lot) and how, nowadays, years later, I don't use it at all, ever. I even consider it a bit "un-pythonic".<br></p>
<p>Do you use this statement in Python ? Has your usage of it changed with time ?</p>
| [
{
"answer_id": 146562,
"author": "ironfroggy",
"author_id": 19687,
"author_profile": "https://Stackoverflow.com/users/19687",
"pm_score": 4,
"selected": false,
"text": "<p>I've never had a legit use for the statement in any production code in my 3+ years of professional use of Python and... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20037/"
] | I was reading a question about the Python *global* statement ( ["Python scope"](https://stackoverflow.com/questions/146359/python-scope) ) and I was remembering about how often I used this statement when I was a Python beginner (I used *global* a lot) and how, nowadays, years later, I don't use it at all, ever. I even consider it a bit "un-pythonic".
Do you use this statement in Python ? Has your usage of it changed with time ? | I use 'global' in a context such as this:
```
_cached_result = None
def myComputationallyExpensiveFunction():
global _cached_result
if _cached_result:
return _cached_result
# ... figure out result
_cached_result = result
return result
```
I use 'global' because it makes sense and is clear to the reader of the function what is happening. I also know there is this pattern, which is equivalent, but places more cognitive load on the reader:
```
def myComputationallyExpensiveFunction():
if myComputationallyExpensiveFunction.cache:
return myComputationallyExpensiveFunction.cache
# ... figure out result
myComputationallyExpensiveFunction.cache = result
return result
myComputationallyExpensiveFunction.cache = None
``` |
146,575 | <p>I'm writing a program (for Mac OS X, using Objective-C) and I need to create a bunch of .webloc files programmatically.</p>
<p>The .webloc file is simply file which is created after you drag-n-drop an URL from Safari's location bar to some folder.</p>
<p>Generally speaking, I need an approach to create items in a filesystem which point to some location in the Web. As I understand .webloc files should be used for this on Mac OS X.</p>
<p>So, is it possible to craft a .webloc file having a valid url and some title for it?</p>
| [
{
"answer_id": 146605,
"author": "millenomi",
"author_id": 6061,
"author_profile": "https://Stackoverflow.com/users/6061",
"pm_score": 2,
"selected": false,
"text": "<p>It uses a resource fork-based binary format.</p>\n\n<p>Valid workarounds:</p>\n\n<ul>\n<li>Have the user drag a URL fro... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20294/"
] | I'm writing a program (for Mac OS X, using Objective-C) and I need to create a bunch of .webloc files programmatically.
The .webloc file is simply file which is created after you drag-n-drop an URL from Safari's location bar to some folder.
Generally speaking, I need an approach to create items in a filesystem which point to some location in the Web. As I understand .webloc files should be used for this on Mac OS X.
So, is it possible to craft a .webloc file having a valid url and some title for it? | It is little known - but there is also a simple plist based file format for weblocs.
When creating webloc files you *DO NOT NEED* to save them using the resource method the other three posters describe. You can also write a simple plist:
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>URL</key>
<string>http://apple.com</string>
</dict>
</plist>
```
The binary resource format is still in active use and if you want to read a plist file - then sure you need to read both file formats. But when writing the file - use the plist based format - it is a lot easier. |
146,576 | <p>The method signature of a Java <code>main</code>method is:</p>
<pre><code>public static void main(String[] args) {
...
}
</code></pre>
<p><strong>Is there a reason why this method must be static?</strong></p>
| [
{
"answer_id": 146581,
"author": "Logan",
"author_id": 3518,
"author_profile": "https://Stackoverflow.com/users/3518",
"pm_score": 3,
"selected": false,
"text": "<p>It's just a convention, but probably more convenient than the alternative. With a static main, all you need to know to invo... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2937/"
] | The method signature of a Java `main`method is:
```
public static void main(String[] args) {
...
}
```
**Is there a reason why this method must be static?** | The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this:
```
public class JavaClass{
protected JavaClass(int x){}
public void main(String[] args){
}
}
```
Should the JVM call `new JavaClass(int)`? What should it pass for `x`?
If not, should the JVM instantiate `JavaClass` without running any constructor method? I think it shouldn't, because that will special-case your entire class - sometimes you have an instance that hasn't been initialized, and you have to check for it in every method that could be called.
There are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That's why `main` is static.
I have no idea why `main` is always marked `public` though. |
146,602 | <p>Has anyone had any recent requirements for programming automated DOS Batch style tasks on a Windows box?</p>
<p>I've got some automation to do and I'd rather not sit and write a pile of .BAT files in Notepad if there is a better way of automating these tasks: mainly moving of files under certain date and time conditions, as well as triggering Windows applications before and after moving the files.</p>
<p>I am thinking along the lines of an IDE that has all the DOS commands 'available' to the editor with the correct parameter syntax checking. Is there anything like this out there, or should I be solving this problem with something other than .BAT files?</p>
| [
{
"answer_id": 146613,
"author": "Mikael Jansson",
"author_id": 18753,
"author_profile": "https://Stackoverflow.com/users/18753",
"pm_score": 2,
"selected": false,
"text": "<p>Try Python.</p>\n"
},
{
"answer_id": 146617,
"author": "jeffm",
"author_id": 1544,
"author_p... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22376/"
] | Has anyone had any recent requirements for programming automated DOS Batch style tasks on a Windows box?
I've got some automation to do and I'd rather not sit and write a pile of .BAT files in Notepad if there is a better way of automating these tasks: mainly moving of files under certain date and time conditions, as well as triggering Windows applications before and after moving the files.
I am thinking along the lines of an IDE that has all the DOS commands 'available' to the editor with the correct parameter syntax checking. Is there anything like this out there, or should I be solving this problem with something other than .BAT files? | For simple Windows automation beyond BAT files, [VBScript](http://msdn.microsoft.com/en-us/library/sx7b3k7y(VS.85).aspx) and [Powershell](http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx) might be worth a look. If you're wondering where to start first, VBScript+Windows Task Scheduler would be the first place I'd start. Copying a file with VBS can be as simple as:
```
Dim objFSO
Set objFSO = CreateObject ("Scripting.FileSystemObject")
If objFSO.FileExists("C:\source\your_file.txt") Then
objFSO.CopyFile "C:\source\your_file.txt", "C:\destination\your_file.txt"
EndIf
``` |
146,604 | <p>I have a new object with a collection of new objects within it on some property as an IList. I see through sql profiler two insert queries being executed.. one for the parent, which has the new guid id, and one for the child, however, the foreign-key on the child that references the parent, is an empty guid. Here is my mapping on the parent: </p>
<pre><code><id name="BackerId">
<generator class="guid" />
</id>
<property name="Name" />
<property name="PostCardSizeId" />
<property name="ItemNumber" />
<bag name="BackerEntries" table="BackerEntry" cascade="all" lazy="false" order-by="Priority">
<key column="BackerId" />
<one-to-many class="BackerEntry" />
</bag>
</code></pre>
<p>On the Backer.cs class, I defined BackerEntries property as </p>
<pre><code>IList<BackerEntry>
</code></pre>
<p>When I try to SaveOrUpdate the passed in entity I get the following results in sql profiler:</p>
<p>exec sp_executesql N'INSERT INTO Backer (Name, PostCardSizeId, ItemNumber, BackerId) VALUES (@p0, @p1, @p2, @p3)',N'@p0 nvarchar(3),@p1 uniqueidentifier,@p2 nvarchar(3),@p3
uniqueidentifier',@p0=N'qaa',@p1='BC95E7EB-5EE8-44B2-82FF30F5176684D',@p2=N'qaa',@p3='18FBF8CE-FD22-4D08-A3B1-63D6DFF426E5'</p>
<p>exec sp_executesql N'INSERT INTO BackerEntry (BackerId, BackerEntryTypeId, Name, Description, MaxLength, IsRequired, Priority, BackerEntryId) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7)',N'@p0 uniqueidentifier,@p1 uniqueidentifier,@p2 nvarchar(5),@p3 nvarchar(5),@p4 int,@p5 bit,@p6 int,@p7 uniqueidentifier',@p0='00000000-0000-0000-0000-000000000000',@p1='2C5BDD33-5DD3-42EC-AA0E-F1E548A5F6E4',@p2=N'qaadf',@p3=N'wasdf',@p4=0,@p5=1,@p6=0,@p7='FE9C4A35-6211-4E17-A75A-60CCB526F1CA'</p>
<p>As you can see, its not resetting the empty guid for BackerId on the child to the new real guid of the parent.</p>
<p>Finally, the exception throw is: </p>
<pre><code>"NHibernate.Exceptions.GenericADOException: could not insert: [CB.ThePostcardCompany.MiddleTier.BackerEntry][SQL: INSERT INTO BackerEntry (BackerId, BackerEntryTypeId, Name, Description, MaxLength, IsRequired, Priority, BackerEntryId) VALUES (?, ?, ?, ?, ?, ?, ?, ?)] ---\u003e System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint
</code></pre>
<p>EDIT: SOLVED! The first answer below pointed me into the correct direction. I needed to add that back reference on the child mapping and class. This allowed it to work in a purely .net way - however, when accepting json, there was a disconnect so I had to come up with some quirky code to 're-attach' the children.</p>
| [
{
"answer_id": 146640,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 4,
"selected": true,
"text": "<p>You may need to add NOT-NULL=\"true\" to your mapping class:</p>\n\n<pre><code><bag name=\"BackerEntries\" table=\"Backe... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6350/"
] | I have a new object with a collection of new objects within it on some property as an IList. I see through sql profiler two insert queries being executed.. one for the parent, which has the new guid id, and one for the child, however, the foreign-key on the child that references the parent, is an empty guid. Here is my mapping on the parent:
```
<id name="BackerId">
<generator class="guid" />
</id>
<property name="Name" />
<property name="PostCardSizeId" />
<property name="ItemNumber" />
<bag name="BackerEntries" table="BackerEntry" cascade="all" lazy="false" order-by="Priority">
<key column="BackerId" />
<one-to-many class="BackerEntry" />
</bag>
```
On the Backer.cs class, I defined BackerEntries property as
```
IList<BackerEntry>
```
When I try to SaveOrUpdate the passed in entity I get the following results in sql profiler:
exec sp\_executesql N'INSERT INTO Backer (Name, PostCardSizeId, ItemNumber, BackerId) VALUES (@p0, @p1, @p2, @p3)',N'@p0 nvarchar(3),@p1 uniqueidentifier,@p2 nvarchar(3),@p3
uniqueidentifier',@p0=N'qaa',@p1='BC95E7EB-5EE8-44B2-82FF30F5176684D',@p2=N'qaa',@p3='18FBF8CE-FD22-4D08-A3B1-63D6DFF426E5'
exec sp\_executesql N'INSERT INTO BackerEntry (BackerId, BackerEntryTypeId, Name, Description, MaxLength, IsRequired, Priority, BackerEntryId) VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7)',N'@p0 uniqueidentifier,@p1 uniqueidentifier,@p2 nvarchar(5),@p3 nvarchar(5),@p4 int,@p5 bit,@p6 int,@p7 uniqueidentifier',@p0='00000000-0000-0000-0000-000000000000',@p1='2C5BDD33-5DD3-42EC-AA0E-F1E548A5F6E4',@p2=N'qaadf',@p3=N'wasdf',@p4=0,@p5=1,@p6=0,@p7='FE9C4A35-6211-4E17-A75A-60CCB526F1CA'
As you can see, its not resetting the empty guid for BackerId on the child to the new real guid of the parent.
Finally, the exception throw is:
```
"NHibernate.Exceptions.GenericADOException: could not insert: [CB.ThePostcardCompany.MiddleTier.BackerEntry][SQL: INSERT INTO BackerEntry (BackerId, BackerEntryTypeId, Name, Description, MaxLength, IsRequired, Priority, BackerEntryId) VALUES (?, ?, ?, ?, ?, ?, ?, ?)] ---\u003e System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint
```
EDIT: SOLVED! The first answer below pointed me into the correct direction. I needed to add that back reference on the child mapping and class. This allowed it to work in a purely .net way - however, when accepting json, there was a disconnect so I had to come up with some quirky code to 're-attach' the children. | You may need to add NOT-NULL="true" to your mapping class:
```
<bag name="BackerEntries" table="BackerEntry" cascade="all" lazy="false" order-by="Priority">
<key column="BackerId" not-null="true"/>
<one-to-many class="BackerEntry" />
</bag>
```
as well as make sure that you have the reverse of the mapping defined for the child class:
```
<many-to-one name="parent" column="PARENT_ID" not-null="true"/>
```
I had similar issues with hibernate on my current project with parent-child relationships, and this was a part of the solution. |
146,607 | <p>My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:</p>
<p>This input:</p>
<blockquote>
The Web
</blockquote>
<p>Should produce this output:</p>
<blockquote>
<p>The Web This Is A Test Variable</p>
</blockquote>
<p>I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)</p>
<p>This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.</p>
<pre><code>def stripMatchedQuotes(item):
MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE)
MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE)
item = MatchedSingleQuotes.sub(r'\1', item, 1)
item = MatchedDoubleQuotes.sub(r'\1', item, 1)
return item
def processVariables(item):
VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE)
VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE)
Variables={}
while VariableDefinition.search(item):
VarName, VarDef = VariableDefinition.search(item).groups()
VarName = stripMatchedQuotes(VarName).upper().strip()
VarDef = stripMatchedQuotes(VarDef.strip())
Variables[VarName] = VarDef
item = VariableDefinition.sub('', item, 1)
while VariableUse.search(item):
VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip()
item = VariableUse.sub(Variables[VarName], item, 1)
return item
</code></pre>
| [
{
"answer_id": 146637,
"author": "JesperE",
"author_id": 13051,
"author_profile": "https://Stackoverflow.com/users/13051",
"pm_score": 2,
"selected": false,
"text": "<p>Never create your own programming language. Ever. (I used to have an exception to this rule, but not any more.)</p>\n\n... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19207/"
] | My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this:
This input:
>
> The Web
>
Should produce this output:
>
> The Web This Is A Test Variable
>
>
>
I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.)
This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with.
```
def stripMatchedQuotes(item):
MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE)
MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE)
item = MatchedSingleQuotes.sub(r'\1', item, 1)
item = MatchedDoubleQuotes.sub(r'\1', item, 1)
return item
def processVariables(item):
VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE)
VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE)
Variables={}
while VariableDefinition.search(item):
VarName, VarDef = VariableDefinition.search(item).groups()
VarName = stripMatchedQuotes(VarName).upper().strip()
VarDef = stripMatchedQuotes(VarDef.strip())
Variables[VarName] = VarDef
item = VariableDefinition.sub('', item, 1)
while VariableUse.search(item):
VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip()
item = VariableUse.sub(Variables[VarName], item, 1)
return item
``` | The first thing that may improve things is to move the re.compile outside the function. The compilation is cached, but there is a speed hit in checking this to see if its compiled.
Another possibility is to use a single regex as below:
```
MatchedQuotes = re.compile(r"(['\"])(.*)\1", re.LOCALE)
item = MatchedQuotes.sub(r'\2', item, 1)
```
Finally, you can combine this into the regex in processVariables. Taking [Torsten Marek's](https://stackoverflow.com/questions/146607/im-using-python-regexes-in-a-criminally-inefficient-manner#146683) suggestion to use a function for re.sub, this improves and simplifies things dramatically.
```
VariableDefinition = re.compile(r'<%(["\']?)(.*?)\1=(["\']?)(.*?)\3%>', re.LOCALE)
VarRepl = re.compile(r'<%(["\']?)(.*?)\1%>', re.LOCALE)
def processVariables(item):
vars = {}
def findVars(m):
vars[m.group(2).upper()] = m.group(4)
return ""
item = VariableDefinition.sub(findVars, item)
return VarRepl.sub(lambda m: vars[m.group(2).upper()], item)
print processVariables('<%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%>')
```
Here are my timings for 100000 runs:
```
Original : 13.637
Global regexes : 12.771
Single regex : 9.095
Final version : 1.846
```
[Edit] Add missing non-greedy specifier
[Edit2] Added .upper() calls so case insensitive like original version |
146,622 | <p>I'm in the process of learning Erlang. As an exercise I picked up the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="noreferrer">Sieve of Eratosthenes</a> algorithm of generating prime numbers. Here is my code:</p>
<pre><code>-module(seed2).
-export([get/1]).
get(N) -> WorkList = lists:duplicate(N, empty),
get(2, N, WorkList, []).
get(thats_the_end, _N, _WorkList, ResultList) -> lists:reverse(ResultList);
get(CurrentPrime, N, WorkList, ResultList) -> ModWorkList = markAsPrime(CurrentPrime, N, WorkList),
NextPrime = findNextPrime(CurrentPrime + 1, N, WorkList),
get(NextPrime, N, ModWorkList, [CurrentPrime|ResultList]).
markAsPrime(CurrentPrime, N, WorkList) when CurrentPrime =< N -> WorkListMod = replace(CurrentPrime, WorkList, prime),
markAllMultiples(CurrentPrime, N, 2*CurrentPrime, WorkListMod).
markAllMultiples(_ThePrime, N, TheCurentMark, WorkList) when TheCurentMark > N -> WorkList;
markAllMultiples(ThePrime, N, TheCurrentMark, WorkList) -> WorkListMod = replace(TheCurrentMark, WorkList, marked),
markAllMultiples(ThePrime, N, TheCurrentMark + ThePrime, WorkListMod).
findNextPrime(Iterator, N, _WorkList) when Iterator > N -> thats_the_end;
findNextPrime(Iterator, N, WorkList) -> I = lists:nth(Iterator, WorkList),
if
I =:= empty -> Iterator;
true -> findNextPrime(Iterator + 1, N, WorkList)
end.
replace(N, L, New)-> {L1, [_H|L2]} = lists:split(N - 1, L),
lists:append(L1, [New|L2]).
</code></pre>
<p>This code actually works :) . The problem is that I have this feeling that it is not the best possible implementation. </p>
<p>My question is what would be the "erlangish" way of implementing the "Sieve of Eratosthenes"</p>
<p>EDIT: OK, Andreas solution is very good but it is slow. Any ideas how to improve that? </p>
| [
{
"answer_id": 146626,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 2,
"selected": false,
"text": "<p>I approached the problem by using concurrent processing.</p>\n\n<p><a href=\"http://web.archive.org/web/20080911213200/... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13635/"
] | I'm in the process of learning Erlang. As an exercise I picked up the [Sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) algorithm of generating prime numbers. Here is my code:
```
-module(seed2).
-export([get/1]).
get(N) -> WorkList = lists:duplicate(N, empty),
get(2, N, WorkList, []).
get(thats_the_end, _N, _WorkList, ResultList) -> lists:reverse(ResultList);
get(CurrentPrime, N, WorkList, ResultList) -> ModWorkList = markAsPrime(CurrentPrime, N, WorkList),
NextPrime = findNextPrime(CurrentPrime + 1, N, WorkList),
get(NextPrime, N, ModWorkList, [CurrentPrime|ResultList]).
markAsPrime(CurrentPrime, N, WorkList) when CurrentPrime =< N -> WorkListMod = replace(CurrentPrime, WorkList, prime),
markAllMultiples(CurrentPrime, N, 2*CurrentPrime, WorkListMod).
markAllMultiples(_ThePrime, N, TheCurentMark, WorkList) when TheCurentMark > N -> WorkList;
markAllMultiples(ThePrime, N, TheCurrentMark, WorkList) -> WorkListMod = replace(TheCurrentMark, WorkList, marked),
markAllMultiples(ThePrime, N, TheCurrentMark + ThePrime, WorkListMod).
findNextPrime(Iterator, N, _WorkList) when Iterator > N -> thats_the_end;
findNextPrime(Iterator, N, WorkList) -> I = lists:nth(Iterator, WorkList),
if
I =:= empty -> Iterator;
true -> findNextPrime(Iterator + 1, N, WorkList)
end.
replace(N, L, New)-> {L1, [_H|L2]} = lists:split(N - 1, L),
lists:append(L1, [New|L2]).
```
This code actually works :) . The problem is that I have this feeling that it is not the best possible implementation.
My question is what would be the "erlangish" way of implementing the "Sieve of Eratosthenes"
EDIT: OK, Andreas solution is very good but it is slow. Any ideas how to improve that? | Here's a simple (but not terribly fast) sieve implementation:
```
-module(primes).
-export([sieve/1]).
-include_lib("eunit/include/eunit.hrl").
sieve([]) ->
[];
sieve([H|T]) ->
List = lists:filter(fun(N) -> N rem H /= 0 end, T),
[H|sieve(List)];
sieve(N) ->
sieve(lists:seq(2,N)).
``` |
146,657 | <p>I have a couple of header files, which boil down to:</p>
<p>tree.h:</p>
<pre><code>#include "element.h"
typedef struct tree_
{
struct *tree_ first_child;
struct *tree_ next_sibling;
int tag;
element *obj;
....
} tree;
</code></pre>
<p>and element.h:</p>
<pre><code>#include "tree.h"
typedef struct element_
{
tree *tree_parent;
char *name;
...
} element;
</code></pre>
<p>The problem is that they both reference each other, so tree needs element to be included, and element needs tree to be included.</p>
<p>This doesn't work because to define the 'tree' structure, the element structure must be already known, but to define the element structure, the tree structure must be known.</p>
<p>How to resolve these types of loops (I think this may have something to do with 'forward declaration'?)?</p>
| [
{
"answer_id": 146665,
"author": "x0n",
"author_id": 6920,
"author_profile": "https://Stackoverflow.com/users/6920",
"pm_score": 0,
"selected": false,
"text": "<p>These are known as \"once-only headers.\" See <a href=\"http://developer.apple.com/DOCUMENTATION/DeveloperTools/gcc-4.0.1/cpp... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19214/"
] | I have a couple of header files, which boil down to:
tree.h:
```
#include "element.h"
typedef struct tree_
{
struct *tree_ first_child;
struct *tree_ next_sibling;
int tag;
element *obj;
....
} tree;
```
and element.h:
```
#include "tree.h"
typedef struct element_
{
tree *tree_parent;
char *name;
...
} element;
```
The problem is that they both reference each other, so tree needs element to be included, and element needs tree to be included.
This doesn't work because to define the 'tree' structure, the element structure must be already known, but to define the element structure, the tree structure must be known.
How to resolve these types of loops (I think this may have something to do with 'forward declaration'?)? | I think the problem here is not the missing include guard but the fact that the two structures need each other in their definition. So it's a type define hann and egg problem.
The way to solve these in C or C++ is to do forward declarations on the type. If you tell the compiler that element is a structure of some sort, the compiler is able to generate a pointer to it.
E.g.
Inside tree.h:
```
// tell the compiler that element is a structure typedef:
typedef struct element_ element;
typedef struct tree_ tree;
struct tree_
{
tree *first_child;
tree *next_sibling;
int tag;
// now you can declare pointers to the structure.
element *obj;
};
```
That way you don't have to include element.h inside tree.h anymore.
You should also put include-guards around your header-files as well. |
146,659 | <p>I know this would be easy with position:fixed, but unfortanately I'm stuck with supporting IE 6. How can I do this? I would rather use CSS to be clean, but if I have to use Javascript, that's not the end of the world. In my current implementation I have a "floating footer" that floats above the main content area and is positioned with Javascript. The implementation I have right now is not particular elegant even with the Javascript, so my questions are:</p>
<ol>
<li>Is there a way to do this without Javascript?</li>
<li>If I have to use Javascript, are there any "nice" solutions to this floating footer problem? By "nice" I mean something that will work across browsers, doesn't overload the browser's resources (since it will have to recalculate often), and is elegant/easy to use (i.e. it would be nice to write something like <code>new FloatingFooter("floatingDiv")</code>).</li>
</ol>
<p>I'm going to guess there is no super easy solution that has everything above, but something I can build off of would be great.</p>
<p>Finally, just a more general question. I know this problem is a big pain to solve, so what are other UI alternatives rather than having footer content at the bottom of every page? On my particular site, I use it to show transitions between steps. Are there other ways I could do this?</p>
| [
{
"answer_id": 146689,
"author": "Mattias",
"author_id": 261,
"author_profile": "https://Stackoverflow.com/users/261",
"pm_score": 2,
"selected": false,
"text": "<p>I have done this using CSS expressions in the Past.</p>\n\n<p>Try something like this:</p>\n\n<pre><code>.footer {\n pos... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2484/"
] | I know this would be easy with position:fixed, but unfortanately I'm stuck with supporting IE 6. How can I do this? I would rather use CSS to be clean, but if I have to use Javascript, that's not the end of the world. In my current implementation I have a "floating footer" that floats above the main content area and is positioned with Javascript. The implementation I have right now is not particular elegant even with the Javascript, so my questions are:
1. Is there a way to do this without Javascript?
2. If I have to use Javascript, are there any "nice" solutions to this floating footer problem? By "nice" I mean something that will work across browsers, doesn't overload the browser's resources (since it will have to recalculate often), and is elegant/easy to use (i.e. it would be nice to write something like `new FloatingFooter("floatingDiv")`).
I'm going to guess there is no super easy solution that has everything above, but something I can build off of would be great.
Finally, just a more general question. I know this problem is a big pain to solve, so what are other UI alternatives rather than having footer content at the bottom of every page? On my particular site, I use it to show transitions between steps. Are there other ways I could do this? | This may work for you. It works on IE6 and Firefox 2.0.0.17 for me. Give it a shot. I made the footer's height very tall, just for effect. You would obviously change it to what you need. I hope this works for you.
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Liquid Footer</title>
<style type="text/css">
.footer {
background-color: #cdcdcd;
height: 180px;
text-align: center;
font-size:10px;
color:#CC0000;
font-family:Verdana;
padding-top: 10px;
width: 100%;
position:fixed;
left: 0px;
bottom: 0px;
}
</style>
<!--[if lte IE 6]>
<style type="text/css">
body {height:100%; overflow-y:auto;}
html {overflow-x:auto; overflow-y:hidden;}
* html .footer {position:absolute;}
</style>
<![endif]-->
</head>
<body>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
This is to expand the content on the page<br>
<div class="footer">-- This is your liquid footer --</div>
</body>
</html>
``` |
146,668 | <p>In ruby I am parsing a date in the following format: 24092008.
I want to convert each section (year, month, date) into a number.</p>
<p>I have split them up using a regex which produces three Strings which I am passing into the Integer constructor.</p>
<pre><code> date =~ /^([\d]{2})([\d]{2})([\d]{4})/
year = Integer($3)
month = Integer($2)
day = Integer($1)
</code></pre>
<p>When it hits the month line it crashes as follows:</p>
<pre><code>`Integer': invalid value for Integer: "09" (ArgumentError)
</code></pre>
<p>It took me a while to realise that it's interpreting the leading zero as Octal and 09 is not a valid Octal number (it works fine with "07").</p>
<p>Is there an elegant solution to this or should I just test for numbers less than 10 and remove the zero first?</p>
<p>Thanks.</p>
| [
{
"answer_id": 146679,
"author": "Atiaxi",
"author_id": 2555346,
"author_profile": "https://Stackoverflow.com/users/2555346",
"pm_score": 5,
"selected": true,
"text": "<p>I'm not familiar with regexes, so forgive me if this answer's off-base. I've been assuming that $3, $2, and $1 are s... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/151/"
] | In ruby I am parsing a date in the following format: 24092008.
I want to convert each section (year, month, date) into a number.
I have split them up using a regex which produces three Strings which I am passing into the Integer constructor.
```
date =~ /^([\d]{2})([\d]{2})([\d]{4})/
year = Integer($3)
month = Integer($2)
day = Integer($1)
```
When it hits the month line it crashes as follows:
```
`Integer': invalid value for Integer: "09" (ArgumentError)
```
It took me a while to realise that it's interpreting the leading zero as Octal and 09 is not a valid Octal number (it works fine with "07").
Is there an elegant solution to this or should I just test for numbers less than 10 and remove the zero first?
Thanks. | I'm not familiar with regexes, so forgive me if this answer's off-base. I've been assuming that $3, $2, and $1 are strings. Here's what I did in IRB to replicate the problem:
```
irb(main):003:0> Integer("04")
=> 4
irb(main):004:0> Integer("09")
ArgumentError: invalid value for Integer: "09"
from (irb):4:in `Integer'
from (irb):4
from :0
```
But it looks like .to\_i doesn't have the same issues:
```
irb(main):005:0> "04".to_i
=> 4
irb(main):006:0> "09".to_i
=> 9
``` |
146,704 | <p>Puzzled by the Lua 5.0 documentation references to things like <code>_LOADED</code>, <code>LUA_PATH</code>, <code>_ALERT</code> and so on (that I could not use in Lua 5.1), I discovered all of those have been removed and the functionality put elsewhere. Am I right in thinking that the only one global variable left in Lua 5.1 is <code>_VERSION</code>?</p>
| [
{
"answer_id": 146679,
"author": "Atiaxi",
"author_id": 2555346,
"author_profile": "https://Stackoverflow.com/users/2555346",
"pm_score": 5,
"selected": true,
"text": "<p>I'm not familiar with regexes, so forgive me if this answer's off-base. I've been assuming that $3, $2, and $1 are s... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12291/"
] | Puzzled by the Lua 5.0 documentation references to things like `_LOADED`, `LUA_PATH`, `_ALERT` and so on (that I could not use in Lua 5.1), I discovered all of those have been removed and the functionality put elsewhere. Am I right in thinking that the only one global variable left in Lua 5.1 is `_VERSION`? | I'm not familiar with regexes, so forgive me if this answer's off-base. I've been assuming that $3, $2, and $1 are strings. Here's what I did in IRB to replicate the problem:
```
irb(main):003:0> Integer("04")
=> 4
irb(main):004:0> Integer("09")
ArgumentError: invalid value for Integer: "09"
from (irb):4:in `Integer'
from (irb):4
from :0
```
But it looks like .to\_i doesn't have the same issues:
```
irb(main):005:0> "04".to_i
=> 4
irb(main):006:0> "09".to_i
=> 9
``` |
146,732 | <p>Within SQL Server Integration Services (SSIS) there is the ability to setup a connection to a flat file that can hold millions of records and have that data pushed to a SQL DB. Furthermore, this process can be called from a C# app by referencing and using the Microsoft.SqlServer.Dts.Runtime namespace. </p>
<p>Would a flat file with millions of records best be ran with SSIS, or would the collective "you" prefer a c# app with multiple worker threads(one to read and add the row to variable, one to write from that variable to the DB), and a "mother" class that manages those threads? (the dev box has two cpu's)</p>
<p>I have seen this data (<a href="http://weblogs.sqlteam.com/mladenp/articles/10631.aspx" rel="nofollow noreferrer">sql team blog</a>) stating that for a flat file with a million lines, SSIS is the fastest:</p>
<pre><code>Process Duration (ms)
-------------------- -------------
SSIS - FastParse ON 7322 ms
SSIS - FastParse OFF 8387 ms
Bulk Insert 10534 ms
OpenRowset 10687 ms
BCP 14922 ms
</code></pre>
<p>What are your thoughts?</p>
| [
{
"answer_id": 146752,
"author": "Michael Brown",
"author_id": 14359,
"author_profile": "https://Stackoverflow.com/users/14359",
"pm_score": 1,
"selected": false,
"text": "<p>SSIS is incredibly fast. In addition, if it's something that needs to occur repeatedly, you can setup an agent to... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952/"
] | Within SQL Server Integration Services (SSIS) there is the ability to setup a connection to a flat file that can hold millions of records and have that data pushed to a SQL DB. Furthermore, this process can be called from a C# app by referencing and using the Microsoft.SqlServer.Dts.Runtime namespace.
Would a flat file with millions of records best be ran with SSIS, or would the collective "you" prefer a c# app with multiple worker threads(one to read and add the row to variable, one to write from that variable to the DB), and a "mother" class that manages those threads? (the dev box has two cpu's)
I have seen this data ([sql team blog](http://weblogs.sqlteam.com/mladenp/articles/10631.aspx)) stating that for a flat file with a million lines, SSIS is the fastest:
```
Process Duration (ms)
-------------------- -------------
SSIS - FastParse ON 7322 ms
SSIS - FastParse OFF 8387 ms
Bulk Insert 10534 ms
OpenRowset 10687 ms
BCP 14922 ms
```
What are your thoughts? | I can only speak for myself and my experience. I would go with SSIS, since this is one of those cases where you might be re-inventing the wheel unnecessarily. This is a repetitive task that has already been solved by SSIS.
I have about 57 jobs (combination of DTS and SSIS) that I manage on a daily basis. Four of those routinely handle exporting between 5 to 100 million records. The database I manage has about 2 billion rows. I made use of a script task to append the date, down to the millisecond, so that I can run jobs several times a day. Been doing that for about 22 months now. It's been great!
SSIS jobs can also be scheduled. So you can set it and forget it. I do monitor everything every day, but the file handling part has never broken down.
The only time I had to resort to a custom C# program, was when I needed to split the very large files into smaller chunks. SSIS is dog slow for that sort of stuff. A one gig text file took about one hour to split, using the script task. The C# custom program handled that in 12 minutes.
In the end, just use what you feel comfortable using. |
146,737 | <p>So I'm programming along in a nice, up to date, object oriented fashion. I regularly make use of the various aspects of OOP that PHP implements but I am wondering when might I need to use closures. Any experts out there that can shed some light on when it would be useful to implement closures?</p>
| [
{
"answer_id": 146775,
"author": "Dan Udey",
"author_id": 21450,
"author_profile": "https://Stackoverflow.com/users/21450",
"pm_score": 4,
"selected": false,
"text": "<p>When you will need a function in the future which performs a task that you have decided upon now.</p>\n\n<p>For exampl... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11252/"
] | So I'm programming along in a nice, up to date, object oriented fashion. I regularly make use of the various aspects of OOP that PHP implements but I am wondering when might I need to use closures. Any experts out there that can shed some light on when it would be useful to implement closures? | PHP will support closures natively in 5.3. A closure is good when you want a local function that's only used for some small, specific purpose. The [RFC for closures](http://wiki.php.net/rfc/closures) gives a good example:
```
function replace_spaces ($text) {
$replacement = function ($matches) {
return str_replace ($matches[1], ' ', ' ').' ';
};
return preg_replace_callback ('/( +) /', $replacement, $text);
}
```
This lets you define the `replacement` function locally inside `replace_spaces()`, so that it's not:
**1)** cluttering up the global namespace
**2)** making people three years down the line wonder why there's a function defined globally that's only used inside one other function
It keeps things organized. Notice how the function itself has no name, it's simply defined and assigned as a reference to `$replacement`.
But remember, you have to wait for PHP 5.3 :) |
146,743 | <p>I need to store a list of key value pairs of (integer, boolean) in .NET</p>
<p>When I use a dictionary it re-orders them. Is there a built in collection that will handle this.</p>
| [
{
"answer_id": 146751,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": true,
"text": "<pre><code> List<KeyValuePair<int, bool>> l = \n new List<KeyValuePair<in... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4998/"
] | I need to store a list of key value pairs of (integer, boolean) in .NET
When I use a dictionary it re-orders them. Is there a built in collection that will handle this. | ```
List<KeyValuePair<int, bool>> l =
new List<KeyValuePair<int, bool>>();
l.Add(new KeyValuePair<int, bool>(1, false));
``` |
146,789 | <p>This question is related to (but perhaps not quite the same as):</p>
<p><a href="https://stackoverflow.com/questions/61451/does-django-have-html-helpers">Does Django have HTML helpers?</a></p>
<p>My problem is this: In Django, I am constantly reproducing the basic formatting for low-level database objects. Here's an example:</p>
<p>I have two classes, Person and Address. There are multiple Addresses for each Person, setup likeso (in their respective <strong>models.py</strong>)</p>
<pre><code>class Person(models.Model):
...
class Address(models.Model):
contact = models.ForeignKey(Person)
</code></pre>
<p>Now, whenever I look at a Person, I want to see all their Addresses. So suppose <strong>Persons/views.py</strong> has something likeso:</p>
<pre><code>def detail(request, person_id):
person = get_object_or_404( Person, pk=person_id )
return render_to_response('persons/details.html',
{ 'title' : unicode(person), 'addresses': person.address_set.all() } )
</code></pre>
<p>And, I have a template, <strong>persons/details.html</strong>, with code, for example, like-so:</p>
<pre><code>{% extends "base.html" %}
{% for address in addresses %}
<b>{{ address.name }}</b>
{{ address.type }} <br>
{{ address.street_1 }}<br>
{{ address.street_2 }}<br>
{{ address.city }} {{ address.stateprov }} {{ address.postalcode }}<br>
{{ address.country }}
<hr>
{{ endfor }}
</code></pre>
<p>I am repeating this code quite a bit, often with minor variations, such when it's in a table, and then < br > must be substituted by < /td >< td >. Other times, I don't want a street_2 to display (or the < br > after it). All to say, there is fundamental logic that I want to express, that I am even more loath to tote around with block-and-copy!</p>
<p>What I want is a <strong>persons/details.html</strong> with, for example, the following: </p>
<pre><code>{% extends "base.html" %}
{% for address in addresses %}
{% address.as_html4 %}
{% endfor %}
</code></pre>
<p>And if I want inline table, something likeso (I guess!):</p>
<pre><code>{% extends "base.html" %}
<table><tr>
{% for address in addresses %}
<tr><td> {% address.as_html4 </td><td> %} </td></tr>
{% endfor %}
</table>
</code></pre>
<p>The question is, then: Where is the best place to put the formatting? The logic?</p>
<p>Django seem to have the following (plausible) options:</p>
<ol>
<li><p>Put the formatting in models.py</p></li>
<li><p>Put the logic/formatting in views.py</p></li>
<li><p>Put the logic/formatting in some other sub-class of Person or Address (i.e. addresses/html4.py)</p></li>
<li><p>Create custom tags</p></li>
</ol>
<p>Help / insight much appreciated!</p>
| [
{
"answer_id": 146829,
"author": "jamting",
"author_id": 2639,
"author_profile": "https://Stackoverflow.com/users/2639",
"pm_score": 2,
"selected": false,
"text": "<p>I would use a template tag outputting data using a template html-file a k a <a href=\"http://docs.djangoproject.com/en/de... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19212/"
] | This question is related to (but perhaps not quite the same as):
[Does Django have HTML helpers?](https://stackoverflow.com/questions/61451/does-django-have-html-helpers)
My problem is this: In Django, I am constantly reproducing the basic formatting for low-level database objects. Here's an example:
I have two classes, Person and Address. There are multiple Addresses for each Person, setup likeso (in their respective **models.py**)
```
class Person(models.Model):
...
class Address(models.Model):
contact = models.ForeignKey(Person)
```
Now, whenever I look at a Person, I want to see all their Addresses. So suppose **Persons/views.py** has something likeso:
```
def detail(request, person_id):
person = get_object_or_404( Person, pk=person_id )
return render_to_response('persons/details.html',
{ 'title' : unicode(person), 'addresses': person.address_set.all() } )
```
And, I have a template, **persons/details.html**, with code, for example, like-so:
```
{% extends "base.html" %}
{% for address in addresses %}
<b>{{ address.name }}</b>
{{ address.type }} <br>
{{ address.street_1 }}<br>
{{ address.street_2 }}<br>
{{ address.city }} {{ address.stateprov }} {{ address.postalcode }}<br>
{{ address.country }}
<hr>
{{ endfor }}
```
I am repeating this code quite a bit, often with minor variations, such when it's in a table, and then < br > must be substituted by < /td >< td >. Other times, I don't want a street\_2 to display (or the < br > after it). All to say, there is fundamental logic that I want to express, that I am even more loath to tote around with block-and-copy!
What I want is a **persons/details.html** with, for example, the following:
```
{% extends "base.html" %}
{% for address in addresses %}
{% address.as_html4 %}
{% endfor %}
```
And if I want inline table, something likeso (I guess!):
```
{% extends "base.html" %}
<table><tr>
{% for address in addresses %}
<tr><td> {% address.as_html4 </td><td> %} </td></tr>
{% endfor %}
</table>
```
The question is, then: Where is the best place to put the formatting? The logic?
Django seem to have the following (plausible) options:
1. Put the formatting in models.py
2. Put the logic/formatting in views.py
3. Put the logic/formatting in some other sub-class of Person or Address (i.e. addresses/html4.py)
4. Create custom tags
Help / insight much appreciated! | Sounds like an [inclusion tag](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags) is what you're looking for. You could have a template and tag for each major variation and use the tag's arguments to customise the context for each template as required.
Basic tag definition:
```
@register.inclusion_tag('person/address.html')
def display_address(address):
return {'address': address}
```
Use in templates (assuming the templatetag module containing it has already been `{% load %}`-ed):
```
{% display_address address %}
``` |
146,794 | <p>I'm running into an unusual problem in my unit tests. The class I'm testing creates a dependency property dynamically at runtime and the type of that dependency property can vary depending on the circumstances. While writing my unit tests, I need to create the dependency property with different types and that leads to errors because you can't redefine an existing dependency property.</p>
<p>So is there any way to either un-register a dependency property or to change the type of an existing dependency property?</p>
<p>Thanks!</p>
<hr>
<p>OverrideMetadata() only lets you change a very few things like default value so it isn't helpful. The AppDomain approach is a good idea and might work but seems more complicated than I really wanted to delve into for the sake of unit testing.</p>
<p>I never did find a way to unregister a dependency property so I punted and carefully reorganized my unit tests to avoid the issue. I'm getting a bit less test coverage, but since this problem would never occur in a real application and only during unit testing I can live with it.</p>
<p>Thanks for the help!</p>
| [
{
"answer_id": 146830,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think you can un-register a dependency property but you can redefine it by overriding the metadata like this:</p>... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9045/"
] | I'm running into an unusual problem in my unit tests. The class I'm testing creates a dependency property dynamically at runtime and the type of that dependency property can vary depending on the circumstances. While writing my unit tests, I need to create the dependency property with different types and that leads to errors because you can't redefine an existing dependency property.
So is there any way to either un-register a dependency property or to change the type of an existing dependency property?
Thanks!
---
OverrideMetadata() only lets you change a very few things like default value so it isn't helpful. The AppDomain approach is a good idea and might work but seems more complicated than I really wanted to delve into for the sake of unit testing.
I never did find a way to unregister a dependency property so I punted and carefully reorganized my unit tests to avoid the issue. I'm getting a bit less test coverage, but since this problem would never occur in a real application and only during unit testing I can live with it.
Thanks for the help! | I had similar issue just yesterday when trying to test my own DependencyProperty creating class. I came across this question, and noticed there was no real solution to unregister dependency properties. So I did some digging using [Red Gate .NET Reflector](http://www.red-gate.com/products/reflector/) to see what I could come up with.
Looking at the `DependencyProperty.Register` overloads, they all seemed to point to `DependencyProperty.RegisterCommon`. That method has two portions:
First to check if the property is already registered
```
FromNameKey key = new FromNameKey(name, ownerType);
lock (Synchronized)
{
if (PropertyFromName.Contains(key))
{
throw new ArgumentException(SR.Get("PropertyAlreadyRegistered",
new object[] { name, ownerType.Name }));
}
}
```
Second, Registering the DependencyProperty
```
DependencyProperty dp =
new DependencyProperty(name, propertyType, ownerType,
defaultMetadata, validateValueCallback);
defaultMetadata.Seal(dp, null);
//...Yada yada...
lock (Synchronized)
{
PropertyFromName[key] = dp;
}
```
Both pieces center around `DependencyProperty.PropertyFromName`, a HashTable. I also noticed the `DependencyProperty.RegisteredPropertyList`, an `ItemStructList<DependencyProperty>` but have not seen where it is used. However, for safety, I figured I'd try to remove from that as well if possible.
So I wound up with the following code that allowed me to "unregister" a dependency property.
```
private void RemoveDependency(DependencyProperty prop)
{
var registeredPropertyField = typeof(DependencyProperty).
GetField("RegisteredPropertyList", BindingFlags.NonPublic | BindingFlags.Static);
object list = registeredPropertyField.GetValue(null);
var genericMeth = list.GetType().GetMethod("Remove");
try
{
genericMeth.Invoke(list, new[] { prop });
}
catch (TargetInvocationException)
{
Console.WriteLine("Does not exist in list");
}
var propertyFromNameField = typeof(DependencyProperty).
GetField("PropertyFromName", BindingFlags.NonPublic | BindingFlags.Static);
var propertyFromName = (Hashtable)propertyFromNameField.GetValue(null);
object keyToRemove = null;
foreach (DictionaryEntry item in propertyFromName)
{
if (item.Value == prop)
keyToRemove = item.Key;
}
if (keyToRemove != null)
propertyFromName.Remove(keyToRemove);
}
```
It worked well enough for me to run my tests without getting an "AlreadyRegistered" exception. However, I strongly recommend that you **do not use this in any sort of production code.** There is likely a reason that MSFT chose not to have a formal way to unregister a dependency property, and attempting to go against it is just asking for trouble. |
146,795 | <p>I can't use the <code>Get*Profile</code> functions because I'm using an older version of the Windows CE platform SDK which doesn't have those. It doesn't have to be too general.</p>
<pre><code>[section]
name = some string
</code></pre>
<p>I just need to open the file, check for the existence of "section", and the value associated with "name". Standard C++ is preferred.</p>
| [
{
"answer_id": 146830,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think you can un-register a dependency property but you can redefine it by overriding the metadata like this:</p>... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
] | I can't use the `Get*Profile` functions because I'm using an older version of the Windows CE platform SDK which doesn't have those. It doesn't have to be too general.
```
[section]
name = some string
```
I just need to open the file, check for the existence of "section", and the value associated with "name". Standard C++ is preferred. | I had similar issue just yesterday when trying to test my own DependencyProperty creating class. I came across this question, and noticed there was no real solution to unregister dependency properties. So I did some digging using [Red Gate .NET Reflector](http://www.red-gate.com/products/reflector/) to see what I could come up with.
Looking at the `DependencyProperty.Register` overloads, they all seemed to point to `DependencyProperty.RegisterCommon`. That method has two portions:
First to check if the property is already registered
```
FromNameKey key = new FromNameKey(name, ownerType);
lock (Synchronized)
{
if (PropertyFromName.Contains(key))
{
throw new ArgumentException(SR.Get("PropertyAlreadyRegistered",
new object[] { name, ownerType.Name }));
}
}
```
Second, Registering the DependencyProperty
```
DependencyProperty dp =
new DependencyProperty(name, propertyType, ownerType,
defaultMetadata, validateValueCallback);
defaultMetadata.Seal(dp, null);
//...Yada yada...
lock (Synchronized)
{
PropertyFromName[key] = dp;
}
```
Both pieces center around `DependencyProperty.PropertyFromName`, a HashTable. I also noticed the `DependencyProperty.RegisteredPropertyList`, an `ItemStructList<DependencyProperty>` but have not seen where it is used. However, for safety, I figured I'd try to remove from that as well if possible.
So I wound up with the following code that allowed me to "unregister" a dependency property.
```
private void RemoveDependency(DependencyProperty prop)
{
var registeredPropertyField = typeof(DependencyProperty).
GetField("RegisteredPropertyList", BindingFlags.NonPublic | BindingFlags.Static);
object list = registeredPropertyField.GetValue(null);
var genericMeth = list.GetType().GetMethod("Remove");
try
{
genericMeth.Invoke(list, new[] { prop });
}
catch (TargetInvocationException)
{
Console.WriteLine("Does not exist in list");
}
var propertyFromNameField = typeof(DependencyProperty).
GetField("PropertyFromName", BindingFlags.NonPublic | BindingFlags.Static);
var propertyFromName = (Hashtable)propertyFromNameField.GetValue(null);
object keyToRemove = null;
foreach (DictionaryEntry item in propertyFromName)
{
if (item.Value == prop)
keyToRemove = item.Key;
}
if (keyToRemove != null)
propertyFromName.Remove(keyToRemove);
}
```
It worked well enough for me to run my tests without getting an "AlreadyRegistered" exception. However, I strongly recommend that you **do not use this in any sort of production code.** There is likely a reason that MSFT chose not to have a formal way to unregister a dependency property, and attempting to go against it is just asking for trouble. |
146,801 | <p>I am using virtual machines for development,but each time I need a new VM, I copy the file and create a new server, but I need a new name for the server to add it to our network.</p>
<p>After renaming the server, the Sharepoint sites have many errors and do not run.</p>
| [
{
"answer_id": 146830,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think you can un-register a dependency property but you can redefine it by overriding the metadata like this:</p>... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13813/"
] | I am using virtual machines for development,but each time I need a new VM, I copy the file and create a new server, but I need a new name for the server to add it to our network.
After renaming the server, the Sharepoint sites have many errors and do not run. | I had similar issue just yesterday when trying to test my own DependencyProperty creating class. I came across this question, and noticed there was no real solution to unregister dependency properties. So I did some digging using [Red Gate .NET Reflector](http://www.red-gate.com/products/reflector/) to see what I could come up with.
Looking at the `DependencyProperty.Register` overloads, they all seemed to point to `DependencyProperty.RegisterCommon`. That method has two portions:
First to check if the property is already registered
```
FromNameKey key = new FromNameKey(name, ownerType);
lock (Synchronized)
{
if (PropertyFromName.Contains(key))
{
throw new ArgumentException(SR.Get("PropertyAlreadyRegistered",
new object[] { name, ownerType.Name }));
}
}
```
Second, Registering the DependencyProperty
```
DependencyProperty dp =
new DependencyProperty(name, propertyType, ownerType,
defaultMetadata, validateValueCallback);
defaultMetadata.Seal(dp, null);
//...Yada yada...
lock (Synchronized)
{
PropertyFromName[key] = dp;
}
```
Both pieces center around `DependencyProperty.PropertyFromName`, a HashTable. I also noticed the `DependencyProperty.RegisteredPropertyList`, an `ItemStructList<DependencyProperty>` but have not seen where it is used. However, for safety, I figured I'd try to remove from that as well if possible.
So I wound up with the following code that allowed me to "unregister" a dependency property.
```
private void RemoveDependency(DependencyProperty prop)
{
var registeredPropertyField = typeof(DependencyProperty).
GetField("RegisteredPropertyList", BindingFlags.NonPublic | BindingFlags.Static);
object list = registeredPropertyField.GetValue(null);
var genericMeth = list.GetType().GetMethod("Remove");
try
{
genericMeth.Invoke(list, new[] { prop });
}
catch (TargetInvocationException)
{
Console.WriteLine("Does not exist in list");
}
var propertyFromNameField = typeof(DependencyProperty).
GetField("PropertyFromName", BindingFlags.NonPublic | BindingFlags.Static);
var propertyFromName = (Hashtable)propertyFromNameField.GetValue(null);
object keyToRemove = null;
foreach (DictionaryEntry item in propertyFromName)
{
if (item.Value == prop)
keyToRemove = item.Key;
}
if (keyToRemove != null)
propertyFromName.Remove(keyToRemove);
}
```
It worked well enough for me to run my tests without getting an "AlreadyRegistered" exception. However, I strongly recommend that you **do not use this in any sort of production code.** There is likely a reason that MSFT chose not to have a formal way to unregister a dependency property, and attempting to go against it is just asking for trouble. |
146,835 | <p>I have a project the requires the use of the exec family. My project consist of making an interactive shell. The shell will implement a few basic commands like cd, ls, echo, etc. I have been researching the use of exec, but have not found a useful site. Any suggested links would help.</p>
<pre><code>int ret;
ret = execl ("/bin/ls", "ls", "-1", (char *)0);
</code></pre>
<p>How would i get the output of this operation to show on the screen?</p>
| [
{
"answer_id": 146885,
"author": "Jose Vega",
"author_id": 17162,
"author_profile": "https://Stackoverflow.com/users/17162",
"pm_score": 2,
"selected": false,
"text": "<p>doing<br> </p>\n\n<pre><code>int fd = 1;\ndup(fd);\nclose(fd);\n</code></pre>\n\n<p>gets the output to the screen.</p... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17162/"
] | I have a project the requires the use of the exec family. My project consist of making an interactive shell. The shell will implement a few basic commands like cd, ls, echo, etc. I have been researching the use of exec, but have not found a useful site. Any suggested links would help.
```
int ret;
ret = execl ("/bin/ls", "ls", "-1", (char *)0);
```
How would i get the output of this operation to show on the screen? | The code you wrote works for me in a simple test program that does nothing else. Remember, when you call execl, the process retains all of the old file handles. So whatever stdout was when you call execl, it will be the same when the new binary is loaded. If you just want the output to go to the terminal, just make sure stdout goes to the terminal.
If you want to do I/O with another program, popen is good for this (as mgb mentioned). It will fork a new process, set up plumbing for you, call some variant of exec, and return a file handle you can use for communication. |
146,893 | <p>I am a firm believer in the idea that one of the most important things you get from learning a new language is not how to use a new language, but the knowledge of concepts that you get from it. I am not asking how important or useful you think Assembly is, nor do I care if I never use it in any of my real projects. </p>
<p>What I want to know is what concepts of Assembly do you think are most important for any general programmer to know? It doesn't have to be directly related to Assembly - it can also be something that you feel the typical programmer who spends all their time in higher-level languages would not understand or takes for granted, such as the CPU cache.</p>
| [
{
"answer_id": 146908,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 2,
"selected": false,
"text": "<p>Memory, registers, jumps, loops, shifts and the various operations one can perform in assembler. I don't miss the days o... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23175/"
] | I am a firm believer in the idea that one of the most important things you get from learning a new language is not how to use a new language, but the knowledge of concepts that you get from it. I am not asking how important or useful you think Assembly is, nor do I care if I never use it in any of my real projects.
What I want to know is what concepts of Assembly do you think are most important for any general programmer to know? It doesn't have to be directly related to Assembly - it can also be something that you feel the typical programmer who spends all their time in higher-level languages would not understand or takes for granted, such as the CPU cache. | I think assembly language can teach you lots of little things, as well as a few big concepts.
I'll list a few things I can think of here, but there is no substitute for going and learning and using both x86 and a RISC instruction set.
You probably think that integer operations are fastest. If you want to find an integer square root of an integer (i.e. floor(sqrt(i))) it's best to use an integer-only approximation routine, right?
Nah. The math coprocessor (on x86 that is) has a **fsqrt** instruction. Converting to float, taking the square root, and converting to int again is faster than an all-integers algorithm.
Then there are things like accessing memory that you can follow, but not properly apprecatiate, until you've delved into assembly. Say you had a linked list, and the first element in the list contains a variable that you will need to access frequently. The list is reordered rarely. Well, each time you need to access that variable, you need to load the pointer to the first element in the list, then using that, load the variable (assuming you can't keep the address of the variable in a register between uses). If you instead stored the variable outside of the list, you only need a single load operation.
Of course saving a couple of cycles here and there is usually not important these days. But if you plan on writing code that needs to be fast, this kind of knowledge can be applied both with inline assembly and generally in other languages.
How about calling conventions? (Some assemblers take care of this for you - Real Programmers don't use those.) Does the caller or callee clean up the stack? Do you even use the stack? You can pass values in registers - but due to the funny x86 instruction set, it's better to pass certain things in certain registers. And which registers will be preserved? One thing C compilers can't really optimise by themselves is calls.
There are little tricks like PUSHing a return address and then JMPing into a procedure; when the procedure returns it will go to the PUSHed address. This departure from the usual way of thinking about function calls is another one of those "states of enlightenment". If you were ever to design a programming language with innovative features, you ought to know about funny things that the hardware is capable of.
A knowledge of assembly language teaches you architecture-specific things about computer security. How you might exploit buffer overflows, or break into kernel mode, and how to prevent such attacks.
Then there's the ubercoolness of self-modifying code, and as a related issue, mechanisms for things such as relocations and applying patches to code (this needs investigation of machine code as well).
But all these things need the right sort of mind. If you're the sort of person who can put
```
while(x--)
{
...
}
```
to good use once you learn what it does, but would find it difficult to work out what it does by yourself, then assembly language is probably a waste of your time. |
146,896 | <p>How can I access <code>UserId</code> in ASP.NET Membership without using <code>Membership.GetUser(username)</code> in ASP.NET Web Application Project?</p>
<p>Can <code>UserId</code> be included in <code>Profile</code> namespace next to <code>UserName</code> (<code>System.Web.Profile.ProfileBase</code>)?</p>
| [
{
"answer_id": 147660,
"author": "Ted",
"author_id": 9344,
"author_profile": "https://Stackoverflow.com/users/9344",
"pm_score": 4,
"selected": false,
"text": "<p>Is your reason for this to save a database call everytime you need the UserId? If so, when I'm using the ASP.NET MembershipPr... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23280/"
] | How can I access `UserId` in ASP.NET Membership without using `Membership.GetUser(username)` in ASP.NET Web Application Project?
Can `UserId` be included in `Profile` namespace next to `UserName` (`System.Web.Profile.ProfileBase`)? | I decided to write authentication of users users on my own (very simple but it works) and I should done this long time ago.
My original question was about UserId and it is not available from:
```
System.Web.HttpContext.Current.User.Identity.Name
``` |
146,897 | <p>This is a bit of a weird one, and I could well be coding this completely wrong - hence why I've hit the same error twice in two days, in completely different parts of a script. The code I'm using is below:</p>
<pre><code>
public function findAll( $constraints = array() ) {
// Select all records
$SQL = 'SELECT * FROM ' . $this->tableName;
// See if there's any constraints
if( count( $constraints ) > 0 ) {
$SQL .= ' WHERE ';
foreach( $constraints as $field => $value ) {
$SQL .= $field . ' = :' . $field . ' AND ';
}
}
// Remove the final AND and prepare the statement
$SQL = substr( $SQL, 0, -5 );
$PDOStatement = $this->PDO->prepare( $SQL );
// Loop through constraints and bind parameters
foreach( $constraints as $field => $value ) {
print 'Binding ' . $field . ' to ' . $value . ' <br />';
$PDOStatement->bindParam( $field, $value );
}
$PDOStatement->execute();
var_dump($PDOStatement);
while ( $results = $PDOStatement->fetch( PDO::FETCH_ASSOC ) ) {
var_dump($results);
}
}
</code></pre>
<p>I'm pretty new to using PDO, but basically I'm attempting to pass an array of constraints e.g. <pre><code>array( 'active' => 1, 'name' => 'James' )</code></pre> and return all rows from the table <pre><code>WHERE active = 1 AND name = 'James'</code></pre></p>
<p>If I use this array, the SQL executed from the first <pre><code>var_dump( )</code></pre> is <pre><code>SELECT * FROM {table} WHERE active = :active AND name = 'James'</code></pre> - exactly as I expect. The bound parameters prints 'Binding active to 1' and 'Binding name to James' - exactly as expected. The rows exist in the database, and yet the second <pre><code>var_dump()</code></pre> call for $results outputs nothing - i.e. no rows are returned.</p>
<p>If I pass an array of a single constraint, e.g. <pre><code>array( 'active' => 1 )</code></pre>, this works perfectly fine. It appears to be whenever multiple constraints are passed that it stops working.</p>
| [
{
"answer_id": 146925,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 4,
"selected": true,
"text": "<p>That's because <a href=\"http://docs.php.net/manual/en/pdostatement.bindparam.php\" rel=\"noreferrer\"><code>bindParam<... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/393028/"
] | This is a bit of a weird one, and I could well be coding this completely wrong - hence why I've hit the same error twice in two days, in completely different parts of a script. The code I'm using is below:
```
public function findAll( $constraints = array() ) {
// Select all records
$SQL = 'SELECT * FROM ' . $this->tableName;
// See if there's any constraints
if( count( $constraints ) > 0 ) {
$SQL .= ' WHERE ';
foreach( $constraints as $field => $value ) {
$SQL .= $field . ' = :' . $field . ' AND ';
}
}
// Remove the final AND and prepare the statement
$SQL = substr( $SQL, 0, -5 );
$PDOStatement = $this->PDO->prepare( $SQL );
// Loop through constraints and bind parameters
foreach( $constraints as $field => $value ) {
print 'Binding ' . $field . ' to ' . $value . '
';
$PDOStatement->bindParam( $field, $value );
}
$PDOStatement->execute();
var_dump($PDOStatement);
while ( $results = $PDOStatement->fetch( PDO::FETCH_ASSOC ) ) {
var_dump($results);
}
}
```
I'm pretty new to using PDO, but basically I'm attempting to pass an array of constraints e.g.
```
array( 'active' => 1, 'name' => 'James' )
```
and return all rows from the table
```
WHERE active = 1 AND name = 'James'
```
If I use this array, the SQL executed from the first
```
var_dump( )
```
is
```
SELECT * FROM {table} WHERE active = :active AND name = 'James'
```
- exactly as I expect. The bound parameters prints 'Binding active to 1' and 'Binding name to James' - exactly as expected. The rows exist in the database, and yet the second
```
var_dump()
```
call for $results outputs nothing - i.e. no rows are returned.
If I pass an array of a single constraint, e.g.
```
array( 'active' => 1 )
```
, this works perfectly fine. It appears to be whenever multiple constraints are passed that it stops working. | That's because [`bindParam`](http://docs.php.net/manual/en/pdostatement.bindparam.php) works by binding to a variable, and you are re-using the variable (`$value`) for multiple values. Try with [`bindValue`](http://docs.php.net/manual/en/pdostatement.bindvalue.php) instead.
Or even better yet; Pass the values as an array to [`execute`](http://docs.php.net/manual/en/pdostatement.execute.php) instead. This makes the statement stateless, which is generally a good thing in programming. |
146,914 | <p>Is there any way to see an overview of what kind of queries are spent the most time on every day on MySQL?</p>
| [
{
"answer_id": 146922,
"author": "petr k.",
"author_id": 15497,
"author_profile": "https://Stackoverflow.com/users/15497",
"pm_score": 1,
"selected": false,
"text": "<p>You can always set up query logging as described here:<br>\n<a href=\"http://dev.mysql.com/doc/refman/5.0/en/query-log.... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8005/"
] | Is there any way to see an overview of what kind of queries are spent the most time on every day on MySQL? | Yes, mysql can create a slow query log. You'll need to start `mysqld` with the `--log-slow-queries` flag:
```
mysqld --log-slow-queries=/path/to/your.log
```
Then you can parse the log using `mysqldumpslow`:
```
mysqldumpslow /path/to/your.log
```
More info is here (<http://dev.mysql.com/doc/refman/5.0/en/slow-query-log.html>). |
146,916 | <p>I have the following problem:</p>
<p>I have an HTML textbox (<code><input type="text"></code>) whose contents are modified by a script I cannot touch (it is my page, but i'm using external components).</p>
<p>I want to be notified in my script every time the value of that textbox changes, so I can react to it.</p>
<p>I've tried this:</p>
<pre><code>txtStartDate.observe('change', function() { alert('change' + txtStartDate.value) });
</code></pre>
<p>which (predictably) doesn't work. It only gets executed if I myself change the textbox value with the keyboard and then move the focus elsewhere, but it doesn't get executed if the script changes the value.</p>
<p>Is there another event I can listen to, that i'm not aware of?</p>
<p><br /><br /></p>
<p>I'm using the Prototype library, and in case it's relevant, the external component modifying the textbox value is Basic Date Picker (www.basicdatepicker.com) </p>
| [
{
"answer_id": 146928,
"author": "noah",
"author_id": 12034,
"author_profile": "https://Stackoverflow.com/users/12034",
"pm_score": 4,
"selected": true,
"text": "<p>As you've implied, change (and other events) only fire when the user takes some action. A script modifying things won't fir... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] | I have the following problem:
I have an HTML textbox (`<input type="text">`) whose contents are modified by a script I cannot touch (it is my page, but i'm using external components).
I want to be notified in my script every time the value of that textbox changes, so I can react to it.
I've tried this:
```
txtStartDate.observe('change', function() { alert('change' + txtStartDate.value) });
```
which (predictably) doesn't work. It only gets executed if I myself change the textbox value with the keyboard and then move the focus elsewhere, but it doesn't get executed if the script changes the value.
Is there another event I can listen to, that i'm not aware of?
I'm using the Prototype library, and in case it's relevant, the external component modifying the textbox value is Basic Date Picker (www.basicdatepicker.com) | As you've implied, change (and other events) only fire when the user takes some action. A script modifying things won't fire any events. Your only solution is to find some hook into the control that you can hook up to your listener.
Here is how I would do it:
```
basicDatePicker.selectDate = basicDatePicker.selectDate.wrap(function(orig,year,month,day,hide) {
myListener(year,month,day);
return orig(year,month,day,hide);
});
```
That's based on a cursory look with Firebug (I'm not familiar with the component). If there are other ways of selecting a date, then you'll need to wrap those methods as well. |
146,931 | <p>I am working with a log of events where there are about 60 different "types" of events. Each event shares about 10 properties, and then there are subcategories of events that share various extra properties.</p>
<p>How I work with these events does depend on their type or what categorical interfaces they implement.</p>
<p>But it seems to be leading to code bloat. I have a lot of redundancy in the subclass methods because they implement some of the same interfaces.</p>
<p>Is it more appropriate to use a single event class with a "type" property and write logic that checks type and maintain some organization of categories of types (e.g. a list of event types that are category a, a second list that are category b, etc)? Or is the subclass design more appropriate in this case?</p>
<p>First Approach:</p>
<pre><code>public interface Category1 {}
public interface Category2 {}
public abstract class Event {
private base properties...;
}
public class EventType1 extends Event implements Category1, Category2 {
private extra properties ...;
}
public class EventType2 extends Event implements Category3, Category4 {
private extra properties ...;
}
</code></pre>
<p>Second Approach:</p>
<pre><code>public enum EventType {TYPE1, TYPE2, TYPE3, ...}
public class Event {
private union of all possible properties;
private EventType type;
}
</code></pre>
<p>My personal opinion is that it seems like a single event object is what is appropriate, because, if I am thinking about it correctly, there is no need for using inheritance to represent the model because it is really only the behavior and my conditions that alter based on the type. </p>
<p>I need to have code that does stuff like:</p>
<pre><code>if(event instanceof Category1) {
...
}
</code></pre>
<p>This works well in the first approach in that instead of instanceof I can just call the method on the event and implement "the same code" in each of the appropriate subclasses. </p>
<p>But the second approach is so much more concise. Then I write stuff like:</p>
<pre><code>if(CATEGORY1_TYPES.contains(event.getEventType()) {
...
}
</code></pre>
<p>And all my "processing logic" can be organized into a single class and none of it is redundantly spread out among the subclasses. So is this a case where although OO appears more appropriate, it would be better not too?</p>
| [
{
"answer_id": 146946,
"author": "petr k.",
"author_id": 15497,
"author_profile": "https://Stackoverflow.com/users/15497",
"pm_score": 1,
"selected": false,
"text": "<p>I would go with the object per event type solution, but I would instead group commonly used combinations of interfaces ... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2204759/"
] | I am working with a log of events where there are about 60 different "types" of events. Each event shares about 10 properties, and then there are subcategories of events that share various extra properties.
How I work with these events does depend on their type or what categorical interfaces they implement.
But it seems to be leading to code bloat. I have a lot of redundancy in the subclass methods because they implement some of the same interfaces.
Is it more appropriate to use a single event class with a "type" property and write logic that checks type and maintain some organization of categories of types (e.g. a list of event types that are category a, a second list that are category b, etc)? Or is the subclass design more appropriate in this case?
First Approach:
```
public interface Category1 {}
public interface Category2 {}
public abstract class Event {
private base properties...;
}
public class EventType1 extends Event implements Category1, Category2 {
private extra properties ...;
}
public class EventType2 extends Event implements Category3, Category4 {
private extra properties ...;
}
```
Second Approach:
```
public enum EventType {TYPE1, TYPE2, TYPE3, ...}
public class Event {
private union of all possible properties;
private EventType type;
}
```
My personal opinion is that it seems like a single event object is what is appropriate, because, if I am thinking about it correctly, there is no need for using inheritance to represent the model because it is really only the behavior and my conditions that alter based on the type.
I need to have code that does stuff like:
```
if(event instanceof Category1) {
...
}
```
This works well in the first approach in that instead of instanceof I can just call the method on the event and implement "the same code" in each of the appropriate subclasses.
But the second approach is so much more concise. Then I write stuff like:
```
if(CATEGORY1_TYPES.contains(event.getEventType()) {
...
}
```
And all my "processing logic" can be organized into a single class and none of it is redundantly spread out among the subclasses. So is this a case where although OO appears more appropriate, it would be better not too? | It depends on if each type of event inherently has different behavior that the event itself can execute.
Do your Event objects need methods that behave differently per type? If so, use inheritance.
If not, use an enum to classify the event type. |
146,943 | <p>This is something simple I came up with for <a href="https://stackoverflow.com/questions/146795/how-to-read-config-file-entries-from-an-ini-file">this question</a>. I'm not entirely happy with it and I saw it as a chance to help improve my use of STL and streams based programming.</p>
<pre><code>std::wifstream file(L"\\Windows\\myini.ini");
if (file)
{
bool section=false;
while (!file.eof())
{
std::wstring line;
std::getline(file, line);
if (line.empty()) continue;
switch (line[0])
{
// new header
case L'[':
{
std::wstring header;
size_t pos=line.find(L']');
if (pos!=std::wstring::npos)
{
header=line.substr(1, pos);
if (header==L"Section")
section=true;
else
section=false;
}
}
break;
// comments
case ';':
case ' ':
case '#':
break;
// var=value
default:
{
if (!section) continue;
// what if the name = value does not have white space?
// what if the value is enclosed in quotes?
std::wstring name, dummy, value;
lineStm >> name >> dummy;
ws(lineStm);
WCHAR _value[256];
lineStm.getline(_value, ELEMENTS(_value));
value=_value;
}
}
}
}
</code></pre>
<p>How would you improve this? Please do not recommend alternative libraries - I just want a simple method for parsing out some config strings from an INI file.</p>
| [
{
"answer_id": 146998,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 1,
"selected": false,
"text": "<p>This:</p>\n\n<pre><code>for (size_t i=1; i<line.length(); i++)\n {\n if (line[i]!=L']')\n ... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3146/"
] | This is something simple I came up with for [this question](https://stackoverflow.com/questions/146795/how-to-read-config-file-entries-from-an-ini-file). I'm not entirely happy with it and I saw it as a chance to help improve my use of STL and streams based programming.
```
std::wifstream file(L"\\Windows\\myini.ini");
if (file)
{
bool section=false;
while (!file.eof())
{
std::wstring line;
std::getline(file, line);
if (line.empty()) continue;
switch (line[0])
{
// new header
case L'[':
{
std::wstring header;
size_t pos=line.find(L']');
if (pos!=std::wstring::npos)
{
header=line.substr(1, pos);
if (header==L"Section")
section=true;
else
section=false;
}
}
break;
// comments
case ';':
case ' ':
case '#':
break;
// var=value
default:
{
if (!section) continue;
// what if the name = value does not have white space?
// what if the value is enclosed in quotes?
std::wstring name, dummy, value;
lineStm >> name >> dummy;
ws(lineStm);
WCHAR _value[256];
lineStm.getline(_value, ELEMENTS(_value));
value=_value;
}
}
}
}
```
How would you improve this? Please do not recommend alternative libraries - I just want a simple method for parsing out some config strings from an INI file. | >
> // what if the name = value does not have white space?
>
> // what if the value is enclosed in quotes?
>
>
>
I would use boost::regex to match for every different type of element, something like:
```
boost::smatch matches;
boost::regex name_value("(\S+)\s*=\s*(\S+)");
if(boost::regex_match(line, matches, name_value))
{
name = matches[1];
value = matches[2];
}
```
the regular expressions might need some tweaking.
I would also replace de stream.getline with std::getline, getting rid of the static char array. |
146,963 | <p>I'm creating an ORM in PHP, and I've got a class 'ORM' which basically creates an object corresponding to a database table (I'm aiming for similar to/same functionality as an ActiveRecord pattern.) ORM itself extends 'Database', which sets up the database connection. </p>
<p>So, I can call: <code><pre>$c = new Customer();
$c->name = 'John Smith';
$c->save();</pre></code></p>
<p>The ORM class provides this functionality (sets up the class properties, provides save(), find(), findAll() etc. methods), and Customer extends ORM. However, in the future I may be wanting to add extra public methods to Customer (or any other model I create), so should this be extending ORM or not?</p>
<p>I know I haven't provided much information here, but hopefully this is understandable on a vague explanation, as opposed to posting up 300+ lines of code.</p>
| [
{
"answer_id": 146969,
"author": "petr k.",
"author_id": 15497,
"author_profile": "https://Stackoverflow.com/users/15497",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, place your business logic in a descendant class. This is a very common pattern seen in most Data Access Layers gen... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/393028/"
] | I'm creating an ORM in PHP, and I've got a class 'ORM' which basically creates an object corresponding to a database table (I'm aiming for similar to/same functionality as an ActiveRecord pattern.) ORM itself extends 'Database', which sets up the database connection.
So, I can call: ````
$c = new Customer();
$c->name = 'John Smith';
$c->save();
````
The ORM class provides this functionality (sets up the class properties, provides save(), find(), findAll() etc. methods), and Customer extends ORM. However, in the future I may be wanting to add extra public methods to Customer (or any other model I create), so should this be extending ORM or not?
I know I haven't provided much information here, but hopefully this is understandable on a vague explanation, as opposed to posting up 300+ lines of code. | I agree with the other answers here - put the additional methods into a descendant class. I'd also add an asterisk to that though: each time you extend the class with extra methods, think about what you are trying to achieve with the extension, and think about whether or not it can be generalised and worked back into the parent class. For example:
```
// Customer.class.php
function getByName($name) {
// SELECT * FROM `customer` WHERE `name` = $name
}
// ** this could instead be written as: **
// ORM.class.php
function getByField($field, $value) {
// SELECT * FROM `$this->table` WHERE `$field` = $value
}
``` |
146,973 | <p>I'm making an automated script to read a list from a site posting the latest compiled code. That's the part I've already figured out. The next part of the script is to grab that compiled code from a server with an Untrusted Cert.</p>
<p>This is how I'm going about grabbing the file:</p>
<pre><code>$web = new-object System.Net.WebClient
$web.DownloadFile("https://uri/file.msi", "installer.msi")
</code></pre>
<p>Then I get the following error:</p>
<blockquote>
<p>Exception calling "DownloadFile" with "2" argument(s): "The underlying
connection was closed: Could not establish trust relationship for the
SSL/TLS secure channel."</p>
</blockquote>
<p>I know I'm missing something, but I can't get the correct way to search for it.</p>
| [
{
"answer_id": 147006,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 3,
"selected": true,
"text": "<p>You need to write a callback handler for <a href=\"http://msdn.microsoft.com/en-us/library/system.net.servicepointmana... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm making an automated script to read a list from a site posting the latest compiled code. That's the part I've already figured out. The next part of the script is to grab that compiled code from a server with an Untrusted Cert.
This is how I'm going about grabbing the file:
```
$web = new-object System.Net.WebClient
$web.DownloadFile("https://uri/file.msi", "installer.msi")
```
Then I get the following error:
>
> Exception calling "DownloadFile" with "2" argument(s): "The underlying
> connection was closed: Could not establish trust relationship for the
> SSL/TLS secure channel."
>
>
>
I know I'm missing something, but I can't get the correct way to search for it. | You need to write a callback handler for [ServicePointManager.ServerCertificateValidationCallback](http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.servercertificatevalidationcallback.aspx). |
146,986 | <p>I'm writing some semi-portable code and want to be able to detect when I'm compiling for iPhone. So I want something like <code>#ifdef IPHONE_SDK...</code>. </p>
<p>Presumably Xcode defines something, but I can't see anything under project properties, and Google isn't much help.</p>
| [
{
"answer_id": 147027,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 8,
"selected": true,
"text": "<p>It's in the SDK docs under \"Compiling source code conditionally\"</p>\n\n<p>The relevant definitions are TARGET_O... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18017/"
] | I'm writing some semi-portable code and want to be able to detect when I'm compiling for iPhone. So I want something like `#ifdef IPHONE_SDK...`.
Presumably Xcode defines something, but I can't see anything under project properties, and Google isn't much help. | It's in the SDK docs under "Compiling source code conditionally"
The relevant definitions are TARGET\_OS\_IPHONE (and he deprecated TARGET\_IPHONE\_SIMULATOR), which are defined in /usr/include/TargetConditionals.h within the iOS framework. On earlier versions of the toolchain, you had to write:
```
#include "TargetConditionals.h"
```
but this is no longer necessary on the current (xCode 6/iOS8) toolchain.
So, for example, if you want to only compile a block of code if you are building for the device, then you should do
```
#if !(TARGET_OS_SIMULATOR)
...
#endif
``` |
146,989 | <p>One of my nasty (?) programming habits in C++ and Java is to always precede calls or accesses to members with a <code>this</code>. For example: <code>this.process(this.event)</code>.</p>
<p>A few of my students commented on this, and I'm wondering if I am teaching bad habits. </p>
<p>My rationale is:</p>
<ol>
<li>Makes code more readable — Easier to distinguish fields from local variables.</li>
<li>Makes it easier to distinguish standard calls from static calls (especially in Java)</li>
<li>Makes me remember that this call (unless the target is final) could end up on a different target, for example in an overriding version in a subclass.</li>
</ol>
<p>Obviously, this has zero impact on the compiled program, it's just readability. So am I making it more or less readable?</p>
<p>Note: I turned it into a CW since there really isn't a correct answer.</p>
| [
{
"answer_id": 146995,
"author": "cynicalman",
"author_id": 410,
"author_profile": "https://Stackoverflow.com/users/410",
"pm_score": 6,
"selected": false,
"text": "<p>I think it's less readable, especially in environments where fields are highlighted differently from local variables. T... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23072/"
] | One of my nasty (?) programming habits in C++ and Java is to always precede calls or accesses to members with a `this`. For example: `this.process(this.event)`.
A few of my students commented on this, and I'm wondering if I am teaching bad habits.
My rationale is:
1. Makes code more readable — Easier to distinguish fields from local variables.
2. Makes it easier to distinguish standard calls from static calls (especially in Java)
3. Makes me remember that this call (unless the target is final) could end up on a different target, for example in an overriding version in a subclass.
Obviously, this has zero impact on the compiled program, it's just readability. So am I making it more or less readable?
Note: I turned it into a CW since there really isn't a correct answer. | I think it's less readable, especially in environments where fields are highlighted differently from local variables. The only time I want to see "this" is when it is required, for example:
```
this.fieldName = fieldName
```
When assigning the field.
That said, if you need some way to differentiate fields for some reason, I prefer "this.fieldName" to other conventions, like "m\_fieldName" or "\_fieldName" |
146,994 | <p>I'm looking for a free, preferably open source, http <a href="http://en.wikipedia.org/wiki/Image_server" rel="noreferrer">image processing server</a>. I.e. I would send it a request like this:</p>
<pre><code>http://myimageserver/rotate?url=http%3A%2F%2Fstackoverflow.com%2FContent%2FImg%2Fstackoverflow-logo-250.png&angle=90
</code></pre>
<p>and it would return that image rotated. Features wanted:</p>
<ul>
<li>Server-side caching</li>
<li>Several operations/effects (like scaling, watermarking, etc). The more the merrier.</li>
<li>POST support to supply the image (instead of the server GETting it).</li>
<li>Different output formats (PNG, JPEG, etc).</li>
<li>Batch operations</li>
</ul>
<p>It would be something like <a href="http://leadtools.com/SDK/web-services/Image-Service/default.htm" rel="noreferrer">this</a>, but free and less SOAPy. Is there anything like this or am I asking too much?</p>
| [
{
"answer_id": 147012,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"http://libgd.org\" rel=\"nofollow noreferrer\">LibGD</a> or <a href=\"http://www.imagemagick.org\... | 2008/09/28 | [
"https://Stackoverflow.com/questions/146994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21239/"
] | I'm looking for a free, preferably open source, http [image processing server](http://en.wikipedia.org/wiki/Image_server). I.e. I would send it a request like this:
```
http://myimageserver/rotate?url=http%3A%2F%2Fstackoverflow.com%2FContent%2FImg%2Fstackoverflow-logo-250.png&angle=90
```
and it would return that image rotated. Features wanted:
* Server-side caching
* Several operations/effects (like scaling, watermarking, etc). The more the merrier.
* POST support to supply the image (instead of the server GETting it).
* Different output formats (PNG, JPEG, etc).
* Batch operations
It would be something like [this](http://leadtools.com/SDK/web-services/Image-Service/default.htm), but free and less SOAPy. Is there anything like this or am I asking too much? | The [ImageResizing.Net library](http://imageresizing.net) is both a .NET library and an IIS module. It's an image server or an image library, whichever you prefer.
It's open-source, under an [MIT-style license](http://imageresizing.net/licenses/), and is supported by plugins.
It has excellent performance, and supports 3 pipelines: GDI+, Windows Imaging Components, and FreeImage. WIC is the fastest, and can do some operations in under 15ms. It supports disk caching (for up to 1 million files), and is CDN compatible (Amazon CloudFront is ideal).
It has a very human-friendly URL syntax. Ex. `image.jpg?width=100&height=100&mode=crop`.
It supports resizing, cropping, padding, rotation, PNG/GIF/JPG output, borders, watermarking, remote URLs, Amazon S3, MS SQL, Amazon CloudFront, batch operations, image filters, disk caching, and lots of other cool stuff, like seam carving.
It doesn't support POST delivery of images, but that's easy to do with a plugin. And don't you typically want to store images that are delivered via POST instead of just replying to the POST command with the result?
[Disclosure: I'm the author of ImageResizer] |
147,040 | <p>Is there a way to have Visual Studio 2008 automatically add heading information to files? For example, "Copyright 2008" or something along those lines. I've been digging through the options, but nothing seems to be jumping out at me.</p>
| [
{
"answer_id": 147043,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 3,
"selected": true,
"text": "<p>I assume you'd like to modify the class file templates. They're in:</p>\n\n<pre><code>%ProgramFiles%\\Microsoft... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1880/"
] | Is there a way to have Visual Studio 2008 automatically add heading information to files? For example, "Copyright 2008" or something along those lines. I've been digging through the options, but nothing seems to be jumping out at me. | I assume you'd like to modify the class file templates. They're in:
```
%ProgramFiles%\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033
```
[More specific details here](http://blogs.southworks.net/jpgarcia/2008/09/01/visual-studio-2008-templates-compliant-with-microsoft-stylecop/) |
147,049 | <p>In other words, is it correct to use:</p>
<pre><code>public class CustomerList : System.Collections.Generic.List<Customer>
{
/// supposed to be empty
}
</code></pre>
<p>instead of:</p>
<pre><code>using CustomerList = System.Collections.Generic.List<Customer>
</code></pre>
<p>I'd rather use the first approach because I'd just define CustomerList once, and every time I needed a customer list I'd always use the same type. On the other hand, using the name aliasing approach not only forces me to have to redefine it everywhere, but also a different alias could be given every time someone wanted to use it (think of a big team), and thus cause the code to be less readable.</p>
<p>Please note that the intention in this case would never be to extend the class, just to create an alias.</p>
| [
{
"answer_id": 147060,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": 4,
"selected": false,
"text": "<p>well, unless you are adding some functionality to the base class there is no point in creating a wrapper object. I would g... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7839/"
] | In other words, is it correct to use:
```
public class CustomerList : System.Collections.Generic.List<Customer>
{
/// supposed to be empty
}
```
instead of:
```
using CustomerList = System.Collections.Generic.List<Customer>
```
I'd rather use the first approach because I'd just define CustomerList once, and every time I needed a customer list I'd always use the same type. On the other hand, using the name aliasing approach not only forces me to have to redefine it everywhere, but also a different alias could be given every time someone wanted to use it (think of a big team), and thus cause the code to be less readable.
Please note that the intention in this case would never be to extend the class, just to create an alias. | Don't do it. When people read:
```
List<Customer>
```
they immediately understand it. When they read:
```
CustomerList
```
they have to go and figure out what a CustomerList is, and that makes your code harder to read. Unless you are the only one working on your codebase, writing readable code is a good idea. |
147,053 | <p>I'm creating a new mail item, in C# VS-2008 outlook 2007, and attaching a file. The first issue is that I don't see an attachment area under the subject line showing the attachment. If I send the e-mail its properties show that there is an attachment and the e-mail size has grown by the attachment amount. I just cannot see it or extract the attachment.</p>
<p>Here is the code I'm using:</p>
<pre><code>Outlook.MailItem mailItem = (Outlook.MailItem)this.Application.CreateItem(Outlook.OlItemType.olMailItem);
attachments.Add(ReleaseForm.ZipFile, Outlook.OlAttachmentType.olByValue, 0, "DisplayName");
</code></pre>
<p>I am expecting the part "DisplayName" would show as the attachment name and I should be using the filename.</p>
<p>I don't call .Send() on the e-mail programmatically, I call mailItem.Display(true) to show the e-mail to the user for any final edits. At this point I can look at the properties and see that there is an attachment there.</p>
<p>If I press send (sending to myself) I see the same thing, the attachment appears to be there but not accessible.</p>
| [
{
"answer_id": 147188,
"author": "John Dyer",
"author_id": 2862,
"author_profile": "https://Stackoverflow.com/users/2862",
"pm_score": 2,
"selected": false,
"text": "<p>I have found the issue. I change the code to use the following:</p>\n\n<pre><code>attachments.Add(ReleaseForm.ZipFile,... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2862/"
] | I'm creating a new mail item, in C# VS-2008 outlook 2007, and attaching a file. The first issue is that I don't see an attachment area under the subject line showing the attachment. If I send the e-mail its properties show that there is an attachment and the e-mail size has grown by the attachment amount. I just cannot see it or extract the attachment.
Here is the code I'm using:
```
Outlook.MailItem mailItem = (Outlook.MailItem)this.Application.CreateItem(Outlook.OlItemType.olMailItem);
attachments.Add(ReleaseForm.ZipFile, Outlook.OlAttachmentType.olByValue, 0, "DisplayName");
```
I am expecting the part "DisplayName" would show as the attachment name and I should be using the filename.
I don't call .Send() on the e-mail programmatically, I call mailItem.Display(true) to show the e-mail to the user for any final edits. At this point I can look at the properties and see that there is an attachment there.
If I press send (sending to myself) I see the same thing, the attachment appears to be there but not accessible. | I have found the issue. I change the code to use the following:
```
attachments.Add(ReleaseForm.ZipFile, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
```
It appears that the Position and DisplayName parameters control what happens with an olByValue. Using Type.Missing and now I see the attachments correctly in the e-mail. |
147,083 | <p>I have a standard windows server that inherits from the ServiceBase class.</p>
<p>On the OnStart method I want to check for certain conditions before I get to the main purpose of what my service does.</p>
<p>For example:</p>
<pre><code>protected override void OnStart(string[] args)
{
if (condition == false)
{
EventLog.WriteEntry("Pre-condition not met, service was unable to start");
// TODO: Convert service state to "Stopped" because my precondition wasn't met
return;
}
InnitializeService();
}
</code></pre>
<p>Anybody have a good example for how a service can control its own state?</p>
| [
{
"answer_id": 147127,
"author": "Lounges",
"author_id": 8918,
"author_profile": "https://Stackoverflow.com/users/8918",
"pm_score": 5,
"selected": true,
"text": "<p>Checkout the source for the wordpress app. They might be using XML-RPC. :)</p>\n\n<p><a href=\"http://iphone.wordpress.or... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2049/"
] | I have a standard windows server that inherits from the ServiceBase class.
On the OnStart method I want to check for certain conditions before I get to the main purpose of what my service does.
For example:
```
protected override void OnStart(string[] args)
{
if (condition == false)
{
EventLog.WriteEntry("Pre-condition not met, service was unable to start");
// TODO: Convert service state to "Stopped" because my precondition wasn't met
return;
}
InnitializeService();
}
```
Anybody have a good example for how a service can control its own state? | Checkout the source for the wordpress app. They might be using XML-RPC. :)
<http://iphone.wordpress.org/> |
147,126 | <p>Short Q.: What does this exception mean? "EXC_BAD_ACCESS (0x0001)"</p>
<p>Full Q.: How can I use this error log info (and thread particulars that I omitted here) to diagnosis this app crash? (NB: I have no expertise with crash logs or OS kernels.)</p>
<p>In this case, my email client (Eudora) crashes immediately on launch, every time, after no apparent system changes.</p>
<pre><code>Host Name: [name of Mac]
Date/Time: 2008-09-28 14:46:54.177 -0400
OS Version: 10.4.11 (Build 8S165)
Report Version: 4
Command: Eudora
Path: /Applications/[...]/Eudora Application Folder/Eudora.app/Contents/MacOS/Eudora
Parent: WindowServer [59]
Version: 6.2.4 (6.2.4)
PID: 231
Thread: 0
Exception: EXC_BAD_ACCESS (0x0001)
Codes: KERN_PROTECTION_FAILURE (0x0002) at 0x00000001
</code></pre>
| [
{
"answer_id": 147150,
"author": "Dprado",
"author_id": 21943,
"author_profile": "https://Stackoverflow.com/users/21943",
"pm_score": 1,
"selected": false,
"text": "<p>Even if you page the apps memory to disk and keep it in memory, you would still have to decide when should an applicatio... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23306/"
] | Short Q.: What does this exception mean? "EXC\_BAD\_ACCESS (0x0001)"
Full Q.: How can I use this error log info (and thread particulars that I omitted here) to diagnosis this app crash? (NB: I have no expertise with crash logs or OS kernels.)
In this case, my email client (Eudora) crashes immediately on launch, every time, after no apparent system changes.
```
Host Name: [name of Mac]
Date/Time: 2008-09-28 14:46:54.177 -0400
OS Version: 10.4.11 (Build 8S165)
Report Version: 4
Command: Eudora
Path: /Applications/[...]/Eudora Application Folder/Eudora.app/Contents/MacOS/Eudora
Parent: WindowServer [59]
Version: 6.2.4 (6.2.4)
PID: 231
Thread: 0
Exception: EXC_BAD_ACCESS (0x0001)
Codes: KERN_PROTECTION_FAILURE (0x0002) at 0x00000001
``` | According to this [1](http://www.linux-tutorial.info/modules.php?name=MContent&pageid=314) that is exactly what Linux does.
I'm still trying to make sense of a lot of this, so any authoritative links would be appreciated. |
147,129 | <p><strong>Is there a better way of binding a list of base class to a UI other than downcasting e.g:</strong></p>
<pre><code>static void Main(string[] args) {
List<Animal> list = new List<Animal>();
Pig p = new Pig(5);
Dog d = new Dog("/images/dog1.jpg");
list.Add(p);
list.Add(d);
foreach (Animal a in list)
{
DoPigStuff(a as Pig);
DoDogStuff(a as Dog);
}
}
static void DoPigStuff(Pig p)
{
if (p != null)
{
label1.Text = String.Format("The pigs tail is {0}", p.TailLength);
}
}
static void DoDogStuff(Dog d) {
if (d != null)
{
Image1.src = d.Image;
}
}
class Animal {
public String Name { get; set; }
}
class Pig : Animal{
public int TailLength { get; set; }
public Pig(int tailLength)
{
Name = "Mr Pig";
TailLength = tailLength;
}
}
class Dog : Animal {
public String Image { get; set; }
public Dog(String image)
{
Name = "Mr Dog";
Image = image;
}
}
</code></pre>
| [
{
"answer_id": 147139,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 3,
"selected": false,
"text": "<p>Why not make Animal include an abstract method that Pig and Dog are forced to implement </p>\n\n<pre><code>public clas... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736/"
] | **Is there a better way of binding a list of base class to a UI other than downcasting e.g:**
```
static void Main(string[] args) {
List<Animal> list = new List<Animal>();
Pig p = new Pig(5);
Dog d = new Dog("/images/dog1.jpg");
list.Add(p);
list.Add(d);
foreach (Animal a in list)
{
DoPigStuff(a as Pig);
DoDogStuff(a as Dog);
}
}
static void DoPigStuff(Pig p)
{
if (p != null)
{
label1.Text = String.Format("The pigs tail is {0}", p.TailLength);
}
}
static void DoDogStuff(Dog d) {
if (d != null)
{
Image1.src = d.Image;
}
}
class Animal {
public String Name { get; set; }
}
class Pig : Animal{
public int TailLength { get; set; }
public Pig(int tailLength)
{
Name = "Mr Pig";
TailLength = tailLength;
}
}
class Dog : Animal {
public String Image { get; set; }
public Dog(String image)
{
Name = "Mr Dog";
Image = image;
}
}
``` | When faced with this type of problem, I follow the [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern).
```
interface IVisitor
{
void DoPigStuff(Piggy p);
void DoDogStuff(Doggy d);
}
class GuiVisitor : IVisitor
{
void DoPigStuff(Piggy p)
{
label1.Text = String.Format("The pigs tail is {0}", p.TailLength);
}
void DoDogStuff(Doggy d)
{
Image1.src = d.Image;
}
}
abstract class Animal
{
public String Name { get; set; }
public abstract void Visit(IVisitor visitor);
}
class Piggy : Animal
{
public int TailLength { get; set; }
public Piggy(int tailLength)
{
Name = "Mr Pig";
TailLength = tailLength;
}
public void Visit(IVisitor visitor)
{
visitor.DoPigStuff(this);
}
}
class Doggy : Animal
{
public String Image { get; set; }
public Doggy(String image)
{
Name = "Mr Dog";
Image = image;
}
public void Visit(IVisitor visitor)
{
visitor.DoDogStuff(this);
}
}
public class AnimalProgram
{
static void Main(string[] args) {
List<Animal> list = new List<Animal>();
Pig p = new Pig(5);
Dog d = new Dog("/images/dog1.jpg");
list.Add(p);
list.Add(d);
IVisitor visitor = new GuiVisitor();
foreach (Animal a in list)
{
a.Visit(visitor);
}
}
}
```
Thus the visitor pattern simulates double dispatch in a conventional single-dispatch object-oriented language such as Java, Smalltalk, C#, and C++.
The only advantage of this code over [jop](https://stackoverflow.com/questions/147129/c-downcasting-when-binding-to-and-interface#147383)'s is that the IVisitor interface can be implemented on a different class later when you need to add a new type of visitor (like a **XmlSerializeVisitor** or a **FeedAnimalVisitor**). |
147,173 | <p>I am trying to understand some assembly.</p>
<p>The assembly as follows, I am interested in the <code>testl</code> line:</p>
<pre><code>000319df 8b4508 movl 0x08(%ebp), %eax
000319e2 8b4004 movl 0x04(%eax), %eax
000319e5 85c0 testl %eax, %eax
000319e7 7407 je 0x000319f0
</code></pre>
<p>I am trying to understand that point of <code>testl</code> between <code>%eax</code> and <code>%eax</code>? I think the specifics of what this code isn't important, I am just trying to understand the test with itself - wouldn't the value always be true?</p>
| [
{
"answer_id": 147176,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 8,
"selected": true,
"text": "<p>It tests whether <code>eax</code> is 0, or above, or below. In this case, the jump is taken if <code>eax</code> is 0.</p>\... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10733/"
] | I am trying to understand some assembly.
The assembly as follows, I am interested in the `testl` line:
```
000319df 8b4508 movl 0x08(%ebp), %eax
000319e2 8b4004 movl 0x04(%eax), %eax
000319e5 85c0 testl %eax, %eax
000319e7 7407 je 0x000319f0
```
I am trying to understand that point of `testl` between `%eax` and `%eax`? I think the specifics of what this code isn't important, I am just trying to understand the test with itself - wouldn't the value always be true? | It tests whether `eax` is 0, or above, or below. In this case, the jump is taken if `eax` is 0. |
147,178 | <p>Suppose I have a date, i.e. year, month and day, as integers. What's a good (correct), concise and fairly readable algorithm for computing the <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO 8601</a> <a href="http://en.wikipedia.org/wiki/ISO_week_date" rel="noreferrer">week number</a> of the week the given date falls into? I have come across some truly horrendous code that makes me think surely there must be a better way.</p>
<p>I'm looking to do this in Java but psuedocode for any kind of object-oriented language is fine.</p>
| [
{
"answer_id": 147193,
"author": "technophile",
"author_id": 23029,
"author_profile": "https://Stackoverflow.com/users/23029",
"pm_score": 4,
"selected": false,
"text": "<p>I believe you can use the Calendar object (just set FirstDayOfWeek to Monday and MinimalDaysInFirstWeek to 4 to get... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9511/"
] | Suppose I have a date, i.e. year, month and day, as integers. What's a good (correct), concise and fairly readable algorithm for computing the [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601) [week number](http://en.wikipedia.org/wiki/ISO_week_date) of the week the given date falls into? I have come across some truly horrendous code that makes me think surely there must be a better way.
I'm looking to do this in Java but psuedocode for any kind of object-oriented language is fine. | tl;dr
=====
```
LocalDate.of( 2015 , 12 , 30 )
.get (
IsoFields.WEEK_OF_WEEK_BASED_YEAR
)
```
>
> 53
>
>
>
…or…
```
org.threeten.extra.YearWeek.from (
LocalDate.of( 2015 , 12 , 30 )
)
```
>
> 2015-W53
>
>
>
java.time
=========
Support for the [ISO 8601 week](https://en.wikipedia.org/wiki/ISO_week_date) is now built into Java 8 and later, in the [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) framework. Avoid the old and notoriously troublesome java.util.Date/.Calendar classes as they have been supplanted by java.time.
These new java.time classes include [`LocalDate`](http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html) for date-only value without time-of-day or time zone. Note that you must specify a time zone to determine ‘today’ as the date is not simultaneously the same around the world.
```
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now ( zoneId );
```
Or specify the year, month, and day-of-month as suggested in the Question.
```
LocalDate localDate = LocalDate.of( year , month , dayOfMonth );
```
The [`IsoFields`](https://docs.oracle.com/javase/8/docs/api/java/time/temporal/IsoFields.html) class provides info according to the ISO 8601 standard including the week-of-year for a week-based year.
```
int calendarYear = now.getYear();
int weekNumber = now.get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR );
int weekYear = now.get ( IsoFields.WEEK_BASED_YEAR );
```
Near the beginning/ending of a year, the week-based-year may be ±1 different than the calendar-year. For example, notice the difference between the Gregorian and ISO 8601 calendars for the end of 2015: Weeks 52 & 1 become 52 & 53.
[](https://i.stack.imgur.com/8WO81.png)
[](https://i.stack.imgur.com/kHwC5.png)
ThreeTen-Extra — `YearWeek`
===========================
The [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html) class represents both the ISO 8601 week-based year number *and* the week number together as a single object. This class is found in the [*ThreeTen-Extra*](http://www.threeten.org/threeten-extra/) project. The project adds functionality to the java.time classes built into Java.
```
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
YearWeek yw = YearWeek.now( zoneId ) ;
```
Generate a `YearWeek` from a date.
```
YearWeek yw = YearWeek.from (
LocalDate.of( 2015 , 12 , 30 )
)
```
This class can generate and parse strings in standard ISO 8601 format.
```
String output = yw.toString() ;
```
>
> 2015-W53
>
>
>
```
YearWeek yw = YearWeek.parse( "2015-W53" ) ;
```
You can extract the week number or the week-based-year number.
```
int weekNumber = yw.getWeek() ;
int weekBasedYearNumber = yw.getYear() ;
```
You can generate a particular date (`LocalDate`) by specifying a desired day-of-week to be found within that week. To specify the day-of-week, use the `DayOfWeek` enum built into Java 8 and later.
```
LocalDate ld = yw.atDay( DayOfWeek.WEDNESDAY ) ;
```
---
About *java.time*
=================
The [*java.time*](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old [legacy](https://en.wikipedia.org/wiki/Legacy_system) date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), & [`SimpleDateFormat`](http://docs.oracle.com/javase/10/docs/api/java/text/SimpleDateFormat.html).
To learn more, see the [*Oracle Tutorial*](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Specification is [JSR 310](https://jcp.org/en/jsr/detail?id=310).
The [*Joda-Time*](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [java.time](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes.
You may exchange *java.time* objects directly with your database. Use a [JDBC driver](https://en.wikipedia.org/wiki/JDBC_driver) compliant with [JDBC 4.2](http://openjdk.java.net/jeps/170) or later. No need for strings, no need for `java.sql.*` classes.
Where to obtain the java.time classes?
* [**Java SE 8**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8), [**Java SE 9**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9), [**Java SE 10**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_10), [**Java SE 11**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_11), and later - Part of the standard Java API with a bundled implementation.
+ Java 9 adds some minor features and fixes.
* [**Java SE 6**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6) and [**Java SE 7**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7)
+ Most of the *java.time* functionality is back-ported to Java 6 & 7 in [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/).
* [**Android**](https://en.wikipedia.org/wiki/Android_(operating_system))
+ Later versions of Android bundle implementations of the *java.time* classes.
+ For earlier Android (<26), the [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP) project adapts [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) (mentioned above). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706).
The [**ThreeTen-Extra**](http://www.threeten.org/threeten-extra/) project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as [`Interval`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html), [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html), [`YearQuarter`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html), and [more](http://www.threeten.org/threeten-extra/apidocs/index.html). |
147,208 | <p>Is there a way to hide table rows without affecting the overall table width? I've got some javascript that shows/hides some table rows, but when the rows are set to <code>display: none;</code>, the table with shrinks to fit the contents of the visible rows.</p>
| [
{
"answer_id": 147216,
"author": "levik",
"author_id": 4465,
"author_profile": "https://Stackoverflow.com/users/4465",
"pm_score": 4,
"selected": true,
"text": "<p>If you are looking to preserve the overall width of the table, you can check it prior to hiding a row, and explicitly set th... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] | Is there a way to hide table rows without affecting the overall table width? I've got some javascript that shows/hides some table rows, but when the rows are set to `display: none;`, the table with shrinks to fit the contents of the visible rows. | If you are looking to preserve the overall width of the table, you can check it prior to hiding a row, and explicitly set the width style property to this value:
```
table.style.width = table.clientWidth + "px";
table.rows[3].style.display = "none";
```
However, this may cause the individual columns to reflow when you hide the row. A possible way to mitigate this is by adding a style to your table:
```
table {
table-layout: fixed;
}
``` |
147,210 | <p>I have a T-SQL <strong>table variable</strong> (not a table) which has an auto incrementing identity column. I want to clear all data from this variable and reset the identity column value to 1. How can this be done?</p>
| [
{
"answer_id": 147224,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 5,
"selected": false,
"text": "<p>Truncating the table will dump ALL the data, and reset the identity seed.</p>\n\n<p>Otherwise, you can use this ... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/747/"
] | I have a T-SQL **table variable** (not a table) which has an auto incrementing identity column. I want to clear all data from this variable and reset the identity column value to 1. How can this be done? | If you're using a table variable, you can't do it. If it were a table, you could truncate it or use `DBCC CHECKIDENT`. But, if you *have* to use a table variable, you have to use something other than an identity column. Or, more accurately, use the identity column in your table variable but output using `ROWNUMBER`:
```
DECLARE @t table (pkint int IDENTITY(1,1), somevalue nvarchar(50))
INSERT INTO @t (somevalue) VALUES( 'one')
INSERT INTO @t (somevalue) VALUES('twp')
INSERT INTO @t (somevalue) VALUES('three')
SELECT row_number() OVER (ORDER BY pkint), somevalue FROM @t
DELETE FROM @t
INSERT INTO @t (somevalue) VALUES('four')
SELECT row_number() OVER (ORDER BY pkint), somevalue FROM @t
```
It's the best you can do with the table variable. |
147,240 | <pre><code>('1' * N) !~ /^1?$|^(11+?)\1+$/
</code></pre>
<p>On the net, I found this piece of Ruby code that works for N >= 0 that determines whether or not N is a prime. From what I can tell, it looks like play with regex but I have no idea how it works. Could someone tell me how it works?</p>
| [
{
"answer_id": 147251,
"author": "Jay",
"author_id": 20840,
"author_profile": "https://Stackoverflow.com/users/20840",
"pm_score": 6,
"selected": true,
"text": "<p>You can find a lengthy explanation of this code here: \n<a href=\"http://www.noulakaz.net/weblog/2007/03/18/a-regular-expres... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
('1' * N) !~ /^1?$|^(11+?)\1+$/
```
On the net, I found this piece of Ruby code that works for N >= 0 that determines whether or not N is a prime. From what I can tell, it looks like play with regex but I have no idea how it works. Could someone tell me how it works? | You can find a lengthy explanation of this code here:
<http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/> |
147,267 | <p>Here's what I am trying to do: </p>
<pre><code>typedef enum { ONE, TWO, THREE } Numbers;
</code></pre>
<p>I am trying to write a function that would do a switch case similar to the following: </p>
<pre><code>char num_str[10];
int process_numbers_str(Numbers num) {
switch(num) {
case ONE:
case TWO:
case THREE:
{
strcpy(num_str, num); //some way to get the symbolic constant name in here?
} break;
default:
return 0; //no match
return 1;
}
</code></pre>
<p>Instead of defining at every case, is there a way to set it using the enum variable like I am trying to do above?</p>
| [
{
"answer_id": 147283,
"author": "sk.",
"author_id": 16399,
"author_profile": "https://Stackoverflow.com/users/16399",
"pm_score": 5,
"selected": true,
"text": "<p>There's no built-in solution. The easiest way is with an array of <code>char*</code> where the enum's int value indexes to a... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9628/"
] | Here's what I am trying to do:
```
typedef enum { ONE, TWO, THREE } Numbers;
```
I am trying to write a function that would do a switch case similar to the following:
```
char num_str[10];
int process_numbers_str(Numbers num) {
switch(num) {
case ONE:
case TWO:
case THREE:
{
strcpy(num_str, num); //some way to get the symbolic constant name in here?
} break;
default:
return 0; //no match
return 1;
}
```
Instead of defining at every case, is there a way to set it using the enum variable like I am trying to do above? | There's no built-in solution. The easiest way is with an array of `char*` where the enum's int value indexes to a string containing the descriptive name of that enum. If you have a sparse `enum` (one that doesn't start at 0 or has gaps in the numbering) where some of the `int` mappings are high enough to make an array-based mapping impractical then you could use a hash table instead. |
147,307 | <p>The System.Diagnostics.EventLog class provides a way to interact with a windows event log. I use it all the time for simple logging...</p>
<pre><code>System.Diagnostics.EventLog.WriteEntry("MyEventSource", "My Special Message")
</code></pre>
<p>Is there a way to set the user information in the resulting event log entry using .NET?</p>
| [
{
"answer_id": 147318,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 0,
"selected": false,
"text": "<p>You need to add it yourself into the event message.</p>\n\n<p>Use the System.Security.Principal namespace to get the current id... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23303/"
] | The System.Diagnostics.EventLog class provides a way to interact with a windows event log. I use it all the time for simple logging...
```
System.Diagnostics.EventLog.WriteEntry("MyEventSource", "My Special Message")
```
Is there a way to set the user information in the resulting event log entry using .NET? | Toughie ...
I looked for a way to fill the user field with a .NET method. Unfortunately there is none, and you must import the plain old Win32 API [ReportEvent function](<http://msdn.microsoft.com/en-us/library/aa363679(VS.85).aspx)> with a `DLLImportAttribute`
You must also redeclare the function with the right types, as [Platform Invoke Data Types](http://msdn.microsoft.com/en-us/library/ac7ay120.aspx) says
So
```
BOOL ReportEvent(
__in HANDLE hEventLog,
__in WORD wType,
__in WORD wCategory,
__in DWORD dwEventID,
__in PSID lpUserSid,
__in WORD wNumStrings,
__in DWORD dwDataSize,
__in LPCTSTR *lpStrings,
__in LPVOID lpRawData
);
```
becomes
```
[DllImport("Advapi32.dll", EntryPoint="ReportEventW", SetLastError=true,
CharSet=CharSet.Unicode)]
bool WriteEvent(
IntPtr hEventLog, //Where to find it ?
ushort wType,
ushort wCategory,
ulong dwEventID,
IntPtr lpUserSid, // We'll leave this struct alone, so just feed it a pointer
ushort wNumStrings,
ushort dwDataSize,
string[] lpStrings,
IntPtr lpRawData
);
```
You also want to look at [OpenEventLog](<http://msdn.microsoft.com/en-us/library/aa363672(VS.85).aspx)> and [ConvertStringSidToSid](<http://msdn.microsoft.com/en-us/library/aa376402(VS.85).aspx)>
Oh, and you're writing unmanaged code now... Watch out for memory leaks.Good luck :p |
147,328 | <p>I need to accept form data to a WCF-based service. Here's the interface:</p>
<pre><code>[OperationContract]
[WebInvoke(UriTemplate = "lead/inff",
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
int Inff(Stream input);
</code></pre>
<p>Here's the implementation (sample - no error handling and other safeguards):</p>
<pre><code>public int Inff(Stream input)
{
StreamReader sr = new StreamReader(input);
string s = sr.ReadToEnd();
sr.Dispose();
NameValueCollection qs = HttpUtility.ParseQueryString(s);
Debug.WriteLine(qs["field1"]);
Debug.WriteLine(qs["field2"]);
return 0;
}
</code></pre>
<p>Assuming WCF, is there a better way to accomplish this besides parsing the incoming stream? </p>
| [
{
"answer_id": 170398,
"author": "James Bender",
"author_id": 22848,
"author_profile": "https://Stackoverflow.com/users/22848",
"pm_score": 4,
"selected": true,
"text": "<p>I remember speaking to you about this at DevLink.</p>\n\n<p>Since you have to support form fields the mechanics of ... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14836/"
] | I need to accept form data to a WCF-based service. Here's the interface:
```
[OperationContract]
[WebInvoke(UriTemplate = "lead/inff",
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
int Inff(Stream input);
```
Here's the implementation (sample - no error handling and other safeguards):
```
public int Inff(Stream input)
{
StreamReader sr = new StreamReader(input);
string s = sr.ReadToEnd();
sr.Dispose();
NameValueCollection qs = HttpUtility.ParseQueryString(s);
Debug.WriteLine(qs["field1"]);
Debug.WriteLine(qs["field2"]);
return 0;
}
```
Assuming WCF, is there a better way to accomplish this besides parsing the incoming stream? | I remember speaking to you about this at DevLink.
Since you have to support form fields the mechanics of getting those (what you are currently doing) don't change.
Something that might be helpful, especially if you want to reuse your service for new applications that don't require the form fields is to create a channel that deconstructs your stream and repackages it to XML/JSON/SOAP/Whatever and have your form clients communicate with the service through that while clients that don't use forms can use another channel stack. Just an idea...
Hope that helps. If you need help with the channel feel free to let me know. |
147,359 | <p>I have this function in VB.net "ENCRYPT" (see below)</p>
<pre><code>Private key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}
Private iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219}
Public Function Encrypt(ByVal plainText As String) As Byte()
' Declare a UTF8Encoding object so we may use the GetByte
' method to transform the plainText into a Byte array.
Dim utf8encoder As UTF8Encoding = New UTF8Encoding()
Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText)
' Create a new TripleDES service provider
Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
' The ICryptTransform interface uses the TripleDES
' crypt provider along with encryption key and init vector
' information
Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv)
' All cryptographic functions need a stream to output the
' encrypted information. Here we declare a memory stream
' for this purpose.
Dim encryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write)
' Write the encrypted information to the stream. Flush the information
' when done to ensure everything is out of the buffer.
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock()
encryptedStream.Position = 0
' Read the stream back into a Byte array and return it to the calling method.
Dim result(encryptedStream.Length - 1) As Byte
encryptedStream.Read(result, 0, encryptedStream.Length)
cryptStream.Close()
Return result
End Function
</code></pre>
<p>I want to save the encrypted string in the SQL database. How do I do it?</p>
| [
{
"answer_id": 147367,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 0,
"selected": false,
"text": "<p>Encode the array of byte into a string. 0x00 can be \"00\" and 0xFF can be \"FF.\" Or you can take at look at <a hr... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21963/"
] | I have this function in VB.net "ENCRYPT" (see below)
```
Private key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}
Private iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219}
Public Function Encrypt(ByVal plainText As String) As Byte()
' Declare a UTF8Encoding object so we may use the GetByte
' method to transform the plainText into a Byte array.
Dim utf8encoder As UTF8Encoding = New UTF8Encoding()
Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText)
' Create a new TripleDES service provider
Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
' The ICryptTransform interface uses the TripleDES
' crypt provider along with encryption key and init vector
' information
Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv)
' All cryptographic functions need a stream to output the
' encrypted information. Here we declare a memory stream
' for this purpose.
Dim encryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write)
' Write the encrypted information to the stream. Flush the information
' when done to ensure everything is out of the buffer.
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock()
encryptedStream.Position = 0
' Read the stream back into a Byte array and return it to the calling method.
Dim result(encryptedStream.Length - 1) As Byte
encryptedStream.Read(result, 0, encryptedStream.Length)
cryptStream.Close()
Return result
End Function
```
I want to save the encrypted string in the SQL database. How do I do it? | Simply store in a binary column. (Mostly done from memory, corrections welcome!)
```
CREATE TABLE [Test]
(
[Id] NOT NULL IDENTITY(1,1) PRIMARY KEY,
[Username] NOT NULL VARCHAR(500),
[Password] NOT NULL VARBINARY(500)
)
```
Then insert such:
```
Dim conn As SqlConnection
Try
conn = New SqlConnection("<connectionstring>")
Dim command As New SqlCommand("INSERT INTO [Test] ([Username], [Password]) VALUES (@Username, @Password)", conn)
Dim usernameParameter = New SqlParameter("@Username", SqlDbType.VarChar)
usernameParameter.Value = username
command.Parameters.Add(usernameParameter)
Dim passwordParameter = New SqlParameter("@Password", SqlDbType.VarBinary)
passwordParameter.Value = password
command.Parameters.Add(passwordParameter)
command.ExecuteNonQuery()
Finally
If (Not (conn Is Nothing)) Then
conn.Close()
End If
End Try
``` |
147,364 | <p>In one of my ASP.NET Web Applications, I am using a <a href="http://blogs.msdn.com/mattdotson/articles/490868.aspx" rel="nofollow noreferrer">BulkEditGridView</a> (a GridView which allows all rows to be edited at the same time) to implement an order form. In my grid, I have a column which calculates the total for each item (cost x quantity) and a grand total field at the bottom of the page. Currently, however, these fields are only refreshed on every post-back. I need to have these fields updated dynamically so that as users change quantities, the totals and grand total update to reflect the new values. I have attempted to use AJAX solutions to accomplish this, but the asynchronous post-backs interfere with the focus on the page. I imagine that a purely client-side solution exists, and I'm hopeful that someone in the community can share.</p>
| [
{
"answer_id": 147620,
"author": "WebDude",
"author_id": 15360,
"author_profile": "https://Stackoverflow.com/users/15360",
"pm_score": 1,
"selected": false,
"text": "<p>One solution is to build some javascript in you RowDataBound method to constantly update those totals when the textboxe... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317/"
] | In one of my ASP.NET Web Applications, I am using a [BulkEditGridView](http://blogs.msdn.com/mattdotson/articles/490868.aspx) (a GridView which allows all rows to be edited at the same time) to implement an order form. In my grid, I have a column which calculates the total for each item (cost x quantity) and a grand total field at the bottom of the page. Currently, however, these fields are only refreshed on every post-back. I need to have these fields updated dynamically so that as users change quantities, the totals and grand total update to reflect the new values. I have attempted to use AJAX solutions to accomplish this, but the asynchronous post-backs interfere with the focus on the page. I imagine that a purely client-side solution exists, and I'm hopeful that someone in the community can share. | If your calculations can be reproduced in JavaScript the easiest method would be using jQuery to get all the items like this:
```
$("#myGridView input[type='text']").each(function(){
this.change(function(){
updateTotal(this.value);
});
});
```
Or if your calculations are way too complex to be done in JavaScript (or time restraints prevent it) then an AJAX call to a web service is the best way. Lets say we've got our webservice like this:
```
[WebMethod, ScriptMethod]
public int UpdateTotal(int currTotal, int changedValue){
// do stuff, then return
}
```
You'll need some JavaScript to invoke the webservice, you can do it either with jQuery or MS AJAX. I'll show a combo of both, just for fun:
```
$("#myGridView input[type='text']").each(function(){
this.change(function(){
Sys.Net.WebServiceProxy.invoke(
"/Helpers.asmx",
"UpdateTotal",
false,
{ currTotal: $get('totalField').innerHTML, changedValue: this.value },
showNewTotal
);
});
});
function showNewTotal(res){
$get('totalField').innerHTML = res;
}
```
Check out this link for full info on the Sys.Net.WebServiceProxy.invoke method: <http://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys.Net/WebServiceProxyClass/WebServiceProxyInvokeMethod.aspx> |
147,372 | <pre><code>#include <vector>
std::vector<long int> as;
long int a(size_t n){
if(n==1) return 1;
if(n==2) return -2;
if(as.size()<n+1)
as.resize(n+1);
if(as[n]<=0)
{
as[n]=-4*a(n-1)-4*a(n-2);
}
return mod(as[n], 65535);
}
</code></pre>
<p>The above code sample using memoization to calculate a recursive formula based on some input <code>n</code>. I know that this uses memoization, because I have written a purely recursive function that uses the same formula, but this one much, much faster for much larger values of <code>n</code>. I've never used vectors before, but I've done some research and I understand the concept of them. I understand that memoization is supposed to store each calculated value, so that instead of performing the same calculations over again, it can simply retrieve ones that have already been calculated. </p>
<p>My question is: how is this memoization, and how does it work? I can't seem to see in the code at which point it checks to see if a value for n already exists. Also, I don't understand the purpose of the <code>if(as[n]<=0)</code>. This formula can yield positive and negative values, so I'm not sure what this check is looking for.</p>
<hr>
<p>Thank you, I think I'm close to understanding how this works, it's actually a bit more simple than I was thinking it was.</p>
<p>I do not think the values in the sequence can ever be 0, so this should work for me, as I think n has to start at 1. </p>
<p>However, if zero was a viable number in my sequence, what is another way I could solve it? For example, what if five could never appear? Would I just need to fill my vector with fives?</p>
<p>Edit: Wow, I got a lot of other responses while checking code and typing this one. Thanks for the help everyone, I think I understand it now.</p>
| [
{
"answer_id": 147374,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": true,
"text": "<p><code>if (as[n] <= 0)</code> is the check. If valid values can be negative like you say, then you need a different sent... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23323/"
] | ```
#include <vector>
std::vector<long int> as;
long int a(size_t n){
if(n==1) return 1;
if(n==2) return -2;
if(as.size()<n+1)
as.resize(n+1);
if(as[n]<=0)
{
as[n]=-4*a(n-1)-4*a(n-2);
}
return mod(as[n], 65535);
}
```
The above code sample using memoization to calculate a recursive formula based on some input `n`. I know that this uses memoization, because I have written a purely recursive function that uses the same formula, but this one much, much faster for much larger values of `n`. I've never used vectors before, but I've done some research and I understand the concept of them. I understand that memoization is supposed to store each calculated value, so that instead of performing the same calculations over again, it can simply retrieve ones that have already been calculated.
My question is: how is this memoization, and how does it work? I can't seem to see in the code at which point it checks to see if a value for n already exists. Also, I don't understand the purpose of the `if(as[n]<=0)`. This formula can yield positive and negative values, so I'm not sure what this check is looking for.
---
Thank you, I think I'm close to understanding how this works, it's actually a bit more simple than I was thinking it was.
I do not think the values in the sequence can ever be 0, so this should work for me, as I think n has to start at 1.
However, if zero was a viable number in my sequence, what is another way I could solve it? For example, what if five could never appear? Would I just need to fill my vector with fives?
Edit: Wow, I got a lot of other responses while checking code and typing this one. Thanks for the help everyone, I think I understand it now. | `if (as[n] <= 0)` is the check. If valid values can be negative like you say, then you need a different sentinel to check against. Can valid values ever be zero? If not, then just make the test `if (as[n] == 0)`. This makes your code easier to write, because by default vectors of `int`s are filled with zeroes. |
147,391 | <p>I have a program that uses the mt19937 random number generator from boost::random. I need to do a random_shuffle and want the random numbers generated for this to be from this shared state so that they can be deterministic with respect to the mersenne twister's previously generated numbers.</p>
<p>I tried something like this:</p>
<pre><code>void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
struct bar {
boost::mt19937 &_state;
unsigned operator()(unsigned i) {
boost::uniform_int<> rng(0, i - 1);
return rng(_state);
}
bar(boost::mt19937 &state) : _state(state) {}
} rand(state);
std::random_shuffle(vec.begin(), vec.end(), rand);
}
</code></pre>
<p>But i get a template error calling random_shuffle with rand. However this works:</p>
<pre><code>unsigned bar(unsigned i)
{
boost::mt19937 no_state;
boost::uniform_int<> rng(0, i - 1);
return rng(no_state);
}
void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
std::random_shuffle(vec.begin(), vec.end(), bar);
}
</code></pre>
<p>Probably because it is an actual function call. But obviously this doesn't keep the state from the original mersenne twister. What gives? Is there any way to do what I'm trying to do without global variables?</p>
| [
{
"answer_id": 147406,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 5,
"selected": true,
"text": "<p>In C++03, you cannot instantiate a template based on a function-local type. If you move the rand class out of the functio... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5963/"
] | I have a program that uses the mt19937 random number generator from boost::random. I need to do a random\_shuffle and want the random numbers generated for this to be from this shared state so that they can be deterministic with respect to the mersenne twister's previously generated numbers.
I tried something like this:
```
void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
struct bar {
boost::mt19937 &_state;
unsigned operator()(unsigned i) {
boost::uniform_int<> rng(0, i - 1);
return rng(_state);
}
bar(boost::mt19937 &state) : _state(state) {}
} rand(state);
std::random_shuffle(vec.begin(), vec.end(), rand);
}
```
But i get a template error calling random\_shuffle with rand. However this works:
```
unsigned bar(unsigned i)
{
boost::mt19937 no_state;
boost::uniform_int<> rng(0, i - 1);
return rng(no_state);
}
void foo(std::vector<unsigned> &vec, boost::mt19937 &state)
{
std::random_shuffle(vec.begin(), vec.end(), bar);
}
```
Probably because it is an actual function call. But obviously this doesn't keep the state from the original mersenne twister. What gives? Is there any way to do what I'm trying to do without global variables? | In C++03, you cannot instantiate a template based on a function-local type. If you move the rand class out of the function, it should work fine (disclaimer: not tested, there could be other sinister bugs).
This requirement has been relaxed in C++0x, but I don't know whether the change has been implemented in GCC's C++0x mode yet, and I would be highly surprised to find it present in any other compiler. |
147,408 | <p>From what I've seen in the past, StackOverflow seems to like programming challenges, such as the <a href="https://stackoverflow.com/questions/69115/char-to-hex-string-exercise">fast char to string exercise problem</a> which got dozens of responses. This is an optimization challenge: take a very simple function and see if you can come up with a smarter way of doing it.</p>
<p>I've had a function that I've wanted to further optimize for quite some time but I always find that my optimizations have some hole that result in incorrect output--some rare special case in which they fail. But, given the function, I've always figured one should be able to do better than this.</p>
<p>The function takes an input datastream (effectively random bits, from an entropy perspective) and wraps it into a NAL unit. This involves placing escape codes: any byte sequence of 00 00 00, 00 00 01, 00 00 02, or 00 00 03 gets replaced with 00 00 03 XX, where XX is that last byte of the original sequence. As one can guess, these only get placed about 1 in every 4 million bytes of input, given the odds against such a sequence--so this is a challenge where one is <strong>searching an enormous amount of data and doing almost nothing to it</strong> except in very rare cases. However, because "doing something" involves <em>inserting bytes</em>, it makes things a bit trickier. The current unoptimized code is the following C:</p>
<p>src and dst are pointers to arrays of bytes, and end is the pointer to the end of the input data.</p>
<pre><code>int i_count = 0;
while( src < end )
{
if( i_count == 2 && *src <= 0x03 )
{
*dst++ = 0x03;
i_count = 0;
}
if( *src == 0 )
i_count++;
else
i_count = 0;
*dst++ = *src++;
}
</code></pre>
<p>Common input sizes to this function range from roughly between 1000 and 1000000 bytes of data.</p>
<p>Initial ideas of mine include a function which (somehow) quickly searches the input for situations where an escape code is needed, to avoid more complex logic in the vast majority of inputs where escape codes don't need to be placed.</p>
<hr>
| [
{
"answer_id": 147424,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Applying the obvious optimisations to your code:</p>\n\n<pre><code>#define unlikely(x) __builtin_expect((x),0)\n\nwhile( sr... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11206/"
] | From what I've seen in the past, StackOverflow seems to like programming challenges, such as the [fast char to string exercise problem](https://stackoverflow.com/questions/69115/char-to-hex-string-exercise) which got dozens of responses. This is an optimization challenge: take a very simple function and see if you can come up with a smarter way of doing it.
I've had a function that I've wanted to further optimize for quite some time but I always find that my optimizations have some hole that result in incorrect output--some rare special case in which they fail. But, given the function, I've always figured one should be able to do better than this.
The function takes an input datastream (effectively random bits, from an entropy perspective) and wraps it into a NAL unit. This involves placing escape codes: any byte sequence of 00 00 00, 00 00 01, 00 00 02, or 00 00 03 gets replaced with 00 00 03 XX, where XX is that last byte of the original sequence. As one can guess, these only get placed about 1 in every 4 million bytes of input, given the odds against such a sequence--so this is a challenge where one is **searching an enormous amount of data and doing almost nothing to it** except in very rare cases. However, because "doing something" involves *inserting bytes*, it makes things a bit trickier. The current unoptimized code is the following C:
src and dst are pointers to arrays of bytes, and end is the pointer to the end of the input data.
```
int i_count = 0;
while( src < end )
{
if( i_count == 2 && *src <= 0x03 )
{
*dst++ = 0x03;
i_count = 0;
}
if( *src == 0 )
i_count++;
else
i_count = 0;
*dst++ = *src++;
}
```
Common input sizes to this function range from roughly between 1000 and 1000000 bytes of data.
Initial ideas of mine include a function which (somehow) quickly searches the input for situations where an escape code is needed, to avoid more complex logic in the vast majority of inputs where escape codes don't need to be placed.
--- | Hmm...how about something like this?
```
#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)
while( likely(src < end) )
{
//Copy non-zero run
int runlen = strlen( src );
if( unlikely(src+runlen >= end) )
{
memcpy( dest, src, end-src );
dest += end-src;
src = end;
break;
}
memcpy( dest, src, runlen );
src += runlen;
dest += runlen;
//Deal with 0 byte
if( unlikely(src[1]==0 && src[2]<=3 && src<=end-3) )
{
*dest++ = 0;
*dest++ = 0;
*dest++ = 3;
*dest++ = *src++;
}
else
{
*dest++ = 0;
src++;
}
}
```
There's some duplication of effort between strcpy and memcpy it'd be nice to get rid of though. |
147,416 | <p>In .NET (VB), how can I take all of the items in one collection, and add them to a second collection (without losing pre-existing items in the second collection)? I'm looking for something a little more efficient than this:</p>
<pre><code>For Each item As Host In hostCollection1
hostCollection2.Add(item)
Next
</code></pre>
<p>My collections are generic collections, inherited from the base class -- Collection(Of )</p>
| [
{
"answer_id": 147418,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 3,
"selected": false,
"text": "<p>I know you're asking for VB, but in C# you can just use the constructor of the collection to initialize it with any... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5473/"
] | In .NET (VB), how can I take all of the items in one collection, and add them to a second collection (without losing pre-existing items in the second collection)? I'm looking for something a little more efficient than this:
```
For Each item As Host In hostCollection1
hostCollection2.Add(item)
Next
```
My collections are generic collections, inherited from the base class -- Collection(Of ) | You can use AddRange: `hostCollection2.AddRange(hostCollection1)`. |
147,437 | <p>I am trying to use Difflib.SequenceMatcher to compute the similarities between two files. These two files are almost identical except that one contains some extra whitespaces, empty lines and other doesn't. I am trying to use</p>
<pre><code>s=difflib.SequenceMatcher(isjunk,text1,text2)
ratio =s.ratio()
</code></pre>
<p>for this purpose.</p>
<p>So, the question is how to write the lambda expression for this isjunk method so the SequenceMatcher method will discount all the whitespaces, empty lines etc. I tried to use the parameter lambda x: x==" ", but the result isn't as great. For two closely similar text, the ratio is very low. This is highly counter intuitive. </p>
<p>For testing purpose, here are the two strings that you can use on testing:</p>
<blockquote>
<p>What Motivates jwovu to do your Job
Well? OK, this is an entry trying to
win $100 worth of software development
books despite the fact that I don‘t
read </p>
<p>programming books. In order to win the
prize you have to write an entry and<br>
what motivatesfggmum to do your job
well. Hence this post. First
motivation </p>
<p>money. I know, this doesn‘t sound like
a great inspiration to many, and
saying that money is one of the
motivation factors might just blow my
chances away. </p>
<p>As if money is a taboo in programming
world. I know there are people who
can‘t be motivated by money. Mme, on
the other hand, am living in a real
world, </p>
<p>with house mortgage to pay, myself to
feed and bills to cover. So I can‘t
really exclude money from my
consideration. If I can get a large
sum of money for </p>
<p>doing a good job, then definitely
boost my morale. I won‘t care whether
I am using an old workstation, or
forced to share rooms or cubicle with
other </p>
<p>people, or have to put up with an
annoying boss, or whatever. The fact
that at the end of the day I will walk
off with a large pile of money itself
is enough </p>
<p>for me to overcome all the obstacles,
put up with all the hard feelings and
hurt egos, tolerate a slow computer
and even endure</p>
</blockquote>
<p>And here's another string</p>
<blockquote>
<p>What Motivates You to do your Job
Well? OK, this is an entry trying to
win $100 worth of software development
books, despite the fact that I don't
read programming books. In order to
win the prize you have to write an
entry and describes what motivates you
to do your job well. Hence this post.</p>
<p>First motivation, money. I know, this
doesn't sound like a great inspiration
to many, and saying that money is one
of the motivation factors might just
blow my chances away. As if money is a
taboo in programming world. I know
there are people who can't be
motivated by money. Kudos to them. Me,
on the other hand, am living in a real
world, with house mortgage to pay,
myself to feed and bills to cover. So
I can't really exclude money from my
consideration.</p>
<p>If I can get a large sum of money for
doing a good job, then thatwill
definitely boost my morale. I won't
care whether I am using an old
workstation, or forced to share rooms
or cubicle with other people, or have
to put up with an annoying boss, or
whatever. The fact that at the end of
the day I will walk off with a large
pile of money itself is enough for me
to overcome all the obstacles, put up
with all the hard feelings and hurt
egos, tolerate a slow computer and
even endure</p>
</blockquote>
<p>I ran the above command, and set the isjunk to lambda x:x==" ", the ratio is only 0.36. </p>
| [
{
"answer_id": 147443,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't used Difflib.SequenceMatcher, but have you considered pre-processing the files to remove all blank lines ... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] | I am trying to use Difflib.SequenceMatcher to compute the similarities between two files. These two files are almost identical except that one contains some extra whitespaces, empty lines and other doesn't. I am trying to use
```
s=difflib.SequenceMatcher(isjunk,text1,text2)
ratio =s.ratio()
```
for this purpose.
So, the question is how to write the lambda expression for this isjunk method so the SequenceMatcher method will discount all the whitespaces, empty lines etc. I tried to use the parameter lambda x: x==" ", but the result isn't as great. For two closely similar text, the ratio is very low. This is highly counter intuitive.
For testing purpose, here are the two strings that you can use on testing:
>
> What Motivates jwovu to do your Job
> Well? OK, this is an entry trying to
> win $100 worth of software development
> books despite the fact that I don‘t
> read
>
>
> programming books. In order to win the
> prize you have to write an entry and
>
> what motivatesfggmum to do your job
> well. Hence this post. First
> motivation
>
>
> money. I know, this doesn‘t sound like
> a great inspiration to many, and
> saying that money is one of the
> motivation factors might just blow my
> chances away.
>
>
> As if money is a taboo in programming
> world. I know there are people who
> can‘t be motivated by money. Mme, on
> the other hand, am living in a real
> world,
>
>
> with house mortgage to pay, myself to
> feed and bills to cover. So I can‘t
> really exclude money from my
> consideration. If I can get a large
> sum of money for
>
>
> doing a good job, then definitely
> boost my morale. I won‘t care whether
> I am using an old workstation, or
> forced to share rooms or cubicle with
> other
>
>
> people, or have to put up with an
> annoying boss, or whatever. The fact
> that at the end of the day I will walk
> off with a large pile of money itself
> is enough
>
>
> for me to overcome all the obstacles,
> put up with all the hard feelings and
> hurt egos, tolerate a slow computer
> and even endure
>
>
>
And here's another string
>
> What Motivates You to do your Job
> Well? OK, this is an entry trying to
> win $100 worth of software development
> books, despite the fact that I don't
> read programming books. In order to
> win the prize you have to write an
> entry and describes what motivates you
> to do your job well. Hence this post.
>
>
> First motivation, money. I know, this
> doesn't sound like a great inspiration
> to many, and saying that money is one
> of the motivation factors might just
> blow my chances away. As if money is a
> taboo in programming world. I know
> there are people who can't be
> motivated by money. Kudos to them. Me,
> on the other hand, am living in a real
> world, with house mortgage to pay,
> myself to feed and bills to cover. So
> I can't really exclude money from my
> consideration.
>
>
> If I can get a large sum of money for
> doing a good job, then thatwill
> definitely boost my morale. I won't
> care whether I am using an old
> workstation, or forced to share rooms
> or cubicle with other people, or have
> to put up with an annoying boss, or
> whatever. The fact that at the end of
> the day I will walk off with a large
> pile of money itself is enough for me
> to overcome all the obstacles, put up
> with all the hard feelings and hurt
> egos, tolerate a slow computer and
> even endure
>
>
>
I ran the above command, and set the isjunk to lambda x:x==" ", the ratio is only 0.36. | If you match all whitespaces the similarity is better:
```
difflib.SequenceMatcher(lambda x: x in " \t\n", doc1, doc2).ratio()
```
However, difflib is not ideal to such a problem because these are two nearly identical documents, but typos and such produce differences for difflib where a human wouldn't see many.
Try reading up on [tf-idf](http://en.wikipedia.org/wiki/Tf-idf), [Bayesian probability](http://en.wikipedia.org/wiki/Bayesian_probability), [Vector space Models](http://en.wikipedia.org/wiki/Vector_space_model) and [w-shingling](http://en.wikipedia.org/wiki/W-shingling)
I have written a an [implementation of tf-idf](http://hg.codeflow.org/tfclassify) applying it to a vector space and using the dot product as a distance measure to classify documents. |
147,451 | <p>In an HTML form post what are valid characters for creating a multipart boundary?</p>
| [
{
"answer_id": 147467,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": true,
"text": "<p>According to <a href=\"https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1\" rel=\"nofollow noreferrer\">RFC 2046</a>, se... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740/"
] | In an HTML form post what are valid characters for creating a multipart boundary? | According to [RFC 2046](https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1), section 5.1.1:
```
boundary := 0*69<bchars> bcharsnospace
bchars := bcharsnospace / " "
bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
"+" / "_" / "," / "-" / "." /
"/" / ":" / "=" / "?"
```
So it can be between 1 and 70 characters long, consisting of alphanumeric, and the punctuation you see in the list. Spaces are allowed except at the end. |
147,454 | <p>It is much more convenient and cleaner to use a single statement like</p>
<pre><code>import java.awt.*;
</code></pre>
<p>than to import a bunch of individual classes</p>
<pre><code>import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...
</code></pre>
<p>What is wrong with using a wildcard in the <code>import</code> statement?</p>
| [
{
"answer_id": 147461,
"author": "Benjamin Pollack",
"author_id": 2354,
"author_profile": "https://Stackoverflow.com/users/2354",
"pm_score": 10,
"selected": true,
"text": "<p>The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22807/"
] | It is much more convenient and cleaner to use a single statement like
```
import java.awt.*;
```
than to import a bunch of individual classes
```
import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...
```
What is wrong with using a wildcard in the `import` statement? | The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need `java.awt.Event`, and are also interfacing with the company's calendaring system, which has `com.mycompany.calendar.Event`. If you import both using the wildcard method, one of these three things happens:
1. You have an outright naming conflict between `java.awt.Event` and `com.mycompany.calendar.Event`, and so you can't even compile.
2. You actually manage only to import one (only one of your two imports does `.*`), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.
3. When you compile your code there is no `com.mycompany.calendar.Event`, but when they later add one your previously valid code suddenly stops compiling.
The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code that much easier. If you're just doing a quick one-off thing, there's nothing explicitly *wrong*, but future maintainers will thank you for your clarity otherwise. |
147,458 | <p>I have an ASP.NET 3.5 WebForm that leverages the frameworks Page.ClientScript.GetCallbackEventReference() method and I'd like some of the calls to be synchronous. </p>
<p>Now, the documentation says that the 5th parameter (see below) controls this. Specifically, when you pass 'false' it's supposed to be a non-asynchronous call. However, regardless if it's true or false, it still processes the call asynchronously. </p>
<pre><code>Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context",false);
</code></pre>
<p>Is there a work-around for this or perhaps I'm doing something wrong? </p>
| [
{
"answer_id": 16345178,
"author": "Javal Patel",
"author_id": 896527,
"author_profile": "https://Stackoverflow.com/users/896527",
"pm_score": 1,
"selected": false,
"text": "<p><strong>ASPX Page</strong></p>\n\n<pre><code><%@ Page Language=\"VB\" AutoEventWireup=\"false\" CodeFile=\"H... | 2008/09/29 | [
"https://Stackoverflow.com/questions/147458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4646/"
] | I have an ASP.NET 3.5 WebForm that leverages the frameworks Page.ClientScript.GetCallbackEventReference() method and I'd like some of the calls to be synchronous.
Now, the documentation says that the 5th parameter (see below) controls this. Specifically, when you pass 'false' it's supposed to be a non-asynchronous call. However, regardless if it's true or false, it still processes the call asynchronously.
```
Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context",false);
```
Is there a work-around for this or perhaps I'm doing something wrong? | **ASPX Page**
```
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="How-to-use-GetCallbackEventReference.aspx.vb" Inherits="How_to_use_Callback" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to use GetCallbackEventReference</title>
<script type="text/javascript">
function GetNumber() {
UseCallback();
}
function GetRandomNumberFromServer(txtGetNumber, context) {
document.forms[0].txtGetNumber.value = txtGetNumber
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="Get Random Number" onclick="GetNumber()" /><br /><br />
<asp:TextBox ID="txtGetNumber" runat="server"></asp:TextBox> </div>
</form>
</body>
</html>
```
**Code Behind**
```
Partial Class How_to_use_Callback
Inherits System.Web.UI.Page
Implements System.Web.UI.ICallbackEventHandler
Dim CallbackResult As String = Nothing
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim cbReference As String = Page.ClientScript.GetCallbackEventReference(Me, "arg", "GetRandomNumberFromServer", "context")
Dim cbScript As String = "function UseCallback(arg,context)" & "{" & cbReference & " ; " & "}"
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "UseCallback", cbScript, True)
End Sub
Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
Return CallbackResult
End Function
Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
CallbackResult = Rnd().ToString()
End Sub
End Class
``` |