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 |
|---|---|---|---|---|---|---|
98,224 | <p>After downloading files from a remote UNIX FTP server, you want to verify that you have downloaded all the files correctly. Minimal you will get information similar to "dir /s" command in Windows command prompt. The FTP client runs on Windows.</p>
| [
{
"answer_id": 98234,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 6,
"selected": true,
"text": "<p>Sadly this was written for Unix/Linux users :/</p>\n\n<p>Personally, I would install CYGWIN just to get Linux binari... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13584/"
] | After downloading files from a remote UNIX FTP server, you want to verify that you have downloaded all the files correctly. Minimal you will get information similar to "dir /s" command in Windows command prompt. The FTP client runs on Windows. | Sadly this was written for Unix/Linux users :/
Personally, I would install CYGWIN just to get Linux binaries of LFTP/RSYNC to work on windows, as there appears not to be anything that competes with it.
As @zadok.myopenid.com
mentioned rsync, this appears to be a windows build for it using CYGWIN ( if you manage to be able to get ssh access to the box eventually )
<http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp>
Rsync is handy in that it will compare everything with check sums, and optimally transfer partial change blocks.
---
If you get CYGWIN/Linux:
<http://lftp.yar.ru/> is my favorite exploration tool for this.
It can do almost everything bash can do, albeit remotely.
Example:
```
$ lftp mirror.3fl.net.au
lftp mirror.3fl.net.au:~> ls
drwxr-xr-x 14 root root 4096 Nov 27 2007 games
drwx------ 2 root root 16384 Apr 13 2006 lost+found
drwxr-xr-x 15 mirror mirror 4096 Jul 15 05:20 pub
lftp mirror.3fl.net.au:/> cd games/misc
lftp mirror.3fl.net.au:/games/misc>find
./
./dreamchess/
./dreamchess/full_game/
./dreamchess/full_game/dreamchess-0.2.0-win32.exe
./frets_on_fire/
./frets_on_fire/full_game/
./frets_on_fire/full_game/FretsOnFire-1.2.451-macosx.zip
./frets_on_fire/full_game/FretsOnFire-1.2.512-win32.zip
./frets_on_fire/full_game/FretsOnFire_ghc_mod.zip
./gametap_setup.exe
......
lftp mirror.3fl.net.au:/games/misc> du gametap_setup.exe
32442 gametap_setup.exe
lftp mirror.3fl.net.au:/games/misc> du -sh gametap_setup.exe
32M gametap_setup.exe
lftp mirror.3fl.net.au:/games/misc>
``` |
98,242 | <blockquote>
<p><strong>Possible Duplicate:</strong><br />
<a href="https://stackoverflow.com/questions/6457130/pre-post-increment-operator-behavior-in-c-c-java-c-sharp">Pre & post increment operator behavior in C, C++, Java, & C#</a></p>
</blockquote>
<p>Here is a test case:</p>
<pre><code>
void foo(int i, int j)
{
printf("%d %d", i, j);
}
...
test = 0;
foo(test++, test);
</code></pre>
<p>I would expect to get a "0 1" output, but I get "0 0"
What gives??</p>
| [
{
"answer_id": 98256,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 7,
"selected": true,
"text": "<p>This is an example of unspecified behavior. The standard does <strong>not</strong> say what order arguments should be eva... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
] | >
> **Possible Duplicate:**
>
> [Pre & post increment operator behavior in C, C++, Java, & C#](https://stackoverflow.com/questions/6457130/pre-post-increment-operator-behavior-in-c-c-java-c-sharp)
>
>
>
Here is a test case:
```
void foo(int i, int j)
{
printf("%d %d", i, j);
}
...
test = 0;
foo(test++, test);
```
I would expect to get a "0 1" output, but I get "0 0"
What gives?? | This is an example of unspecified behavior. The standard does **not** say what order arguments should be evaluated in. This is a compiler implementation decision. The compiler is free to evaluate the arguments to the function in any order.
In this case, it looks like actually processes the arguments right to left instead of the expected left to right.
In general, doing side-effects in arguments is bad programming practice.
Instead of **foo(test++, test);** you should write **foo(test, test+1); test++;**
It would be semantically equivalent to what you are trying to accomplish.
Edit:
As Anthony correctly points out, it is undefined to both read and modify a single variable without an intervening sequence point. So in this case, the behavior is indeed **undefined**. So the compiler is free to generate whatever code it wants. |
98,274 | <p>Is it possible to integrate SSRS reports to the webforms..an example will be enough to keep me moving. </p>
| [
{
"answer_id": 98312,
"author": "user10635",
"author_id": 10635,
"author_profile": "https://Stackoverflow.com/users/10635",
"pm_score": 0,
"selected": false,
"text": "<p>this is a knowledge base article which describes how to render report output to an aspx page in a particular file form... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14752/"
] | Is it possible to integrate SSRS reports to the webforms..an example will be enough to keep me moving. | Absolutely it is.
What you are looking for is the ReportViewer control, located in the Microsoft.Reporting.WebForms assembly. It will allow you to place a control right on your web form that will give people an interface for setting report parameters and getting the report.
Alternatively you can set all the parameters yourself and output the report in whatever format you need. We use it in our application to output PDF.
For instance - this is how we setup a reportviewer object for one of our reports and get the PDF, and then send it back to the user. The particular code block is a web handler.
```
public void ProcessRequest(HttpContext context)
{
string report = null;
int managerId = -1;
int planId = -1;
GetParametersFromSession(context.Session, out report, out managerId, out planId);
if (report == null || managerId == -1 || planId == -1)
{
return;
}
CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
List<ReportParameter> parameters = new List<ReportParameter>();
parameters.Add(new ReportParameter("Prefix", report));
parameters.Add(new ReportParameter("ManagerId", managerId.ToString()));
parameters.Add(new ReportParameter("ActionPlanId", planId.ToString()));
string language = Thread.CurrentThread.CurrentCulture.Name;
language = String.Format("{0}_{1}", language.Substring(0, 2), language.Substring(3, 2).ToLower());
parameters.Add(new ReportParameter("Lang", language));
ReportViewer rv = new ReportViewer();
rv.ProcessingMode = ProcessingMode.Remote;
rv.ServerReport.ReportServerUrl = new Uri(ConfigurationManager.AppSettings["ReportServer"]);
if (ConfigurationManager.AppSettings["DbYear"] == "2007")
{
rv.ServerReport.ReportPath = "/ActionPlanning/Plan";
}
else
{
rv.ServerReport.ReportPath = String.Format("/ActionPlanning{0}/Plan", ConfigurationManager.AppSettings["DbYear"]);
}
rv.ServerReport.SetParameters(parameters);
string mimeType = null;
string encoding = null;
string extension = null;
string[] streamIds = null;
Warning[] warnings = null;
byte[] output = rv.ServerReport.Render("pdf", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
context.Response.ContentType = mimeType;
context.Response.BinaryWrite(output);
}
``` |
98,320 | <p>My model layer is being used by a handful of different projects and I'd like to use a single XML Spring Configuration file for the model regardless of which project is using it.</p>
<p>My question is: Since not all beans are used in all projects am I wasting resources to any significant amount if there not being instantiated? I'm not too sure how lazy Spring is about loading them since it's never been an issue until now.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 98456,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 0,
"selected": false,
"text": "<p>By default Spring beans are singletons and are instantiated when the application context is created (at startup). So assumin... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] | My model layer is being used by a handful of different projects and I'd like to use a single XML Spring Configuration file for the model regardless of which project is using it.
My question is: Since not all beans are used in all projects am I wasting resources to any significant amount if there not being instantiated? I'm not too sure how lazy Spring is about loading them since it's never been an issue until now.
Any ideas? | Taken from the [Spring Reference Manual](http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-lazy-init):
>
> The default behavior for ApplicationContext implementations is to eagerly pre-instantiate all singleton beans at startup. Pre-instantiation means that an ApplicationContext will eagerly create and configure all of its singleton beans as part of its initialization process. Generally this is a good thing, because it means that any errors in the configuration or in the surrounding environment will be discovered immediately (as opposed to possibly hours or even days down the line).
>
>
> However, there are times when this behavior is not what is wanted. If you do not want a singleton bean to be pre-instantiated when using an ApplicationContext, you can selectively control this by marking a bean definition as lazy-initialized. A lazily-initialized bean indicates to the IoC container whether or not a bean instance should be created at startup or when it is first requested.
>
>
> When configuring beans via XML, this lazy loading is controlled by the 'lazy-init' attribute on the [bean element] ; for example:
>
>
>
```
<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>
```
But, unless your beans are using up resources like file locks or database connections, I wouldn't worry too much about simple memory overhead if it is easier for you to have this one configuration for multiple (but different) profiles. |
98,340 | <p>An example of unspecified behavior in the C language is the order of evaluation of arguments to a function. It might be left to right or right to left, you just don't know. This would affect how <code>foo(c++, c)</code> or <code>foo(++c, c)</code> gets evaluated.</p>
<p>What other unspecified behavior is there that can surprise the unaware programmer?</p>
| [
{
"answer_id": 98351,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 1,
"selected": false,
"text": "<p>Be sure to always initialize your variables before you use them! When I had just started with C, that caused me a... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
] | An example of unspecified behavior in the C language is the order of evaluation of arguments to a function. It might be left to right or right to left, you just don't know. This would affect how `foo(c++, c)` or `foo(++c, c)` gets evaluated.
What other unspecified behavior is there that can surprise the unaware programmer? | A language lawyer question. Hmkay.
My personal top3:
1. violating the strict aliasing rule
2. violating the strict aliasing rule
3. violating the strict aliasing rule
:-)
**Edit** Here is a little example that does it wrong twice:
(assume 32 bit ints and little endian)
```
float funky_float_abs (float a)
{
unsigned int temp = *(unsigned int *)&a;
temp &= 0x7fffffff;
return *(float *)&temp;
}
```
That code tries to get the absolute value of a float by bit-twiddling with the sign bit directly in the representation of a float.
However, the result of creating a pointer to an object by casting from one type to another is not valid C. The compiler may assume that pointers to different types don't point to the same chunk of memory. This is true for all kind of pointers except void\* and char\* (sign-ness does not matter).
In the case above I do that twice. Once to get an int-alias for the float a, and once to convert the value back to float.
There are three valid ways to do the same.
Use a char or void pointer during the cast. These always alias to anything, so they are safe.
```
float funky_float_abs (float a)
{
float temp_float = a;
// valid, because it's a char pointer. These are special.
unsigned char * temp = (unsigned char *)&temp_float;
temp[3] &= 0x7f;
return temp_float;
}
```
Use memcopy. Memcpy takes void pointers, so it will force aliasing as well.
```
float funky_float_abs (float a)
{
int i;
float result;
memcpy (&i, &a, sizeof (int));
i &= 0x7fffffff;
memcpy (&result, &i, sizeof (int));
return result;
}
```
The third valid way: use unions. This is explicitly **not undefined since C99:**
```
float funky_float_abs (float a)
{
union
{
unsigned int i;
float f;
} cast_helper;
cast_helper.f = a;
cast_helper.i &= 0x7fffffff;
return cast_helper.f;
}
``` |
98,376 | <p>I need to store some simple properties in a file and access them from Ruby.</p>
<p>I absolutely love the .properties file format that is the standard for such things in Java (using the java.util.Properties class)... it is simple, easy to use and easy to read.</p>
<p>So, is there a Ruby class somewhere that will let me load up some key value pairs from a file like that without a lot of effort?</p>
<p>I don't want to use XML, so please don't suggest REXML (my purpose does not warrant the "angle bracket tax").</p>
<p>I have considered rolling my own solution... it would probably be about 5-10 lines of code tops, but I would still rather use an existing library (if it is essentially a hash built from a file)... as that would bring it down to 1 line....</p>
<hr>
<p>UPDATE: It's actually a straight Ruby app, not rails, but I think YAML will do nicely (it was in the back of my mind, but I had forgotten about it... have seen but never used as of yet), thanks everyone!</p>
| [
{
"answer_id": 98415,
"author": "Ryan Bigg",
"author_id": 15245,
"author_profile": "https://Stackoverflow.com/users/15245",
"pm_score": 6,
"selected": true,
"text": "<p>Is this for a Rails application or a Ruby one?</p>\n\n<p>Really with either you may be able to stick your properties in... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | I need to store some simple properties in a file and access them from Ruby.
I absolutely love the .properties file format that is the standard for such things in Java (using the java.util.Properties class)... it is simple, easy to use and easy to read.
So, is there a Ruby class somewhere that will let me load up some key value pairs from a file like that without a lot of effort?
I don't want to use XML, so please don't suggest REXML (my purpose does not warrant the "angle bracket tax").
I have considered rolling my own solution... it would probably be about 5-10 lines of code tops, but I would still rather use an existing library (if it is essentially a hash built from a file)... as that would bring it down to 1 line....
---
UPDATE: It's actually a straight Ruby app, not rails, but I think YAML will do nicely (it was in the back of my mind, but I had forgotten about it... have seen but never used as of yet), thanks everyone! | Is this for a Rails application or a Ruby one?
Really with either you may be able to stick your properties in a yaml file and then `YAML::Load(File.open("file"))` it.
---
**NOTE from Mike Stone:** It would actually be better to do:
```
File.open("file") { |yf| YAML::load(yf) }
```
or
```
YAML.load_file("file")
```
as the ruby docs suggest, otherwise the file won't be closed till garbage collection, but good suggestion regardless :-) |
98,394 | <p>I looked for the name of a procedure, which applies a tree structure of procedures to a tree structure of data, yielding a tree structure of results - all three trees having the same structure. </p>
<p>Such a procedure might have the signature: </p>
<pre>(map-tree data functree)</pre>
<p>Its return value would be the result of elementwise application of functree's elements on the corresponding data elements. </p>
<p>Examples (assuming that the procedure is called map-tree): </p>
<p>Example 1: </p>
<pre>(define *2 (lambda (x) (* 2 x)))
; and similar definitions for *3 and *5
(map-tree '(100 (10 1)) '(*2 (*3 *5)))</pre>
<p>would yield the result <pre>(200 (30 5))</pre></p>
<p>Example 2: </p>
<pre>(map-tree '(((aa . ab) (bb . bc)) (cc . (cd . ce)))
'((car cdr) cadr))</pre>
<p>yields the result <pre>((aa bc) cd)</pre></p>
<p>However I did not find such a function in the SLIB documentation, which I consulted. </p>
<p>Does such a procedure already exist?<br>
If not, what would be a suitable name for the procedure, and how would you order its arguments?</p>
| [
{
"answer_id": 98520,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": true,
"text": "<p>I don't have a very good name for the function. I'm pasting my implementation below (I've called it <code>map-traversing</c... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11886/"
] | I looked for the name of a procedure, which applies a tree structure of procedures to a tree structure of data, yielding a tree structure of results - all three trees having the same structure.
Such a procedure might have the signature:
```
(map-tree data functree)
```
Its return value would be the result of elementwise application of functree's elements on the corresponding data elements.
Examples (assuming that the procedure is called map-tree):
Example 1:
```
(define *2 (lambda (x) (* 2 x)))
; and similar definitions for *3 and *5
(map-tree '(100 (10 1)) '(*2 (*3 *5)))
```
would yield the result
```
(200 (30 5))
```
Example 2:
```
(map-tree '(((aa . ab) (bb . bc)) (cc . (cd . ce)))
'((car cdr) cadr))
```
yields the result
```
((aa bc) cd)
```
However I did not find such a function in the SLIB documentation, which I consulted.
Does such a procedure already exist?
If not, what would be a suitable name for the procedure, and how would you order its arguments? | I don't have a very good name for the function. I'm pasting my implementation below (I've called it `map-traversing`; others should suggest a better name). I've made the argument order mirror that of `map` itself.
```
(define (map-traversing func data)
(if (list? func)
(map map-traversing func data)
(func data)))
```
Using your sample data, we have:
```
(map-traversing `((,car ,cdr) ,cadr) '(((aa . ab) (bb . bc)) (cc cd . ce)))
```
The second sample requires SRFI 26. (Allows writing `(cut * 2 <>)` instead of `(lambda (x) (* 2 x))`.)
```
(map-traversing `(,(cut * 2 <>) (,(cut * 3 <>) ,(cut * 5 <>))) '(100 (10 1)))
```
The most important thing is that your functions must all be unquoted, unlike your example. |
98,479 | <p>What is the maximum value of an int in ChucK? Is there a symbolic constant for it?</p>
| [
{
"answer_id": 98500,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://chuck.cs.princeton.edu/doc/program/stdlib.html\" rel=\"nofollow noreferrer\">The ChucK API referenc... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7648/"
] | What is the maximum value of an int in ChucK? Is there a symbolic constant for it? | New in the latest version!
```
<<<Math.INT_MAX>>>;
```
For reference though, it uses the "`long`" keyword in C++ to represent integers.
So on 32-bit computers the max should be `0x7FFFFFFF`, or `2147483647`.
On 64-bit computers it will be `0x7FFFFFFFFFFFFFFFFF`, or `9223372036854775807`.
Answer from Kassen and Stephen Sinclair on the [chuck-users mailing list](https://lists.cs.princeton.edu/mailman/listinfo/chuck-users). |
98,497 | <p>Hi i need to generate 9 digit unique account numbers. Here is my pseudocode:</p>
<pre><code>function generateAccNo()
generate an account number between 100,000,000 and 999,999,999
if the account number already exists in the DB
call generateAccNo() /* recursive call */
else
return new accout number
end if
end function
</code></pre>
<p>The function seems to be working well, however I am a bit worried about the recursive call. </p>
<p>Will this cause any memory leaks (PHP 5 under apache)?</p>
<p>Is this an acceptable way to tackle this problem?</p>
<p>Thanks for your input.</p>
| [
{
"answer_id": 98502,
"author": "Esteban Araya",
"author_id": 781,
"author_profile": "https://Stackoverflow.com/users/781",
"pm_score": 4,
"selected": true,
"text": "<p>You realize this could very well cause a stack overflow, right? As the number of customesr increases, the probability o... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Hi i need to generate 9 digit unique account numbers. Here is my pseudocode:
```
function generateAccNo()
generate an account number between 100,000,000 and 999,999,999
if the account number already exists in the DB
call generateAccNo() /* recursive call */
else
return new accout number
end if
end function
```
The function seems to be working well, however I am a bit worried about the recursive call.
Will this cause any memory leaks (PHP 5 under apache)?
Is this an acceptable way to tackle this problem?
Thanks for your input. | You realize this could very well cause a stack overflow, right? As the number of customesr increases, the probability of not finding a an acceptable account number increases.
Also, why can't you just do sequential account numbers and just increase by one every time? With this approach, you'd just have to read the max id currently in the database and just increment it.
Sorry to be so blunt, but your solution is a terrible way to tackle the problem. It'll use tons of memory (as the stack possibly grows infinitely) and it will makes tons of expensive calls to the database.
**You should really consider some other approach:**
I strongly recommend just incrementing the customer number every time you create a customer. In fact, if you set up your db properly (with auto increment on the id column), you won't even have to set the id. The id will be set for you whenever you insert a new customer. |
98,559 | <pre><code>uint color;
bool parsedhex = uint.TryParse(TextBox1.Text, out color);
//where Text is of the form 0xFF0000
if(parsedhex)
//...
</code></pre>
<p>doesn't work. What am i doing wrong?</p>
| [
{
"answer_id": 98572,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 8,
"selected": true,
"text": "<p>Try </p>\n\n<pre><code>Convert.ToUInt32(hex, 16) //Using ToUInt32 not ToUInt64, as per OP comment\n</code></pre>\n"
},
... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1748529/"
] | ```
uint color;
bool parsedhex = uint.TryParse(TextBox1.Text, out color);
//where Text is of the form 0xFF0000
if(parsedhex)
//...
```
doesn't work. What am i doing wrong? | Try
```
Convert.ToUInt32(hex, 16) //Using ToUInt32 not ToUInt64, as per OP comment
``` |
98,597 | <p>I use AutoHotKey for Windows macros. Most commonly I use it to define hotkeys that start/focus particular apps, and one to send an instant email message into my ToDo list. I also have an emergency one that kills all of my big memory-hogging apps (Outlook, Firefox, etc).</p>
<p>So, does anyone have any good AHK macros to share?</p>
| [
{
"answer_id": 98926,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 2,
"selected": false,
"text": "<p>There are tons of good ones in the AutoHotKey Forum:</p>\n\n<p><a href=\"http://www.autohotkey.com/forum/forum-2.html&am... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10934/"
] | I use AutoHotKey for Windows macros. Most commonly I use it to define hotkeys that start/focus particular apps, and one to send an instant email message into my ToDo list. I also have an emergency one that kills all of my big memory-hogging apps (Outlook, Firefox, etc).
So, does anyone have any good AHK macros to share? | Very simple and useful snippet:
```
SetTitleMatchMode RegEx ;
; Stuff to do when Windows Explorer is open
;
#IfWinActive ahk_class ExploreWClass|CabinetWClass
; create new folder
;
^!n::Send !fwf
; create new text file
;
^!t::Send !fwt
; open 'cmd' in the current directory
;
^!c::
OpenCmdInCurrent()
return
#IfWinActive
; Opens the command shell 'cmd' in the directory browsed in Explorer.
; Note: expecting to be run when the active window is Explorer.
;
OpenCmdInCurrent()
{
WinGetText, full_path, A ; This is required to get the full path of the file from the address bar
; Split on newline (`n)
StringSplit, word_array, full_path, `n
full_path = %word_array1% ; Take the first element from the array
; Just in case - remove all carriage returns (`r)
StringReplace, full_path, full_path, `r, , all
full_path := RegExReplace(full_path, "^Address: ", "") ;
IfInString full_path, \
{
Run, cmd /K cd /D "%full_path%"
}
else
{
Run, cmd /K cd /D "C:\ "
}
}
``` |
98,610 | <p>By default, Eclipse won't show my .htaccess file that I maintain in my project. It just shows an empty folder in the Package Viewer tree. How can I get it to show up? No obvious preferences.</p>
| [
{
"answer_id": 98625,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 3,
"selected": false,
"text": "<p>In your package explorer, pull down the menu and select \"Filters ...\". You can adjust what types of files are sho... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4223/"
] | By default, Eclipse won't show my .htaccess file that I maintain in my project. It just shows an empty folder in the Package Viewer tree. How can I get it to show up? No obvious preferences. | In the package explorer, in the upper right corner of the view, there is a little down arrow. Tool tip will say view menu. From that menu, select filters

From there, uncheck .\* resources.
So `Package Explorer -> View Menu -> Filters -> uncheck .* resources`.
With Eclipse Kepler and OS X this is a bit different:
```
Package Explorer -> Customize View -> Filters -> uncheck .* resources
``` |
98,622 | <p>In VisualStudio (Pro 2008), I have just noticed some inconsistent behaviour and wondered if there was any logical reasoning behind it</p>
<p>In a WinForms project, if I use the line</p>
<pre><code>if(myComboBox.Items[i] == myObject)
</code></pre>
<p>I get a compiler warning that I might get 'Possible unintended references' as I am comparing type object to type MyObject. Fair enough.</p>
<p>However, if I instead use an interface to compare against:</p>
<pre><code>if(myComboBox.Items[i] == iMyInterface)
</code></pre>
<p>the compile warning goes away.</p>
<p>Can anyone think if there is any logical reason why this should happen, or just an artifact of the compiler not to check interfaces for comparison warnings. Any thoughts?</p>
<p><strong>EDIT</strong> In my example, the combobox was bound to a List, but that list was generated using <code>list<IMyInterface>.Cast<MyObject>().ToList<MyObject>()</code></p>
<p>Its as if the compiler is only taking still assuming I am binding to the List of IMyInterface.</p>
<p>(Object and Interface methods have been changed to protect the innocent)</p>
| [
{
"answer_id": 98708,
"author": "Jason Stevenson",
"author_id": 13368,
"author_profile": "https://Stackoverflow.com/users/13368",
"pm_score": 0,
"selected": false,
"text": "<p>Lagerdalek,</p>\n\n<p>The warning is generated because you need to cast the item from the Items collection back ... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] | In VisualStudio (Pro 2008), I have just noticed some inconsistent behaviour and wondered if there was any logical reasoning behind it
In a WinForms project, if I use the line
```
if(myComboBox.Items[i] == myObject)
```
I get a compiler warning that I might get 'Possible unintended references' as I am comparing type object to type MyObject. Fair enough.
However, if I instead use an interface to compare against:
```
if(myComboBox.Items[i] == iMyInterface)
```
the compile warning goes away.
Can anyone think if there is any logical reason why this should happen, or just an artifact of the compiler not to check interfaces for comparison warnings. Any thoughts?
**EDIT** In my example, the combobox was bound to a List, but that list was generated using `list<IMyInterface>.Cast<MyObject>().ToList<MyObject>()`
Its as if the compiler is only taking still assuming I am binding to the List of IMyInterface.
(Object and Interface methods have been changed to protect the innocent) | The compile warning for the first sample is because any custom == operator for your class would be ignored and the references compared (maybe not what you intended, hence the warning).
It's not possible to specify that an operator should be overridden on an interface, so this will *always* be a reference comparison. The warning is not needed because you should always expect this.
Here's an example of overriding the == operator:
```
class Program
{
static void Main(string[] args)
{
object t1 = new MyTest() { Key = 1 };
MyTest t2 = new MyTest() { Key = 1 };
Console.WriteLine((MyTest)t1 == t2); // Uses overriden == operator, returns true
Console.WriteLine(t1 == t2); // Reference comparison, returns false
}
}
public class MyTest
{
public int Key { get; set; }
public override bool Equals(object obj)
{
return this.Key == (obj as MyTest).Key;
}
public override int GetHashCode()
{
return this.Key.GetHashCode();
}
public static bool operator ==(MyTest t1, MyTest t2)
{
return t1.Equals(t2);
}
public static bool operator !=(MyTest t1, MyTest t2)
{
return !t1.Equals(t2);
}
}
```
The MyTest class is considered equal if the Key property is equal. If you were to create an interface, you cannot specify that it should include a custom == operator and therefore the comparison would always be a reference comparison (and therefore false in the case of our sample code). |
98,650 | <p>When asking about <a href="https://stackoverflow.com/questions/98340/what-are-the-common-undefinedunspecified-behavior-for-c-that-you-run-into">common undefined behavior in C</a>, people sometimes refer to the strict aliasing rule.<br>
What are they talking about?</p>
| [
{
"answer_id": 98666,
"author": "Jason Dagit",
"author_id": 5113,
"author_profile": "https://Stackoverflow.com/users/5113",
"pm_score": 4,
"selected": false,
"text": "<p>Strict aliasing is not allowing different pointer types to the same data.</p>\n\n<p><a href=\"http://cellperformance.b... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
] | When asking about [common undefined behavior in C](https://stackoverflow.com/questions/98340/what-are-the-common-undefinedunspecified-behavior-for-c-that-you-run-into), people sometimes refer to the strict aliasing rule.
What are they talking about? | A typical situation where you encounter strict aliasing problems is when overlaying a struct (like a device/network msg) onto a buffer of the word size of your system (like a pointer to `uint32_t`s or `uint16_t`s). When you overlay a struct onto such a buffer, or a buffer onto such a struct through pointer casting you can easily violate strict aliasing rules.
So in this kind of setup, if I want to send a message to something I'd have to have two incompatible pointers pointing to the same chunk of memory. I might then naively code something like this:
```
typedef struct Msg
{
unsigned int a;
unsigned int b;
} Msg;
void SendWord(uint32_t);
int main(void)
{
// Get a 32-bit buffer from the system
uint32_t* buff = malloc(sizeof(Msg));
// Alias that buffer through message
Msg* msg = (Msg*)(buff);
// Send a bunch of messages
for (int i = 0; i < 10; ++i)
{
msg->a = i;
msg->b = i+1;
SendWord(buff[0]);
SendWord(buff[1]);
}
}
```
The strict aliasing rule makes this setup illegal: dereferencing a pointer that aliases an object that is not of a [compatible type](http://en.cppreference.com/w/c/language/type) or one of the other types allowed by C 2011 6.5 paragraph 71 is undefined behavior. Unfortunately, you can still code this way, *maybe* get some warnings, have it compile fine, only to have weird unexpected behavior when you run the code.
(GCC appears somewhat inconsistent in its ability to give aliasing warnings, sometimes giving us a friendly warning and sometimes not.)
To see why this behavior is undefined, we have to think about what the strict aliasing rule buys the compiler. Basically, with this rule, it doesn't have to think about inserting instructions to refresh the contents of `buff` every run of the loop. Instead, when optimizing, with some annoyingly unenforced assumptions about aliasing, it can omit those instructions, load `buff[0]` and `buff[1]` into CPU registers once before the loop is run, and speed up the body of the loop. Before strict aliasing was introduced, the compiler had to live in a state of paranoia that the contents of `buff` could change by any preceding memory stores. So to get an extra performance edge, and assuming most people don't type-pun pointers, the strict aliasing rule was introduced.
Keep in mind, if you think the example is contrived, this might even happen if you're passing a buffer to another function doing the sending for you, if instead you have.
```
void SendMessage(uint32_t* buff, size_t size32)
{
for (int i = 0; i < size32; ++i)
{
SendWord(buff[i]);
}
}
```
And rewrote our earlier loop to take advantage of this convenient function
```
for (int i = 0; i < 10; ++i)
{
msg->a = i;
msg->b = i+1;
SendMessage(buff, 2);
}
```
The compiler may or may not be able to or smart enough to try to inline SendMessage and it may or may not decide to load or not load buff again. If `SendMessage` is part of another API that's compiled separately, it probably has instructions to load buff's contents. Then again, maybe you're in C++ and this is some templated header only implementation that the compiler thinks it can inline. Or maybe it's just something you wrote in your .c file for your own convenience. Anyway undefined behavior might still ensue. Even when we know some of what's happening under the hood, it's still a violation of the rule so no well defined behavior is guaranteed. So just by wrapping in a function that takes our word delimited buffer doesn't necessarily help.
**So how do I get around this?**
* Use a union. Most compilers support this without complaining about strict aliasing. This is allowed in C99 and explicitly allowed in C11.
```
union {
Msg msg;
unsigned int asBuffer[sizeof(Msg)/sizeof(unsigned int)];
};
```
* You can disable strict aliasing in your compiler ([f[no-]strict-aliasing](http://gcc.gnu.org/onlinedocs/gcc-4.6.1/gcc/Optimize-Options.html#index-fstrict_002daliasing-825) in gcc))
* You can use `char*` for aliasing instead of your system's word. The rules allow an exception for `char*` (including `signed char` and `unsigned char`). It's always assumed that `char*` aliases other types. However this won't work the other way: there's no assumption that your struct aliases a buffer of chars.
**Beginner beware**
This is only one potential minefield when overlaying two types onto each other. You should also learn about [endianness](http://en.wikipedia.org/wiki/Endianness), [word alignment](http://web.archive.org/web/20170708093042/http://www.cs.umd.edu:80/class/sum2003/cmsc311/Notes/Data/aligned.html), and how to deal with alignment issues through [packing structs](http://grok2.com/structure_packing.html) correctly.
Footnote
--------
1 The types that C 2011 6.5 7 allows an lvalue to access are:
* a type compatible with the effective type of the object,
* a qualified version of a type compatible with the effective type of the object,
* a type that is the signed or unsigned type corresponding to the effective type of the object,
* a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
* an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
* a character type. |
98,705 | <p>I understand that the function is not allowed to change the state of the object, but I thought I read somewhere that the compiler was allowed to assume that if the function was called with the same arguments, it would return the same value and thus could reuse a cached value if it was available. e.g.</p>
<pre><code>class object
{
int get_value(int n) const
{
...
}
...
object x;
int a = x.get_value(1);
...
int b = x.get_value(1);
</code></pre>
<p>then the compiler could optimize the second call away and either use the value in a register or simply do <code>b = a;</code></p>
<p>Is this true?</p>
| [
{
"answer_id": 98733,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 0,
"selected": false,
"text": "<p>I doubt it, the function could still call a global function that altered the state of the world and not violate c... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
] | I understand that the function is not allowed to change the state of the object, but I thought I read somewhere that the compiler was allowed to assume that if the function was called with the same arguments, it would return the same value and thus could reuse a cached value if it was available. e.g.
```
class object
{
int get_value(int n) const
{
...
}
...
object x;
int a = x.get_value(1);
...
int b = x.get_value(1);
```
then the compiler could optimize the second call away and either use the value in a register or simply do `b = a;`
Is this true? | `const` is about program semantics and not about implementation details. You should mark a member function `const` when it does not change the visible state of the object, and should be callable on an object that is itself `const`. Within a `const` member function on a class `X`, the type of `this` is `X const *`: pointer to constant `X` object. Thus all member variables are effectively `const` within that member function (except `mutable` ones). If you have a `const` object, you can only call `const` member functions on it.
You can use `mutable` to indicate that a member variable may change even within a `const` member function. This is typically used to identify variables used for caching results, or for variables that don't affect the actual observable state such as mutexes (you still need to lock the mutex in the `const` member functions) or use counters.
```
class X
{
int data;
mutable boost::mutex m;
public:
void set_data(int i)
{
boost::lock_guard<boost::mutex> lk(m);
data=i;
}
int get_data() const // we want to be able to get the data on a const object
{
boost::lock_guard<boost::mutex> lk(m); // this requires m to be non-const
return data;
}
};
```
If you hold the data by pointer rather than directly (including smart pointers such as `std::auto_ptr` or `boost::shared_ptr`) then the pointer becomes `const` in a `const` member function, but not the pointed-to data, so you can modify the pointed-to data.
As for caching: in general the compiler cannot do this because the state might change between calls (especially in my multi-threaded example with the mutex). However, if the definition is inline then the compiler can pull the code into the calling function and optimize what it can see there. This might result in the function *effectively* only being called once.
The next version of the [C++ Standard (C++0x)](http://www.open-std.org/jtc1/sc22/wg21/) will have a new keyword `constexpr`. Functions tagged `constexpr` return a constant value, so the results can be cached. There are limits on what you can do in such a function (in order that the compiler can verify this fact). |
98,774 | <p>I am creating a downloading application and I wish to preallocate room on the harddrive for the files before they are actually downloaded as they could potentially be rather large, and noone likes to see "This drive is full, please delete some files and try again." So, in that light, I wrote this.</p>
<pre><code>// Quick, and very dirty
System.IO.File.WriteAllBytes(filename, new byte[f.Length]);
</code></pre>
<p>It works, atleast until you download a file that is several hundred MB's, or potentially even GB's and you throw Windows into a thrashing frenzy if not totally wipe out the pagefile and kill your systems memory altogether. Oops.</p>
<p>So, with a little more enlightenment, I set out with the following algorithm.</p>
<pre><code>using (FileStream outFile = System.IO.File.Create(filename))
{
// 4194304 = 4MB; loops from 1 block in so that we leave the loop one
// block short
byte[] buff = new byte[4194304];
for (int i = buff.Length; i < f.Length; i += buff.Length)
{
outFile.Write(buff, 0, buff.Length);
}
outFile.Write(buff, 0, f.Length % buff.Length);
}
</code></pre>
<p>This works, well even, and doesn't suffer the crippling memory problem of the last solution. It's still slow though, especially on older hardware since it writes out (potentially GB's worth of) data out to the disk.</p>
<p>The question is this: Is there a better way of accomplishing the same thing? Is there a way of telling Windows to create a file of x size and simply allocate the space on the filesystem rather than actually write out a tonne of data. I don't care about initialising the data in the file at all (the protocol I'm using - bittorrent - provides hashes for the files it sends, hence worst case for random uninitialised data is I get a lucky coincidence and part of the file is correct).</p>
| [
{
"answer_id": 98822,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 3,
"selected": false,
"text": "<p>If you have to create the file, I think that you can probably do something like this:</p>\n\n<pre><code>using (FileStream out... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] | I am creating a downloading application and I wish to preallocate room on the harddrive for the files before they are actually downloaded as they could potentially be rather large, and noone likes to see "This drive is full, please delete some files and try again." So, in that light, I wrote this.
```
// Quick, and very dirty
System.IO.File.WriteAllBytes(filename, new byte[f.Length]);
```
It works, atleast until you download a file that is several hundred MB's, or potentially even GB's and you throw Windows into a thrashing frenzy if not totally wipe out the pagefile and kill your systems memory altogether. Oops.
So, with a little more enlightenment, I set out with the following algorithm.
```
using (FileStream outFile = System.IO.File.Create(filename))
{
// 4194304 = 4MB; loops from 1 block in so that we leave the loop one
// block short
byte[] buff = new byte[4194304];
for (int i = buff.Length; i < f.Length; i += buff.Length)
{
outFile.Write(buff, 0, buff.Length);
}
outFile.Write(buff, 0, f.Length % buff.Length);
}
```
This works, well even, and doesn't suffer the crippling memory problem of the last solution. It's still slow though, especially on older hardware since it writes out (potentially GB's worth of) data out to the disk.
The question is this: Is there a better way of accomplishing the same thing? Is there a way of telling Windows to create a file of x size and simply allocate the space on the filesystem rather than actually write out a tonne of data. I don't care about initialising the data in the file at all (the protocol I'm using - bittorrent - provides hashes for the files it sends, hence worst case for random uninitialised data is I get a lucky coincidence and part of the file is correct). | [FileStream.SetLength](http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength) is the one you want. The syntax:
```
public override void SetLength(
long value
)
``` |
98,778 | <p>I need to execute a batch file as part of the un-install process in a Windows installer project (standard OOTB VS 2008 installer project-vdproj). One cannot execute a bat file directly from the Custom Actions in the installer project, so I wrote a quick vbs script to call the required bat file.<br>
vbs code: </p>
<pre><code>Set WshShell = WScript.CreateObject( "WScript.Shell" )
command = "uninstall-windows-serivce.bat"
msgbox command
WshShell.Run ("cmd /C " & """" & command & """")
Set WshShell = Nothing
</code></pre>
<p>When this script is run independent of the uninstall, it works perfectly. However, when run as part of the uninstall, it does not execute the bat file (but the message box is shown, so I know the vbs file is called). No errors reported (at least that I can tell). Why doesn't this script work as part of the "Uninstall Custom Action"</p>
| [
{
"answer_id": 98839,
"author": "Mike L",
"author_id": 12085,
"author_profile": "https://Stackoverflow.com/users/12085",
"pm_score": 0,
"selected": false,
"text": "<p>In your installer class, are you overriding the Uninstall method: </p>\n\n<pre><code> Public Overrides Sub Uninstall(ByVa... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18449/"
] | I need to execute a batch file as part of the un-install process in a Windows installer project (standard OOTB VS 2008 installer project-vdproj). One cannot execute a bat file directly from the Custom Actions in the installer project, so I wrote a quick vbs script to call the required bat file.
vbs code:
```
Set WshShell = WScript.CreateObject( "WScript.Shell" )
command = "uninstall-windows-serivce.bat"
msgbox command
WshShell.Run ("cmd /C " & """" & command & """")
Set WshShell = Nothing
```
When this script is run independent of the uninstall, it works perfectly. However, when run as part of the uninstall, it does not execute the bat file (but the message box is shown, so I know the vbs file is called). No errors reported (at least that I can tell). Why doesn't this script work as part of the "Uninstall Custom Action" | I've run into this same problem and the issue is that you can't call WScript within the vbs file - you will need to JUST call CreateObject
ie.
```
Set WshShell = CreateObject( "WScript.Shell" )
command = "uninstall-windows-serivce.bat"
msgbox command
WshShell.Run ("cmd /C " & """" & command & """")
Set WshShell = Nothing
``` |
98,827 | <p>I'm looking for a method to assign variables with patterns in regular expressions with C++ .NET
something like </p>
<pre><code>String^ speed;
String^ size;
</code></pre>
<p>"command SPEED=[speed] SIZE=[size]"</p>
<p>Right now I'm using IndexOf() and Substring() but it is quite ugly</p>
| [
{
"answer_id": 98946,
"author": "user10392",
"author_id": 10392,
"author_profile": "https://Stackoverflow.com/users/10392",
"pm_score": 0,
"selected": false,
"text": "<p>If you put all the variables in a class, you can use reflection to iterate over its fields, getting their names and va... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6367/"
] | I'm looking for a method to assign variables with patterns in regular expressions with C++ .NET
something like
```
String^ speed;
String^ size;
```
"command SPEED=[speed] SIZE=[size]"
Right now I'm using IndexOf() and Substring() but it is quite ugly | ```
String^ speed; String^ size;
Match m;
Regex theregex = new Regex (
"SPEED=(?<speed>(.*?)) SIZE=(?<size>(.*?)) ",
RegexOptions::ExplicitCapture);
m = theregex.Match (yourinputstring);
if (m.Success)
{
if (m.Groups["speed"].Success)
speed = m.Groups["speed"].Value;
if (m.Groups["size"].Success)
size = m.Groups["size"].Value;
}
else
throw new FormatException ("Input options not recognized");
```
Apologies for syntax errors, I don't have a compiler to test with right now. |
98,895 | <p>I'm having problems refreshing .Net 2.0 with IIS 6.</p>
<p>I have been able to successfully execute "aspnet_regiis.exe -i", but when I try to register the aspnet_isapi.dll:</p>
<pre><code>regsvr32 “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll"
</code></pre>
<p>I get the error</p>
<blockquote>
<p>C:\Windows..\aspnet_isapi.dll was loaded, but the DllRegisterServer entry point was not found.</p>
<p>The file cannot be registered.</p>
</blockquote>
<p>Does anyone know how to resolve this? Google hasn't been very helpful.</p>
<p><strong>Edit:</strong> My problem is actually that IIS isn't serving my webpages properly - that is, it's returning 404s when I try to request .aspx files that I know exist.</p>
<p>I can access .gif and .js files OK, but I can't access .aspx or other .Net files. I know this is related to .Net being properly configured with IIS, and the above commands are supposed to be the solution, but the second command doesn't work.</p>
<p><strong>@aaronjensen</strong>: Your command to register scripts worked successfully, and investigating the logs I find that I'm getting an entry for my failed request with status 404, substatus 2.</p>
<p>Microsoft tells me this because "<a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0f4ac79a-dc2b-4a5f-89c1-d57266aa6ffe.mspx?mfr=true" rel="nofollow noreferrer">Lockdown Policy Prevents This Request</a>".</p>
<blockquote>
<p>If a request is denied because the
associated ISAPI or CGI has not been
unlocked, a 404.2 error is returned.</p>
</blockquote>
<p>Which I assume is due to the isapi DLL in my original query being denied?</p>
| [
{
"answer_id": 98907,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 0,
"selected": false,
"text": "<p>When you get the error, it means either:</p>\n\n<p>1 The DLL does not need to be registered</p>\n\n<p>or</p>\n\n<p>2 T... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10717/"
] | I'm having problems refreshing .Net 2.0 with IIS 6.
I have been able to successfully execute "aspnet\_regiis.exe -i", but when I try to register the aspnet\_isapi.dll:
```
regsvr32 “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll"
```
I get the error
>
> C:\Windows..\aspnet\_isapi.dll was loaded, but the DllRegisterServer entry point was not found.
>
>
> The file cannot be registered.
>
>
>
Does anyone know how to resolve this? Google hasn't been very helpful.
**Edit:** My problem is actually that IIS isn't serving my webpages properly - that is, it's returning 404s when I try to request .aspx files that I know exist.
I can access .gif and .js files OK, but I can't access .aspx or other .Net files. I know this is related to .Net being properly configured with IIS, and the above commands are supposed to be the solution, but the second command doesn't work.
**@aaronjensen**: Your command to register scripts worked successfully, and investigating the logs I find that I'm getting an entry for my failed request with status 404, substatus 2.
Microsoft tells me this because "[Lockdown Policy Prevents This Request](http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0f4ac79a-dc2b-4a5f-89c1-d57266aa6ffe.mspx?mfr=true)".
>
> If a request is denied because the
> associated ISAPI or CGI has not been
> unlocked, a 404.2 error is returned.
>
>
>
Which I assume is due to the isapi DLL in my original query being denied? | In the end, I think the problem was caused by a step that is missed by the script when you refresh ASP.Net 2.0 with IIS 6.
I managed to resolve this using the following steps:
* Refresh the install using `C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -s /w3svc/1/root`
* Enable ASP.Net Web Service Extension in the IIS 6 Management Console - it looks like the extension was not enabled by default in IIS, hence the 404.2 [Lockdown Policy Prevents This Request](http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0f4ac79a-dc2b-4a5f-89c1-d57266aa6ffe.mspx?mfr=true) errors that I was seeing. Instructions to [enable the ASP.Net webservice extension](http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/596ff388-bc4c-472f-b029-aea2b0418bea.mspx?mfr=true) are on MSDN. |
98,941 | <p>How to add a click event listener to my custom control made with wxWidgets? The custom control uses wxWindow as the base. On the event list I see </p>
<pre><code>wxEVT_LEFT_DOWN
wxEVT_LEFT_UP
wxEVT_LEFT_DCLICK
wxEVT_MIDDLE_DOWN
wxEVT_MIDDLE_UP
wxEVT_MIDDLE_DCLICK
wxEVT_RIGHT_DOWN
wxEVT_RIGHT_UP
wxEVT_RIGHT_DCLICK
wxEVT_MOTION
wxEVT_ENTER_WINDOW
wxEVT_LEAVE_WINDOW
wxEVT_MOUSEWHEEL
</code></pre>
<p>But there is no <code>wxEVT_LEFT_CLICK</code> or similar. </p>
| [
{
"answer_id": 99659,
"author": "Zach Burlingame",
"author_id": 2233,
"author_profile": "https://Stackoverflow.com/users/2233",
"pm_score": 3,
"selected": true,
"text": "<p>Typically, there is no \"click\" event (and in the case of <a href=\"http://www.wxwidgets.org/\" rel=\"nofollow nor... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11238/"
] | How to add a click event listener to my custom control made with wxWidgets? The custom control uses wxWindow as the base. On the event list I see
```
wxEVT_LEFT_DOWN
wxEVT_LEFT_UP
wxEVT_LEFT_DCLICK
wxEVT_MIDDLE_DOWN
wxEVT_MIDDLE_UP
wxEVT_MIDDLE_DCLICK
wxEVT_RIGHT_DOWN
wxEVT_RIGHT_UP
wxEVT_RIGHT_DCLICK
wxEVT_MOTION
wxEVT_ENTER_WINDOW
wxEVT_LEAVE_WINDOW
wxEVT_MOUSEWHEEL
```
But there is no `wxEVT_LEFT_CLICK` or similar. | Typically, there is no "click" event (and in the case of [wxWidgets](http://www.wxwidgets.org/) - [there isn't](http://docs.wxwidgets.org/stable/wx_wxmouseevent.html#wxmouseevent)
). The action of clicking is broken into its two parts: Mouse Down and Mouse Up. Typically what you think of as a "left click" event is actually handled in a "left up" event.
Try it out:
* Hover over a button (such as the "Add Comment" button this page)
* Click the left-mouse button down and hold
* Move the mouse off of the button while holding down
* Release the left-mouse button
* Nothing happens!
This time:
* Hover over the same button
* Click the
left-mouse button down and hold
* Release the left-mouse button
* The "click" action you expect is triggered by the up event! |
98,944 | <p>How do I write a cpp macro which expands to include newlines?</p>
| [
{
"answer_id": 98956,
"author": "Branan",
"author_id": 13894,
"author_profile": "https://Stackoverflow.com/users/13894",
"pm_score": -1,
"selected": false,
"text": "<p>Use <code>\\</code>, like so:</p>\n\n<pre><code>#define my_multiline_macro(a, b, c) \\\nif (a) { \\\n b += c; \\\n}\n... | 2008/09/19 | [
"https://Stackoverflow.com/questions/98944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18458/"
] | How do I write a cpp macro which expands to include newlines? | I am working on a large project that involves a lot of preprocessor macro functions to synthesize any code that cannot be replaced by templates. Believe me, I am familiar with all sorts of template tricks, but as long as there is no standardized, type safe metaprogramming language that can directly create code, we will have to stick with good old preprocessor and its cumbersome macros to solve some problems that would require to write ten times more code without.
Some of the macros span many lines and they are very hard to read in preprocessed code. Therefore, I thought of a solution to that problem and what I came up with is the following:
Let's say we have a C/C++ macro that spans multiple lines, e.g. in a file named *MyMacro.hpp*
```
// Content of MyMacro.hpp
#include "MultilineMacroDebugging.hpp"
#define PRINT_VARIABLE(S) \
__NL__ std::cout << #S << ": " << S << std::endl; \
__NL__ /* more lines if necessary */ \
__NL__ /* even more lines */
```
In every file where I defined such a macro, I include another file *MultilineMacroDebugging.hpp* that contains the following:
```
// Content of MultilineMacroDebugging.hpp
#ifndef HAVE_MULTILINE_DEBUGGING
#define __NL__
#endif
```
This defines an empty macro `__NL__`, which makes the `__NL__` definitions disappear during preprocessing. The macro can then be used somewhere, e.g.
in a file named *MyImplementation.cpp*.
```
// Content of MyImplementation.cpp
// Uncomment the following line to enable macro debugging
//#define HAVE_MULTILINE_DEBUGGING
#include "MyMacro.hpp"
int a = 10;
PRINT_VARIABLE(a)
```
If I need to debug the `PRINT_VARIABLE` macro, I just uncomment the line that defines the macro `HAVE_MULTILINE_DEBUGGING` in *MyImplementation.cpp*. The resulting code does of course not compile, as the `__NL__` macro results undefined, which causes it to remain in the compiled code, but it can, however, be preprocessed.
The crucial step is now to replace the `__NL__` string in the preprocessor output by newlines using your favorite text editor and, voila, you end up with a readable representation of the result of the replaced macro after preprocessing which resembles exactly what the compiler would see, except for the artificially introduced newlines. |
99,045 | <p>We are running Selenium regression tests against our existing code base, and certain screens in our web app use pop-ups for intermediate steps.</p>
<p>Currently we use the commands in the test:</p>
<pre><code>// force new window to open at this point - so we can select it later
selenium().getEval("this.browserbot.getCurrentWindow().open('', 'enquiryPopup')");
selenium().click("//input[@value='Submit']");
selenium().waitForPopUp("enquiryPopup", getWaitTime());
selenium().selectWindow("enquiryPopup");
</code></pre>
<p>...which works <em>most of the time</em>. Occasionally the test will fail on the <code>waitForPopUp()</code> line with </p>
<pre><code>com.thoughtworks.selenium.SeleniumException: Permission denied
</code></pre>
<p>Can anyone suggest a better, more <em>reliable</em> method?</p>
<p>Also, we primarily run these tests on IE6 and 7.</p>
| [
{
"answer_id": 99127,
"author": "Josh",
"author_id": 11702,
"author_profile": "https://Stackoverflow.com/users/11702",
"pm_score": 1,
"selected": false,
"text": "<p>If you are running in *iehta mode then you are going to run into some glitches here and there. We run Selenium at my job an... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
] | We are running Selenium regression tests against our existing code base, and certain screens in our web app use pop-ups for intermediate steps.
Currently we use the commands in the test:
```
// force new window to open at this point - so we can select it later
selenium().getEval("this.browserbot.getCurrentWindow().open('', 'enquiryPopup')");
selenium().click("//input[@value='Submit']");
selenium().waitForPopUp("enquiryPopup", getWaitTime());
selenium().selectWindow("enquiryPopup");
```
...which works *most of the time*. Occasionally the test will fail on the `waitForPopUp()` line with
```
com.thoughtworks.selenium.SeleniumException: Permission denied
```
Can anyone suggest a better, more *reliable* method?
Also, we primarily run these tests on IE6 and 7. | It works!! Just to make it easier for the folks who prefer selenese.
This worked for me using IE7(normal mode).
What a freaking hassle. Thank the spaghetti monster in the sky for SO or there is no way I would have got this working in IE.
```
<tr>
<td>getEval</td>
<td>selenium.browserbot.getCurrentWindow().open('', 'windowName');</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>buttonName</td>
<td></td>
</tr>
<tr>
<td>windowFocus</td>
<td>windowName</td>
<td></td>
</tr>
<tr>
<td>waitForPopUp</td>
<td>windowName</td>
<td>3000</td>
</tr>
<tr>
<td>selectWindow</td>
<td>windowName</td>
<td></td>
</tr>
``` |
99,074 | <p>Would it be useful to be able to provide method return value for null objects?</p>
<p>For a List the null return values might be:</p>
<pre><code>get(int) : null
size() : 0
iterator() : empty iterator
</code></pre>
<p>That would allow the following code that has less null checks.</p>
<pre><code>List items = null;
if(something) {
items = ...
}
for(int index = 0; index < items.size(); index++) {
Object obj = items.get(index);
}
</code></pre>
<p>This would only be used if the class or interface defined it and a null check would still work. Sometimes you don't want to do null checks so it seems like it could be beneficial to have this as an option.</p>
<p>From: <a href="http://jamesjava.blogspot.com/2007/05/method-return-values-for-null-objects.html" rel="nofollow noreferrer">http://jamesjava.blogspot.com/2007/05/method-return-values-for-null-objects.html</a></p>
| [
{
"answer_id": 99112,
"author": "Tim Williscroft",
"author_id": 2789,
"author_profile": "https://Stackoverflow.com/users/2789",
"pm_score": 0,
"selected": false,
"text": "<p><strong>This is a good idea.</strong></p>\n\n<p>Smalltalk does this.</p>\n\n<p>There is a NULL object. It <em>doe... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6770/"
] | Would it be useful to be able to provide method return value for null objects?
For a List the null return values might be:
```
get(int) : null
size() : 0
iterator() : empty iterator
```
That would allow the following code that has less null checks.
```
List items = null;
if(something) {
items = ...
}
for(int index = 0; index < items.size(); index++) {
Object obj = items.get(index);
}
```
This would only be used if the class or interface defined it and a null check would still work. Sometimes you don't want to do null checks so it seems like it could be beneficial to have this as an option.
From: <http://jamesjava.blogspot.com/2007/05/method-return-values-for-null-objects.html> | It's a pattern called Null Object
<http://en.wikipedia.org/wiki/Null_Object_pattern> |
99,098 | <p>What is the best way to generate a current datestamp in Java? </p>
<p>YYYY-MM-DD:hh-mm-ss</p>
| [
{
"answer_id": 99105,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Date d = new Date();\nString formatted = new SimpleDateFormat (\"yyyy-MM-dd:HH-mm-ss\").format (d);\nSystem.... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3020/"
] | What is the best way to generate a current datestamp in Java?
YYYY-MM-DD:hh-mm-ss | Using the standard JDK, you will want to use java.text.SimpleDateFormat
```
Date myDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss");
String myDateString = sdf.format(myDate);
```
However, if you have the option to use the Apache Commons Lang package, you can use org.apache.commons.lang.time.FastDateFormat
```
Date myDate = new Date();
FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd:HH-mm-ss");
String myDateString = fdf.format(myDate);
```
FastDateFormat has the benefit of being thread safe, so you can use a single instance throughout your application. It is strictly for formatting dates and does not support parsing like SimpleDateFormat does in the following example:
```
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss");
Date yourDate = sdf.parse("2008-09-18:22-03-15");
``` |
99,118 | <p>Is there any downside or problem potential to change the Java compiler to automatically cast? In the example below the result of list.get(0) would automatically be casted to the type of the variable hi.</p>
<pre><code>List list = new ArrayList();
list.add("hi");
String hi = list.get(0);
</code></pre>
<p>I know that generics allow you to reduce casting but they do so at the expense of making declaration more difficult. To me, the benefit of generics is that they allow you to have the complier enforce more rules -- not they they reduce casting (but I haven't used them much so I am somewhat uninformed). This proposal would only reduce the amount of code to type, not move it to another place.
Also there are instances where generics can't be used because a collection can have different objectis.
If that "looks too surprising" based on current usage maybe there could be a syntax tweak to use it.</p>
<p>From: <a href="http://jamesjava.blogspot.com/2007/01/automatic-casting.html" rel="nofollow noreferrer">http://jamesjava.blogspot.com/2007/01/automatic-casting.html</a></p>
| [
{
"answer_id": 99135,
"author": "Steve Moyer",
"author_id": 17008,
"author_profile": "https://Stackoverflow.com/users/17008",
"pm_score": 3,
"selected": false,
"text": "<p>Casting is an explicit instruction to the Java compiler to ignore type safety so allowing automatic casts would remo... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6770/"
] | Is there any downside or problem potential to change the Java compiler to automatically cast? In the example below the result of list.get(0) would automatically be casted to the type of the variable hi.
```
List list = new ArrayList();
list.add("hi");
String hi = list.get(0);
```
I know that generics allow you to reduce casting but they do so at the expense of making declaration more difficult. To me, the benefit of generics is that they allow you to have the complier enforce more rules -- not they they reduce casting (but I haven't used them much so I am somewhat uninformed). This proposal would only reduce the amount of code to type, not move it to another place.
Also there are instances where generics can't be used because a collection can have different objectis.
If that "looks too surprising" based on current usage maybe there could be a syntax tweak to use it.
From: <http://jamesjava.blogspot.com/2007/01/automatic-casting.html> | Casting is an explicit instruction to the Java compiler to ignore type safety so allowing automatic casts would remove one of the features purposely designed into the language.
I personally like compiler warnings and errors, since it's much harder to find this type of problem at run time (assuming the compiler somehow managed to force one object type to another). |
99,132 | <p>I need to generate a directory in my makefile and I would like to not get the "directory already exists error" over and over even though I can easily ignore it.</p>
<p>I mainly use mingw/msys but would like something that works across other shells/systems too.</p>
<p>I tried this but it didn't work, any ideas?</p>
<pre><code>ifeq (,$(findstring $(OBJDIR),$(wildcard $(OBJDIR) )))
-mkdir $(OBJDIR)
endif
</code></pre>
| [
{
"answer_id": 99156,
"author": "andrewdotnich",
"author_id": 10569,
"author_profile": "https://Stackoverflow.com/users/10569",
"pm_score": 4,
"selected": false,
"text": "<p>If having the directory already exist is not a problem for you, you could just redirect stderr for that command, g... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
] | I need to generate a directory in my makefile and I would like to not get the "directory already exists error" over and over even though I can easily ignore it.
I mainly use mingw/msys but would like something that works across other shells/systems too.
I tried this but it didn't work, any ideas?
```
ifeq (,$(findstring $(OBJDIR),$(wildcard $(OBJDIR) )))
-mkdir $(OBJDIR)
endif
``` | On UNIX Just use this:
```
mkdir -p $(OBJDIR)
```
The -p option to mkdir prevents the error message if the directory exists. |
99,161 | <p>I search for "nurple" in a file. I found it, great. But now, every occurrence of "nurple" is rendered in sick black on yellow. Forever.</p>
<p>Forever, that is, until I search for something I know won't be found, such as "asdhfalsdflajdflakjdf" simply so it clears the previous search highlighting.</p>
<p>Can't I just hit a magic key to kill the highlights when I'm done searching?</p>
| [
{
"answer_id": 99182,
"author": "Lee H",
"author_id": 18201,
"author_profile": "https://Stackoverflow.com/users/18201",
"pm_score": 9,
"selected": false,
"text": "<p><code>:noh</code> (short for <code>nohighlight</code>) will temporarily clear the search highlight. The next search will s... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18446/"
] | I search for "nurple" in a file. I found it, great. But now, every occurrence of "nurple" is rendered in sick black on yellow. Forever.
Forever, that is, until I search for something I know won't be found, such as "asdhfalsdflajdflakjdf" simply so it clears the previous search highlighting.
Can't I just hit a magic key to kill the highlights when I'm done searching? | Just put this in your .vimrc
```
" <Ctrl-l> redraws the screen and removes any search highlighting.
nnoremap <silent> <C-l> :nohl<CR><C-l>
``` |
99,164 | <p>I often see code like:</p>
<pre><code>Iterator i = list.iterator();
while(i.hasNext()) {
...
}
</code></pre>
<p>but I write that (when Java 1.5 isn't available or for each can't be used) as:</p>
<pre><code>for(Iterator i = list.iterator(); i.hasNext(); ) {
...
}
</code></pre>
<p>because</p>
<ul>
<li>It is shorter</li>
<li>It keeps <code>i</code> in a smaller scope</li>
<li>It reduces the chance of confusion. (Is <code>i</code> used outside the
while? Where is <code>i</code> declared?)</li>
</ul>
<p>I think code should be as simple to understand as possible so that I only have to make complex code to do complex things. What do you think? Which is better?</p>
<p>From: <a href="http://jamesjava.blogspot.com/2006/04/iterating.html" rel="noreferrer">http://jamesjava.blogspot.com/2006/04/iterating.html</a></p>
| [
{
"answer_id": 99177,
"author": "scubabbl",
"author_id": 9450,
"author_profile": "https://Stackoverflow.com/users/9450",
"pm_score": 0,
"selected": false,
"text": "<p>Either is fine. I use for () myself, and I don't know if there are compile issues. I suspect they both get optimized down... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6770/"
] | I often see code like:
```
Iterator i = list.iterator();
while(i.hasNext()) {
...
}
```
but I write that (when Java 1.5 isn't available or for each can't be used) as:
```
for(Iterator i = list.iterator(); i.hasNext(); ) {
...
}
```
because
* It is shorter
* It keeps `i` in a smaller scope
* It reduces the chance of confusion. (Is `i` used outside the
while? Where is `i` declared?)
I think code should be as simple to understand as possible so that I only have to make complex code to do complex things. What do you think? Which is better?
From: <http://jamesjava.blogspot.com/2006/04/iterating.html> | I prefer the for loop because it also sets the scope of the iterator to just the for loop. |
99,211 | <p>I am trying to get Haml to work with my Ruby on Rails project. I am new to Ruby on Rails and I really like it. However, when I attempt to add an <code>aplication.html.haml</code> or <code>index.html.haml</code> for a view, I just receive errors.</p>
<p>I am using NetBeans as my IDE.</p>
| [
{
"answer_id": 105542,
"author": "Ryan McGeary",
"author_id": 8985,
"author_profile": "https://Stackoverflow.com/users/8985",
"pm_score": 5,
"selected": false,
"text": "<p>First, <strong>install haml</strong> as a gem in bundler by adding this to your <code>Gemfile</code>:</p>\n\n<pre><c... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am trying to get Haml to work with my Ruby on Rails project. I am new to Ruby on Rails and I really like it. However, when I attempt to add an `aplication.html.haml` or `index.html.haml` for a view, I just receive errors.
I am using NetBeans as my IDE. | Haml with Rails 3
-----------------
For Rails 3 all you need to do is add `gem "haml", '3.0.25'` to your `Gemfile`. No need to install plugin or run `haml --rails .`.
Just:
```
$ cd awesome-rails-3-app.git
$ echo 'gem "haml"' >> Gemfile
```
And you're done. |
99,279 | <p>I want to parse a web page in Groovy and extract all of the href links and the associated text with it.</p>
<p>If the page contained these links:</p>
<pre><code><a href="http://www.google.com">Google</a><br />
<a href="http://www.apple.com">Apple</a>
</code></pre>
<p>the output would be:</p>
<pre><code>Google, http://www.google.com<br />
Apple, http://www.apple.com
</code></pre>
<p>I'm looking for a Groovy answer. AKA. The easy way!</p>
| [
{
"answer_id": 99293,
"author": "William Keller",
"author_id": 17095,
"author_profile": "https://Stackoverflow.com/users/17095",
"pm_score": 2,
"selected": false,
"text": "<p>A quick google search turned up a nice looking possibility, <a href=\"http://blog.foosion.org/2008/06/09/parse-ht... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I want to parse a web page in Groovy and extract all of the href links and the associated text with it.
If the page contained these links:
```
<a href="http://www.google.com">Google</a><br />
<a href="http://www.apple.com">Apple</a>
```
the output would be:
```
Google, http://www.google.com<br />
Apple, http://www.apple.com
```
I'm looking for a Groovy answer. AKA. The easy way! | Assuming well-formed XHTML, slurp the xml, collect up all the tags, find the 'a' tags, and print out the href and text.
```
input = """<html><body>
<a href = "http://www.hjsoft.com/">John</a>
<a href = "http://www.google.com/">Google</a>
<a href = "http://www.stackoverflow.com/">StackOverflow</a>
</body></html>"""
doc = new XmlSlurper().parseText(input)
doc.depthFirst().collect { it }.findAll { it.name() == "a" }.each {
println "${it.text()}, ${it.@href.text()}"
}
``` |
99,285 | <p>Would it be useful to be able to mark objects where the value ofString.valueOf() would included in any stack trace. In my example below I used "trace". Variables that aren't declared at the point of the stack trace would just be ingored.
It would make debugging much easier and make it much easier to write programs that are easy to debug.</p>
<p>Example stack trace for the code below:</p>
<pre><code>java.lang.NullPointerException:
at Test.main(Test.java:7) index=0, sum=3, obj=null
public class Test {
Object obj;
public void main(String[] args) trace obj {
trace int sum = 0;
for(trace int index = 0; index < args.length; index++) {
sum += Integer.parseInt(args[index]);
sum += obj.hashCode();//Will cause NullPointerException
}
}
}
</code></pre>
<p>From: <a href="http://jamesjava.blogspot.com/2005/04/extra-info-in-stack-traces.html" rel="nofollow noreferrer">http://jamesjava.blogspot.com/2005/04/extra-info-in-stack-traces.html</a></p>
| [
{
"answer_id": 99385,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<p>this might be useful, but i think it clutters the code - presumably when the code is working you would want to remo... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6770/"
] | Would it be useful to be able to mark objects where the value ofString.valueOf() would included in any stack trace. In my example below I used "trace". Variables that aren't declared at the point of the stack trace would just be ingored.
It would make debugging much easier and make it much easier to write programs that are easy to debug.
Example stack trace for the code below:
```
java.lang.NullPointerException:
at Test.main(Test.java:7) index=0, sum=3, obj=null
public class Test {
Object obj;
public void main(String[] args) trace obj {
trace int sum = 0;
for(trace int index = 0; index < args.length; index++) {
sum += Integer.parseInt(args[index]);
sum += obj.hashCode();//Will cause NullPointerException
}
}
}
```
From: <http://jamesjava.blogspot.com/2005/04/extra-info-in-stack-traces.html> | this might be useful, but i think it clutters the code - presumably when the code is working you would want to remove the 'trace' keywords; perhaps some form of metadata would be more appropriate
then there's always print statements... |
99,315 | <p>What if a Java allow both static and dynamic types. That might allow the best of both worlds. i.e.:</p>
<pre><code>String str = "Hello";
var temp = str;
temp = 10;
temp = temp * 5;
</code></pre>
<ol>
<li>Would that be possible?</li>
<li>Would that be beneficial?</li>
<li>Do any languages currently support both and how well does it work out?</li>
</ol>
<p>Here is a better example (generics can't be used but the program does know the type):</p>
<pre><code>var username = HttpServletRequest.getSession().getAttribute("username");//Returns a String
if(username.length() == 0) {
//Error
}
</code></pre>
| [
{
"answer_id": 99333,
"author": "jon",
"author_id": 12215,
"author_profile": "https://Stackoverflow.com/users/12215",
"pm_score": 1,
"selected": false,
"text": "<p>Can you explain the difference between your example and</p>\n\n<pre><code>String str = \"Hello\";\nObject temp = str;\ntemp ... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6770/"
] | What if a Java allow both static and dynamic types. That might allow the best of both worlds. i.e.:
```
String str = "Hello";
var temp = str;
temp = 10;
temp = temp * 5;
```
1. Would that be possible?
2. Would that be beneficial?
3. Do any languages currently support both and how well does it work out?
Here is a better example (generics can't be used but the program does know the type):
```
var username = HttpServletRequest.getSession().getAttribute("username");//Returns a String
if(username.length() == 0) {
//Error
}
``` | C# has a "var" keyword used in the manner you describe, but it ends up being a strongly typed variable based on the types of values that type checking suggests will go into it. |
99,318 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/1217088/what-does-mapname-mean-in-ruby">What does map(&:name) mean in Ruby?</a> </p>
</blockquote>
<p>I was watching a railscast and saw this code.</p>
<pre><code>[Category, Product].(&:delete_all)
</code></pre>
<p>In regards to clearing a database.</p>
<p>I asked about the line in IRC and was told </p>
<pre><code>(&:delete_all)
</code></pre>
<p>was a shortcut for </p>
<pre><code>{|model| model.delete_all}
</code></pre>
<p>I tested this with the following</p>
<pre><code>class ClassOne
def class_method
puts 1
end
end
class ClassTwo
def class_method
puts 2
end
end
[ClassOne, ClassTwo].each(&:class_method)
</code></pre>
<p>I received an error saying</p>
<pre><code>Wrong Argument type Symbol (expected Proc)
</code></pre>
<p>I also tried</p>
<pre><code>one = ClassOne.new
two = ClassTwo.new
[one, two].each(&:class_method)
</code></pre>
<p>But that still failed.</p>
<p>If I modified it to read</p>
<pre><code>[one, two].each{|model| model.class_method}
</code></pre>
<p>Everything worked as expected.</p>
<p>So, what does <code>&:delete_all</code> actually do? The docs say <code>delete_all</code> is a method, so I am confused as to what is going on here.</p>
| [
{
"answer_id": 99336,
"author": "Alex M",
"author_id": 9652,
"author_profile": "https://Stackoverflow.com/users/9652",
"pm_score": 5,
"selected": true,
"text": "<p>This relies upon a Ruby 1.9 extension that can be done in 1.8 by including the following:</p>\n\n<pre><code>class Symbol\n ... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9450/"
] | >
> **Possible Duplicate:**
>
> [What does map(&:name) mean in Ruby?](https://stackoverflow.com/questions/1217088/what-does-mapname-mean-in-ruby)
>
>
>
I was watching a railscast and saw this code.
```
[Category, Product].(&:delete_all)
```
In regards to clearing a database.
I asked about the line in IRC and was told
```
(&:delete_all)
```
was a shortcut for
```
{|model| model.delete_all}
```
I tested this with the following
```
class ClassOne
def class_method
puts 1
end
end
class ClassTwo
def class_method
puts 2
end
end
[ClassOne, ClassTwo].each(&:class_method)
```
I received an error saying
```
Wrong Argument type Symbol (expected Proc)
```
I also tried
```
one = ClassOne.new
two = ClassTwo.new
[one, two].each(&:class_method)
```
But that still failed.
If I modified it to read
```
[one, two].each{|model| model.class_method}
```
Everything worked as expected.
So, what does `&:delete_all` actually do? The docs say `delete_all` is a method, so I am confused as to what is going on here. | This relies upon a Ruby 1.9 extension that can be done in 1.8 by including the following:
```
class Symbol
def to_proc
proc { |obj, *args| obj.send(self, *args) }
end
end
```
I believe Rails defines this in `ActiveSupport`. |
99,350 | <p>Is there an easy way to marshal a PHP associative array to and from XML? For example, I have the following array:</p>
<pre><code>$items = array("1", "2",
array(
"item3.1" => "3.1",
"item3.2" => "3.2"
"isawesome" => true
)
);
</code></pre>
<p>How would I turn it into something similar to the following XML in as few lines as possible, then back again?</p>
<pre><code><items>
<item>1</item>
<item>2</item>
<item>
<item3_1>3.1</item3_1>
<item3_2>3.2</item3_2>
<isawesome>true</isawesome>
</item>
</items>
</code></pre>
<p>I don't really care if I have to change the array structure a bit or if the XML that comes out is different to the above example. I've been trying to work with PHP's <a href="http://php.net/manual/en/book.xmlreader.php" rel="noreferrer">XMLReader</a> and <a href="http://php.net/manual/en/book.xmlwriter.php" rel="noreferrer">XMLWriter</a>, but the documentation is so poor and the code I've produced as a consequence looks nothing like what I feel it should look like:</p>
<pre><code>$xml = SomeXMLWriter::writeArrayToXml($items);
$array = SomeXMLWriter::writeXmlToArray($xml);
</code></pre>
<p>Does it really have to be any harder than that to get a basic, raw XML dump of a PHP array without writing my own custom class?</p>
<p>I try to avoid PEAR. In addition to the configuration headaches I've had with it, I've never stuck with any of the packages I've ever used from it.</p>
| [
{
"answer_id": 99367,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 2,
"selected": false,
"text": "<p>Have you seen the PEAR package XML_Serializer?</p>\n\n<p><a href=\"http://pear.php.net/package/XML_Serializer\" rel=\"nofo... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15004/"
] | Is there an easy way to marshal a PHP associative array to and from XML? For example, I have the following array:
```
$items = array("1", "2",
array(
"item3.1" => "3.1",
"item3.2" => "3.2"
"isawesome" => true
)
);
```
How would I turn it into something similar to the following XML in as few lines as possible, then back again?
```
<items>
<item>1</item>
<item>2</item>
<item>
<item3_1>3.1</item3_1>
<item3_2>3.2</item3_2>
<isawesome>true</isawesome>
</item>
</items>
```
I don't really care if I have to change the array structure a bit or if the XML that comes out is different to the above example. I've been trying to work with PHP's [XMLReader](http://php.net/manual/en/book.xmlreader.php) and [XMLWriter](http://php.net/manual/en/book.xmlwriter.php), but the documentation is so poor and the code I've produced as a consequence looks nothing like what I feel it should look like:
```
$xml = SomeXMLWriter::writeArrayToXml($items);
$array = SomeXMLWriter::writeXmlToArray($xml);
```
Does it really have to be any harder than that to get a basic, raw XML dump of a PHP array without writing my own custom class?
I try to avoid PEAR. In addition to the configuration headaches I've had with it, I've never stuck with any of the packages I've ever used from it. | For those of you not using the PEAR packages, but you've got PHP5 installed. This worked for me:
```
/**
* Build A XML Data Set
*
* @param array $data Associative Array containing values to be parsed into an XML Data Set(s)
* @param string $startElement Root Opening Tag, default fx_request
* @param string $xml_version XML Version, default 1.0
* @param string $xml_encoding XML Encoding, default UTF-8
* @return string XML String containig values
* @return mixed Boolean false on failure, string XML result on success
*/
public function buildXMLData($data, $startElement = 'fx_request', $xml_version = '1.0', $xml_encoding = 'UTF-8') {
if(!is_array($data)) {
$err = 'Invalid variable type supplied, expected array not found on line '.__LINE__." in Class: ".__CLASS__." Method: ".__METHOD__;
trigger_error($err);
if($this->_debug) echo $err;
return false; //return false error occurred
}
$xml = new XmlWriter();
$xml->openMemory();
$xml->startDocument($xml_version, $xml_encoding);
$xml->startElement($startElement);
/**
* Write XML as per Associative Array
* @param object $xml XMLWriter Object
* @param array $data Associative Data Array
*/
function write(XMLWriter $xml, $data) {
foreach($data as $key => $value) {
if(is_array($value)) {
$xml->startElement($key);
write($xml, $value);
$xml->endElement();
continue;
}
$xml->writeElement($key, $value);
}
}
write($xml, $data);
$xml->endElement();//write end element
//Return the XML results
return $xml->outputMemory(true);
}
``` |
99,391 | <p>When I commit I get this error from Subversion:</p>
<pre><code>bash-2.05b$ svn commit -m "testing subversion, still"
Adding baz
svn: Commit failed (details follow):
svn: MKCOL of '/viper/!svn/wrk/6b9bcd38-b2fe-0310-95ff-9d1a44098866/sandboxes/ohammersmith/trunk/baz': 405 Method Not Allowed (http://svn.example.com)
</code></pre>
| [
{
"answer_id": 99413,
"author": "Otto",
"author_id": 9594,
"author_profile": "https://Stackoverflow.com/users/9594",
"pm_score": 8,
"selected": true,
"text": "<p>This happens when you have added a directory that someone else has also added and already committed. The error message on a c... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9594/"
] | When I commit I get this error from Subversion:
```
bash-2.05b$ svn commit -m "testing subversion, still"
Adding baz
svn: Commit failed (details follow):
svn: MKCOL of '/viper/!svn/wrk/6b9bcd38-b2fe-0310-95ff-9d1a44098866/sandboxes/ohammersmith/trunk/baz': 405 Method Not Allowed (http://svn.example.com)
``` | This happens when you have added a directory that someone else has also added and already committed. The error message on a commit is really confusing, but if you do an `svn up` instead you'll see this message:
```
bash-2.05b$ svn up
svn: Failed to add directory 'baz': object of the same name already exists
```
To resolve the issue, remove your directory (or move it aside) and do an `svn update` to get the version on the server and re-do your changes.
As a general rule, be sure to do `svn update` since the error messages tend to be more helpful. |
99,468 | <p>I am retrieving multiple rows into a listview control from an ODBC source. For simple SELECTs it seems to work well with a statement attribute of SQL_SCROLLABLE. How do I do this with a UNION query (with two selects)?</p>
<p>The most likely server will be MS SQL Server (probably 2005). The code is C for the Win32 API.</p>
<p>This code sets (what I think is) a server side cursor which feeds data into the ODBC driver that roughly corresponds with the positional fetches of SQLFetchScroll, which is turn feeds the cache for the listview. (Sometimes using SQL_FETCH_FIRST or SQL_FETCH_LAST as well as):</p>
<pre>
SQLSetStmtAttr(hstmt1Fetch,
SQL_ATTR_CURSOR_SCROLLABLE,
(SQLPOINTER)SQL_SCROLLABLE,
SQL_IS_INTEGER);
SQLSetStmtAttr(hstmt1Fetch,
SQL_ATTR_CURSOR_SENSITIVITY,
(SQLPOINTER)SQL_INSENSITIVE,
SQL_IS_INTEGER);
...
retcode = SQLGetStmtAttr(hstmt1Fetch,
SQL_ATTR_ROW_NUMBER,
&CurrentRowNumber,
SQL_IS_UINTEGER,
NULL);
...
retcode = SQLFetchScroll(hstmt1Fetch, SQL_FETCH_ABSOLUTE, Position);
</pre>
<p>(The above is is a fragment from working code for a single SELECT).</p>
<p>Is this the best way to do it? Given that I need to retrieve the last row to get the number of rows and populate the end buffer is there a better way of doing it? (Can I use forward only scrolling?)</p>
<p>Assuming yes to the above, how do I achieve the same result with a UNION query?</p>
<p>LATE EDIT: The problem with the union query being that effectively it forces forward only scrolling which breaks SQLFetchScroll(hstmt1Fetch, SQL_FETCH_ABSOLUTE, Position). The answer is I suspect: "you can't". And it really means redesigning the DB to included either a view or a single table to replace the UNION. But I'll leave the question open in case I have missed something.</p>
| [
{
"answer_id": 99628,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<p>can you not define a view on the db server that does the union query for you, so from the client code it just looks... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3137/"
] | I am retrieving multiple rows into a listview control from an ODBC source. For simple SELECTs it seems to work well with a statement attribute of SQL\_SCROLLABLE. How do I do this with a UNION query (with two selects)?
The most likely server will be MS SQL Server (probably 2005). The code is C for the Win32 API.
This code sets (what I think is) a server side cursor which feeds data into the ODBC driver that roughly corresponds with the positional fetches of SQLFetchScroll, which is turn feeds the cache for the listview. (Sometimes using SQL\_FETCH\_FIRST or SQL\_FETCH\_LAST as well as):
```
SQLSetStmtAttr(hstmt1Fetch,
SQL_ATTR_CURSOR_SCROLLABLE,
(SQLPOINTER)SQL_SCROLLABLE,
SQL_IS_INTEGER);
SQLSetStmtAttr(hstmt1Fetch,
SQL_ATTR_CURSOR_SENSITIVITY,
(SQLPOINTER)SQL_INSENSITIVE,
SQL_IS_INTEGER);
...
retcode = SQLGetStmtAttr(hstmt1Fetch,
SQL_ATTR_ROW_NUMBER,
&CurrentRowNumber,
SQL_IS_UINTEGER,
NULL);
...
retcode = SQLFetchScroll(hstmt1Fetch, SQL_FETCH_ABSOLUTE, Position);
```
(The above is is a fragment from working code for a single SELECT).
Is this the best way to do it? Given that I need to retrieve the last row to get the number of rows and populate the end buffer is there a better way of doing it? (Can I use forward only scrolling?)
Assuming yes to the above, how do I achieve the same result with a UNION query?
LATE EDIT: The problem with the union query being that effectively it forces forward only scrolling which breaks SQLFetchScroll(hstmt1Fetch, SQL\_FETCH\_ABSOLUTE, Position). The answer is I suspect: "you can't". And it really means redesigning the DB to included either a view or a single table to replace the UNION. But I'll leave the question open in case I have missed something. | can you not define a view on the db server that does the union query for you, so from the client code it just looks like a single select?
if you can't, can you just issue the union operation as part of your select, e.g.
```
select some_fields from table1
union
select same_fields from table2
```
and treat the result as a single result set? |
99,488 | <p>If I'm writing an application that wants to communicate some information through the use of color, how can I change the background and foreground colors of a given widget? I would like to know how to do this in glade if it's possible, as well as programmatically (to a computed color).</p>
<p>I want to know how to do this to a complex widget as well, for example, an <code>HBox</code> that contains a <code>VBox</code> that contains some <code>Labels</code>.</p>
<p>Ideally this would also include a solution solution that allows me to <em>tint</em> the widget's existing colors, and identify the average colors of any images in use by the theme, so that I can programmatically compensate for any color choices which might make text unreadable or otherwise clashing - but I would be happy if I could just turn a button red.</p>
| [
{
"answer_id": 100266,
"author": "Tometzky",
"author_id": 15862,
"author_profile": "https://Stackoverflow.com/users/15862",
"pm_score": 4,
"selected": true,
"text": "<p>Example program:</p>\n\n<pre><code>#include <gtk/gtk.h>\n\nstatic void on_destroy(GtkWidget* widget, gpointer dat... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13564/"
] | If I'm writing an application that wants to communicate some information through the use of color, how can I change the background and foreground colors of a given widget? I would like to know how to do this in glade if it's possible, as well as programmatically (to a computed color).
I want to know how to do this to a complex widget as well, for example, an `HBox` that contains a `VBox` that contains some `Labels`.
Ideally this would also include a solution solution that allows me to *tint* the widget's existing colors, and identify the average colors of any images in use by the theme, so that I can programmatically compensate for any color choices which might make text unreadable or otherwise clashing - but I would be happy if I could just turn a button red. | Example program:
```
#include <gtk/gtk.h>
static void on_destroy(GtkWidget* widget, gpointer data)
{
gtk_main_quit ();
}
int main (int argc, char* argv[])
{
GtkWidget* window;
GtkWidget* button;
gtk_init(&argc, &argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(G_OBJECT (window), "destroy",
G_CALLBACK (on_destroy), NULL);
button = gtk_button_new_with_label("Hello world!");
GdkColor red = {0, 0xffff, 0x0000, 0x0000};
GdkColor green = {0, 0x0000, 0xffff, 0x0000};
GdkColor blue = {0, 0x0000, 0x0000, 0xffff};
gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &red);
gtk_widget_modify_bg(button, GTK_STATE_PRELIGHT, &green);
gtk_widget_modify_bg(button, GTK_STATE_ACTIVE, &blue);
gtk_container_add(GTK_CONTAINER(window), button);
gtk_widget_show_all(window);
gtk_main();
return 0;
}
``` |
99,542 | <p>How do I correct for floating point error in the following physical simulation:</p>
<ul>
<li>Original point (x, y, z),</li>
<li>Desired point (x', y', z') after forces are applied.</li>
<li>Two triangles (A, B, C) and (B, C, D), who share edge BC</li>
</ul>
<p>I am using this method for collision detection:</p>
<pre><code>For each Triangle
If the original point is in front of the current triangle, and the desired point is behind the desired triangle:
Calculate the intersection point of the ray (original-desired) and the plane (triangle's normal).
If the intersection point is inside the triangle edges (!)
Respond to the collision.
End If
End If
Next Triangle
</code></pre>
<p>The problem I am having is that sometimes the point falls into the grey area of floating point math where it is so close to the line BC that it fails to collide with either triangle, even though technically it should always collide with one or the other since they share an edge. When this happens the point passes right between the two edge sharing triangles. I have marked one line of the code with <strong>(!)</strong> because I believe that's where I should be making a change.</p>
<p>One idea that works in very limited situations is to skip the edge testing. Effectively turning the triangles into planes. This only works when my meshes are convex hulls, but I plan to create convex shapes.</p>
<p>I am specifically using the dot product and triangle normals for all of my front-back testing.</p>
| [
{
"answer_id": 99562,
"author": "Statement",
"author_id": 2166173,
"author_profile": "https://Stackoverflow.com/users/2166173",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like you ain't including testing if it's ON the edge (you're writing \"Inside triangle edges\"). Try cha... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581/"
] | How do I correct for floating point error in the following physical simulation:
* Original point (x, y, z),
* Desired point (x', y', z') after forces are applied.
* Two triangles (A, B, C) and (B, C, D), who share edge BC
I am using this method for collision detection:
```
For each Triangle
If the original point is in front of the current triangle, and the desired point is behind the desired triangle:
Calculate the intersection point of the ray (original-desired) and the plane (triangle's normal).
If the intersection point is inside the triangle edges (!)
Respond to the collision.
End If
End If
Next Triangle
```
The problem I am having is that sometimes the point falls into the grey area of floating point math where it is so close to the line BC that it fails to collide with either triangle, even though technically it should always collide with one or the other since they share an edge. When this happens the point passes right between the two edge sharing triangles. I have marked one line of the code with **(!)** because I believe that's where I should be making a change.
One idea that works in very limited situations is to skip the edge testing. Effectively turning the triangles into planes. This only works when my meshes are convex hulls, but I plan to create convex shapes.
I am specifically using the dot product and triangle normals for all of my front-back testing. | This is an inevitable problem when shooting a single ray against some geometry with edges and vertices. It's amazing how physical simulations seem to seek out the smallest of numerical inaccuracies!
Some of the explanations and solutions proposed by other respondents will not work. In particular:
* Numerical inaccuracy really can cause a ray to "fall through the gap". The problem is that we intersect the ray with the plane ABC (getting the point P, say) before testing against line BC. Then we intersect the ray with plane BCD (getting the point Q, say) before testing against line BC. P and Q are both represented by the closest floating-point approximation; there's no reason to expect that these exactly lie on the planes that they are supposed to lie on, and so every possibility that you can have both P to the left of BC and Q to the right of BC.
* Using less-than-or-equal test won't help; it's inaccuracy in the intersection of the ray and the plane that's the trouble.
* Square roots are not the issue; you can do all of the necessary computations using dot products and floating-point division.
Here are some genuine solutions:
* For convex meshes, you can just test against all the planes and ignore the edges and vertices, as you say (thus avoiding the issue entirely).
* Don't intersect the ray with each triangle in turn. Instead, use the [scalar triple product](http://realtimecollisiondetection.net/blog/?p=69). (This method makes the exact same sequence of computations for the ray and the edge BC when considering each triangle, ensuring that any numerical inaccuracy is at least consistent between the two triangles.)
* For non-convex meshes, give the edges and vertices some width. That is, place a small sphere at each vertex in the mesh, and place a thin cylinder along each edge of the mesh. Intersect the ray with these spheres and cylinders as well as with the triangles. These additional geometric figures stop the ray passing through edges and vertices of the mesh.
Let me strongly recommend the book [Real-Time Collision Detection](http://realtimecollisiondetection.net/) by Christer Ericson. There's a discussion of this exact problem on pages 446–448, and an explanation of the scalar triple product approach to intersecting a ray with a triangle on pages 184–188. |
99,546 | <p>I read this <a href="http://smartprogrammer.blogspot.com/2006/04/15-exercises-for-learning-new.html" rel="nofollow noreferrer">article</a> and try to do the exercise in D Programming Language, but encounter a problem in the first exercise.</p>
<blockquote>
<p>(1) Display series of numbers
(1,2,3,4, 5....etc) in an infinite
loop. The program should quit if
someone hits a specific key (Say
ESCAPE key).</p>
</blockquote>
<p>Of course the infinite loop is not a big problem, but the rest is. How could I grab a key hit in D/Tango? In tango FAQ it says use C function kbhit() or get(), but as I know, these are not in C standard library, and does not exist in glibc which come with my Linux machine which I use to programming.</p>
<p>I know I can use some 3rd party library like <a href="http://www.gnu.org/software/ncurses/" rel="nofollow noreferrer">ncurses</a>, but it has same problem just like kbhit() or get(), it is not standard library in C or D and not pre-installed on Windows. What I hope is that I could done this exercise use just D/Tango and could run it on both Linux and Windows machine.</p>
<p>How could I do it?</p>
| [
{
"answer_id": 99593,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "<p>D generally has all the C stdlib available (Tango or Phobos) so answers to this question for GNU C should work in D as well.</... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242644/"
] | I read this [article](http://smartprogrammer.blogspot.com/2006/04/15-exercises-for-learning-new.html) and try to do the exercise in D Programming Language, but encounter a problem in the first exercise.
>
> (1) Display series of numbers
> (1,2,3,4, 5....etc) in an infinite
> loop. The program should quit if
> someone hits a specific key (Say
> ESCAPE key).
>
>
>
Of course the infinite loop is not a big problem, but the rest is. How could I grab a key hit in D/Tango? In tango FAQ it says use C function kbhit() or get(), but as I know, these are not in C standard library, and does not exist in glibc which come with my Linux machine which I use to programming.
I know I can use some 3rd party library like [ncurses](http://www.gnu.org/software/ncurses/), but it has same problem just like kbhit() or get(), it is not standard library in C or D and not pre-installed on Windows. What I hope is that I could done this exercise use just D/Tango and could run it on both Linux and Windows machine.
How could I do it? | Here's how you do it in the D programming language:
```
import std.c.stdio;
import std.c.linux.termios;
termios ostate; /* saved tty state */
termios nstate; /* values for editor mode */
// Open stdin in raw mode
/* Adjust output channel */
tcgetattr(1, &ostate); /* save old state */
tcgetattr(1, &nstate); /* get base of new state */
cfmakeraw(&nstate);
tcsetattr(1, TCSADRAIN, &nstate); /* set mode */
// Read characters in raw mode
c = fgetc(stdin);
// Close
tcsetattr(1, TCSADRAIN, &ostate); // return to original mode
``` |
99,552 | <p>I sometimes notice programs that crash on my computer with the error: "pure virtual function call".</p>
<p>How do these programs even compile when an object cannot be created of an abstract class?</p>
| [
{
"answer_id": 99567,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "<p>I'd guess there is a vtbl created for the abstract class for some internal reason (it might be needed for some sort of run tim... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] | I sometimes notice programs that crash on my computer with the error: "pure virtual function call".
How do these programs even compile when an object cannot be created of an abstract class? | They can result if you try to make a virtual function call from a constructor or destructor. Since you can't make a virtual function call from a constructor or destructor (the derived class object hasn't been constructed or has already been destroyed), it calls the base class version, which in the case of a pure virtual function, doesn't exist.
```
class Base
{
public:
Base() { reallyDoIt(); }
void reallyDoIt() { doIt(); } // DON'T DO THIS
virtual void doIt() = 0;
};
class Derived : public Base
{
void doIt() {}
};
int main(void)
{
Derived d; // This will cause "pure virtual function call" error
}
```
See also Raymond Chen's [2](https://devblogs.microsoft.com/oldnewthing/20040428-00/?p=39613) [articles on the subject](https://devblogs.microsoft.com/oldnewthing/20131011-00/?p=2953) |
99,560 | <p>I am working on a Rails application that needs to handle dates and times in users' time zones. We have recently migrated it to Rails 2.1 and added time zone support, but there are numerous situations in which we use Time#utc and then compare against that time. Wouldn't that be the same as comparing against the original Time object?</p>
<p>When is it appropriate to use Time#utc in Rails 2.1? When is it inappropriate?</p>
| [
{
"answer_id": 99829,
"author": "Ian Terrell",
"author_id": 9269,
"author_profile": "https://Stackoverflow.com/users/9269",
"pm_score": 0,
"selected": false,
"text": "<p>If your application has users in multiple time zones, you should always store your times in UTC (any timezone would wo... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7717/"
] | I am working on a Rails application that needs to handle dates and times in users' time zones. We have recently migrated it to Rails 2.1 and added time zone support, but there are numerous situations in which we use Time#utc and then compare against that time. Wouldn't that be the same as comparing against the original Time object?
When is it appropriate to use Time#utc in Rails 2.1? When is it inappropriate? | If you've set:
```
config.time_zone = 'UTC'
```
In your environment.rb (it's there by default), then times will automagically get converted into UTC when ActiveRecord stores them.
Then if you set Time.zone (in a before\_filter on application.rb is the usual place) to the user's Time Zone, all the times will be automagically converted into the user's timezone from the utc storage.
Just be careful with Time.now.
Also see:
<http://mad.ly/2008/04/09/rails-21-time-zone-support-an-overview/>
<http://errtheblog.com/posts/49-a-zoned-defense> - you can use the JS here to detect zones
Hope that helps. |
99,623 | <p>I'd like to be able to do some drawing to the right of the menu bar, in the nonclient area of a window. </p>
<p>Is this possible, using C++ / MFC?</p>
| [
{
"answer_id": 99629,
"author": "Andrei Belogortseff",
"author_id": 17037,
"author_profile": "https://Stackoverflow.com/users/17037",
"pm_score": 2,
"selected": false,
"text": "<p>In order to draw in the non-client area, you need to get the \"window\" DC (rather than \"client\" DC), and ... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'd like to be able to do some drawing to the right of the menu bar, in the nonclient area of a window.
Is this possible, using C++ / MFC? | Charlie hit on the answer with `WM_NCPAINT`. If you're using MFC, the code would look something like this:
```
// in the message map
ON_WM_NCPAINT()
// ...
void CMainFrame::OnNcPaint()
{
// still want the menu to be drawn, so trigger default handler first
Default();
// get menu bar bounds
MENUBARINFO menuInfo = {sizeof(MENUBARINFO)};
if ( GetMenuBarInfo(OBJID_MENU, 0, &menuInfo) )
{
CRect windowBounds;
GetWindowRect(&windowBounds);
CRect menuBounds(menuInfo.rcBar);
menuBounds.OffsetRect(-windowBounds.TopLeft());
// horrible, horrible icon-drawing code. Don't use this. Seriously.
CWindowDC dc(this);
HICON appIcon = (HICON)::LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);
::DrawIconEx(dc, menuBounds.right-18, menuBounds.top+2, appIcon, 0,0, 0, NULL, DI_NORMAL);
::DestroyIcon(appIcon);
}
}
``` |
99,683 | <p>My question is what do most developers prefer for error handling, Exceptions or Error Return Codes. Please be language(or language family) specific and why you prefer one over the other.</p>
<p>I'm asking this out of curiosity. Personally I prefer Error Return Codes since they are less explosive and don't force user code to pay the exception performance penalty if they don't want to.</p>
<p>update: thanks for all the answers! I must say that although I dislike the unpredictability of code flow with exceptions. The answer about return code (and their elder brother handles) do add lots of Noise to the code.</p>
| [
{
"answer_id": 99694,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 5,
"selected": false,
"text": "<p>I use both actually.</p>\n\n<p>I use return codes if it's a known, possible error. If it's a scenario that I know... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] | My question is what do most developers prefer for error handling, Exceptions or Error Return Codes. Please be language(or language family) specific and why you prefer one over the other.
I'm asking this out of curiosity. Personally I prefer Error Return Codes since they are less explosive and don't force user code to pay the exception performance penalty if they don't want to.
update: thanks for all the answers! I must say that although I dislike the unpredictability of code flow with exceptions. The answer about return code (and their elder brother handles) do add lots of Noise to the code. | For some languages (i.e. C++) Resources leak should not be a reason
===================================================================
C++ is based on RAII.
If you have code that could fail, return or throw (that is, most normal code), then you should have your pointer wrapped inside a smart pointer (assuming you have a *very good* reason to not have your object created on stack).
Return codes are more verbose
=============================
They are verbose, and tend to develop into something like:
```
if(doSomething())
{
if(doSomethingElse())
{
if(doSomethingElseAgain())
{
// etc.
}
else
{
// react to failure of doSomethingElseAgain
}
}
else
{
// react to failure of doSomethingElse
}
}
else
{
// react to failure of doSomething
}
```
In the end, you code is a collection of idented instructions (I saw this kind of code in production code).
This code could well be translated into:
```
try
{
doSomething() ;
doSomethingElse() ;
doSomethingElseAgain() ;
}
catch(const SomethingException & e)
{
// react to failure of doSomething
}
catch(const SomethingElseException & e)
{
// react to failure of doSomethingElse
}
catch(const SomethingElseAgainException & e)
{
// react to failure of doSomethingElseAgain
}
```
Which cleanly separate code and error processing, which **can** be a **good** thing.
Return codes are more brittle
=============================
If not some obscure warning from one compiler (see "phjr" 's comment), they can easily be ignored.
With the above examples, assume than someone forgets to handle its possible error (this happens...). The error is ignored when "returned", and will possibly explode later (i.e. a NULL pointer). The same problem won't happen with exception.
The error won't be ignored. Sometimes, you want it to not explode, though... So you must chose carefully.
Return Codes must sometimes be translated
=========================================
Let's say we have the following functions:
* doSomething, which can return an int called NOT\_FOUND\_ERROR
* doSomethingElse, which can return a bool "false" (for failed)
* doSomethingElseAgain, which can return an Error object (with both the \_\_LINE\_\_, \_\_FILE\_\_ and half the stack variables.
* doTryToDoSomethingWithAllThisMess which, well... Use the above functions, and return an error code of type...
What is the type of the return of doTryToDoSomethingWithAllThisMess if one of its called functions fail ?
Return Codes are not a universal solution
=========================================
Operators cannot return an error code. C++ constructors can't, too.
Return Codes means you can't chain expressions
==============================================
The corollary of the above point. What if I want to write:
```
CMyType o = add(a, multiply(b, c)) ;
```
I can't, because the return value is already used (and sometimes, it can't be changed). So the return value becomes the first parameter, sent as a reference... Or not.
Exception are typed
===================
You can send different classes for each kind of exception. Ressources exceptions (i.e. out of memory) should be light, but anything else could be as heavy as necessary (I like the Java Exception giving me the whole stack).
Each catch can then be specialized.
Don't ever use catch(...) without re-throwing
=============================================
Usually, you should not hide an error. If you do not re-throw, at the very least, log the error in a file, open a messagebox, whatever...
Exception are... NUKE
=====================
The problem with exception is that overusing them will produce code full of try/catches. But the problem is elsewhere: Who try/catch his/her code using STL container? Still, those containers can send an exception.
Of course, in C++, don't ever let an exception exit a destructor.
Exception are... synchronous
============================
Be sure to catch them before they bring out your thread on its knees, or propagate inside your Windows message loop.
The solution could be mixing them?
==================================
So I guess the solution is to throw when something should **not** happen. And when something can happen, then use a return code or a parameter to enable to user to react to it.
So, the only question is "what is something that should not happen?"
It depends on the contract of your function. If the function accepts a pointer, but specifies the pointer must be non-NULL, then it is ok to throw an exception when the user sends a NULL pointer (the question being, in C++, when didn't the function author use references instead of pointers, but...)
Another solution would be to show the error
===========================================
Sometimes, your problem is that you don't want errors. Using exceptions or error return codes are cool, but... You want to know about it.
In my job, we use a kind of "Assert". It will, depending on the values of a configuration file, no matter the debug/release compile options:
* log the error
* open a messagebox with a "Hey, you have a problem"
* open a messagebox with a "Hey, you have a problem, do you want to debug"
In both development and testing, this enable the user to pinpoint the problem exactly when it is detected, and not after (when some code cares about the return value, or inside a catch).
It is easy to add to legacy code. For example:
```
void doSomething(CMyObject * p, int iRandomData)
{
// etc.
}
```
leads a kind of code similar to:
```
void doSomething(CMyObject * p, int iRandomData)
{
if(iRandomData < 32)
{
MY_RAISE_ERROR("Hey, iRandomData " << iRandomData << " is lesser than 32. Aborting processing") ;
return ;
}
if(p == NULL)
{
MY_RAISE_ERROR("Hey, p is NULL !\niRandomData is equal to " << iRandomData << ". Will throw.") ;
throw std::some_exception() ;
}
if(! p.is Ok())
{
MY_RAISE_ERROR("Hey, p is NOT Ok!\np is equal to " << p->toString() << ". Will try to continue anyway") ;
}
// etc.
}
```
(I have similar macros that are active only on debug).
Note that on production, the configuration file does not exist, so the client never sees the result of this macro... But it is easy to activate it when needed.
Conclusion
==========
When you code using return codes, you're preparing yourself for failure, and hope your fortress of tests is secure enough.
When you code using exception, you know that your code can fail, and usually put counterfire catch at chosen strategic position in your code. But usually, your code is more about "what it must do" then "what I fear will happen".
But when you code at all, you must use the best tool at your disposal, and sometimes, it is "Never hide an error, and show it as soon as possible". The macro I spoke above follow this philosophy. |
99,684 | <p>The most basic task in an object oriented environment is executing a method on an object. To do this, you have to have a reference to the object on which you are invoking the method. Is the proper way to establish this reference to pass the object as a parameter to the constructor (or initializer method) of the calling object?</p>
<p>If object <code> foo </code> calls into object <code> bar</code>, is it correct to say (in pseudo-code):</p>
<pre><code>bar = new barClass()
foo = new fooClass(bar)
</code></pre>
<p>What happens if you need to pass messages back and forth? Do you need a method for registering the target object?</p>
<pre><code>foo = new fooClass()
bar = new barClass()
foo.register(bar)
bar.register(foo)
</code></pre>
<p>Is there a pattern that addresses this?</p>
| [
{
"answer_id": 99700,
"author": "scubabbl",
"author_id": 9450,
"author_profile": "https://Stackoverflow.com/users/9450",
"pm_score": 0,
"selected": false,
"text": "<p>Well, depending on the level of messaging, you could implement a messaging service. Objects listen for messages, or regis... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8092/"
] | The most basic task in an object oriented environment is executing a method on an object. To do this, you have to have a reference to the object on which you are invoking the method. Is the proper way to establish this reference to pass the object as a parameter to the constructor (or initializer method) of the calling object?
If object `foo` calls into object `bar`, is it correct to say (in pseudo-code):
```
bar = new barClass()
foo = new fooClass(bar)
```
What happens if you need to pass messages back and forth? Do you need a method for registering the target object?
```
foo = new fooClass()
bar = new barClass()
foo.register(bar)
bar.register(foo)
```
Is there a pattern that addresses this? | Generally dependency injection is the way to go. If you're just talking about two objects communicating then pass an instance of one in as a paramter to the other, as in your first example. Passing in the constructor ensure the reference is always valid. Otherwise you'd have to test to ensure register had been called. Also you'd need to make sure calling register more than once wouldn't have adverse effects.
What if you want a controlling object, to which other objects register for events. It would then be suitable to use a Register method ( which may add to a delegate).
See [Observer Pattern](http://www.dofactory.com/Patterns/PatternObserver.aspx) |
99,732 | <p>Using reflection in .Net, what is the differnce between:</p>
<pre><code> if (foo.IsAssignableFrom(typeof(IBar)))
</code></pre>
<p>And</p>
<pre><code> if (foo.GetInterface(typeof(IBar).FullName) != null)
</code></pre>
<p>Which is more appropriate, why?<br></p>
<p>When could one or the other fail?</p>
| [
{
"answer_id": 99744,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": true,
"text": "<p>If you just want to see if a type implements a given interface, either is fine, though GetInterface() is probably faste... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14484/"
] | Using reflection in .Net, what is the differnce between:
```
if (foo.IsAssignableFrom(typeof(IBar)))
```
And
```
if (foo.GetInterface(typeof(IBar).FullName) != null)
```
Which is more appropriate, why?
When could one or the other fail? | If you just want to see if a type implements a given interface, either is fine, though GetInterface() is probably faster since IsAssignableFrom() does more internal checks than GetInterface(). It'll probably even faster to check the results of Type.GetInterfaces() which returns the same internal list that both of the other methods use anyway. |
99,781 | <p>I have a client that is asking me to give them a listing of every file and folder in the source code (and then a brief explanation of the source tree). Is there an easy way to create some sort of decently formatted list like this from a subversion repository?</p>
| [
{
"answer_id": 99788,
"author": "Subimage",
"author_id": 10596,
"author_profile": "https://Stackoverflow.com/users/10596",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming it's available via HTTP - why not just give them a read-only login, and point them at the web address?</p>\n"
... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1486/"
] | I have a client that is asking me to give them a listing of every file and folder in the source code (and then a brief explanation of the source tree). Is there an easy way to create some sort of decently formatted list like this from a subversion repository? | You'll want the list command. Assuming you're using the command line client
```
svn list -R http://example.com/path/to/repos
```
This will give you a full recursive list of everything that's in the repository. Redirect it to a text file
```
svn list -R http://example.com/path/to/repos > file.txt
```
and then format to your heart's content. |
99,796 | <p>I have recently learned about binary space partitioning trees and their application to 3d graphics and collision detection. I have also briefly perused material relating to quadtrees and octrees. When would you use quadtrees over bsp trees, or vice versa? Are they interchangeable? I would be satisfied if I had enough information to fill out a table like this:</p>
<pre><code> | BSP | Quadtree | Octree
------------+----------------+-------
Situation A | X | |
Situation B | | X |
Situation C | | | X
</code></pre>
<p>What are A, B, and C?</p>
| [
{
"answer_id": 99817,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 1,
"selected": false,
"text": "<p>I don't have much experience with BSPs, but I can say that you should go with octrees over quadtrees when you th... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581/"
] | I have recently learned about binary space partitioning trees and their application to 3d graphics and collision detection. I have also briefly perused material relating to quadtrees and octrees. When would you use quadtrees over bsp trees, or vice versa? Are they interchangeable? I would be satisfied if I had enough information to fill out a table like this:
```
| BSP | Quadtree | Octree
------------+----------------+-------
Situation A | X | |
Situation B | | X |
Situation C | | | X
```
What are A, B, and C? | There is no clear answer to your question. It depends entirely how your data is organized.
Something to keep in mind:
Quadtrees work best for data that is mostly two dimensional like map-rendering in navigation systems. In this case it's faster than octrees because it adapts better to the geometry and keeps the node-structures small.
Octrees and BVHs (Bounding Volume Hierarchies) benefit if the data is three dimensional. It also works very well if your geometric entities are clustered in 3D space. (see [Octree vs BVH](https://web.archive.org/web/20180111010801/http://www.thomasdiewald.com/blog/?p=1488)) (archived from ~~[original](http://thomasdiewald.com/blog/?p=1488)~~)
The benefit of Oc- and Quadtrees is that you can stop generating trees anytime you wish. If you want to render graphics using a graphic accelerator it allows you to just generate trees on an object level and send each object in a single draw-call to the graphics API. This performs **much** better than sending individual triangles (something you have to do if you use BSP-Trees to the full extent).
BSP-Trees are a special case really. They work very very well in 2D and 3D, but generating good BSP-Trees is an art form on its own. BSP-Trees have the drawback that you may have to split your geometry into smaller pieces. This can increase the overall polygon-count of your data-set. They are nice for rendering, but they are much better for collision detection and ray-tracing.
A nice property of the BSP-trees is that they decompose a polygon-soup into a structure that can be perfectly rendered back to front (and vice versa) from any camera position without doing an actual sort. The order from each viewpoint is part of the data-structure and done during BSP-Tree compilation.
That, by the way, is the reason why they were so popular 10 years ago. Quake used them because it allowed the graphic engine / software rasterizer to not use a costly z-buffer.
All the trees mentioned are just families of trees. There are loose octrees, kd-trees hybrid-trees and lots of other related structures as well. |
99,827 | <p>I'm interested in tracing database calls made by LINQ to SQL back to the .NET code that generated the call. For instance, a DBA might have a concern that a particular cached execution plan is doing poorly. If for example a DBA were to tell a developer to address the following code...</p>
<pre><code>exec sp_executesql N'SELECT [t0].[CustomerID]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[ContactName] LIKE @p0
ORDER BY [t0].[CompanyName]',
'N'@p0 nvarchar(2)',@p0=N'c%'
</code></pre>
<p>...it's not immediately obvious which LINQ statement produced the call. Sure you could search through the "Customers" class in the auto-generated data context, but that'd just be a start. With a large application this could quickly become unmanageable.</p>
<p>Is there a way to attach an ID or label to SQL code generated and executed by LINQ to SQL? Thinking out loud, here's an extension function called "TagWith" that illustrates conceptually what I'm interested in doing.</p>
<pre><code>var customers = from c in context.Customers
where c.CompanyName.StartsWith("c")
orderby c.CompanyName
select c.CustomerID;
foreach (var CustomerID in customers.TagWith("CustomerList4"))
{
Console.WriteLine(CustomerID);
}
</code></pre>
<p>If the "CustomerList4" ID/label ends up in the automatically-generated SQL, I'd be set. Thanks.</p>
| [
{
"answer_id": 99839,
"author": "ethyreal",
"author_id": 18159,
"author_profile": "https://Stackoverflow.com/users/18159",
"pm_score": 1,
"selected": false,
"text": "<p>in the <a href=\"http://cftextmate.com/\" rel=\"nofollow noreferrer\">cftextmate</a> bundle you can type any cfml tag w... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360388/"
] | I'm interested in tracing database calls made by LINQ to SQL back to the .NET code that generated the call. For instance, a DBA might have a concern that a particular cached execution plan is doing poorly. If for example a DBA were to tell a developer to address the following code...
```
exec sp_executesql N'SELECT [t0].[CustomerID]
FROM [dbo].[Customers] AS [t0]
WHERE [t0].[ContactName] LIKE @p0
ORDER BY [t0].[CompanyName]',
'N'@p0 nvarchar(2)',@p0=N'c%'
```
...it's not immediately obvious which LINQ statement produced the call. Sure you could search through the "Customers" class in the auto-generated data context, but that'd just be a start. With a large application this could quickly become unmanageable.
Is there a way to attach an ID or label to SQL code generated and executed by LINQ to SQL? Thinking out loud, here's an extension function called "TagWith" that illustrates conceptually what I'm interested in doing.
```
var customers = from c in context.Customers
where c.CompanyName.StartsWith("c")
orderby c.CompanyName
select c.CustomerID;
foreach (var CustomerID in customers.TagWith("CustomerList4"))
{
Console.WriteLine(CustomerID);
}
```
If the "CustomerList4" ID/label ends up in the automatically-generated SQL, I'd be set. Thanks. | These are my favorite shortcuts:
* `cmd`+`t` Start typing name of a file to open it
* `ctrl`+`w` Select word
* `cmd`+`r` Run the ruby or php-script that is open
* `cmd`+`opt`+`m` Define a new macro
* `cmd`+`shift`+`m` Run the macro
* `opt` Switch to vertical selection mode
* `cmd`+`opt`+`a` Edit ends of selected lines |
99,866 | <p>I'm at the beginning/middle of a project that we chose to implement using GWT. Has anyone encountered any major pitfalls in using GWT (and GWT-EXT) that were unable to be overcome? How about from a performance perspective?</p>
<p>A couple things that we've seen/heard already include:</p>
<ul>
<li>Google not being able to index content</li>
<li>CSS and styling in general seems to be a bit flaky</li>
</ul>
<p>Looking for any additional feedback on these items as well. Thanks!</p>
| [
{
"answer_id": 99920,
"author": "Michael Neale",
"author_id": 699,
"author_profile": "https://Stackoverflow.com/users/699",
"pm_score": 3,
"selected": false,
"text": "<p>No major pitfalls that I haven't been able to overcome easily. Use hosted mode heavily. \nAs you are using GWT-ext you... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18402/"
] | I'm at the beginning/middle of a project that we chose to implement using GWT. Has anyone encountered any major pitfalls in using GWT (and GWT-EXT) that were unable to be overcome? How about from a performance perspective?
A couple things that we've seen/heard already include:
* Google not being able to index content
* CSS and styling in general seems to be a bit flaky
Looking for any additional feedback on these items as well. Thanks! | I'll start by saying that I'm a massive GWT fan, but yes there are many pitfalls, but most if not all we were able to overcome:
**Problem:** Long compile times, as your project grows so does the amount of time it takes to compile it. I've heard of reports of 20 minute compiles, but mine are on average about 1 minute.
**Solution:** Split your code into separate modules, and tell ant to only build it when it's changed. Also while developing, you can massively speed up compile times by only building for one browser. You can do this by putting this into your .gwt.xml file:
```
<set-property name="user.agent" value="gecko1_8" />
```
Where gecko1\_8 is Firefox 2+, ie6 is IE, etc.
---
**Problem:** Hosted mode is very slow (on OS X at least) and does not come close to matching the 'live' changes you get when you edit things like JSPs or Rails pages and hit refresh in your browser.
**Solution:** You can give the hosted mode more memory (I generally got for 512M) but it's still slow, I've found once you get good enough with GWT you stop using this. You make a large chunk of changes, then compile for just one browser (generally 20s worth of compile) and then just hit refresh in your browser.
Update: With GWT 2.0+ this is no longer an issue, because you use the new 'Development Mode'. It basically means you can run code directly in your browser of choice, so no loss of speed, plus you can firebug/inspect it, etc.
<http://code.google.com/p/google-web-toolkit/wiki/UsingOOPHM>
---
**Problem:** GWT code is java, and has a different mentality to laying out a HTML page, which makes taking a HTML design and turning it into GWT harder
**Solution:** Again you get used to this, but unfortunately converting a HTML design to a GWT design is always going to be slower than doing something like converting a HTML design to a JSP page.
---
**Problem:** GWT takes a bit of getting your head around, and is not yet mainstream. Meaning that most developers that join your team or maintain your code will have to learn it from scratch
**Solution:** It remains to be seen if GWT will take off, but if you're a company in control of who you hire, then you can always choose people that either know GWT or want to learn it.
---
**Problem:** GWT is a sledgehammer compared to something like jquery or just plain javascript. It takes a lot more setup to get it happening than just including a JS file.
**Solution:** Use libraries like jquery for smaller, simple tasks that are suited to those. Use GWT when you want to build something truly complex in AJAX, or where you need to pass your data back and forth via the RPC mechanism.
---
**Problem:** Sometimes in order to populate your GWT page, you need to make a server call when the page first loads. It can be annoying for the user to sit there and watch a loading symbol while you fetch the data you need.
**Solution:** In the case of a JSP page, your page was already rendered by the server before becoming HTML, so you can actually make all your GWT calls then, and pre-load them onto the page, for an instant load. See here for details:
[Speed up Page Loading by pre-serializing your GWT calls](http://wiki.shiftyjelly.com/index.php/GWT#Speed_up_Page_Loading.2C_by_pre-serializing_your_GWT_calls)
---
I've never had any problems CSS styling my widgets, out of the box, custom or otherwise, so I don't know what you mean by that being a pitfall?
As for performance, I've always found that once compiled GWT code is fast, and AJAX calls are nearly always smaller than doing a whole page refresh, but that's not really unique to GWT, though the native RPC packets that you get if you use a JAVA back end are pretty compact. |
99,876 | <p>I just wanted some opinions from people that have run Selenium (<a href="http://selenium.openqa.org" rel="nofollow noreferrer">http://selenium.openqa.org</a>) I have had a lot of experience with WaTiN and even wrote a recording suite for it. I had it producing some well-structured code but being only maintained by me it seems my company all but abandoned it. </p>
<p>If you have run selenium have you had a lot of success? </p>
<p>I will be using .NET 3.5, does Selenium work well with it? </p>
<p>Is the code produced clean or simply a list of all the interaction? (<a href="http://blogs.conchango.com/richardgriffin/archive/2006/11/14/Testing-Design-Pattern-for-using-WATiR_2F00_N.aspx" rel="nofollow noreferrer">http://blogs.conchango.com/richardgriffin/archive/2006/11/14/Testing-Design-Pattern-for-using-WATiR_2F00_N.aspx</a>) </p>
<p>How well does the distributed testing suite fair?</p>
<p>Any other gripes or compliments on the system would be greatly appreciated!</p>
| [
{
"answer_id": 99965,
"author": "marcospereira",
"author_id": 4600,
"author_profile": "https://Stackoverflow.com/users/4600",
"pm_score": 6,
"selected": true,
"text": "<p>If you are using <a href=\"http://selenium-ide.openqa.org/\" rel=\"nofollow noreferrer\">Selenium IDE</a> to generate... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13688/"
] | I just wanted some opinions from people that have run Selenium (<http://selenium.openqa.org>) I have had a lot of experience with WaTiN and even wrote a recording suite for it. I had it producing some well-structured code but being only maintained by me it seems my company all but abandoned it.
If you have run selenium have you had a lot of success?
I will be using .NET 3.5, does Selenium work well with it?
Is the code produced clean or simply a list of all the interaction? (<http://blogs.conchango.com/richardgriffin/archive/2006/11/14/Testing-Design-Pattern-for-using-WATiR_2F00_N.aspx>)
How well does the distributed testing suite fair?
Any other gripes or compliments on the system would be greatly appreciated! | If you are using [Selenium IDE](http://selenium-ide.openqa.org/) to generate code, then you just get a list of every action that selenium will execute. To me, Selenium IDE is a good way to start or do a fast "try and see" test. But, when you think about maintainability and more readable code, you must write your own code.
A good way to achieve good selenium code is to use the [Page Object Pattern](http://code.google.com/p/webdriver/wiki/PageObjects) in a way that the code represents your navigation flow. Here is a good example that I see in [Coding Dojo Floripa](http://dojofloripa.wordpress.com/2008/04/20/como-usar-tdd-e-page-objects-para-construir-interfaces-web/) (from Brazil):
```
public class GoogleTest {
private Selenium selenium;
@Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*firefox",
"http://www.google.com/webhp?hl=en");
selenium.start();
}
@Test
public void codingDojoShouldBeInFirstPageOfResults() {
GoogleHomePage home = new GoogleHomePage(selenium);
GoogleSearchResults searchResults = home.searchFor("coding dojo");
String firstEntry = searchResults.getResult(0);
assertEquals("Coding Dojo Wiki: FrontPage", firstEntry);
}
@After
public void tearDown() throws Exception {
selenium.stop();
}
}
public class GoogleHomePage {
private final Selenium selenium;
public GoogleHomePage(Selenium selenium) {
this.selenium = selenium;
this.selenium.open("http://www.google.com/webhp?hl=en");
if (!"Google".equals(selenium.getTitle())) {
throw new IllegalStateException("Not the Google Home Page");
}
}
public GoogleSearchResults searchFor(String string) {
selenium.type("q", string);
selenium.click("btnG");
selenium.waitForPageToLoad("5000");
return new GoogleSearchResults(string, selenium);
}
}
public class GoogleSearchResults {
private final Selenium selenium;
public GoogleSearchResults(String string, Selenium selenium) {
this.selenium = selenium;
if (!(string + " - Google Search").equals(selenium.getTitle())) {
throw new IllegalStateException(
"This is not the Google Results Page");
}
}
public String getResult(int i) {
String nameXPath = "xpath=id('res')/div[1]/div[" + (i + 1) + "]/h2/a";
return selenium.getText(nameXPath);
}
}
```
Hope that Helps |
99,880 | <p>I need to write a function that generates an id that is unique for a given machine running a Windows OS.</p>
<p>Currently, I'm using WMI to query various hardware parameters and concatenate them together and hash them to derive the unique id. My question is, what are the suggested parameters I should use?
Currently, I'm using a combination of bios\cpu\disk data to generate the unique id. And am using the first result if multiple results are there for each metric.</p>
<p>However, I ran into an issue where a machine that dual boots into 2 different Windows OS generates different site codes on each OS, which should ideally not happen.</p>
<p>For reference, these are the metrics I'm currently using:</p>
<pre><code>Win32_Processor:UniqueID,ProcessorID,Name,Manufacturer,MaxClockSpeed
Win32_BIOS:Manufacturer
Win32_BIOS:SMBIOSBIOSVersion,IdentificationCode,SerialNumber,ReleaseDate,Version
Win32_DiskDrive:Model, Manufacturer, Signature, TotalHeads
Win32_BaseBoard:Model, Manufacturer, Name, SerialNumber
Win32_VideoController:DriverVersion, Name
</code></pre>
| [
{
"answer_id": 99889,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 1,
"selected": false,
"text": "<p>You should look into using the MAC address on the network card (if it exists). Those are usually unique but can be fabri... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/618/"
] | I need to write a function that generates an id that is unique for a given machine running a Windows OS.
Currently, I'm using WMI to query various hardware parameters and concatenate them together and hash them to derive the unique id. My question is, what are the suggested parameters I should use?
Currently, I'm using a combination of bios\cpu\disk data to generate the unique id. And am using the first result if multiple results are there for each metric.
However, I ran into an issue where a machine that dual boots into 2 different Windows OS generates different site codes on each OS, which should ideally not happen.
For reference, these are the metrics I'm currently using:
```
Win32_Processor:UniqueID,ProcessorID,Name,Manufacturer,MaxClockSpeed
Win32_BIOS:Manufacturer
Win32_BIOS:SMBIOSBIOSVersion,IdentificationCode,SerialNumber,ReleaseDate,Version
Win32_DiskDrive:Model, Manufacturer, Signature, TotalHeads
Win32_BaseBoard:Model, Manufacturer, Name, SerialNumber
Win32_VideoController:DriverVersion, Name
``` | Parse the [SMBIOS](http://www.dmtf.org/standards/smbios/) yourself and hash it to an arbitrary length. See the [PDF specification](http://www.dmtf.org/standards/published_documents/DSP0134_2.6.0.pdf) for all SMBIOS structures available.
To query the SMBIOS info from Windows you could use [`EnumSystemFirmwareEntries`](http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/enumsystemfirmwaretables.asp), [`EnumSystemFirmwareTables`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724259(v=vs.85).aspx) and [`GetSystemFirmwareTable`](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724379%28v=vs.85%29.aspx).
IIRC, the "unique id" from the CPUID instruction is deprecated from P3 and newer. |
99,912 | <p>I am trying to use directory services to add a directory entry to an openldap server. The examples I have seen look pretty simple, but I keep getting the error "There is an naming violation". What does this message mean? How do I resolve it?</p>
<p>I have included the code, ldif file used to create the person container.</p>
<pre><code>Public Function Ldap_Store_Manual_Registration(ByVal userName As String, ByVal firstMiddleName As String, ByVal lastName As String, ByVal password As String)
Dim entry As DirectoryEntry = OpenLDAPconnection() 'OpenLDAPconnection() is DirectoryEntry(domainName, userId, password, AuthenticationTypes.SecureSocketsLayer) )
Dim newUser As DirectoryEntry
newUser = entry.Children.Add("ou=alumni", "organizationalUnit") 'also try with newUser = entry.Children.Add("ou=alumni,o=xxxx", "organizationalUnit") , also not working
SetADProperty(newUser, "objectClass", "organizationalPerson")
SetADProperty(newUser, "objectClass", "person")
SetADProperty(newUser, "cn", userName)
SetADProperty(newUser, "sn", userName)
newUser.CommitChanges()
End Function
Public Shared Sub SetADProperty(ByVal de As DirectoryEntry, _
ByVal pName As String, ByVal pValue As String)
'First make sure the property value isnt "nothing"
If Not pValue Is Nothing Then
'Check to see if the DirectoryEntry contains this property already
If de.Properties.Contains(pName) Then 'The DE contains this property
'Update the properties value
de.Properties(pName)(0) = pValue
Else 'Property doesnt exist
'Add the property and set it's value
de.Properties(pName).Add(pValue)
End If
End If
End Sub
</code></pre>
<p>The ldif file:</p>
<pre><code>version: 1
dn: cn=test3,ou=alumni,o=unimelb
objectClass: organizationalPerson
objectClass: person
objectClass: top
cn: test3
sn: test3
</code></pre>
| [
{
"answer_id": 104942,
"author": "Michael",
"author_id": 13379,
"author_profile": "https://Stackoverflow.com/users/13379",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you need to include this?</p>\n\n<pre><code>SetADProperty(newUser, \"objectClass\", \"top\")\n</code></pre>\n\n<p... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am trying to use directory services to add a directory entry to an openldap server. The examples I have seen look pretty simple, but I keep getting the error "There is an naming violation". What does this message mean? How do I resolve it?
I have included the code, ldif file used to create the person container.
```
Public Function Ldap_Store_Manual_Registration(ByVal userName As String, ByVal firstMiddleName As String, ByVal lastName As String, ByVal password As String)
Dim entry As DirectoryEntry = OpenLDAPconnection() 'OpenLDAPconnection() is DirectoryEntry(domainName, userId, password, AuthenticationTypes.SecureSocketsLayer) )
Dim newUser As DirectoryEntry
newUser = entry.Children.Add("ou=alumni", "organizationalUnit") 'also try with newUser = entry.Children.Add("ou=alumni,o=xxxx", "organizationalUnit") , also not working
SetADProperty(newUser, "objectClass", "organizationalPerson")
SetADProperty(newUser, "objectClass", "person")
SetADProperty(newUser, "cn", userName)
SetADProperty(newUser, "sn", userName)
newUser.CommitChanges()
End Function
Public Shared Sub SetADProperty(ByVal de As DirectoryEntry, _
ByVal pName As String, ByVal pValue As String)
'First make sure the property value isnt "nothing"
If Not pValue Is Nothing Then
'Check to see if the DirectoryEntry contains this property already
If de.Properties.Contains(pName) Then 'The DE contains this property
'Update the properties value
de.Properties(pName)(0) = pValue
Else 'Property doesnt exist
'Add the property and set it's value
de.Properties(pName).Add(pValue)
End If
End If
End Sub
```
The ldif file:
```
version: 1
dn: cn=test3,ou=alumni,o=unimelb
objectClass: organizationalPerson
objectClass: person
objectClass: top
cn: test3
sn: test3
``` | Maybe you need to include this?
```
SetADProperty(newUser, "objectClass", "top")
```
Also, check what the required fields for `organizationalPerson` and `person` are...you might be missing one. |
99,917 | <p>So I was reading these Asp.Net <a href="http://www.hanselman.com/blog/ASPNETInterviewQuestions.aspx" rel="nofollow noreferrer">interview questions</a> at Scott Hanselman's blog and I came across this question. Can anyone shed some light of what he's talking about.</p>
| [
{
"answer_id": 100102,
"author": "WebDude",
"author_id": 15360,
"author_profile": "https://Stackoverflow.com/users/15360",
"pm_score": 0,
"selected": false,
"text": "<p>I think what he's asking here is how you wire up javascript functions to work hand in hand with your ASP.NET postback f... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688440/"
] | So I was reading these Asp.Net [interview questions](http://www.hanselman.com/blog/ASPNETInterviewQuestions.aspx) at Scott Hanselman's blog and I came across this question. Can anyone shed some light of what he's talking about. | ```
<asp:LinkButton ID="lbEdit" CssClass="button"
OnClientClick="javascript:alert('do something')"
onclick="OnEdit" runat="server">Edit</asp:LinkButton>
```
The `OnClientClick` attribute means you can add some JavaScript without losing PostBack functionality would be my answer in the interview. |
99,927 | <p>Can someone provide an explanation of variable scope in JS as it applies to objects, functions and closures? </p>
| [
{
"answer_id": 99949,
"author": "moltenform",
"author_id": 18506,
"author_profile": "https://Stackoverflow.com/users/18506",
"pm_score": 2,
"selected": false,
"text": "<p>Variables not declared with var are global in scope. \nFunctions introduce a scope, but note that if blocks and other... | 2008/09/19 | [
"https://Stackoverflow.com/questions/99927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56663/"
] | Can someone provide an explanation of variable scope in JS as it applies to objects, functions and closures? | ### Global variables
Every variable in Javascript is a named attribute of an object. For example:-
```
var x = 1;
```
x is added to the global object. The global object is provided by the script context and may already have a set of attributes. For example in a browser the global object is window. An equivalent to the above line in a browser would be:-
```
window.x = 1;
```
### Local variables
Now what if we change this to:-
```
function fn()
{
var x = 1;
}
```
When `fn` is called a new object is created called the *execution context* also referred to as the *scope* (I use these terms interchangeably). `x` is added as an attribute to this scope object. Hence each call to `fn` will get its own instance of a scope object and therefore its own instance of the x attribute attached to that scope object.
### Closure
Now lets take this further:-
```
function fnSequence()
{
var x = 1;
return function() { return x++; }
}
var fn1 = fnSequence();
var fn2 = fnSequence();
WScript.Echo(fn1())
WScript.Echo(fn2())
WScript.Echo(fn1())
WScript.Echo(fn2())
WScript.Echo(fn1())
WScript.Echo(fn1())
WScript.Echo(fn2())
WScript.Echo(fn2())
```
**Note:** Replace `WScript.Echo` with whatever writes to stdout in your context.
The sequence you should get is :-
1 1 2 2 3 4 3 4
So what has happened here? We have `fnSequence` which initialises a variable `x` to 1 and returns an anonymous function which will return the value of `x` and then increment it.
When this function is first executed a scope object is created and an attribute `x` is added to that scope object with the value of 1. Also created in the same execution object is an anonymous function. Each function object will have a scope attribute which points to the execution context in which it is created. This creates what is know as a *scope chain* which we will come to later. A reference to this function is returned by `fnSequence` and stored in `fn1`.
Note that `fn1` is now pointing at the anonymous function and that the anonymous function has a scope attribute pointing at a scope object that still has an `x` attribute attached. This is known as `closure` where the contents of an execution context is still reachable after the function it was created for has completed execution.
Now this same sequence happens when assigning to `fn2`. `fn2` will be pointing at a different anonymous function that was created in a different execution context that was create when `fnSequence` was called this second time.
### Scope Chain
What happens when the function held by `fn1` is executed the first time? A new execution context is created for the execution of the anonymous function. A return value is to be found from the identifier `x`. The function's scope object is inspected for an `x` attribute but none is found. This is where the *scope chain* comes in. Having failed to find `x` in the current execution context JavaScript takes the object held by the function's scope attribute and looks for `x` there. It finds it since the functions scope was created inside an execution of `fnSequence`, retrieves its value and increments it. Hence 1 is output and the `x` in this scope is incremented to 2.
Now when `fn2` is executed it is ultimately attached to a different execution context whose `x` attribute is still 1. Hence executing `fn2` also results in 1.
As you can see `fn1` and `fn2` each generate their own independent sequence of numbers. |
100,003 | <p>What are metaclasses? What are they used for?</p>
| [
{
"answer_id": 100037,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 9,
"selected": false,
"text": "<p><em>Note, this answer is for Python 2.x as it was written in 2008, metaclasses are slightly different in 3.x.</em></p>\n\... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] | What are metaclasses? What are they used for? | A metaclass is the class of a class. A class defines how an instance of the class (i.e. an object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass.
While in Python you can use arbitrary callables for metaclasses (like [Jerub](https://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python/100037#100037) shows), the better approach is to make it an actual class itself. `type` is the usual metaclass in Python. `type` is itself a class, and it is its own type. You won't be able to recreate something like `type` purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass `type`.
A metaclass is most commonly used as a class-factory. When you create an object by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass. Combined with the normal `__init__` and `__new__` methods, metaclasses therefore allow you to do 'extra things' when creating a class, like registering the new class with some registry or replace the class with something else entirely.
When the `class` statement is executed, Python first executes the body of the `class` statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be. The metaclass is determined by looking at the baseclasses of the class-to-be (metaclasses are inherited), at the `__metaclass__` attribute of the class-to-be (if any) or the `__metaclass__` global variable. The metaclass is then called with the name, bases and attributes of the class to instantiate it.
However, metaclasses actually define the *type* of a class, not just a factory for it, so you can do much more with them. You can, for instance, define normal methods on the metaclass. These metaclass-methods are like classmethods in that they can be called on the class without an instance, but they are also not like classmethods in that they cannot be called on an instance of the class. `type.__subclasses__()` is an example of a method on the `type` metaclass. You can also define the normal 'magic' methods, like `__add__`, `__iter__` and `__getattr__`, to implement or change how the class behaves.
Here's an aggregated example of the bits and pieces:
```
def make_hook(f):
"""Decorator to turn 'foo' method into '__foo__'"""
f.is_hook = 1
return f
class MyType(type):
def __new__(mcls, name, bases, attrs):
if name.startswith('None'):
return None
# Go over attributes and see if they should be renamed.
newattrs = {}
for attrname, attrvalue in attrs.iteritems():
if getattr(attrvalue, 'is_hook', 0):
newattrs['__%s__' % attrname] = attrvalue
else:
newattrs[attrname] = attrvalue
return super(MyType, mcls).__new__(mcls, name, bases, newattrs)
def __init__(self, name, bases, attrs):
super(MyType, self).__init__(name, bases, attrs)
# classregistry.register(self, self.interfaces)
print "Would register class %s now." % self
def __add__(self, other):
class AutoClass(self, other):
pass
return AutoClass
# Alternatively, to autogenerate the classname as well as the class:
# return type(self.__name__ + other.__name__, (self, other), {})
def unregister(self):
# classregistry.unregister(self)
print "Would unregister class %s now." % self
class MyObject:
__metaclass__ = MyType
class NoneSample(MyObject):
pass
# Will print "NoneType None"
print type(NoneSample), repr(NoneSample)
class Example(MyObject):
def __init__(self, value):
self.value = value
@make_hook
def add(self, other):
return self.__class__(self.value + other.value)
# Will unregister the class
Example.unregister()
inst = Example(10)
# Will fail with an AttributeError
#inst.unregister()
print inst + inst
class Sibling(MyObject):
pass
ExampleSibling = Example + Sibling
# ExampleSibling is now a subclass of both Example and Sibling (with no
# content of its own) although it will believe it's called 'AutoClass'
print ExampleSibling
print ExampleSibling.__mro__
``` |
100,007 | <p>When logging with Log4Net it's very easy to put class that called the log into the log file. I've found in the past that this makes it very easy to trace through the code and see the flow through the classes. In Log4Net I use the %logger property in the conversion pattern like so: </p>
<pre><code><conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</code></pre>
<p>And this gives me the output I want: </p>
<p><code>2008-09-19 15:40:26,906 [3132] ERROR <b>Log4NetTechDemo.Tester</b> [(null)] - Failed method</code></p>
<p>You can see from the output that the class that has called the log is Log4NetTechDemo.Tester, so I can trace the error back to that class quite easily.</p>
<p>In the Logging Applicaton Block I cannot figure out how to do this with a simple log call. Does anyone know how it can be done? If so, an example or steps to do so would be very helpful.</p>
| [
{
"answer_id": 100075,
"author": "Tom Carr",
"author_id": 14954,
"author_profile": "https://Stackoverflow.com/users/14954",
"pm_score": 1,
"selected": false,
"text": "<p>We havn't found an easy way without hitting the StackTrace. If it's an exception, we just grab from that:</p>\n\n<pre... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11908/"
] | When logging with Log4Net it's very easy to put class that called the log into the log file. I've found in the past that this makes it very easy to trace through the code and see the flow through the classes. In Log4Net I use the %logger property in the conversion pattern like so:
```
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
```
And this gives me the output I want:
`2008-09-19 15:40:26,906 [3132] ERROR <b>Log4NetTechDemo.Tester</b> [(null)] - Failed method`
You can see from the output that the class that has called the log is Log4NetTechDemo.Tester, so I can trace the error back to that class quite easily.
In the Logging Applicaton Block I cannot figure out how to do this with a simple log call. Does anyone know how it can be done? If so, an example or steps to do so would be very helpful. | Add the calling method to the LogEntry's ExtendedProperties dictionary; assuming you haven't removed the ExtendedProperties tokens from the formatter template, of course.
Put something like this in a logging wrapper:
```
public void LogSomething(string msg)
{
LogEntry le = new LogEntry { Message = msg };
le.ExtendedProperties.Add("Called from", new StackFrame(1).GetMethod().ReflectedType);
Logger.Write(le);
}
```
Calling this produces something like this at the end of the log:
```
Extended Properties: Called from - LAB_Demo.Tester
``` |
100,045 | <p>What is a good regular expression that can validate a text string to make sure it is a valid Windows filename? (AKA not have <code>\/:*?"<>|</code> characters).</p>
<p>I'd like to use it like the following:</p>
<pre><code>// Return true if string is invalid.
if (Regex.IsMatch(szFileName, "<your regex string>"))
{
// Tell user to reformat their filename.
}
</code></pre>
| [
{
"answer_id": 100057,
"author": "Drejc",
"author_id": 6482,
"author_profile": "https://Stackoverflow.com/users/6482",
"pm_score": 0,
"selected": false,
"text": "<p>Why not using the System.IO.FileInfo class, together with the DirectoryInfo class you have a set of usefull methods. </p>\n... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13115/"
] | What is a good regular expression that can validate a text string to make sure it is a valid Windows filename? (AKA not have `\/:*?"<>|` characters).
I'd like to use it like the following:
```
// Return true if string is invalid.
if (Regex.IsMatch(szFileName, "<your regex string>"))
{
// Tell user to reformat their filename.
}
``` | As answered already, GetInvalidFileNameChars should do it for you, and you don't even need the overhead of regular expressions:
```
if (proposedFilename.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)
{
MessageBox.Show("The filename is invalid");
return;
}
``` |
100,048 | <p>I have two unsorted lists and I need to produce another list which is sorted and where all the elements are unique.</p>
<p>The elements can occur multiple times in both lists and they are originally unsorted.</p>
<p>My function looks like this:</p>
<pre><code>(defun merge-lists (list-a list-b sort-fn)
"Merges two lists of (x, y) coordinates sorting them and removing dupes"
(let ((prev nil))
(remove-if
(lambda (point)
(let ((ret-val (equal point prev)))
(setf prev point)
ret-val))
(sort
(merge 'list list-a list-b sort-fn) ;'
sort-fn))))
</code></pre>
<p>Is there a better way to achieve the same?</p>
<p>Sample call:</p>
<pre><code>[CL]> (merge-lists '(9 8 4 8 9 7 2) '(1 7 3 9 2 6) #'>)
==> (9 8 7 6 4 3 2 1)
</code></pre>
| [
{
"answer_id": 100077,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 1,
"selected": false,
"text": "<p>I think I would first sort the two lists separately and then merge them with a function that also skips over duplicates.... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7780/"
] | I have two unsorted lists and I need to produce another list which is sorted and where all the elements are unique.
The elements can occur multiple times in both lists and they are originally unsorted.
My function looks like this:
```
(defun merge-lists (list-a list-b sort-fn)
"Merges two lists of (x, y) coordinates sorting them and removing dupes"
(let ((prev nil))
(remove-if
(lambda (point)
(let ((ret-val (equal point prev)))
(setf prev point)
ret-val))
(sort
(merge 'list list-a list-b sort-fn) ;'
sort-fn))))
```
Is there a better way to achieve the same?
Sample call:
```
[CL]> (merge-lists '(9 8 4 8 9 7 2) '(1 7 3 9 2 6) #'>)
==> (9 8 7 6 4 3 2 1)
``` | Our neighbourhood friendly Lisp guru pointed out the [remove-duplicates function](http://www.lispworks.com/documentation/HyperSpec/Body/f_rm_dup.htm).
He also provided the following snippet:
```
(defun merge-lists (list-a list-b sort-fn test-fn)
(sort (remove-duplicates (append list-a list-b) :test test-fn) sort-fn))
``` |
100,053 | <p>I posted a <a href="https://stackoverflow.com/questions/81306/wcf-faults-exceptions-versus-messages">question</a> about using Messages versus Fault Exceptions to communicate business rules between services.</p>
<p>I was under the impression it carried overhead to throw this exception over the wire, but considering it's just a message that get serialized and deserialized, they were in fact one and the same.</p>
<p>But this got me thinking about throwing exceptions in general or more specifically throwing FaultExceptions.</p>
<p>Now within my service, if i use</p>
<pre><code>throw new FaultException
</code></pre>
<p>to communicate a simple business rule like "Your account has not been activated",
What overhead does this now carry?
Is it the same overhead as throwing regular exceptions in .NET? or does WCF service handle these more efficiently with the use of Fault Contracts.</p>
<p>So in my user example, which is the optimal/preferred way to write my service method</p>
<p>option a</p>
<pre><code>public void AuthenticateUser()
{
throw new FaultException("Your account has not been activated");
}
</code></pre>
<p>option b</p>
<pre><code>public AutheticateDto AutheticateUser()
{
return new AutheticateDto() {
Success = false,
Message = "Your account has not been activated"};
}
</code></pre>
| [
{
"answer_id": 100088,
"author": "blowdart",
"author_id": 2525,
"author_profile": "https://Stackoverflow.com/users/2525",
"pm_score": 0,
"selected": false,
"text": "<p>It's just like a normal exception, and uses the same wrapping code as a normal exception would to marshal into a fault, ... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15360/"
] | I posted a [question](https://stackoverflow.com/questions/81306/wcf-faults-exceptions-versus-messages) about using Messages versus Fault Exceptions to communicate business rules between services.
I was under the impression it carried overhead to throw this exception over the wire, but considering it's just a message that get serialized and deserialized, they were in fact one and the same.
But this got me thinking about throwing exceptions in general or more specifically throwing FaultExceptions.
Now within my service, if i use
```
throw new FaultException
```
to communicate a simple business rule like "Your account has not been activated",
What overhead does this now carry?
Is it the same overhead as throwing regular exceptions in .NET? or does WCF service handle these more efficiently with the use of Fault Contracts.
So in my user example, which is the optimal/preferred way to write my service method
option a
```
public void AuthenticateUser()
{
throw new FaultException("Your account has not been activated");
}
```
option b
```
public AutheticateDto AutheticateUser()
{
return new AutheticateDto() {
Success = false,
Message = "Your account has not been activated"};
}
``` | Well... In general you shouldn't be throwing exceptions for expected conditions, or anything you *expect* to happen regularly. They are massively slower than doing normal methods. E.g., if you expect a file open to fail, don't throw a that exception up to your caller, pass the back a failure code, or provide a "CanOpenFile" method to do the test.
True, the message text itself isn't much, but a real exception is thrown and handled (possibly more expensively because of IIS), and then real exception is again thrown on the client when the fault is deserialized. So, double hit.
Honestly, if it is a low volume of calls, then you probably won't take any noticeable hit, but is not a good idea anyway. Who wants to put business logic in a catch block :)
[Microsoft : Exceptions And Performance, & Alternatives](http://msdn.microsoft.com/en-us/library/ms229009.aspx)
[Developer Fusion: Performance, with example](http://www.developerfusion.co.uk/show/5250/) |
100,068 | <p>I'd like to know if there's an easier way to insert a record if it doesn't already exist in a table. I'm still trying to build my LINQ to SQL skills. </p>
<p>Here's what I've got, but it seems like there should be an easier way.</p>
<pre><code>public static TEntity InsertIfNotExists<TEntity>
(
DataContext db,
Table<TEntity> table,
Func<TEntity,bool> where,
TEntity record
)
where TEntity : class
{
TEntity existing = table.SingleOrDefault<TEntity>(where);
if (existing != null)
{
return existing;
}
else
{
table.InsertOnSubmit(record);
// Can't use table.Context.SubmitChanges()
// 'cause it's read-only
db.SubmitChanges();
}
return record;
}
</code></pre>
| [
{
"answer_id": 100496,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": true,
"text": "<pre><code>public static void InsertIfNotExists<TEntity>\n (this Table<TEntity> table,\n ... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11574/"
] | I'd like to know if there's an easier way to insert a record if it doesn't already exist in a table. I'm still trying to build my LINQ to SQL skills.
Here's what I've got, but it seems like there should be an easier way.
```
public static TEntity InsertIfNotExists<TEntity>
(
DataContext db,
Table<TEntity> table,
Func<TEntity,bool> where,
TEntity record
)
where TEntity : class
{
TEntity existing = table.SingleOrDefault<TEntity>(where);
if (existing != null)
{
return existing;
}
else
{
table.InsertOnSubmit(record);
// Can't use table.Context.SubmitChanges()
// 'cause it's read-only
db.SubmitChanges();
}
return record;
}
``` | ```
public static void InsertIfNotExists<TEntity>
(this Table<TEntity> table,
TEntity entity,
Expression<Func<TEntity,bool>> predicate)
where TEntity : class
{
if (!table.Any(predicate))
{
table.InsertOnSubmit(record);
table.Context.SubmitChanges();
}
}
table.InsertIfNotExists(entity, e=>e.BooleanProperty);
``` |
100,081 | <p>I have the following C# singleton pattern, is there any way of improving it? </p>
<pre><code> public class Singleton<T> where T : class, new()
{
private static object _syncobj = new object();
private static volatile T _instance = null;
public static T Instance
{
get
{
if (_instance == null)
{
lock (_syncobj)
{
if (_instance == null)
{
_instance = new T();
}
}
}
return _instance;
}
}
public Singleton()
{ }
}
</code></pre>
<p>Preferred usage example: </p>
<pre><code>class Foo : Singleton<Foo>
{
}
</code></pre>
<p><strong>Related</strong>: </p>
<p><a href="https://stackoverflow.com/questions/953259/an-obvious-singleton-implementation-for-net">An obvious singleton implementation for .NET?</a></p>
| [
{
"answer_id": 100093,
"author": "EggyBach",
"author_id": 15475,
"author_profile": "https://Stackoverflow.com/users/15475",
"pm_score": 3,
"selected": false,
"text": "<p>Courtesy of Judith Bishop, <a href=\"http://patterns.cs.up.ac.za/\" rel=\"noreferrer\">http://patterns.cs.up.ac.za/</a... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
] | I have the following C# singleton pattern, is there any way of improving it?
```
public class Singleton<T> where T : class, new()
{
private static object _syncobj = new object();
private static volatile T _instance = null;
public static T Instance
{
get
{
if (_instance == null)
{
lock (_syncobj)
{
if (_instance == null)
{
_instance = new T();
}
}
}
return _instance;
}
}
public Singleton()
{ }
}
```
Preferred usage example:
```
class Foo : Singleton<Foo>
{
}
```
**Related**:
[An obvious singleton implementation for .NET?](https://stackoverflow.com/questions/953259/an-obvious-singleton-implementation-for-net) | According to Jon Skeet in [Implementing the Singleton Pattern in C#](https://csharpindepth.com/articles/Singleton) the code you posted is actually considered as bad code, because it appears broken when checked against the ECMA CLI standard.
Also watch out: everytime you instantiate your object with a new type of T, it becomes another instance; it doesn't get reflected in your original singleton. |
100,104 | <p>I've written a small hello world test app in Silverlight which i want to host on a Linux/Apache2 server. I want the data to come from MySQL (or some other linux compatible db) so that I can databind to things in the db.</p>
<p>I've managed to get it working by using the <a href="http://www.mysql.com/products/connector/net/" rel="nofollow noreferrer">MySQL Connector/.NET</a>:</p>
<pre><code>MySqlConnection conn = new MySqlConnection("Server=the.server.com;Database=theDb;User=myUser;Password=myPassword;");
conn.Open();
MySqlCommand command = new MySqlCommand("SELECT * FROM test;", conn);
using (MySqlDataReader reader = command.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
while (reader.Read())
{
sb.AppendLine(reader.GetString("myColumn"));
}
this.txtResults.Text = sb.ToString();
}
</code></pre>
<p>This works fine if I give the published ClickOnce app full trust (or at least SocketPermission) and <strong>run it locally</strong>. </p>
<p>I want this to run on the server and I can't get it to work, always ending up with permission exception (SocketPermission is not allowed).</p>
<p>The database is hosted on the same server as the silverlight app if that makes any difference.</p>
<p><strong>EDIT</strong>
Ok, I now understand why it's a bad idea to have db credentials in the client app (obviously). How do people do this then? How do you secure the proxy web service so that it relays data to and from the client/db in a secure way? Are there any examples out there on the web?</p>
<p>Surely, I cannot be the first person who'd like to use a database to power a silverlight application?</p>
| [
{
"answer_id": 100286,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 2,
"selected": false,
"text": "<p>Silverlight does not have any capability to directly access database servers. What you can do is to expose your database ... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8521/"
] | I've written a small hello world test app in Silverlight which i want to host on a Linux/Apache2 server. I want the data to come from MySQL (or some other linux compatible db) so that I can databind to things in the db.
I've managed to get it working by using the [MySQL Connector/.NET](http://www.mysql.com/products/connector/net/):
```
MySqlConnection conn = new MySqlConnection("Server=the.server.com;Database=theDb;User=myUser;Password=myPassword;");
conn.Open();
MySqlCommand command = new MySqlCommand("SELECT * FROM test;", conn);
using (MySqlDataReader reader = command.ExecuteReader())
{
StringBuilder sb = new StringBuilder();
while (reader.Read())
{
sb.AppendLine(reader.GetString("myColumn"));
}
this.txtResults.Text = sb.ToString();
}
```
This works fine if I give the published ClickOnce app full trust (or at least SocketPermission) and **run it locally**.
I want this to run on the server and I can't get it to work, always ending up with permission exception (SocketPermission is not allowed).
The database is hosted on the same server as the silverlight app if that makes any difference.
**EDIT**
Ok, I now understand why it's a bad idea to have db credentials in the client app (obviously). How do people do this then? How do you secure the proxy web service so that it relays data to and from the client/db in a secure way? Are there any examples out there on the web?
Surely, I cannot be the first person who'd like to use a database to power a silverlight application? | The easiest way to do what you want (having read through your edits now :)) will be to expose services that can be consumed. The pattern that Microsoft is REALLY pushing right now is to expose WCF services, but the truth is that your Silverlight client can use WCF to consume a lot of different types of services.
What may be easiest for you to do right now would be to use a .NET service on a web server or maybe a PHP REST service, and then point your Silverlight app at that service. By doing so, you're protecting your database not only from people snooping through it, but more importantly, you're restricting what people can do to your database. If your data is supposed to be read-only, and your service's contract only allows reading operations, you're set. Alternatively, your service may negotiate sessions with credentials, again, set up through WCF.
WCF can be a client-only, server-only, or client-server connector platform. What you choose will affect the code you write, but it's all going to be independent of your database. Your code can be structured such that it's a one-to-one mapping to your database table, or it can be far more abstract (you can set up classes that represent full logical views if you choose). |
100,106 | <pre><code>sub foo {[$#{$_[!$||$|]}*@{$_[!!$_^!$_]}?@{$_[!$..!!$.]}[$_[@--@+]%
@{$_[$==~/(?=)//!$`]}..$#{$_[$??!!$?:!$?]},($)?!$):!!$))..$_[$--$-]%@{
$_[$]/$]]}-(!!$++!$+)]:@{$_[!!$^^^!$^^]}]}
</code></pre>
<p>update: I thought the word "puzzle" would imply this, but: <em>I</em> know what it does - I wrote it. If the puzzle doesn't interest you, please don't waste any time on it.</p>
| [
{
"answer_id": 100503,
"author": "nohat",
"author_id": 3101,
"author_profile": "https://Stackoverflow.com/users/3101",
"pm_score": 3,
"selected": false,
"text": "<p>It takes two arrayrefs and returns a new arrayref with the contents of the second array rearranged such that the second par... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17389/"
] | ```
sub foo {[$#{$_[!$||$|]}*@{$_[!!$_^!$_]}?@{$_[!$..!!$.]}[$_[@--@+]%
@{$_[$==~/(?=)//!$`]}..$#{$_[$??!!$?:!$?]},($)?!$):!!$))..$_[$--$-]%@{
$_[$]/$]]}-(!!$++!$+)]:@{$_[!!$^^^!$^^]}]}
```
update: I thought the word "puzzle" would imply this, but: *I* know what it does - I wrote it. If the puzzle doesn't interest you, please don't waste any time on it. | ### Here is how you figure out how to de-obfuscate this subroutine.
*Sorry for the length*
First let's tidy up the code, and add useful comments.
```
sub foo {
[
(
# ($#{$_[1]})
$#{
$_[
! ( $| | $| )
# $OUTPUT_AUTOFLUSH === $|
# $| is usually 0
# ! ( $| | $| )
# ! ( 0 | 0 )
# ! ( 0 )
# 1
]
}
*
# @{$_[1]}
@{
$_[
!!$_ ^ !$_
# !! 1 ^ ! 1
# ! 0 ^ 0
# 1 ^ 0
# 1
# !! 0 ^ ! 0
# ! 1 ^ 1
# 0 ^ 1
# 1
]
}
)
?
# @{$_[1]}
@{
$_[
!$. . !!$.
# $INPUT_LINE_NUMBER === $.
# $. starts at 1
# !$. . !!$.
# ! 1 . !! 1
# 0 . ! 0
# 0 . 1
# 01
]
}
[
# $_[0]
$_[
# @LAST_MATCH_START - @LAST_MATCH_END
# 0
@- - @+
]
%
# @{$_[1]}
@{
$_[
$= =~ /(?=)/ / !$` #( fix highlighting )`/
# $= is usually 60
# /(?=)/ will match, returns 1
# $` will be ''
# 1 / ! ''
# 1 / ! 0
# 1 / 1
# 1
]
}
..
# $#{$_[1]}
$#{
$_[
$? ? !!$? : !$?
# $CHILD_ERROR === $?
# $? ? !!$? : !$?
# 0 ? !! 0 : ! 0
# 0 ? 0 : 1
# 1
# 1 ? !! 1 : ! 1
# 1 ? 1 : 0
# 1
]
}
,
# ( 0 )
(
$) ? !$) : !!$)
# $EFFECTIVE_GROUP_ID === $)
# $) ? !$) : !!$)
# 0 ? ! 0 : !! 0
# 0 ? 1 : 0
# 0
# 1 ? ! 1 : !! 1
# 1 ? 0 : 1
# 0
)
..
# $_[0]
$_[
$- - $- # 0
# $LAST_PAREN_MATCH = $-
# 1 - 1 == 0
# 5 - 5 == 0
]
%
# @{$_[1]}
@{
$_[
$] / $]
# $] === The version + patchlevel / 1000 of the Perl interpreter.
# 1 / 1 == 1
# 5 / 5 == 1
]
}
-
# ( 1 )
(
!!$+ + !$+
# !! 1 + ! 1
# ! 0 + 0
# 1 + 0
# 1
)
]
:
# @{$_[1]}
@{
$_[
!!$^^ ^ !$^^
# !! 1 ^ ! 1
# ! 0 ^ 0
# 1 ^ 0
# 1
# !! 0 ^ ! 0
# ! 1 ^ 1
# 0 ^ 1
# 1
]
}
]
}
```
Now let's remove some of the obfuscation.
```
sub foo{
[
(
$#{$_[1]} * @{$_[1]}
)
?
@{$_[1]}[
( $_[0] % @{$_[1]} ) .. $#{$_[1]}
,
0 .. ( $_[0] % @{$_[1]} - 1 )
]
:
@{$_[1]}
]
}
```
Now that we have some idea of what is going on, let's name the variables.
```
sub foo{
my( $item_0, $arr_1 ) = @_;
my $len_1 = @$arr_1;
[
# This essentially just checks that the length of $arr_1 is greater than 1
( ( $len_1 -1 ) * $len_1 )
# ( ( $len_1 -1 ) * $len_1 )
# ( ( 5 -1 ) * 5 )
# 4 * 5
# 20
# 20 ? 1 : 0 == 1
# ( ( $len_1 -1 ) * $len_1 )
# ( ( 2 -1 ) * 2 )
# 1 * 2
# 2
# 2 ? 1 : 0 == 1
# ( ( $len_1 -1 ) * $len_1 )
# ( ( 1 -1 ) * 1 )
# 0 * 1
# 0
# 0 ? 1 : 0 == 0
# ( ( $len_1 -1 ) * $len_1 )
# ( ( 0 -1 ) * 0 )
# -1 * 0
# 0
# 0 ? 1 : 0 == 0
?
@{$arr_1}[
( $item_0 % $len_1 ) .. ( $len_1 -1 ),
0 .. ( $item_0 % $len_1 - 1 )
]
:
# If we get here, @$arr_1 is either empty or has only one element
@$arr_1
]
}
```
Let's refactor the code to make it a little bit more readable.
```
sub foo{
my( $item_0, $arr_1 ) = @_;
my $len_1 = @$arr_1;
if( $len_1 > 1 ){
return [
@{$arr_1}[
( $item_0 % $len_1 ) .. ( $len_1 -1 ),
0 .. ( $item_0 % $len_1 - 1 )
]
];
}elsif( $len_1 ){
return [ @$arr_1 ];
}else{
return [];
}
}
``` |
100,107 | <p>I'm investigating the following <code>java.lang.VerifyError</code></p>
<pre><code>java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMonthData signature: (IILjava/util/Collection;Ljava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageRe˜̴Mt̴MÚw€mçw€mp:”MŒŒ
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357)
at java.lang.Class.getConstructor0(Class.java:2671)
</code></pre>
<p>It occurs when the jboss server in which the servlet is deployed is started.
It is compiled with jdk-1.5.0_11 and I tried to recompile it with jdk-1.5.0_15 without succes. That is the compilation runs fine but when deployed, the java.lang.VerifyError occurs.</p>
<p>When I changed the method name and got the following error:</p>
<pre><code>java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMD signature: (IILjava/util/Collection;Lj ava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageResources ØÅN|ØÅNÚw€mçw€mX#ÖM|XÔM
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357
at java.lang.Class.getConstructor0(Class.java:2671)
at java.lang.Class.newInstance0(Class.java:321)
at java.lang.Class.newInstance(Class.java:303)
</code></pre>
<p>You can see that more of the method signature is shown.</p>
<p>The actual method signature is</p>
<pre><code> private PgasePdfTable getMonthData(int month, int year, Collection dayTypes,
Collection calendarDays,
HashMap bcSpecialDays,
Collection activityPeriods,
Locale locale, MessageResources resources) throws Exception {
</code></pre>
<p>I already tried looking at it with <code>javap</code> and that gives the method signature as it should be.</p>
<p>When my other colleagues check out the code, compile it and deploy it, they have the same problem. When the build server picks up the code and deploys it on development or testing environments (HPUX), the same error occurs. Also an automated testing machine running Ubuntu shows the same error during server startup.</p>
<p>The rest of the application runs okay, only that one servlet is out of order.
Any ideas where to look would be helpful.</p>
| [
{
"answer_id": 100131,
"author": "Lars Westergren",
"author_id": 15627,
"author_profile": "https://Stackoverflow.com/users/15627",
"pm_score": 1,
"selected": false,
"text": "<p>This page may give you some hints -\n<a href=\"http://www.zanthan.com/itymbi/archives/000337.html\" rel=\"nofol... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15490/"
] | I'm investigating the following `java.lang.VerifyError`
```
java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMonthData signature: (IILjava/util/Collection;Ljava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageRe˜̴Mt̴MÚw€mçw€mp:”MŒŒ
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357)
at java.lang.Class.getConstructor0(Class.java:2671)
```
It occurs when the jboss server in which the servlet is deployed is started.
It is compiled with jdk-1.5.0\_11 and I tried to recompile it with jdk-1.5.0\_15 without succes. That is the compilation runs fine but when deployed, the java.lang.VerifyError occurs.
When I changed the method name and got the following error:
```
java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMD signature: (IILjava/util/Collection;Lj ava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageResources ØÅN|ØÅNÚw€mçw€mX#ÖM|XÔM
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357
at java.lang.Class.getConstructor0(Class.java:2671)
at java.lang.Class.newInstance0(Class.java:321)
at java.lang.Class.newInstance(Class.java:303)
```
You can see that more of the method signature is shown.
The actual method signature is
```
private PgasePdfTable getMonthData(int month, int year, Collection dayTypes,
Collection calendarDays,
HashMap bcSpecialDays,
Collection activityPeriods,
Locale locale, MessageResources resources) throws Exception {
```
I already tried looking at it with `javap` and that gives the method signature as it should be.
When my other colleagues check out the code, compile it and deploy it, they have the same problem. When the build server picks up the code and deploys it on development or testing environments (HPUX), the same error occurs. Also an automated testing machine running Ubuntu shows the same error during server startup.
The rest of the application runs okay, only that one servlet is out of order.
Any ideas where to look would be helpful. | `java.lang.VerifyError` can be the result when you have compiled against a different library than you are using at runtime.
For example, this happened to me when trying to run a program that was compiled against Xerces 1, but Xerces 2 was found on the classpath. The required classes (in `org.apache.*` namespace) were found at runtime, so `ClassNotFoundException` was ***not*** the result. There had been changes to the classes and methods, so that the method signatures found at runtime did not match what was there at compile-time.
Normally, the compiler will flag problems where method signatures do not match. The JVM will verify the bytecode again when the class is loaded, and throws `VerifyError` when the bytecode is trying to do something that should not be allowed -- e.g. calling a method that returns `String` and then stores that return value in a field that holds a `List`. |
100,161 | <p>I was happily using Eclipse 3.2 (or as happy as one can be using Eclipse) when for a forgotten reason I decided to upgrade to 3.4. I'm primarily using PyDev, Aptana, and Subclipse, very little Java development.</p>
<p>I've noticed 3.4 tends to really give my laptop a hernia compared to 3.2 (vista, core2duo, 2G). Is memory usage on 3.4 actually higher than on 3.2, and if so is there a way to reduce it?</p>
<p>EDIT: I tried disabling plugins (I didn't have much enabled anyway) and used the jvm monitor; the latter was interesting but I couldn't figure out how to use the info in any practical way. I'm still not able to reduce its memory footprint. I've also noticed every once in a while Eclipse just hangs for ~30 seconds, then magically comes back.</p>
| [
{
"answer_id": 100180,
"author": "Drejc",
"author_id": 6482,
"author_profile": "https://Stackoverflow.com/users/6482",
"pm_score": 2,
"selected": false,
"text": "<p>Yes memory usage can get real high and you might run into problems with your JVM, as the default setting is a bit to low.\n... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] | I was happily using Eclipse 3.2 (or as happy as one can be using Eclipse) when for a forgotten reason I decided to upgrade to 3.4. I'm primarily using PyDev, Aptana, and Subclipse, very little Java development.
I've noticed 3.4 tends to really give my laptop a hernia compared to 3.2 (vista, core2duo, 2G). Is memory usage on 3.4 actually higher than on 3.2, and if so is there a way to reduce it?
EDIT: I tried disabling plugins (I didn't have much enabled anyway) and used the jvm monitor; the latter was interesting but I couldn't figure out how to use the info in any practical way. I'm still not able to reduce its memory footprint. I've also noticed every once in a while Eclipse just hangs for ~30 seconds, then magically comes back. | Yes memory usage can get real high and you might run into problems with your JVM, as the default setting is a bit to low.
Consider using this startup parameters when running eclipse:
```
-vmargs -XX:MaxPermSize=1024M -Xms256M -Xmx1024M
``` |
100,170 | <p>I have a folder on my server to which I had a number of symbolic links pointing. I've since created a new folder and I want to change all those symbolic links to point to the new folder. I'd considered replacing the original folder with a symlink to the new folder, but it seems that if I continued with that practice it could get very messy very fast.</p>
<p>What I've been doing is manually changing the symlinks to point to the new folder, but I may have missed a couple. </p>
<p>Is there a way to check if there are any symlinks pointing to a particular folder?</p>
| [
{
"answer_id": 100200,
"author": "skymt",
"author_id": 18370,
"author_profile": "https://Stackoverflow.com/users/18370",
"pm_score": 7,
"selected": true,
"text": "<p>I'd use the find command.</p>\n\n<pre><code>find . -lname /particular/folder\n</code></pre>\n\n<p>That will recursively se... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] | I have a folder on my server to which I had a number of symbolic links pointing. I've since created a new folder and I want to change all those symbolic links to point to the new folder. I'd considered replacing the original folder with a symlink to the new folder, but it seems that if I continued with that practice it could get very messy very fast.
What I've been doing is manually changing the symlinks to point to the new folder, but I may have missed a couple.
Is there a way to check if there are any symlinks pointing to a particular folder? | I'd use the find command.
```
find . -lname /particular/folder
```
That will recursively search the current directory for symlinks to `/particular/folder`. Note that it will only find absolute symlinks. A similar command can be used to search for all symlinks pointing at objects called "folder":
```
find . -lname '*folder'
```
From there you would need to weed out any false positives. |
100,209 | <p>I have an OWL ontology and I am using Pellet to do reasoning over it. Like most ontologies it starts by including various standard ontologies:</p>
<pre><code><rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns:owl="http://www.w3.org/2002/07/owl#">
</code></pre>
<p>I know that some reasoners have these standard ontologies 'built-in', but Pellet doesn't. Is there any way I can continue to use Pellet when I am offline & can't access them? (Or if their URL goes offline, like dublincore.org did last week for routine maintenance)</p>
| [
{
"answer_id": 103736,
"author": "Ian Terrell",
"author_id": 9269,
"author_profile": "https://Stackoverflow.com/users/9269",
"pm_score": 1,
"selected": false,
"text": "<p>Make local copies of the four files and replace the remote URLs with local URIs (i.e. file://... or serve them from y... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12405/"
] | I have an OWL ontology and I am using Pellet to do reasoning over it. Like most ontologies it starts by including various standard ontologies:
```
<rdf:RDF
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns:owl="http://www.w3.org/2002/07/owl#">
```
I know that some reasoners have these standard ontologies 'built-in', but Pellet doesn't. Is there any way I can continue to use Pellet when I am offline & can't access them? (Or if their URL goes offline, like dublincore.org did last week for routine maintenance) | Pellet recognizes all of these namespaces when loading and should not attempt to dereference the URIs. If it does, it suggests the application using Pellet is doing something incorrectly.
You may find more help on [the pellet-users mailing list](http://lists.owldl.com/mailman/listinfo/pellet-users/). |
100,210 | <p>Given a <code>datetime.time</code> value in Python, is there a standard way to add an integer number of seconds to it, so that <code>11:34:59</code> + 3 = <code>11:35:02</code>, for example?</p>
<p>These obvious ideas don't work:</p>
<pre><code>>>> datetime.time(11, 34, 59) + 3
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int'
>>> datetime.time(11, 34, 59) + datetime.timedelta(0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'
>>> datetime.time(11, 34, 59) + datetime.time(0, 0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'
</code></pre>
<p>In the end I have written functions like this:</p>
<pre><code>def add_secs_to_time(timeval, secs_to_add):
secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second
secs += secs_to_add
return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60)
</code></pre>
<p>I can't help thinking that I'm missing an easier way to do this though.</p>
<h3>Related</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/656297/python-time-timedelta-equivalent">python time + timedelta equivalent</a></li>
</ul>
| [
{
"answer_id": 100250,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 0,
"selected": false,
"text": "<p>Try adding a <code>datetime.datetime</code> to a <code>datetime.timedelta</code>. If you only want the time portio... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5536/"
] | Given a `datetime.time` value in Python, is there a standard way to add an integer number of seconds to it, so that `11:34:59` + 3 = `11:35:02`, for example?
These obvious ideas don't work:
```
>>> datetime.time(11, 34, 59) + 3
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int'
>>> datetime.time(11, 34, 59) + datetime.timedelta(0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'
>>> datetime.time(11, 34, 59) + datetime.time(0, 0, 3)
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time'
```
In the end I have written functions like this:
```
def add_secs_to_time(timeval, secs_to_add):
secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second
secs += secs_to_add
return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60)
```
I can't help thinking that I'm missing an easier way to do this though.
### Related
* [python time + timedelta equivalent](https://stackoverflow.com/questions/656297/python-time-timedelta-equivalent) | You can use full `datetime` variables with `timedelta`, and by providing a dummy date then using `time` to just get the time value.
For example:
```
import datetime
a = datetime.datetime(100,1,1,11,34,59)
b = a + datetime.timedelta(0,3) # days, seconds, then other fields.
print(a.time())
print(b.time())
```
results in the two values, three seconds apart:
```
11:34:59
11:35:02
```
You could also opt for the more readable
```
b = a + datetime.timedelta(seconds=3)
```
if you're so inclined.
---
If you're after a function that can do this, you can look into using `addSecs` below:
```
import datetime
def addSecs(tm, secs):
fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
fulldate = fulldate + datetime.timedelta(seconds=secs)
return fulldate.time()
a = datetime.datetime.now().time()
b = addSecs(a, 300)
print(a)
print(b)
```
This outputs:
```
09:11:55.775695
09:16:55
``` |
100,211 | <p>I just installed Glassfish V2 on my local machine just to play around with it.</p>
<p>I was wondering if there is a way to retrieve a param passed in by the GET HTTP method.</p>
<p>For instance,</p>
<pre><code>http://localhost:8080/HelloWorld/resources/helloWorld?name=ABC
</code></pre>
<p>How do I retrieve the "name" param in my Java code?</p>
| [
{
"answer_id": 100396,
"author": "tgdavies",
"author_id": 11002,
"author_profile": "https://Stackoverflow.com/users/11002",
"pm_score": 3,
"selected": true,
"text": "<p>Like this:</p>\n\n<pre><code>@Path(\"/helloWorld\")\n@Consumes({\"application/xml\", \"application/json\"})\n@Produces(... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4004/"
] | I just installed Glassfish V2 on my local machine just to play around with it.
I was wondering if there is a way to retrieve a param passed in by the GET HTTP method.
For instance,
```
http://localhost:8080/HelloWorld/resources/helloWorld?name=ABC
```
How do I retrieve the "name" param in my Java code? | Like this:
```
@Path("/helloWorld")
@Consumes({"application/xml", "application/json"})
@Produces({"application/xml", "application/json"})
@Singleton
public class MyService {
@GET
public String getRequest(@QueryParam("name") String name) {
return "Name was " + name;
}
}
``` |
100,216 | <p>I'm trying to integrate running Fitnesse tests from MSBuild im my nightly build on TFS.</p>
<p>In an attempt to make it self contained I would like to start the seleniumRC server only when it's needed from fitness.</p>
<p>I've seen that there is a "Command Line Fixture" but it's written in java can I use that?</p>
| [
{
"answer_id": 100638,
"author": "David Laing",
"author_id": 13238,
"author_profile": "https://Stackoverflow.com/users/13238",
"pm_score": 0,
"selected": false,
"text": "<p>What about writing a simple .NET app that does a Process.Start(\"selenumRC commandline\") which gets run by your bu... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11434/"
] | I'm trying to integrate running Fitnesse tests from MSBuild im my nightly build on TFS.
In an attempt to make it self contained I would like to start the seleniumRC server only when it's needed from fitness.
I've seen that there is a "Command Line Fixture" but it's written in java can I use that? | I think you might be able to. You can call any process easily in MSBuild using the task. However, the problem with doing this is that the exec task will wait for the Selinium process to finish before continuing, which is not the bahaviour you want. You want to run the process, keep it running during your build and then tear it down as your build finishes.
Therefore, I think you are probably going to need to create a custom MSBuild task to do this. See the following post for an example of a tasks that someone has created that will run asynchronously returning control back to the build script:
<http://blog.eleutian.com/2007/03/01/AsyncExecMsBuildTask.aspx>
And for an example of calling a Java program from MSBuild (but in this case synchronously) take a look at my task that calls [Ant from MSBuild](http://teamprise.com/products/build/) here
<http://teamprise.com/products/build/>
As part of your MSBuild task, you will want to output the process id that you created to an output property so that at the end of your build script you can call another custom MSBuild task that kills the process. It can do this by looking for the process id passed in as a variable in MSBuild and then call [Process.Kill](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx) method i.e.
```
Process process = Process.GetProcessById(ProcessId);
process.Kill();
```
That said, you would need to be careful to ensure that your kill task was always executed in MSBuild by making sure it was included during error paths etc in the build. You could probably make things a bit more resilient by making the selenium RC starter task look for other seleniumRC processes and killing them before starting a new one - that way if a process didn't get closed properly for some reason, it would only run until the next build.
Anyway - my answer sounds like a lot of work so hopefully someone else will come up with an easier way. You might be able to create the seleniumRC process in the test suite start up of the FitNesse tests and kill it in the suite tear down, or you might be able to write a custom task that extends your FitNesse runner tasks and fires up seleiniumRC asynronously before running the test process and then kills it afterwards.
Good luck,
Martin. |
100,228 | <p>I'm trying to set up part of a schema that's like a "Sequence" where all child elements are optional, but at least one of the elements <strong>must</strong> be present, and there could be more than one of them.</p>
<p>I tried doing the following, but XMLSpy complains that "The content model contains the elements <element name="DateConstant"> and <element name="DateConstant"> which cannot be uniquely determined.":</p>
<pre><code> <xs:choice>
<xs:sequence>
<xs:element name="DateConstant"/>
<xs:element name="TimeConstant"/>
</xs:sequence>
<xs:element name="DateConstant"/>
<xs:element name="TimeConstant"/>
</xs:choice>
</code></pre>
<p>Can this be done (and if so, how)?</p>
<p>Some clarification:
I only want to allow one of each element of the same name. There can be one "DateConstant" and/or one "TimeConstant", but not two of either.
Gizmo's answer matches my requirements, but it's impractical for a larger number of elements.
Hurst's answer allows two or more elements of the same name, which I don't want.</p>
| [
{
"answer_id": 100313,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 6,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code><xs:choice>\n <xs:sequence>\n <xs:element name=\"Elem1\" />\n <xs:el... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18603/"
] | I'm trying to set up part of a schema that's like a "Sequence" where all child elements are optional, but at least one of the elements **must** be present, and there could be more than one of them.
I tried doing the following, but XMLSpy complains that "The content model contains the elements <element name="DateConstant"> and <element name="DateConstant"> which cannot be uniquely determined.":
```
<xs:choice>
<xs:sequence>
<xs:element name="DateConstant"/>
<xs:element name="TimeConstant"/>
</xs:sequence>
<xs:element name="DateConstant"/>
<xs:element name="TimeConstant"/>
</xs:choice>
```
Can this be done (and if so, how)?
Some clarification:
I only want to allow one of each element of the same name. There can be one "DateConstant" and/or one "TimeConstant", but not two of either.
Gizmo's answer matches my requirements, but it's impractical for a larger number of elements.
Hurst's answer allows two or more elements of the same name, which I don't want. | Try this:
```
<xs:choice>
<xs:sequence>
<xs:element name="Elem1" />
<xs:element name="Elem2" minOccurs="0" />
<xs:element name="Elem3" minOccurs="0" />
</xs:sequence>
<xs:sequence>
<xs:element name="Elem2" />
<xs:element name="Elem3" minOccurs="0" />
</xs:sequence>
<xs:element name="Elem3" />
</xs:choice>
```
Doing so, you force either to choose the first element and then the rest is optional, either the second element and the rest is optional, either the third element.
This should do what you want, I hope.
Of course, you could place the sub-sequences into groups, to avoid to duplicate an element in each sequence if you realize you miss one. |
100,235 | <p>For an open source project I am looking for a good, simple implementation of a Dictionary that is backed by a file. Meaning, if an application crashes or restarts the dictionary will keep its state. I would like it to update the underlying file every time the dictionary is touched. (Add a value or remove a value). A FileWatcher is not required but it could be useful. </p>
<pre><code>class PersistentDictionary<T,V> : IDictionary<T,V>
{
public PersistentDictionary(string filename)
{
}
}
</code></pre>
<p>Requirements: </p>
<ul>
<li>Open Source, with no dependency on native code (no sqlite) </li>
<li>Ideally a very short and simple implementation</li>
<li>When setting or clearing a value it should not re-write the entire underlying file, instead it should seek to the position in the file and update the value.</li>
</ul>
<p><strong>Similar Questions</strong> </p>
<ul>
<li><a href="https://stackoverflow.com/questions/108435/persistent-binary-tree-hash-table-in-net">Persistent Binary Tree / Hash table in .Net</a></li>
<li><a href="https://stackoverflow.com/questions/408401/disk-backed-dictionary-cache-for-c">Disk backed dictionary/cache for c#</a></li>
<li><a href="http://izlooite.blogspot.com/2011/04/persistent-dictionary.html" rel="noreferrer"><code>PersistentDictionary<Key,Value></code></a></li>
</ul>
| [
{
"answer_id": 100672,
"author": "chrisb",
"author_id": 8262,
"author_profile": "https://Stackoverflow.com/users/8262",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds cool, but how will you get around changes to the stored value (if it was a reference type) itself? If its immutabl... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17174/"
] | For an open source project I am looking for a good, simple implementation of a Dictionary that is backed by a file. Meaning, if an application crashes or restarts the dictionary will keep its state. I would like it to update the underlying file every time the dictionary is touched. (Add a value or remove a value). A FileWatcher is not required but it could be useful.
```
class PersistentDictionary<T,V> : IDictionary<T,V>
{
public PersistentDictionary(string filename)
{
}
}
```
Requirements:
* Open Source, with no dependency on native code (no sqlite)
* Ideally a very short and simple implementation
* When setting or clearing a value it should not re-write the entire underlying file, instead it should seek to the position in the file and update the value.
**Similar Questions**
* [Persistent Binary Tree / Hash table in .Net](https://stackoverflow.com/questions/108435/persistent-binary-tree-hash-table-in-net)
* [Disk backed dictionary/cache for c#](https://stackoverflow.com/questions/408401/disk-backed-dictionary-cache-for-c)
* [`PersistentDictionary<Key,Value>`](http://izlooite.blogspot.com/2011/04/persistent-dictionary.html) | * [**bplustreedotnet**](http://bplusdotnet.sourceforge.net/)
The bplusdotnet package is a library of cross compatible data structure implementations in C#, java, and Python which are useful for applications which need to store and retrieve persistent information. The bplusdotnet data structures make it easy to **store string keys associated with values permanently**.
* [**ESENT Managed Interface**](http://www.codeplex.com/ManagedEsent)
*Not 100% managed code but it's worth mentioning it as unmanaged library itself is already part of every windows XP/2003/Vista/7 box*
ESENT is an embeddable database storage engine (ISAM) which is part of Windows. It provides reliable, transacted, concurrent, high-performance data storage with row-level locking, write-ahead logging and snapshot isolation. This is a managed wrapper for the ESENT Win32 API.
* [**Akavache**](https://github.com/github/Akavache)
\*Akavache is an asynchronous, persistent key-value cache created for writing native desktop and mobile applications in C#. Think of it like memcached for desktop apps.
- [**The C5 Generic Collection Library**](http://www.itu.dk/research/c5/)
C5 provides functionality and data structures not provided by the standard .Net `System.Collections.Generic` namespace, such as **persistent tree data structures**, heap based priority queues, hash indexed array lists and linked lists, and events on collection changes. |
100,236 | <p>How can I insert ASCII special characters (e.g. with the ASCII value 0x01) into a string?</p>
<p>I ask because I am using the following:</p>
<pre><code>str.Replace( "<TAG1>", Convert.ToChar(0x01).ToString() );
</code></pre>
<p>and I feel that there must be a better way than this. Any Ideas?</p>
<p>Update:</p>
<p>Also If I use this methodology, do I need to worry about unicode & ASCII clashing?</p>
| [
{
"answer_id": 100244,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 4,
"selected": true,
"text": "<p>I believe you can use <code>\\uXXXX</code> to insert specified codes into your string.</p>\n\n<p>ETA: I just tested it and... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1816/"
] | How can I insert ASCII special characters (e.g. with the ASCII value 0x01) into a string?
I ask because I am using the following:
```
str.Replace( "<TAG1>", Convert.ToChar(0x01).ToString() );
```
and I feel that there must be a better way than this. Any Ideas?
Update:
Also If I use this methodology, do I need to worry about unicode & ASCII clashing? | I believe you can use `\uXXXX` to insert specified codes into your string.
ETA: I just tested it and it works. :-)
```
using System;
class Uxxxx {
public static void Main() {
Console.WriteLine("\u20AC");
}
}
``` |
100,242 | <p>You can use </p>
<p>SelectFolder() to get a folder</p>
<p>or </p>
<p>GetOpenFolderitem(filter as string) to get files</p>
<p>but can you select either a folder or file? ( or for that matter selecting multiple files )</p>
| [
{
"answer_id": 100251,
"author": "Enrique",
"author_id": 17134,
"author_profile": "https://Stackoverflow.com/users/17134",
"pm_score": -1,
"selected": false,
"text": "<p>Assuming you're using .Net I think you'll need to create your own control (or buy one). </p>\n"
},
{
"answer_i... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10472/"
] | You can use
SelectFolder() to get a folder
or
GetOpenFolderitem(filter as string) to get files
but can you select either a folder or file? ( or for that matter selecting multiple files ) | The MonkeyBread plugin allows this in the OpenDialogMBS class.
<http://www.monkeybreadsoftware.net/pluginhelp/navigation-opendialogmbs.shtml>
```
OpenDialogMBS.AllowFolderSelection as Boolean
property, Navigation, MBS Util Plugin (OpenDialog), class OpenDialogMBS, Plugin version: 7.5, Mac OS X: Works, Windows: Does nothing, Linux x86: Does nothing, Feedback.
Function: Whether folders can be selected.
Example:
dim o as OpenDialogMBS
dim i,c as integer
dim f as FolderItem
o=new OpenDialogMBS
o.ShowHiddenFiles=true
o.PromptText="Select one or more files/folders:"
o.MultipleSelection=false
o.ActionButtonLabel="Open files/folders"
o.CancelButtonLabel="no, thanks."
o.WindowTitle="This is a window title."
o.ClientName="Client Name?"
o.AllowFolderSelection=true
o.ShowDialog
c=o.FileCount
if c>0 then
for i=0 to c-1
f=o.Files(i)
FileList.List.AddRow f.AbsolutePath
next
end if
Notes:
Default is false.
Setting this to true on Windows or Linux has no effect there.
(Read and Write property)
``` |
100,247 | <p>I'm using C# in .Net 2.0, and I want to read in a PNG image file and check for the first row and first column that has non-transparent pixels. </p>
<p>What assembly and/or class should I use?</p>
| [
{
"answer_id": 100292,
"author": "Roy Tang",
"author_id": 18494,
"author_profile": "https://Stackoverflow.com/users/18494",
"pm_score": 1,
"selected": false,
"text": "<p>Of course I googled already and found the PngBitmapDecoder class, but it doesn't seem to be available in .Net 2.0? </p... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18494/"
] | I'm using C# in .Net 2.0, and I want to read in a PNG image file and check for the first row and first column that has non-transparent pixels.
What assembly and/or class should I use? | [Bitmap](http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.aspx) class from System.Drawing.dll assembly:
```
Bitmap bitmap = new Bitmap(@"C:\image.png");
Color clr = bitmap.GetPixel(0, 0);
``` |
100,291 | <p>Imagine I have an function which goes through one million/billion strings and checks smth in them.</p>
<p>f.ex:</p>
<pre><code>foreach (String item in ListOfStrings)
{
result.add(CalculateSmth(item));
}
</code></pre>
<p>it consumes lot's of time, because CalculateSmth is very time consuming function.</p>
<p>I want to ask: how to integrate multithreading in this kinda process?</p>
<p>f.ex: I want to fire-up 5 threads and each of them returns some results, and thats goes-on till the list has items.</p>
<p>Maybe anyone can show some examples or articles.. </p>
<p>Forgot to mention I need it in .NET 2.0</p>
| [
{
"answer_id": 100307,
"author": "Tobi",
"author_id": 5422,
"author_profile": "https://Stackoverflow.com/users/5422",
"pm_score": 5,
"selected": true,
"text": "<p>You could try the <a href=\"http://msdn.microsoft.com/en-us/concurrency/default.aspx\" rel=\"noreferrer\">Parallel extensions... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5369/"
] | Imagine I have an function which goes through one million/billion strings and checks smth in them.
f.ex:
```
foreach (String item in ListOfStrings)
{
result.add(CalculateSmth(item));
}
```
it consumes lot's of time, because CalculateSmth is very time consuming function.
I want to ask: how to integrate multithreading in this kinda process?
f.ex: I want to fire-up 5 threads and each of them returns some results, and thats goes-on till the list has items.
Maybe anyone can show some examples or articles..
Forgot to mention I need it in .NET 2.0 | You could try the [Parallel extensions](http://msdn.microsoft.com/en-us/concurrency/default.aspx) (part of .NET 4.0)
These allow you to write something like:
```
Parallel.Foreach (ListOfStrings, (item) =>
result.add(CalculateSmth(item));
);
```
Of course result.add would need to be thread safe. |
100,365 | <p>In cake 1.2 there is a feature that allows the developer to no have to create models, but rather have cake do the detective work at run time and create the model for you. This process happens each time and is neat but in my case very hazardous. I read about this somewhere and now I'm experiencing the bad side of this.</p>
<p>I've created a plugin with all the files and everything appeared to be just great. That is until i tried to use some of the model's associations and functions. Then cake claims that this model i've created doesn't exist. <strong>I've narrowed it down to cake using this auto model feature instead of throwing and error</strong>! So i have no idea what's wrong!</p>
<p>Does anybody know how to disable this auto model feature? It's a good thought, but I can't seem to find where i've gone wrong with my plugin and an error would be very helpful!</p>
| [
{
"answer_id": 100426,
"author": "deceze",
"author_id": 476,
"author_profile": "https://Stackoverflow.com/users/476",
"pm_score": 2,
"selected": false,
"text": "<p>There's always the possibility to actually create the model file and set var $useTable = false.<br>\nIf this is not what you... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5261/"
] | In cake 1.2 there is a feature that allows the developer to no have to create models, but rather have cake do the detective work at run time and create the model for you. This process happens each time and is neat but in my case very hazardous. I read about this somewhere and now I'm experiencing the bad side of this.
I've created a plugin with all the files and everything appeared to be just great. That is until i tried to use some of the model's associations and functions. Then cake claims that this model i've created doesn't exist. **I've narrowed it down to cake using this auto model feature instead of throwing and error**! So i have no idea what's wrong!
Does anybody know how to disable this auto model feature? It's a good thought, but I can't seem to find where i've gone wrong with my plugin and an error would be very helpful! | **Cake 1.2**
It's a hack and it's ugly cus you need to edit core cake files but this is how i do it:
\cake\libs\class\_registry.php : line 127ish
```
if (App::import($type, $plugin . $class)) {
${$class} =& new $class($options);
} elseif ($type === 'Model') {
/* Print out whatever debug info we have then exit */
pr($objects);
die("unable to find class $type, $plugin$class");
/* We don't want to base this on the app model */
${$class} =& new AppModel($options);
}
```
**Cake 2**
Costa recommends changing $strict to true in the init function on line 95 of `Cake\Utility\ClassRegistry.php`
[See Cake Api Docs for init](http://api.cakephp.org/2.3/class-ClassRegistry.html#_init)
[ClassRegistry.php - init function](https://github.com/cakephp/cakephp/blob/c989624f8053f28d2ac37f5e84dc436965235177/lib/Cake/Utility/ClassRegistry.php#L96) |
100,376 | <p>Anyone know how to do picture overlay or appear on top of each other in HTML? The effect will be something like the marker/icon appear on Google Map where the user can specify the coordinate of the second picture appear on the first picture.</p>
<p>Thanks.</p>
| [
{
"answer_id": 100402,
"author": "Subimage",
"author_id": 10596,
"author_profile": "https://Stackoverflow.com/users/10596",
"pm_score": 2,
"selected": false,
"text": "<p>Use a DIV tag and CSS absolute positioning, with the z-index property.</p>\n\n<p><a href=\"http://www.w3.org/TR/CSS2/v... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14790/"
] | Anyone know how to do picture overlay or appear on top of each other in HTML? The effect will be something like the marker/icon appear on Google Map where the user can specify the coordinate of the second picture appear on the first picture.
Thanks. | You can use `<div>` containers to seperate content into multiple layers. Therefore the div containers have to be positioned absolutely and marked with a z-index. for instance:
```
<div style="position: absolute; z-index:100">This is in background</div>
<div style="position: absolute; z-index:5000">This is in foreground</div>
```
Of course the content also can contains images, etc. |
100,415 | <p>I'm looking for an open source, cross platform (Windows & Linux at least) command line tool to take some code (C++, but multiple languages would be sweet), and spit out valid a XHTML representation of that code, with syntax highlighting included.</p>
<p>Ideally the XHTML should just wrap the code with <code><span></code> and <code><div></code> tags with different classes so I can supply the CSS code and change the colouration, but that's an optional extra.</p>
<p>Does anyone know of such an application?</p>
| [
{
"answer_id": 100439,
"author": "PW.",
"author_id": 927,
"author_profile": "https://Stackoverflow.com/users/927",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.vim.org/\" rel=\"nofollow noreferrer\">Vim</a> can save any code it highlights to \"colored\" HTML (it run... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1304/"
] | I'm looking for an open source, cross platform (Windows & Linux at least) command line tool to take some code (C++, but multiple languages would be sweet), and spit out valid a XHTML representation of that code, with syntax highlighting included.
Ideally the XHTML should just wrap the code with `<span>` and `<div>` tags with different classes so I can supply the CSS code and change the colouration, but that's an optional extra.
Does anyone know of such an application? | I can recommend [Pygments](http://pygments.org/). It's easy to work with and supports a lot of languages. It does what you want, i.e., it wraps the code in `<span>` tags:
```
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
code = 'print "Hello World"'
print highlight(code, PythonLexer(), HtmlFormatter())
```
gives
```
<div class="highlight">
<pre><span class="k">print</span> <span class="s">"Hello World"</span></pre>
</div>
```
and you can then use one of the supplied style sheets of make your own.
You can also call it via it's `pygmentize` script. The script can format the output in different ways: HTML, LaTeX, ANSI color terminal output. |
100,416 | <p>In SQL Server 2000/2005,</p>
<p>Is it possible to force the default value to be written to already existing rows when adding a new column to a table <strong>without</strong> using NOT NULL on the new column?</p>
| [
{
"answer_id": 100560,
"author": "chrisb",
"author_id": 8262,
"author_profile": "https://Stackoverflow.com/users/8262",
"pm_score": 1,
"selected": false,
"text": "<p>I doubt it.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms190273(SQL.90).aspx\" rel=\"nofollow noreferrer\... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7241/"
] | In SQL Server 2000/2005,
Is it possible to force the default value to be written to already existing rows when adding a new column to a table **without** using NOT NULL on the new column? | You need two statements. First create the column with not null. Then change the not null constraint to nullable
```
alter table mytable add mycolumn varchar(10) not null default ('a value')
alter table mytable alter column mycolumn varchar(10) null
``` |
100,435 | <p>I'm using a ASP.NET menu control. I'd like the menu to look like this, where link 1 through 10 are in one sitemap file and link 11 through 20 in another. </p>
<pre><code>root
--link 1
(...)
--link 10
--link 11
(...)
--link 20
</code></pre>
<p>However, sitemap file MUST have a root which I cannot seem to suppress.</p>
<p>Any thoughts?</p>
<p>-Edoode</p>
| [
{
"answer_id": 101374,
"author": "Jeremiah Peschka",
"author_id": 11780,
"author_profile": "https://Stackoverflow.com/users/11780",
"pm_score": 2,
"selected": true,
"text": "<p>Is there any reason that you can't add a dummy root node and then subclass the ASP.NET menu control to ignore y... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6399/"
] | I'm using a ASP.NET menu control. I'd like the menu to look like this, where link 1 through 10 are in one sitemap file and link 11 through 20 in another.
```
root
--link 1
(...)
--link 10
--link 11
(...)
--link 20
```
However, sitemap file MUST have a root which I cannot seem to suppress.
Any thoughts?
-Edoode | Is there any reason that you can't add a dummy root node and then subclass the ASP.NET menu control to ignore your dummy "root" node?
You should be able to tell your SiteMapProvider to use different site maps for the menu.
The other question I have is what's the purpose of having multiple sitemap files? I'm sure you have a valid reason for this, but knowing what's going on would make it easier to understand and come up with a better solution.
That being said, I would come up with a homegrown menu system. You could use jQuery and the superfish plugin on the front end and use C# to read your site map files on the back end to build the menuing structure. |
100,444 | <p>I'm trying to automate a gdb session using the <code>--command</code> flag. I'm trying to set a breakpoint on a function in a shared library (the Unix equivalent of a DLL) . My cmds.gdb looks like this:</p>
<pre><code>set args /home/shlomi/conf/bugs/kde/font-break.txt
b IA__FcFontMatch
r
</code></pre>
<p>However, I'm getting the following:</p>
<pre>
shlomi:~/progs/bugs-external/kde/font-breaking$ gdb --command=cmds.gdb...
GNU gdb 6.8-2mdv2009.0 (Mandriva Linux release 2009.0)
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i586-mandriva-linux-gnu"...
(no debugging symbols found)
Function "IA__FcFontMatch" not defined.
Make breakpoint pending on future shared library load? (y or [n]) [answered N; input not from terminal]
</pre>
<p>So it doesn't set the breakpoint after all. How can I make it default to answer "y" to set breakpoints on pending future shared library load?</p>
<p>I recall that I was able to do something, but cannot recall what.</p>
| [
{
"answer_id": 100501,
"author": "Shlomi Fish",
"author_id": 7709,
"author_profile": "https://Stackoverflow.com/users/7709",
"pm_score": 8,
"selected": true,
"text": "<p>Replying to myself, I'd like to give the answer that someone gave me on IRC:</p>\n\n<pre>\n(gdb) apropos pending\nacti... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7709/"
] | I'm trying to automate a gdb session using the `--command` flag. I'm trying to set a breakpoint on a function in a shared library (the Unix equivalent of a DLL) . My cmds.gdb looks like this:
```
set args /home/shlomi/conf/bugs/kde/font-break.txt
b IA__FcFontMatch
r
```
However, I'm getting the following:
```
shlomi:~/progs/bugs-external/kde/font-breaking$ gdb --command=cmds.gdb...
GNU gdb 6.8-2mdv2009.0 (Mandriva Linux release 2009.0)
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i586-mandriva-linux-gnu"...
(no debugging symbols found)
Function "IA__FcFontMatch" not defined.
Make breakpoint pending on future shared library load? (y or [n]) [answered N; input not from terminal]
```
So it doesn't set the breakpoint after all. How can I make it default to answer "y" to set breakpoints on pending future shared library load?
I recall that I was able to do something, but cannot recall what. | Replying to myself, I'd like to give the answer that someone gave me on IRC:
```
(gdb) apropos pending
actions -- Specify the actions to be taken at a tracepoint
set breakpoint -- Breakpoint specific settings
set breakpoint pending -- Set debugger's behavior regarding pending breakpoints
show breakpoint -- Breakpoint specific settings
show breakpoint pending -- Show debugger's behavior regarding pending breakpoints
```
And so **set breakpoint pending on** does the trick; it is used in `cmds.gdb` like e.g.
```
set breakpoint pending on
break <source file name>:<line number>
``` |
100,504 | <p>Say I have a table called myTable. What is the SQL command to return all of the field names of this table? If the answer is database specific then I need SQL Server right now but would be interested in seeing the solution for other database systems as well.</p>
| [
{
"answer_id": 100513,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 7,
"selected": true,
"text": "<p>MySQL 3 and 4 (and 5):</p>\n\n<pre><code>desc tablename\n</code></pre>\n\n<p>which is an alias for</p>\n\n<pre><co... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1856916/"
] | Say I have a table called myTable. What is the SQL command to return all of the field names of this table? If the answer is database specific then I need SQL Server right now but would be interested in seeing the solution for other database systems as well. | MySQL 3 and 4 (and 5):
```
desc tablename
```
which is an alias for
```
show fields from tablename
```
SQL Server (from 2000) and MySQL 5:
```
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = 'tablename'
```
Completing the answer: like people below have said, in SQL Server you can also use the stored procedure `sp_help`
```
exec sp_help 'tablename'
``` |
100,533 | <p>Is it possible to do like this:</p>
<pre><code>interface IDBBase {
DataTable getDataTableSql(DataTable curTable,IDbCommand cmd);
...
}
class DBBase : IDBBase {
public DataTable getDataTableSql(DataTable curTable, SqlCommand cmd) {
...
}
}
</code></pre>
<p>I want to use the interface to implement to d/t providers (MS-SQL,Oracle...); in it there are some signatures to be implemented in the corresponding classes that implement it. I also tried like this:</p>
<pre><code>genClass<typeOj>
{
typeOj instOj;
public genClass(typeOj o)
{ instOj=o; }
public typeOj getType()
{ return instOj; }
</code></pre>
<p>...</p>
<pre><code>interface IDBBase
{
DataTable getDataTableSql(DataTable curTable,genClass<idcommand> cmd);
...
}
class DBBase : IDBBase
{
public DataTable getDataTableSql(DataTable curTable, genClass<SqlCommand> cmd)
{
...
}
}
</code></pre>
| [
{
"answer_id": 100562,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>No it's not possible. Method should have same signature that one declared in the interface.</p>\n\n<p>However you can use typ... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Is it possible to do like this:
```
interface IDBBase {
DataTable getDataTableSql(DataTable curTable,IDbCommand cmd);
...
}
class DBBase : IDBBase {
public DataTable getDataTableSql(DataTable curTable, SqlCommand cmd) {
...
}
}
```
I want to use the interface to implement to d/t providers (MS-SQL,Oracle...); in it there are some signatures to be implemented in the corresponding classes that implement it. I also tried like this:
```
genClass<typeOj>
{
typeOj instOj;
public genClass(typeOj o)
{ instOj=o; }
public typeOj getType()
{ return instOj; }
```
...
```
interface IDBBase
{
DataTable getDataTableSql(DataTable curTable,genClass<idcommand> cmd);
...
}
class DBBase : IDBBase
{
public DataTable getDataTableSql(DataTable curTable, genClass<SqlCommand> cmd)
{
...
}
}
``` | No it's not possible. Method should have same signature that one declared in the interface.
However you can use type parameter constraints:
```
interface IDBClass<T> where T:IDbCommand
{
void Test(T cmd);
}
class DBClass:IDBClass<SqlCommand>
{
public void Test(SqlCommand cmd)
{
}
}
``` |
100,624 | <p>How to wait for multiple child processes in Python on Windows, without active wait (polling)? Something like this <em>almost</em> works for me:</p>
<pre><code>proc1 = subprocess.Popen(['python','mytest.py'])
proc2 = subprocess.Popen(['python','mytest.py'])
proc1.wait()
print "1 finished"
proc2.wait()
print "2 finished"
</code></pre>
<p>The problem is that when <code>proc2</code> finishes before <code>proc1</code>, the parent process will still wait for <code>proc1</code>. On Unix one would use <code>waitpid(0)</code> in a loop to get the child processes' return codes as they finish - how to achieve something like this in Python on Windows?</p>
| [
{
"answer_id": 100886,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 5,
"selected": true,
"text": "<p>It might seem overkill, but, here it goes:</p>\n\n<pre><code>import Queue, thread, subprocess\n\nresults= Queue.Queue()\ndef ... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12166/"
] | How to wait for multiple child processes in Python on Windows, without active wait (polling)? Something like this *almost* works for me:
```
proc1 = subprocess.Popen(['python','mytest.py'])
proc2 = subprocess.Popen(['python','mytest.py'])
proc1.wait()
print "1 finished"
proc2.wait()
print "2 finished"
```
The problem is that when `proc2` finishes before `proc1`, the parent process will still wait for `proc1`. On Unix one would use `waitpid(0)` in a loop to get the child processes' return codes as they finish - how to achieve something like this in Python on Windows? | It might seem overkill, but, here it goes:
```
import Queue, thread, subprocess
results= Queue.Queue()
def process_waiter(popen, description, que):
try: popen.wait()
finally: que.put( (description, popen.returncode) )
process_count= 0
proc1= subprocess.Popen( ['python', 'mytest.py'] )
thread.start_new_thread(process_waiter,
(proc1, "1 finished", results))
process_count+= 1
proc2= subprocess.Popen( ['python', 'mytest.py'] )
thread.start_new_thread(process_waiter,
(proc2, "2 finished", results))
process_count+= 1
# etc
while process_count > 0:
description, rc= results.get()
print "job", description, "ended with rc =", rc
process_count-= 1
``` |
100,631 | <p>After our Ruby on Rails application has run for a while, it starts throwing 500s with "MySQL server has gone away". Often this happens overnight. It's started doing this recently, with no obvious change in our server configuration.</p>
<pre><code> Mysql::Error: MySQL server has gone away: SELECT * FROM `widgets`
</code></pre>
<p>Restarting the mongrels (not the MySQL server) fixes it.</p>
<p>How can we fix this?</p>
| [
{
"answer_id": 100688,
"author": "David Precious",
"author_id": 4040,
"author_profile": "https://Stackoverflow.com/users/4040",
"pm_score": 1,
"selected": false,
"text": "<p>The connection to the MySQL server is probably timing out.</p>\n\n<p>You should be able to increase the timeout in... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18666/"
] | After our Ruby on Rails application has run for a while, it starts throwing 500s with "MySQL server has gone away". Often this happens overnight. It's started doing this recently, with no obvious change in our server configuration.
```
Mysql::Error: MySQL server has gone away: SELECT * FROM `widgets`
```
Restarting the mongrels (not the MySQL server) fixes it.
How can we fix this? | This is probably caused by the persistent connections to MySQL going away (time out is likely if it's happening over night) and Ruby on Rails is failing to restore the connection, which it should be doing by default:
In the file vendor/rails/actionpack/lib/action\_controller/dispatcher.rb is the code:
```
if defined?(ActiveRecord)
before_dispatch { ActiveRecord::Base.verify_active_connections! }
to_prepare(:activerecord_instantiate_observers) {ActiveRecord::Base.instantiate_observers }
end
```
The method `verify_active_connections!` performs several actions, one of which is to recreate any expired connections.
The most likely cause of this error is that this is because a [monkey patch](https://en.wikipedia.org/wiki/Monkey_patch) has redefined the dispatcher to not call `verify_active_connections!`, or `verify_active_connections!` has been changed, etc. |
100,633 | <p>Why is it bad practice to declare variables on one line?</p>
<p>e.g.</p>
<pre><code>private String var1, var2, var3
</code></pre>
<p>instead of: </p>
<pre><code>private String var1;
private String var2;
private String var3;
</code></pre>
| [
{
"answer_id": 100639,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 3,
"selected": false,
"text": "<p>Because in some languages, var2 and var3 in your example would <em>not</em> be strings, they would be variants (untype... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15352/"
] | Why is it bad practice to declare variables on one line?
e.g.
```
private String var1, var2, var3
```
instead of:
```
private String var1;
private String var2;
private String var3;
``` | I think that there are various reasons, but they all boil down to that the first is just less readable and more prone to failure because a single line is doing more than one thing.
And all that for no real gain, and don't you tell me you find two lines of saved space is a real gain.
It's a similar thing to what happens when you have
```
if ((foo = some_function()) == 0) {
//do something
}
```
Of course this example is much worse than yours. |
100,645 | <p>Are there any tools available for calculating Cyclomatic Complexity in Javascript? </p>
<p>I've found it a very helpful metric in the past while working on server side code, and would like to be able to use it for the client side Javascript I write.</p>
| [
{
"answer_id": 198179,
"author": "kentaromiura",
"author_id": 27340,
"author_profile": "https://Stackoverflow.com/users/27340",
"pm_score": 3,
"selected": false,
"text": "<p>Since cyclomatic complexity is evaluated counting the number of keyword\n\"if, switch, while for break\" etc.. eve... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2932/"
] | Are there any tools available for calculating Cyclomatic Complexity in Javascript?
I've found it a very helpful metric in the past while working on server side code, and would like to be able to use it for the client side Javascript I write. | I helped write a tool to perform software complexity analysis on JavaScript projects:
[complexity-report](https://github.com/escomplex/complexity-report)
It reports a bunch of different complexity metrics: lines of code, number of parameters, cyclomatic complexity, cyclomatic density, Halstead complexity measures, the maintainability index, first-order density, change cost and core size.
It is released under the MIT license and built using Node.js and the [Esprima](http://esprima.org/) JavaScript parser. It can be installed via npm, like so:
```
npm i -g complexity-report
``` |
100,654 | <p>I've got a c# application that plays simple wav files through directsound. With the test data I had, the code worked fine. However when I used real-world data, it produced a very unhelpful error on creation of the secondary buffer: "ArgumentException: Value does not fall within the expected range."</p>
<p>The test wavs had a 512kbps bit rate, 16bit audio sample size, and 32kHz audio sample rate. The new wavs is 1152kbps, 24bit and 48kHz respectively. How can I get directsound to cope with these larger values, or if not how can I programatically detect these values before attempting to play the file?</p>
<p>it's managed DirectX v9.00.1126 I'm using, and I've included some sample code below:</p>
<pre><code>using DS = Microsoft.DirectX.DirectSound;
...
DS.Device device = new DS.Device();
device.SetCooperativeLevel(this, CooperativeLevel.Normal);
...
BufferDescription bufferDesc = new BufferDescription();
bufferDesc.ControlEffects = false;
...
try
{
SecondaryBuffer sound = new SecondaryBuffer(path, bufferDesc, device);
sound.Play(0, BufferPlayFlags.Default);
}
...
</code></pre>
<p>Additional info: the real-world wav files won't play in windows media player either, telling me a codec is needed to play the file, while they play fine in winamp.</p>
<p>Additional info 2: Comparing the bytes of the working test data and the bad real-world data, I can see that past the RIFF chunk, the bad data has a "bext" chunk, that the internet informs me is metadata associated with the broadcast audio extension, while the test data goes straight into a fmt chunk. There /is/ a fmt chunk in the bad data, so I don't know if it's badly-formed or if the loaders should be looking further for fmt data. I can see if I can get some information on this rouge bext chunk from the people supplying me the data - if they can remove it my code may still work.</p>
| [
{
"answer_id": 100675,
"author": "Mark Heath",
"author_id": 7532,
"author_profile": "https://Stackoverflow.com/users/7532",
"pm_score": 4,
"selected": true,
"text": "<p>Not all soundcards support 24 bit sample playback, and even when they do, they often have to be exclusively opened in t... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11801/"
] | I've got a c# application that plays simple wav files through directsound. With the test data I had, the code worked fine. However when I used real-world data, it produced a very unhelpful error on creation of the secondary buffer: "ArgumentException: Value does not fall within the expected range."
The test wavs had a 512kbps bit rate, 16bit audio sample size, and 32kHz audio sample rate. The new wavs is 1152kbps, 24bit and 48kHz respectively. How can I get directsound to cope with these larger values, or if not how can I programatically detect these values before attempting to play the file?
it's managed DirectX v9.00.1126 I'm using, and I've included some sample code below:
```
using DS = Microsoft.DirectX.DirectSound;
...
DS.Device device = new DS.Device();
device.SetCooperativeLevel(this, CooperativeLevel.Normal);
...
BufferDescription bufferDesc = new BufferDescription();
bufferDesc.ControlEffects = false;
...
try
{
SecondaryBuffer sound = new SecondaryBuffer(path, bufferDesc, device);
sound.Play(0, BufferPlayFlags.Default);
}
...
```
Additional info: the real-world wav files won't play in windows media player either, telling me a codec is needed to play the file, while they play fine in winamp.
Additional info 2: Comparing the bytes of the working test data and the bad real-world data, I can see that past the RIFF chunk, the bad data has a "bext" chunk, that the internet informs me is metadata associated with the broadcast audio extension, while the test data goes straight into a fmt chunk. There /is/ a fmt chunk in the bad data, so I don't know if it's badly-formed or if the loaders should be looking further for fmt data. I can see if I can get some information on this rouge bext chunk from the people supplying me the data - if they can remove it my code may still work. | Not all soundcards support 24 bit sample playback, and even when they do, they often have to be exclusively opened in that mode. There is a similar issue with sample rates. Your soundcard may be operating at 44.1kHz, in which case 48kHz needs to be resampled to be played.
I have written an open source .NET audio library called [NAudio](http://www.codeplex.com/naudio) which will allow you to find out what sample rate and bit depth a given WAV file is. It also offers alternative ways of playing back audio (e.g. through the Wav... APIs), and the ability to resample files using the DMO resampler object. |
100,678 | <pre><code>LRESULT result = ::SendMessage(hWnd, s_MaxGetTaskInterface, (WPARAM)&pUnkReturn, 0);
</code></pre>
<p>The value of result after the call is 0</p>
<p>I expect it to return with a valid value of pUnkReturn , but it returns with a NULL value .</p>
<p>Necessary Information before this call :</p>
<pre><code>const UINT CMotionUtils::s_MaxGetTaskInterface = RegisterWindowMessage(_T("NI:Max:GetTaskInterface"));
</code></pre>
<p>The value of <code>s_MaxGetTaskInterface</code> i get here is 49896 . </p>
<p>The value of hWnd is also proper . I checked that with Spy++ ( Visual Studio tool ) .</p>
<p>Microft Spy++ Messages window shows me the following for this window . </p>
<pre><code><00001> 009F067C S message:0xC2E8 [Registered:"NI:Max:GetTaskInterface"]wParam:0224C2D0 lParam:00000000
<00002> 009F067C S message:0xC2E8 [Registered:"NI:Max:GetTaskInterface"]lResult:00000000
</code></pre>
<p>Please help me to get a valid address stored in pUnkReturn after the call . </p>
| [
{
"answer_id": 100692,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 0,
"selected": false,
"text": "<p>When I Googled for <code>NI:Max:GetTaskInterface</code> I couldn't find anything. In general, how a window will handle a ... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
LRESULT result = ::SendMessage(hWnd, s_MaxGetTaskInterface, (WPARAM)&pUnkReturn, 0);
```
The value of result after the call is 0
I expect it to return with a valid value of pUnkReturn , but it returns with a NULL value .
Necessary Information before this call :
```
const UINT CMotionUtils::s_MaxGetTaskInterface = RegisterWindowMessage(_T("NI:Max:GetTaskInterface"));
```
The value of `s_MaxGetTaskInterface` i get here is 49896 .
The value of hWnd is also proper . I checked that with Spy++ ( Visual Studio tool ) .
Microft Spy++ Messages window shows me the following for this window .
```
<00001> 009F067C S message:0xC2E8 [Registered:"NI:Max:GetTaskInterface"]wParam:0224C2D0 lParam:00000000
<00002> 009F067C S message:0xC2E8 [Registered:"NI:Max:GetTaskInterface"]lResult:00000000
```
Please help me to get a valid address stored in pUnkReturn after the call . | I think the & in &pUnkReturn is needed, based on the hungarian prefix. I expect pUnkReturn to have type IUnknown\*. The message receiver will provide the IUnknown\*. The address where it will store that IUnknown\* is an IUnknown\*\*. Hence, this code passes in &pUnkReturn and the message receiver writes to \*(IUnknown\*\*)wParam. |
100,689 | <p>I have a problem that confuses my users, being that although an item is highlighted (by the hover style) when the user mouses over it, they have to mouse over the actual item text, sometimes quite small compared to the item. Is there a way to make the whole item clickable?</p>
| [
{
"answer_id": 100706,
"author": "David Heggie",
"author_id": 4309,
"author_profile": "https://Stackoverflow.com/users/4309",
"pm_score": 3,
"selected": true,
"text": "<p>Add some padding to the A element? Or if it's in a menu contained within a block-level element, make the A display as... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] | I have a problem that confuses my users, being that although an item is highlighted (by the hover style) when the user mouses over it, they have to mouse over the actual item text, sometimes quite small compared to the item. Is there a way to make the whole item clickable? | Add some padding to the A element? Or if it's in a menu contained within a block-level element, make the A display as block too:
```
a {
display: block;
width: 100%;
}
``` |
100,721 | <p>I am using <code>DirectoryInfo.GetDirectories()</code> recursively to find the all the sub-directories under a given path.
However, I want to exclude the System folders and there is no clear way for that.
In FindFirstFile/FindNextFile things were clearer with the attributes.</p>
| [
{
"answer_id": 100760,
"author": "rslite",
"author_id": 15682,
"author_profile": "https://Stackoverflow.com/users/15682",
"pm_score": 0,
"selected": false,
"text": "<p>You'd probably have to loop through the results and reject those with the attributes that you don't want (use the Attrib... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am using `DirectoryInfo.GetDirectories()` recursively to find the all the sub-directories under a given path.
However, I want to exclude the System folders and there is no clear way for that.
In FindFirstFile/FindNextFile things were clearer with the attributes. | @rslite is right, .NET doesn't give such filtering out-of-box, but it's not hard to implement:
```
static IEnumerable<string> GetNonSystemDirs(string path)
{
var dirs = from d in Directory.GetDirectories(path)
let inf = new DirectoryInfo(d)
where (inf.Attributes & FileAttributes.System) == 0
select d;
foreach (var dir in dirs)
{
yield return dir;
foreach (var subDir in GetNonSystemDirs(dir))
{
yield return subDir;
}
}
}
```
MSDN links:
[FileSystemInfo.Attributes Property](http://msdn.microsoft.com/en-us/library/system.io.filesysteminfo.attributes.aspx)
[FileAttributes Enumeration](http://msdn.microsoft.com/en-us/library/system.io.fileattributes.aspx) |
100,732 | <p>I've seen several examples of code like this:</p>
<pre><code>if not someobj:
#do something
</code></pre>
<p>But I'm wondering why not doing:</p>
<pre><code>if someobj == None:
#do something
</code></pre>
<p>Is there any difference? Does one have an advantage over the other?</p>
| [
{
"answer_id": 100762,
"author": "Sylvain Defresne",
"author_id": 5353,
"author_profile": "https://Stackoverflow.com/users/5353",
"pm_score": 9,
"selected": true,
"text": "<p>In the first test, Python try to convert the object to a <code>bool</code> value if it is not already one. Roughl... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10708/"
] | I've seen several examples of code like this:
```
if not someobj:
#do something
```
But I'm wondering why not doing:
```
if someobj == None:
#do something
```
Is there any difference? Does one have an advantage over the other? | In the first test, Python try to convert the object to a `bool` value if it is not already one. Roughly, **we are asking the object : are you meaningful or not ?** This is done using the following algorithm :
1. If the object has a `__nonzero__` special method (as do numeric built-ins, `int` and `float`), it calls this method. It must either return a `bool` value which is then directly used, or an `int` value that is considered `False` if equal to zero.
2. Otherwise, if the object has a `__len__` special method (as do container built-ins, `list`, `dict`, `set`, `tuple`, ...), it calls this method, considering a container `False` if it is empty (length is zero).
3. Otherwise, the object is considered `True` unless it is `None` in which case, it is considered `False`.
In the second test, the object is compared for equality to `None`. Here, **we are asking the object, "Are you equal to this other value?"** This is done using the following algorithm :
1. If the object has a `__eq__` method, it is called, and the return value is then converted to a `bool`value and used to determine the outcome of the `if`.
2. Otherwise, if the object has a `__cmp__` method, it is called. This function must return an `int` indicating the order of the two object (`-1` if `self < other`, `0` if `self == other`, `+1` if `self > other`).
3. Otherwise, the object are compared for identity (ie. they are reference to the same object, as can be tested by the `is` operator).
There is another test possible using the `is` operator. **We would be asking the object, "Are you this particular object?"**
Generally, I would recommend to use the first test with non-numerical values, to use the test for equality when you want to compare objects of the same nature (two strings, two numbers, ...) and to check for identity only when using sentinel values (`None` meaning not initialized for a member field for exemple, or when using the `getattr` or the `__getitem__` methods).
To summarize, we have :
```
>>> class A(object):
... def __repr__(self):
... return 'A()'
... def __nonzero__(self):
... return False
>>> class B(object):
... def __repr__(self):
... return 'B()'
... def __len__(self):
... return 0
>>> class C(object):
... def __repr__(self):
... return 'C()'
... def __cmp__(self, other):
... return 0
>>> class D(object):
... def __repr__(self):
... return 'D()'
... def __eq__(self, other):
... return True
>>> for obj in ['', (), [], {}, 0, 0., A(), B(), C(), D(), None]:
... print '%4s: bool(obj) -> %5s, obj == None -> %5s, obj is None -> %5s' % \
... (repr(obj), bool(obj), obj == None, obj is None)
'': bool(obj) -> False, obj == None -> False, obj is None -> False
(): bool(obj) -> False, obj == None -> False, obj is None -> False
[]: bool(obj) -> False, obj == None -> False, obj is None -> False
{}: bool(obj) -> False, obj == None -> False, obj is None -> False
0: bool(obj) -> False, obj == None -> False, obj is None -> False
0.0: bool(obj) -> False, obj == None -> False, obj is None -> False
A(): bool(obj) -> False, obj == None -> False, obj is None -> False
B(): bool(obj) -> False, obj == None -> False, obj is None -> False
C(): bool(obj) -> True, obj == None -> True, obj is None -> False
D(): bool(obj) -> True, obj == None -> True, obj is None -> False
None: bool(obj) -> False, obj == None -> True, obj is None -> True
``` |
100,774 | <p>The following JavaScript supposes to read the popular tags from an XML file and applies the XSL Stylesheet and output to the browser as HTML.</p>
<pre><code>function ShowPopularTags() {
xml = XMLDocLoad("http://localhost/xml/tags/popular.xml?s=94987898");
xsl = XMLDocLoad("http://localhost/xml/xsl/popular-tags.xsl");
if (window.ActiveXObject) {
// code for IE
ex = xml.transformNode(xsl);
ex = ex.replace(/\\/g, "");
document.getElementById("popularTags").innerHTML = ex;
} else if (document.implementation && document.implementation.createDocument) {
// code for Mozilla, Firefox, Opera, etc.
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml, document);
document.getElementById("popularTags").appendChild(resultDocument);
var ihtml = document.getElementById("popularTags").innerHTML;
ihtml = ihtml.replace(/\\/g, "");
document.getElementById("popularTags").innerHTML = ihtml;
}
}
ShowPopularTags();
</code></pre>
<p>The issue with this script is sometime it manages to output the resulting HTML code, sometime it doesn't. Anyone knows where is going wrong?</p>
| [
{
"answer_id": 100887,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 0,
"selected": false,
"text": "<p>Well, that code follows entirely different paths for IE and everything-else. I assume the problem is limited to one of them... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17074/"
] | The following JavaScript supposes to read the popular tags from an XML file and applies the XSL Stylesheet and output to the browser as HTML.
```
function ShowPopularTags() {
xml = XMLDocLoad("http://localhost/xml/tags/popular.xml?s=94987898");
xsl = XMLDocLoad("http://localhost/xml/xsl/popular-tags.xsl");
if (window.ActiveXObject) {
// code for IE
ex = xml.transformNode(xsl);
ex = ex.replace(/\\/g, "");
document.getElementById("popularTags").innerHTML = ex;
} else if (document.implementation && document.implementation.createDocument) {
// code for Mozilla, Firefox, Opera, etc.
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml, document);
document.getElementById("popularTags").appendChild(resultDocument);
var ihtml = document.getElementById("popularTags").innerHTML;
ihtml = ihtml.replace(/\\/g, "");
document.getElementById("popularTags").innerHTML = ihtml;
}
}
ShowPopularTags();
```
The issue with this script is sometime it manages to output the resulting HTML code, sometime it doesn't. Anyone knows where is going wrong? | Are you forced into the synchronous solution you are using now, or is an asynchronous solution an option as well? I recall Firefox has had it's share of problems with synchronous calls in the past, and I don't know how much of that is still carried with it. I have seen situations where the entire Firefox interface would lock up for as long as the request was running (which, depending on timeout settings, can take a very long time).
It would require a bit more work on your end, but the solution would be something like the following. This is the code I use for handling XSLT stuff with Ajax (rewrote it slightly because my code is object oriented and contains a loop that parses out the appropriate XSL document from the XML document first loaded)
Note: make sure you declare your version of oCurrentRequest and oXMLRequest outside of the functions, since it will be carried over.
```
if (window.XMLHttpRequest)
{
oCurrentRequest = new XMLHttpRequest();
oCurrentRequest.onreadystatechange = processReqChange;
oCurrentRequest.open('GET', sURL, true);
oCurrentRequest.send(null);
}
else if (window.ActiveXObject)
{
oCurrentRequest = new ActiveXObject('Microsoft.XMLHTTP');
if (oCurrentRequest)
{
oCurrentRequest.onreadystatechange = processReqChange;
oCurrentRequest.open('GET', sURL, true);
oCurrentRequest.send();
}
}
```
After this you'd just need a function named processReqChange that contains something like the following:
```
function processReqChange()
{
if (oCurrentRequest.readyState == 4)
{
if (oCurrentRequest.status == 200)
{
oXMLRequest = oCurrentRequest;
oCurrentRequest = null;
loadXSLDoc();
}
}
}
```
And ofcourse you'll need to produce a second set of functions to handle the XSL loading (starting from loadXSLDoc on, for example).
Then at the end of you processXSLReqChange you can grab your XML result and XSL result and do the transformation. |
100,808 | <p>I want to receive the following <code>HTTP</code> request in <code>PHP:</code></p>
<pre><code>Content-type: multipart/form-data;boundary=main_boundary
--main_boundary
Content-type: text/xml
<?xml version='1.0'?>
<content>
Some content goes here
</content>
--main_boundary
Content-type: multipart/mixed;boundary=sub_boundary
--sub_boundary
Content-type: application/octet-stream
File A contents
--sub_boundary
Content-type: application/octet-stream
File B contents
--sub_boundary
--main_boundary--
</code></pre>
<p>(Note: I have indented the sub-parts only to make it more readable for this post.)</p>
<p>I'm not very fluent in PHP and would like to get some help/pointers to figure out how to receive this kind of multipart form request in PHP code. I have once written some code where I received a standard HTML form and then I could access the form elements by using their name as index key in the <code>$HTTP_GET_VARS</code> array, but in this case there are no form element names, and the form data parts are not linear (i.e. sub parts = multilevel array).</p>
<p>Grateful for any help!</p>
<p>/Robert</p>
| [
{
"answer_id": 100825,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": -1,
"selected": false,
"text": "<p>Uploadeds files will be accessible through the $_FILE global variable, other parameters will be accessible trough the $_GE... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7891/"
] | I want to receive the following `HTTP` request in `PHP:`
```
Content-type: multipart/form-data;boundary=main_boundary
--main_boundary
Content-type: text/xml
<?xml version='1.0'?>
<content>
Some content goes here
</content>
--main_boundary
Content-type: multipart/mixed;boundary=sub_boundary
--sub_boundary
Content-type: application/octet-stream
File A contents
--sub_boundary
Content-type: application/octet-stream
File B contents
--sub_boundary
--main_boundary--
```
(Note: I have indented the sub-parts only to make it more readable for this post.)
I'm not very fluent in PHP and would like to get some help/pointers to figure out how to receive this kind of multipart form request in PHP code. I have once written some code where I received a standard HTML form and then I could access the form elements by using their name as index key in the `$HTTP_GET_VARS` array, but in this case there are no form element names, and the form data parts are not linear (i.e. sub parts = multilevel array).
Grateful for any help!
/Robert | `$HTTP_GET_VARS`, `$HTTP_POST_VARS`, etc. is an obsolete notation, you should be using `$_GET`, `$_POST`, etc.
Now, the file contents should be in the `$_FILES` global array, whereas, if there are no element names, I'm not sure about whether the rest of the content will show up in `$_POST`. Anyway, if `always_populate_raw_post_data` setting is true in *php.ini*, the data should be in `$HTTP_RAW_POST_DATA`. Also, the whole request should show up when reading *php://input*. |
100,812 | <p>Not for the first time, I've accidentally done "svn switch" from somewhere below the root of my project. This switches that subdirectory only, but how do I undo this?</p>
<p>If I try switching the subdirectory back to the original branch I get:</p>
<pre><code>"svn: Directory 'subdir\_svn' containing working copy admin area is missing"
</code></pre>
<p><strong>Update</strong>: I've got changes in the subdir, so I don't want to do a delete. </p>
<p>In the short term I've fixed it by reapplying the changes, but I was after a way to get Subversion to re-switch back to where I came from... or is this a missing feature?</p>
| [
{
"answer_id": 100823,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 3,
"selected": false,
"text": "<p>Quick hack: Delete the directory, go one level up, and run svn update.</p>\n"
},
{
"answer_id": 100870,
"... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17641/"
] | Not for the first time, I've accidentally done "svn switch" from somewhere below the root of my project. This switches that subdirectory only, but how do I undo this?
If I try switching the subdirectory back to the original branch I get:
```
"svn: Directory 'subdir\_svn' containing working copy admin area is missing"
```
**Update**: I've got changes in the subdir, so I don't want to do a delete.
In the short term I've fixed it by reapplying the changes, but I was after a way to get Subversion to re-switch back to where I came from... or is this a missing feature? | Quick hack: Delete the directory, go one level up, and run svn update. |
100,824 | <p>The code below shows a sample that I've used recently to explain the different behaviour of structs and classes to someone brand new to development. Is there a better way of doing so? (Yes - the code uses public fields - that's purely for brevity)</p>
<pre><code>namespace StructsVsClasses
{
class Program
{
static void Main(string[] args)
{
sampleStruct struct1 = new sampleStruct();
struct1.IntegerValue = 3;
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
sampleStruct struct2 = struct1;
Console.WriteLine();
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);
struct1.IntegerValue = 5;
Console.WriteLine();
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);
sampleClass class1 = new sampleClass();
class1.IntegerValue = 3;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
sampleClass class2 = class1;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);
class1.IntegerValue = 5;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);
Console.ReadKey();
}
}
struct sampleStruct
{
public int IntegerValue;
}
class sampleClass
{
public int IntegerValue;
}
}
</code></pre>
| [
{
"answer_id": 100856,
"author": "Grimtron",
"author_id": 17378,
"author_profile": "https://Stackoverflow.com/users/17378",
"pm_score": 1,
"selected": false,
"text": "<p>I guess it's OK to show the difference as far as value/reference types are concerned this way. It might be a little bi... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7872/"
] | The code below shows a sample that I've used recently to explain the different behaviour of structs and classes to someone brand new to development. Is there a better way of doing so? (Yes - the code uses public fields - that's purely for brevity)
```
namespace StructsVsClasses
{
class Program
{
static void Main(string[] args)
{
sampleStruct struct1 = new sampleStruct();
struct1.IntegerValue = 3;
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
sampleStruct struct2 = struct1;
Console.WriteLine();
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);
struct1.IntegerValue = 5;
Console.WriteLine();
Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);
sampleClass class1 = new sampleClass();
class1.IntegerValue = 3;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
sampleClass class2 = class1;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);
class1.IntegerValue = 5;
Console.WriteLine();
Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);
Console.ReadKey();
}
}
struct sampleStruct
{
public int IntegerValue;
}
class sampleClass
{
public int IntegerValue;
}
}
``` | The difference might be easier to understand when the struct/class is a member of another class.
Example with class:
```
class PointClass {
int double X;
int double Y;
}
class Circle {
PointClass Center = new PointClass() { X = 0, Y = 0; }
}
static void Main() {
Circle c = new Circle();
Console.WriteLine(c.Center.X);
c.Center.X = 42;
Console.WriteLine(c.Center.X);
}
```
Output:
```
0
42
```
Example with struct:
```
struct Point {
int double X;
int double Y;
}
class Circle {
PointStruct Center = new PointStruct() { X = 0, Y = 0; }
}
static void Main() {
Circle c = new Circle();
Console.WriteLine(c.Center.X);
c.Center.X = 42;
Console.WriteLine(c.Center.X);
}
```
Output:
```
0
0
``` |
100,829 | <p>I'm trying to write a script to allow me to log in to a console servers 48 ports so that I can quickly determine what devices are connected to each serial line.</p>
<p>Essentially I want to be able to have a script that, given a list of hosts/ports, telnets to the first device in the list and leaves me in interactive mode so that I can log in and confirm the device, then when I close the telnet session, connects to the next session in the list.</p>
<p>The problem I'm facing is that if I start a telnet session from within an executable bash script, the session terminates immediately, rather than waiting for input.</p>
<p>For example, given the following code:</p>
<pre><code>$ cat ./telnetTest.sh
#!/bin/bash
while read line
do
telnet $line
done
$
</code></pre>
<p>When I run the command 'echo "hostname" | testscript.sh' I receive the following output:</p>
<pre><code>$ echo "testhost" | ./telnetTest.sh
Trying 192.168.1.1...
Connected to testhost (192.168.1.1).
Escape character is '^]'.
Connection closed by foreign host.
$
</code></pre>
<p>Does anyone know of a way to stop the telnet session being closed automatically?</p>
| [
{
"answer_id": 100842,
"author": "stephanea",
"author_id": 8776,
"author_profile": "https://Stackoverflow.com/users/8776",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps you could try bash -i to force the session to be in interactive mode.</p>\n"
},
{
"answer_id": 100879,
... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6306/"
] | I'm trying to write a script to allow me to log in to a console servers 48 ports so that I can quickly determine what devices are connected to each serial line.
Essentially I want to be able to have a script that, given a list of hosts/ports, telnets to the first device in the list and leaves me in interactive mode so that I can log in and confirm the device, then when I close the telnet session, connects to the next session in the list.
The problem I'm facing is that if I start a telnet session from within an executable bash script, the session terminates immediately, rather than waiting for input.
For example, given the following code:
```
$ cat ./telnetTest.sh
#!/bin/bash
while read line
do
telnet $line
done
$
```
When I run the command 'echo "hostname" | testscript.sh' I receive the following output:
```
$ echo "testhost" | ./telnetTest.sh
Trying 192.168.1.1...
Connected to testhost (192.168.1.1).
Escape character is '^]'.
Connection closed by foreign host.
$
```
Does anyone know of a way to stop the telnet session being closed automatically? | You need to redirect the Terminal input to the `telnet` process. This should be `/dev/tty`. So your script will look something like:
```
#!/bin/bash
for HOST in `cat`
do
echo Connecting to $HOST...
telnet $HOST </dev/tty
done
``` |
100,832 | <p>I would like to repeatedly capture snippets of audio on a Nokia mobile phone with a Java Midlet. My current experience is that using the code in Sun's documentation (see: <a href="http://java.sun.com/javame/reference/apis/jsr135/javax/microedition/media/control/RecordControl.html" rel="nofollow noreferrer">http://java.sun.com/javame/reference/apis/jsr135/javax/microedition/media/control/RecordControl.html</a>) and wrapping this in a "while(true)" loop works, but the application slowly consumes all the memory on the phone and the program eventually throws an exception and fails to initiate further recordings.</p>
<p>The consumed memory isn't Java heap memory---my example program (below) shows that Java memory stays roughly static at around 185,000 bytes---but there is some kind of memory leak in the underlying supporting library provided by Nokia; I believe the memory leak occurs because if you try and start another (non-Java) application (e.g. web browser) after running the Java application for a while, the phone kills that application with a warning about lack of memory.</p>
<p>I've tried several different approaches from that taken by Sun's canonical example in the documentation (initialize everything each time round the loop, initialize as much as possible only once, call as many of the deallocate-style functions which shouldn't be strictly necessary etc.). None appear to be successful. Below is a simple example program which I believe should work, but crashes after running for 15 minutes or so on both the N80 (despite a firmware update) and N95. Other forums report this problem too, but the solutions presented there do not appear to work (for example, see: <a href="http://discussion.forum.nokia.com/forum/showthread.php?t=129876" rel="nofollow noreferrer">http://discussion.forum.nokia.com/forum/showthread.php?t=129876</a>).</p>
<pre><code>import javax.microedition.media.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class Standalone extends MIDlet {
protected void startApp() {
final Form form = new Form("Test audio recording");
final StringItem status = new StringItem("Status","");
form.append(status);
final Command exit = new Command("Exit", Command.EXIT, 1);
form.addCommand(exit);
form.setCommandListener(new CommandListener() {
public void commandAction(Command cmd, Displayable disp) {
if (cmd == exit) {
destroyApp(false);
notifyDestroyed();
}
}
});
Thread t = new Thread(){
public void run() {
int counter = 0;
while(true) {
//Code cut 'n' paste from Sun JSR135 javadocs for RecordControl:
try {
Player p = Manager.createPlayer("capture://audio");
p.realize();
RecordControl rc = (RecordControl)p.getControl("RecordControl");
ByteArrayOutputStream output = new ByteArrayOutputStream();
rc.setRecordStream(output);
rc.startRecord();
p.start();
Thread.currentThread().sleep(5000);
rc.commit();
p.close();
} catch (Exception e) {
status.setText("completed "+counter+
" T="+Runtime.getRuntime().totalMemory()+
" F="+Runtime.getRuntime().freeMemory()+
": Error: "+e);
break;
}
counter++;
status.setText("completed "+counter+
" T="+Runtime.getRuntime().totalMemory()+
" F="+Runtime.getRuntime().freeMemory());
System.gc(); //One forum post suggests this, but doesn't help
this.yield();
}
}
};
t.start();
final Display display = Display.getDisplay(this);
display.setCurrent(form);
}
protected void pauseApp() {}
protected void destroyApp(boolean bool) {}
}
</code></pre>
| [
{
"answer_id": 100871,
"author": "Sarien",
"author_id": 1994377,
"author_profile": "https://Stackoverflow.com/users/1994377",
"pm_score": 0,
"selected": false,
"text": "<p>I think you should file a bugreport instead of trying to work around that.</p>\n"
},
{
"answer_id": 109485,
... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18699/"
] | I would like to repeatedly capture snippets of audio on a Nokia mobile phone with a Java Midlet. My current experience is that using the code in Sun's documentation (see: <http://java.sun.com/javame/reference/apis/jsr135/javax/microedition/media/control/RecordControl.html>) and wrapping this in a "while(true)" loop works, but the application slowly consumes all the memory on the phone and the program eventually throws an exception and fails to initiate further recordings.
The consumed memory isn't Java heap memory---my example program (below) shows that Java memory stays roughly static at around 185,000 bytes---but there is some kind of memory leak in the underlying supporting library provided by Nokia; I believe the memory leak occurs because if you try and start another (non-Java) application (e.g. web browser) after running the Java application for a while, the phone kills that application with a warning about lack of memory.
I've tried several different approaches from that taken by Sun's canonical example in the documentation (initialize everything each time round the loop, initialize as much as possible only once, call as many of the deallocate-style functions which shouldn't be strictly necessary etc.). None appear to be successful. Below is a simple example program which I believe should work, but crashes after running for 15 minutes or so on both the N80 (despite a firmware update) and N95. Other forums report this problem too, but the solutions presented there do not appear to work (for example, see: <http://discussion.forum.nokia.com/forum/showthread.php?t=129876>).
```
import javax.microedition.media.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class Standalone extends MIDlet {
protected void startApp() {
final Form form = new Form("Test audio recording");
final StringItem status = new StringItem("Status","");
form.append(status);
final Command exit = new Command("Exit", Command.EXIT, 1);
form.addCommand(exit);
form.setCommandListener(new CommandListener() {
public void commandAction(Command cmd, Displayable disp) {
if (cmd == exit) {
destroyApp(false);
notifyDestroyed();
}
}
});
Thread t = new Thread(){
public void run() {
int counter = 0;
while(true) {
//Code cut 'n' paste from Sun JSR135 javadocs for RecordControl:
try {
Player p = Manager.createPlayer("capture://audio");
p.realize();
RecordControl rc = (RecordControl)p.getControl("RecordControl");
ByteArrayOutputStream output = new ByteArrayOutputStream();
rc.setRecordStream(output);
rc.startRecord();
p.start();
Thread.currentThread().sleep(5000);
rc.commit();
p.close();
} catch (Exception e) {
status.setText("completed "+counter+
" T="+Runtime.getRuntime().totalMemory()+
" F="+Runtime.getRuntime().freeMemory()+
": Error: "+e);
break;
}
counter++;
status.setText("completed "+counter+
" T="+Runtime.getRuntime().totalMemory()+
" F="+Runtime.getRuntime().freeMemory());
System.gc(); //One forum post suggests this, but doesn't help
this.yield();
}
}
};
t.start();
final Display display = Display.getDisplay(this);
display.setCurrent(form);
}
protected void pauseApp() {}
protected void destroyApp(boolean bool) {}
}
``` | There is a known memory leak with the N-series Nokia devices. It is not specific to Java and is in the underbelly of the OS somewhere.
Recently working on a game that targeted the Nokia N90, I had similar problems. I would run into memory problems that would accumulate over several different restarts of the application. The solution was just to reduce the overall quality and the amount of resources in the game...
I would recommend attempting to update your firmware as newer versions supposedly address this problem. However, Nokia does not make it very easy to upgrade the firmware, in most cases you have to send the device off to Nokia. And, if this app is not just for your own personal use, you have to expect anyone using the N-series devices to not have the latest firmware.
Finally, I would recommend spending some time looking around Forum Nokia as I know there are posts related to memory leaks and the N-series devices. Here is a post that seems to address the problem you are having.
<http://discussion.forum.nokia.com/forum/showthread.php?t=123486> |
100,853 | <p>While editing an aspx file I found both these opening tags used for seemingly the same thing. Is there a difference and if yes, what is it?</p>
| [
{
"answer_id": 100875,
"author": "Sergio Acosta",
"author_id": 2954,
"author_profile": "https://Stackoverflow.com/users/2954",
"pm_score": 1,
"selected": false,
"text": "<p>The difference is that the # symbol specifies a data binding directive, that is resolved at data binding time (for ... | 2008/09/19 | [
"https://Stackoverflow.com/questions/100853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5018/"
] | While editing an aspx file I found both these opening tags used for seemingly the same thing. Is there a difference and if yes, what is it? | `<%=` is a equivalent to `<% Repsonse.Write()`
You can write any content out here: for example
```
<%=myProperty + " additional Text" %>
```
`<%#` is a binding expression. You can retrieve any public value in the current context (for example in GridViews). But you cannot mix content here.
Take a look at [MSDN](http://msdn.microsoft.com/en-us/library/ms178366.aspx) for more information. |