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 |
|---|---|---|---|---|---|---|
70,405 | <p>I'm doing simple string input parsing and I am in need of a string tokenizer. I am new to C# but have programmed Java, and it seems natural that C# should have a string tokenizer. Does it? Where is it? How do I use it?</p>
| [
{
"answer_id": 70413,
"author": "Steve Morgan",
"author_id": 5806,
"author_profile": "https://Stackoverflow.com/users/5806",
"pm_score": 2,
"selected": false,
"text": "<p>I think the nearest in the .NET Framework is </p>\n\n<pre>\nstring.Split()\n</pre>\n"
},
{
"answer_id": 70425... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] | I'm doing simple string input parsing and I am in need of a string tokenizer. I am new to C# but have programmed Java, and it seems natural that C# should have a string tokenizer. Does it? Where is it? How do I use it? | You could use [String.Split method](http://msdn.microsoft.com/en-us/library/system.string.split.aspx "String.Split method msdn reference").
```
class ExampleClass
{
public ExampleClass()
{
string exampleString = "there is a cat";
// Split string on spaces. This will separate all the words in a string
string[] words = exampleString.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word);
// there
// is
// a
// cat
}
}
}
```
For more information see [Sam Allen's article about splitting strings in c#](http://www.dotnetperls.com/split "C# Split String Examples by Sam Allen") (Performance, Regex) |
70,417 | <p>I have the following code:</p>
<pre><code>Dim obj As New Access.Application
obj.OpenCurrentDatabase (CurrentProject.Path & "\Working.mdb")
obj.Run "Routine"
obj.CloseCurrentDatabase
Set obj = Nothing
</code></pre>
<p>The problem I'm experimenting is a pop-up that tells me Access can't set the focus on the other database. As you can see from the code, I want to run a Subroutine in another mdb. Any other way to achieve this will be appreciated.</p>
<p>I'm working with MS Access 2003.</p>
<p>This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened.</p>
<p>I suspect this may occur when someone is working with this or the other database.</p>
<p>The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database.</p>
<p>Maybe, it's because of the first line in the 'Routines' code:
If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then
Exit Function
End If</p>
<p>I'll make another subroutine without the MsgBox.</p>
<p>I've been able to reproduce this behaviour. It happens when the focus has to shift to the called database, but the user sets the focus ([ALT]+[TAB]) on the first database. The 'solution' was to educate the user.</p>
<hr>
<p>This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened.</p>
<p>I suspect this may occur when someone is working with this or the other database.</p>
<p>The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database.</p>
<p>Maybe, it's because of the first line in the 'Routines' code:
If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then
Exit Function
End If</p>
<p>I'll make another subroutine without the MsgBox.</p>
<hr>
<p>I've tried this in our development database and it works. This doesn't mean anything as the other code also workes fine in development.</p>
| [
{
"answer_id": 70413,
"author": "Steve Morgan",
"author_id": 5806,
"author_profile": "https://Stackoverflow.com/users/5806",
"pm_score": 2,
"selected": false,
"text": "<p>I think the nearest in the .NET Framework is </p>\n\n<pre>\nstring.Split()\n</pre>\n"
},
{
"answer_id": 70425... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11498/"
] | I have the following code:
```
Dim obj As New Access.Application
obj.OpenCurrentDatabase (CurrentProject.Path & "\Working.mdb")
obj.Run "Routine"
obj.CloseCurrentDatabase
Set obj = Nothing
```
The problem I'm experimenting is a pop-up that tells me Access can't set the focus on the other database. As you can see from the code, I want to run a Subroutine in another mdb. Any other way to achieve this will be appreciated.
I'm working with MS Access 2003.
This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened.
I suspect this may occur when someone is working with this or the other database.
The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database.
Maybe, it's because of the first line in the 'Routines' code:
If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then
Exit Function
End If
I'll make another subroutine without the MsgBox.
I've been able to reproduce this behaviour. It happens when the focus has to shift to the called database, but the user sets the focus ([ALT]+[TAB]) on the first database. The 'solution' was to educate the user.
---
This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened.
I suspect this may occur when someone is working with this or the other database.
The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database.
Maybe, it's because of the first line in the 'Routines' code:
If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then
Exit Function
End If
I'll make another subroutine without the MsgBox.
---
I've tried this in our development database and it works. This doesn't mean anything as the other code also workes fine in development. | You could use [String.Split method](http://msdn.microsoft.com/en-us/library/system.string.split.aspx "String.Split method msdn reference").
```
class ExampleClass
{
public ExampleClass()
{
string exampleString = "there is a cat";
// Split string on spaces. This will separate all the words in a string
string[] words = exampleString.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word);
// there
// is
// a
// cat
}
}
}
```
For more information see [Sam Allen's article about splitting strings in c#](http://www.dotnetperls.com/split "C# Split String Examples by Sam Allen") (Performance, Regex) |
70,455 | <p>I want to port data from one server's database to another server's database.
The databases are both on a different mssql 2005 server.
Replication is probably not an option since the destination database is generated from scratch on a [time interval] basis.</p>
<p>Preferebly I would do something like</p>
<pre><code>insert *
from db1/table1
into db2/table2
where rule1 = true
</code></pre>
<p>It's obvious that connection credentials would go in somehwere in this script.</p>
| [
{
"answer_id": 70464,
"author": "Thomas Rushton",
"author_id": 6977,
"author_profile": "https://Stackoverflow.com/users/6977",
"pm_score": 0,
"selected": false,
"text": "<p>Can you use the Data Transformation Services to do the job? This provides all sorts of bolt-together tools for doi... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] | I want to port data from one server's database to another server's database.
The databases are both on a different mssql 2005 server.
Replication is probably not an option since the destination database is generated from scratch on a [time interval] basis.
Preferebly I would do something like
```
insert *
from db1/table1
into db2/table2
where rule1 = true
```
It's obvious that connection credentials would go in somehwere in this script. | I think what you want to do is create a linked server as per [this webarchive snapshot of msdn article from 2015](http://web.archive.org/web/20150628090613/https://msdn.microsoft.com/en-us/library/aa213778(SQL.80).aspx) or [this article from learn.microsoft.com](https://learn.microsoft.com/en-us/sql/relational-databases/linked-servers/create-linked-servers-sql-server-database-engine?view=sql-server-ver15). You would then select using a 4 part object name eg:
```
Select * From ServerName.DbName.SchemaName.TableName
``` |
70,471 | <p>So, I have willfully kept myself a Java n00b until recently, and my first real exposure brought about a minor shock: Java does not have C# style properties!</p>
<p>Ok, I can live with that. However, I can also swear that I have seen property getter/setter code in Java in one codebase, but I cannot remember where. How was that achieved? Is there a language extension for that? Is it related to NetBeans or something?</p>
| [
{
"answer_id": 70519,
"author": "Mark Embling",
"author_id": 6844,
"author_profile": "https://Stackoverflow.com/users/6844",
"pm_score": 2,
"selected": false,
"text": "<p>My Java experience is not that high either, so anyone feel free to correct me. But AFAIK, the general convention is t... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/227/"
] | So, I have willfully kept myself a Java n00b until recently, and my first real exposure brought about a minor shock: Java does not have C# style properties!
Ok, I can live with that. However, I can also swear that I have seen property getter/setter code in Java in one codebase, but I cannot remember where. How was that achieved? Is there a language extension for that? Is it related to NetBeans or something? | There is a "standard" pattern for getters and setters in Java, called [Bean properties](http://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html). Basically any method starting with `get`, taking no arguments and returning a value, is a property getter for a property named as the rest of the method name (with a lowercased start letter). Likewise `set` creates a setter of a void method with a single argument.
For example:
```
// Getter for "awesomeString"
public String getAwesomeString() {
return awesomeString;
}
// Setter for "awesomeString"
public void setAwesomeString( String awesomeString ) {
this.awesomeString = awesomeString;
}
```
Most Java IDEs will generate these methods for you if you ask them (in Eclipse it's as simple as moving the cursor to a field and hitting `Ctrl`-`1`, then selecting the option from the list).
For what it's worth, for readability you can actually use `is` and `has` in place of `get` for boolean-type properties too, as in:
```
public boolean isAwesome();
public boolean hasAwesomeStuff();
``` |
70,501 | <p>I have a method in .NET (C#) which returns <code>string[][]</code>. When using RegAsm or TlbExp (from the .NET 2.0 SDK) to create a COM type library for the containing assembly, I get the following warning:</p>
<blockquote>
<p>WARNING: There is no marshaling support for nested arrays.</p>
</blockquote>
<p>This warning results in the method in question not being exported into the generated type library. I've been told there's ways around this using Variant as the COM return type, and then casting/etc on the COM client side. For this particular assembly, the target client audience is VB6. <b>But how do you actually do this on the .NET side?</b></p>
<p><i>Note</i>: I have an existing legacy DLL (with its exported type library) where the return type is Variant, but this DLL (and the .tlb) is generated using pre-.NET legacy tools, so I can't use them. </p>
<p>Would it help at all if the assembly was written in VB.NET instead?</p>
| [
{
"answer_id": 71395,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The equivalent of variant in C# is System.Object. So you might want to try to return the result cast to object and pick it ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7724/"
] | I have a method in .NET (C#) which returns `string[][]`. When using RegAsm or TlbExp (from the .NET 2.0 SDK) to create a COM type library for the containing assembly, I get the following warning:
>
> WARNING: There is no marshaling support for nested arrays.
>
>
>
This warning results in the method in question not being exported into the generated type library. I've been told there's ways around this using Variant as the COM return type, and then casting/etc on the COM client side. For this particular assembly, the target client audience is VB6. **But how do you actually do this on the .NET side?**
*Note*: I have an existing legacy DLL (with its exported type library) where the return type is Variant, but this DLL (and the .tlb) is generated using pre-.NET legacy tools, so I can't use them.
Would it help at all if the assembly was written in VB.NET instead? | Even if you were to return an Object (which maps to a Variant in COM Interop), that doesn't solve your problem. VB will be able to "hold" onto it and "pass it around", but it won't be able to do anything with it.
Technically, there is no exact equivalent in VB for a string[][]. However, if your array is not "jagged" (that is, all the sub-arrays are the same length), you should be able to use a two-dimensional array as your return type. COM Interop should be able to translate that.
```
string [,] myReturnValue = new string[rowCount,colCount];
```
Whether your method formally returns an Object (which will look like a Variant to VB), or a string[,] (which will look like an Array of Strings in VB), is somewhat immaterial. The String array is a nicer return, but not a requirement.
If you array *is* jagged, then you are going to have to come up with a different method. For example, you could choose to make your return 2D array as big as the biggest of the sub-arrays, and then pass the length information in a separate [out] int[] parameter, so that VB can know which elements are used. |
70,528 | <p>Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: <code>__myPrivateMethod()</code>. How, then, can one explain this</p>
<pre><code>>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>What's the deal?!</p>
<p>I'll explain this a little for those who didn't quite get that.</p>
<pre><code>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
</code></pre>
<p>I create a class with a public method and a private method and instantiate it.</p>
<p>Next, I call its public method.</p>
<pre><code>>>> obj.myPublicMethod()
public method
</code></pre>
<p>Next, I try and call its private method.</p>
<pre><code>>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
</code></pre>
<p>Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running <code>dir()</code> on the object reveals a new magical method that Python creates magically for all of your 'private' methods.</p>
<pre><code>>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
</code></pre>
<p>This new method's name is always an underscore, followed by the class name, followed by the method name.</p>
<pre><code>>>> obj._MyClass__myPrivateMethod()
this is private!!
</code></pre>
<p>So much for encapsulation, eh?</p>
<p>In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?</p>
| [
{
"answer_id": 70555,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 7,
"selected": false,
"text": "<p>From <em><a href=\"http://www.faqs.org/docs/diveintopython/fileinfo_private.html\" rel=\"noreferrer\">Dive Into Python, 3.9.... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1943957/"
] | Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: `__myPrivateMethod()`. How, then, can one explain this
```
>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
What's the deal?!
I'll explain this a little for those who didn't quite get that.
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
```
I create a class with a public method and a private method and instantiate it.
Next, I call its public method.
```
>>> obj.myPublicMethod()
public method
```
Next, I try and call its private method.
```
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
```
Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running `dir()` on the object reveals a new magical method that Python creates magically for all of your 'private' methods.
```
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
```
This new method's name is always an underscore, followed by the class name, followed by the method name.
```
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
So much for encapsulation, eh?
In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives? | The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from outside.
For example:
```
>>> class Foo(object):
... def __init__(self):
... self.__baz = 42
... def foo(self):
... print self.__baz
...
>>> class Bar(Foo):
... def __init__(self):
... super(Bar, self).__init__()
... self.__baz = 21
... def bar(self):
... print self.__baz
...
>>> x = Bar()
>>> x.foo()
42
>>> x.bar()
21
>>> print x.__dict__
{'_Bar__baz': 21, '_Foo__baz': 42}
```
Of course, it breaks down if two different classes have the same name. |
70,529 | <p>In order to know how many times a pattern exists in current buffer, I do:</p>
<pre><code>:%s/pattern-here/pattern-here/g
</code></pre>
<p>It gives the number of occurrences of the pattern, but is obviously cumbersome and also has the side-effect of setting the 'changed' status.</p>
<p>Is there a more elegant way to count?</p>
| [
{
"answer_id": 70657,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 8,
"selected": true,
"text": "<p>To avoid the substitution, leave the second pattern empty, and add the “n” flag:</p>\n\n<pre><code>:%s/pattern-here... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6984/"
] | In order to know how many times a pattern exists in current buffer, I do:
```
:%s/pattern-here/pattern-here/g
```
It gives the number of occurrences of the pattern, but is obviously cumbersome and also has the side-effect of setting the 'changed' status.
Is there a more elegant way to count? | To avoid the substitution, leave the second pattern empty, and add the “n” flag:
```
:%s/pattern-here//gn
```
This is described as [an official tip](http://vimdoc.sourceforge.net/htmldoc/tips.html#count-items). |
70,560 | <p>When entering a question, stackoverflow presents you with a list of questions that it thinks likely to cover the same topic. I have seen similar features on other sites or in other programs, too (Help file systems, for example), but I've never programmed something like this myself. Now I'm curious to know what sort of algorithm one would use for that.</p>
<p>The first approach that comes to my mind is splitting the phrase into words and look for phrases containing these words. Before you do that, you probably want to throw away insignificant words (like 'the', 'a', 'does' etc), and then you will want to rank the results.</p>
<p>Hey, wait - let's do that for web pages, and then we can have a ... watchamacallit ... - a "search engine", and then we can sell ads, and then ...</p>
<p>No, seriously, what are the common ways to solve this problem?</p>
| [
{
"answer_id": 70656,
"author": "Antti Rasinen",
"author_id": 8570,
"author_profile": "https://Stackoverflow.com/users/8570",
"pm_score": 5,
"selected": true,
"text": "<p>One approach is the so called bag-of-words model.</p>\n\n<p>As you guessed, first you count how many times words appe... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
] | When entering a question, stackoverflow presents you with a list of questions that it thinks likely to cover the same topic. I have seen similar features on other sites or in other programs, too (Help file systems, for example), but I've never programmed something like this myself. Now I'm curious to know what sort of algorithm one would use for that.
The first approach that comes to my mind is splitting the phrase into words and look for phrases containing these words. Before you do that, you probably want to throw away insignificant words (like 'the', 'a', 'does' etc), and then you will want to rank the results.
Hey, wait - let's do that for web pages, and then we can have a ... watchamacallit ... - a "search engine", and then we can sell ads, and then ...
No, seriously, what are the common ways to solve this problem? | One approach is the so called bag-of-words model.
As you guessed, first you count how many times words appear in the text (usually called document in the NLP-lingo). Then you throw out the so called stop words, such as "the", "a", "or" and so on.
You're left with words and word counts. Do this for a while and you get a comprehensive set of words that appear in your documents. You can then create an index for these words:
"aardvark" is 1, "apple" is 2, ..., "z-index" is 70092.
Now you can take your word bags and turn them into vectors. For example, if your document contains two references for aardvarks and nothing else, it would look like this:
```
[2 0 0 ... 70k zeroes ... 0].
```
After this you can count the "angle" between the two vectors with [a dot product](http://en.wikipedia.org/wiki/Dot_product). The smaller the angle, the closer the documents are.
This is a simple version and there other more advanced techniques. May the [Wikipedia be with you](http://en.wikipedia.org/wiki/Document_classification). |
70,575 | <p>Is there any need of Virtual Constructors? If so can any one post a scenario?</p>
| [
{
"answer_id": 70589,
"author": "grigy",
"author_id": 1692070,
"author_profile": "https://Stackoverflow.com/users/1692070",
"pm_score": 1,
"selected": false,
"text": "<p>In what language? In C++ for example the constructors can not be virtual.</p>\n"
},
{
"answer_id": 70597,
... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11554/"
] | Is there any need of Virtual Constructors? If so can any one post a scenario? | If you are talking about virtual destructors in C++ (there isn't any such thing as virtual constructors) then they should always be used if you are using your child classes polymorphically.
```
class A
{
~A();
}
class B : public A
{
~B();
}
A* pB = new B();
delete pB; // NOTE: WILL NOT CALL B's destructor
class A
{
virtual ~A();
}
class B : public A
{
virtual ~B();
}
A* pB = new B();
delete pB; // NOTE: WILL CALL B's destructor
```
**Edit:** Not sure why I've got a downvote for this (would be helpful if you left a comment...) but have a read here as well
<http://blogs.msdn.com/oldnewthing/archive/2004/05/07/127826.aspx> |
70,600 | <p>I'm trying to find a way of finding out who is downloading what image from an image gallery. Users can download using a button beside the thumbnail or right click and use the "save link as" Is it possible to relate a user session or ID to a "save link as" action from all browsers using either PHP or JavaScript.</p>
| [
{
"answer_id": 70633,
"author": "Jesper Blad Jensen",
"author_id": 11559,
"author_profile": "https://Stackoverflow.com/users/11559",
"pm_score": 0,
"selected": false,
"text": "<p>You need a gateway script, like ImageDownload.php?picture=me.jpg, or something like that.</p>\n\n<p>That page... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm trying to find a way of finding out who is downloading what image from an image gallery. Users can download using a button beside the thumbnail or right click and use the "save link as" Is it possible to relate a user session or ID to a "save link as" action from all browsers using either PHP or JavaScript. | Yes, my preferred way of doing this would be via PHP. You'd have to set up a script which would load up the file and send it to the user browser. This script would also be able to log the download somewhere (e.g. your database).
For example - in very rough pseudo-code:
download.php
```
$file = $_GET['file'];
updateFileCount($file);
header('Content-Type: image/jpeg');
sendFile($file);
```
Then, you just have your download link point to download.php instead of the actual file. (Note that updateFileCount and sendFile are functions that you would have to provide, of course - [this script](http://elouai.com/force-download.php) is an example of a download script which you could use)
Note: I highly recommend avoiding the use of $\_GET['file'] to get the whole filename - malicious users could use it to retrieve sensitive files from your web server. But the safe use of PHP downloads is a topic for another question. |
70,614 | <p>I've just introduced a friend to <strong>GNU Screen</strong> and they're having a hard time getting used to it. That makes me think about the essential things he needs to know about the excellent <strong>Screen</strong> utility, the same things that you'd think worthwhile to teach someone, a beginner, from the ground up. What are some analogies and handy tips for remembering binds, etc.?</p>
<p>It would be awesome.</p>
| [
{
"answer_id": 70683,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 5,
"selected": false,
"text": "<p>If your friend is in the habit of pressing <code>^A</code> to get to the beginning of the line in Bash, he/she is in for som... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6414/"
] | I've just introduced a friend to **GNU Screen** and they're having a hard time getting used to it. That makes me think about the essential things he needs to know about the excellent **Screen** utility, the same things that you'd think worthwhile to teach someone, a beginner, from the ground up. What are some analogies and handy tips for remembering binds, etc.?
It would be awesome. | I've been using `Screen` for over 10 years and probably use less than half the features. So it's definitely not necessary to learn all its features right away (and I wouldn't recommend trying). My day-to-day commands are:
```
^A ^W - window list, where am I
^A ^C - create new window
^A space - next window
^A p - previous window
^A ^A - switch to previous screen (toggle)
^A [0-9] - go to window [0-9]
^A esc - copy mode, which I use for scrollback
```
I think that's it. I sometimes use the split screen features, but certainly not daily. The other tip is if screen seems to have locked up because you hit some random key combination by accident, do both `^Q` and `^A ^Q` to try to unlock it. |
70,625 | <p>How would you refactor these two classes to abstract out the similarities? An abstract class? Simple inheritance? What would the refactored class(es) look like?</p>
<pre><code>public class LanguageCode
{
/// <summary>
/// Get the lowercase two-character ISO 639-1 language code.
/// </summary>
public readonly string Value;
public LanguageCode(string language)
{
this.Value = new CultureInfo(language).TwoLetterISOLanguageName;
}
public static LanguageCode TryParse(string language)
{
if (language == null)
{
return null;
}
if (language.Length > 2)
{
language = language.Substring(0, 2);
}
try
{
return new LanguageCode(language);
}
catch (ArgumentException)
{
return null;
}
}
}
public class RegionCode
{
/// <summary>
/// Get the uppercase two-character ISO 3166 region/country code.
/// </summary>
public readonly string Value;
public RegionCode(string region)
{
this.Value = new RegionInfo(region).TwoLetterISORegionName;
}
public static RegionCode TryParse(string region)
{
if (region == null)
{
return null;
}
if (region.Length > 2)
{
region = region.Substring(0, 2);
}
try
{
return new RegionCode(region);
}
catch (ArgumentException)
{
return null;
}
}
}
</code></pre>
| [
{
"answer_id": 70645,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 2,
"selected": false,
"text": "<p>It depends, if they are not going to do much more, then I would probably leave them as is - IMHO factoring out stu... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11574/"
] | How would you refactor these two classes to abstract out the similarities? An abstract class? Simple inheritance? What would the refactored class(es) look like?
```
public class LanguageCode
{
/// <summary>
/// Get the lowercase two-character ISO 639-1 language code.
/// </summary>
public readonly string Value;
public LanguageCode(string language)
{
this.Value = new CultureInfo(language).TwoLetterISOLanguageName;
}
public static LanguageCode TryParse(string language)
{
if (language == null)
{
return null;
}
if (language.Length > 2)
{
language = language.Substring(0, 2);
}
try
{
return new LanguageCode(language);
}
catch (ArgumentException)
{
return null;
}
}
}
public class RegionCode
{
/// <summary>
/// Get the uppercase two-character ISO 3166 region/country code.
/// </summary>
public readonly string Value;
public RegionCode(string region)
{
this.Value = new RegionInfo(region).TwoLetterISORegionName;
}
public static RegionCode TryParse(string region)
{
if (region == null)
{
return null;
}
if (region.Length > 2)
{
region = region.Substring(0, 2);
}
try
{
return new RegionCode(region);
}
catch (ArgumentException)
{
return null;
}
}
}
``` | Unless you have a strong reason for refactoring (because you are going to add more classes like those in near future) the penalty of changing the design for such a small and contrived example would overcome the gain in maintenance or overhead in this scenario. Anyhow here is a possible design based on generic and lambda expressions.
```
public class TwoLetterCode<T>
{
private readonly string value;
public TwoLetterCode(string value, Func<string, string> predicate)
{
this.value = predicate(value);
}
public static T TryParse(string value, Func<string, T> predicate)
{
if (value == null)
{
return default(T);
}
if (value.Length > 2)
{
value = value.Substring(0, 2);
}
try
{
return predicate(value);
}
catch (ArgumentException)
{
return default(T);
}
}
public string Value { get { return this.value; } }
}
public class LanguageCode : TwoLetterCode<LanguageCode> {
public LanguageCode(string language)
: base(language, v => new CultureInfo(v).TwoLetterISOLanguageName)
{
}
public static LanguageCode TryParse(string language)
{
return TwoLetterCode<LanguageCode>.TryParse(language, v => new LanguageCode(v));
}
}
public class RegionCode : TwoLetterCode<RegionCode>
{
public RegionCode(string language)
: base(language, v => new CultureInfo(v).TwoLetterISORegionName)
{
}
public static RegionCode TryParse(string language)
{
return TwoLetterCode<RegionCode>.TryParse(language, v => new RegionCode(v));
}
}
``` |
70,653 | <p>I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing.
I have found several method in web framework such as django or turbogears.</p>
<p>I just want a kind of username-password association stored into a local file.
I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption).</p>
| [
{
"answer_id": 70712,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 2,
"selected": false,
"text": "<p>I think you should make your own authentication method as you can make it fit your application best but use a library fo... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11563/"
] | I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing.
I have found several method in web framework such as django or turbogears.
I just want a kind of username-password association stored into a local file.
I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption). | Treat the following as pseudo-code..
```
try:
from hashlib import sha as hasher
except ImportError:
# You could probably exclude the try/except bit,
# but older Python distros dont have hashlib.
try:
import sha as hasher
except ImportError:
import md5 as hasher
def hash_password(password):
"""Returns the hashed version of a string
"""
return hasher.new( str(password) ).hexdigest()
def load_auth_file(path):
"""Loads a comma-seperated file.
Important: make sure the username
doesn't contain any commas!
"""
# Open the file, or return an empty auth list.
try:
f = open(path)
except IOError:
print "Warning: auth file not found"
return {}
ret = {}
for line in f.readlines():
split_line = line.split(",")
if len(split_line) > 2:
print "Warning: Malformed line:"
print split_line
continue # skip it..
else:
username, password = split_line
ret[username] = password
#end if
#end for
return ret
def main():
auth_file = "/home/blah/.myauth.txt"
u = raw_input("Username:")
p = raw_input("Password:") # getpass is probably better..
if auth_file.has_key(u.strip()):
if auth_file[u] == hash_password(p):
# The hash matches the stored one
print "Welcome, sir!"
```
Instead of using a comma-separated file, I would recommend using SQLite3 (which could be used for other settings and such.
Also, remember that this isn't very secure - if the application is local, evil users could probably just replace the `~/.myauth.txt` file.. Local application auth is difficult to do well. You'll have to encrypt any data it reads using the users password, and generally be very careful. |
70,668 | <p>What is the best way to backup VMWare Servers (1.0.x)?
The virtual machines in question are our development environment, and run isololated from the main network (so you can't just copy data from virtual to real servers).</p>
<p>The image files are normally in use and locked when the server is running, so it is difficult to back these up with the machines running.</p>
<p>Currently: I manually pause the servers when I leave and have a scheduled task that runs at midnight to robocopy the images to a remote NAS. </p>
<p>Is there a better way to do this, ideally without having to remember to pause the virtual machines?</p>
| [
{
"answer_id": 70692,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 0,
"selected": false,
"text": "<p>If I recall correctly, VMWare Server has a scripting interface, available via Perl or COM. You might be able to us... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11538/"
] | What is the best way to backup VMWare Servers (1.0.x)?
The virtual machines in question are our development environment, and run isololated from the main network (so you can't just copy data from virtual to real servers).
The image files are normally in use and locked when the server is running, so it is difficult to back these up with the machines running.
Currently: I manually pause the servers when I leave and have a scheduled task that runs at midnight to robocopy the images to a remote NAS.
Is there a better way to do this, ideally without having to remember to pause the virtual machines? | VMWare server includes the command line tool "vmware-cmd", which can be used to perform virtually any operation that can be performed through the console.
In this case you would simply add a "vmware-cmd susepend" to your script before starting your backup, and a "vmware-cmd start" after the backup is completed.
We use vmware-server as part of our build system to provide a known environment to run automated DB upgrades against, so we end up rolling back state as part of each build (driven by CruiseControl), and have found this interface to be rock solid.
```
Usage: /usr/bin/vmware-cmd <options> <vm-cfg-path> <vm-action> <arguments>
/usr/bin/vmware-cmd -s <options> <server-action> <arguments>
Options:
Connection Options:
-H <host> specifies an alternative host (if set, -U and -P must also be set)
-O <port> specifies an alternative port
-U <username> specifies a user
-P <password> specifies a password
General Options:
-h More detailed help.
-q Quiet. Minimal output
-v Verbose.
Server Operations:
/usr/bin/vmware-cmd -l
/usr/bin/vmware-cmd -s register <config_file_path>
/usr/bin/vmware-cmd -s unregister <config_file_path>
/usr/bin/vmware-cmd -s getresource <variable>
/usr/bin/vmware-cmd -s setresource <variable> <value>
VM Operations:
/usr/bin/vmware-cmd <cfg> getconnectedusers
/usr/bin/vmware-cmd <cfg> getstate
/usr/bin/vmware-cmd <cfg> start <powerop_mode>
/usr/bin/vmware-cmd <cfg> stop <powerop_mode>
/usr/bin/vmware-cmd <cfg> reset <powerop_mode>
/usr/bin/vmware-cmd <cfg> suspend <powerop_mode>
/usr/bin/vmware-cmd <cfg> setconfig <variable> <value>
/usr/bin/vmware-cmd <cfg> getconfig <variable>
/usr/bin/vmware-cmd <cfg> setguestinfo <variable> <value>
/usr/bin/vmware-cmd <cfg> getguestinfo <variable>
/usr/bin/vmware-cmd <cfg> getid
/usr/bin/vmware-cmd <cfg> getpid
/usr/bin/vmware-cmd <cfg> getproductinfo <prodinfo>
/usr/bin/vmware-cmd <cfg> connectdevice <device_name>
/usr/bin/vmware-cmd <cfg> disconnectdevice <device_name>
/usr/bin/vmware-cmd <cfg> getconfigfile
/usr/bin/vmware-cmd <cfg> getheartbeat
/usr/bin/vmware-cmd <cfg> getuptime
/usr/bin/vmware-cmd <cfg> getremoteconnections
/usr/bin/vmware-cmd <cfg> gettoolslastactive
/usr/bin/vmware-cmd <cfg> getresource <variable>
/usr/bin/vmware-cmd <cfg> setresource <variable> <value>
/usr/bin/vmware-cmd <cfg> setrunasuser <username> <password>
/usr/bin/vmware-cmd <cfg> getrunasuser
/usr/bin/vmware-cmd <cfg> getcapabilities
/usr/bin/vmware-cmd <cfg> addredo <disk_device_name>
/usr/bin/vmware-cmd <cfg> commit <disk_device_name> <level> <freeze> <wait>
/usr/bin/vmware-cmd <cfg> answer
``` |
70,681 | <p>Is there a way to make psycopg and postgres deal with errors without having to reestablish the connection, like MySQLdb? The commented version of the below works with MySQLdb, the comments make it work with Psycopg2:</p>
<pre><code>results = {'felicitas': 3, 'volumes': 8, 'acillevs': 1, 'mosaics': 13, 'perat\xe9': 1, 'representative': 6....}
for item in sorted(results):
try:
cur.execute("""insert into resultstab values ('%s', %d)""" % (item, results[item]))
print item, results[item]
# conn.commit()
except:
# conn=psycopg2.connect(user='bvm', database='wdb', password='redacted')
# cur=conn.cursor()
print 'choked on', item
continue
</code></pre>
<p>This must slow things down, could anyone give a suggestion for passing over formatting errors? Obviously the above chokes on apostrophes, but is there a way to make it pass over that without getting something like the following, or committing, reconnecting, etc?:</p>
<pre><code>agreement 19
agreements 1
agrees 1
agrippa 9
choked on agrippa's
choked on agrippina
</code></pre>
| [
{
"answer_id": 70692,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 0,
"selected": false,
"text": "<p>If I recall correctly, VMWare Server has a scripting interface, available via Perl or COM. You might be able to us... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11596/"
] | Is there a way to make psycopg and postgres deal with errors without having to reestablish the connection, like MySQLdb? The commented version of the below works with MySQLdb, the comments make it work with Psycopg2:
```
results = {'felicitas': 3, 'volumes': 8, 'acillevs': 1, 'mosaics': 13, 'perat\xe9': 1, 'representative': 6....}
for item in sorted(results):
try:
cur.execute("""insert into resultstab values ('%s', %d)""" % (item, results[item]))
print item, results[item]
# conn.commit()
except:
# conn=psycopg2.connect(user='bvm', database='wdb', password='redacted')
# cur=conn.cursor()
print 'choked on', item
continue
```
This must slow things down, could anyone give a suggestion for passing over formatting errors? Obviously the above chokes on apostrophes, but is there a way to make it pass over that without getting something like the following, or committing, reconnecting, etc?:
```
agreement 19
agreements 1
agrees 1
agrippa 9
choked on agrippa's
choked on agrippina
``` | VMWare server includes the command line tool "vmware-cmd", which can be used to perform virtually any operation that can be performed through the console.
In this case you would simply add a "vmware-cmd susepend" to your script before starting your backup, and a "vmware-cmd start" after the backup is completed.
We use vmware-server as part of our build system to provide a known environment to run automated DB upgrades against, so we end up rolling back state as part of each build (driven by CruiseControl), and have found this interface to be rock solid.
```
Usage: /usr/bin/vmware-cmd <options> <vm-cfg-path> <vm-action> <arguments>
/usr/bin/vmware-cmd -s <options> <server-action> <arguments>
Options:
Connection Options:
-H <host> specifies an alternative host (if set, -U and -P must also be set)
-O <port> specifies an alternative port
-U <username> specifies a user
-P <password> specifies a password
General Options:
-h More detailed help.
-q Quiet. Minimal output
-v Verbose.
Server Operations:
/usr/bin/vmware-cmd -l
/usr/bin/vmware-cmd -s register <config_file_path>
/usr/bin/vmware-cmd -s unregister <config_file_path>
/usr/bin/vmware-cmd -s getresource <variable>
/usr/bin/vmware-cmd -s setresource <variable> <value>
VM Operations:
/usr/bin/vmware-cmd <cfg> getconnectedusers
/usr/bin/vmware-cmd <cfg> getstate
/usr/bin/vmware-cmd <cfg> start <powerop_mode>
/usr/bin/vmware-cmd <cfg> stop <powerop_mode>
/usr/bin/vmware-cmd <cfg> reset <powerop_mode>
/usr/bin/vmware-cmd <cfg> suspend <powerop_mode>
/usr/bin/vmware-cmd <cfg> setconfig <variable> <value>
/usr/bin/vmware-cmd <cfg> getconfig <variable>
/usr/bin/vmware-cmd <cfg> setguestinfo <variable> <value>
/usr/bin/vmware-cmd <cfg> getguestinfo <variable>
/usr/bin/vmware-cmd <cfg> getid
/usr/bin/vmware-cmd <cfg> getpid
/usr/bin/vmware-cmd <cfg> getproductinfo <prodinfo>
/usr/bin/vmware-cmd <cfg> connectdevice <device_name>
/usr/bin/vmware-cmd <cfg> disconnectdevice <device_name>
/usr/bin/vmware-cmd <cfg> getconfigfile
/usr/bin/vmware-cmd <cfg> getheartbeat
/usr/bin/vmware-cmd <cfg> getuptime
/usr/bin/vmware-cmd <cfg> getremoteconnections
/usr/bin/vmware-cmd <cfg> gettoolslastactive
/usr/bin/vmware-cmd <cfg> getresource <variable>
/usr/bin/vmware-cmd <cfg> setresource <variable> <value>
/usr/bin/vmware-cmd <cfg> setrunasuser <username> <password>
/usr/bin/vmware-cmd <cfg> getrunasuser
/usr/bin/vmware-cmd <cfg> getcapabilities
/usr/bin/vmware-cmd <cfg> addredo <disk_device_name>
/usr/bin/vmware-cmd <cfg> commit <disk_device_name> <level> <freeze> <wait>
/usr/bin/vmware-cmd <cfg> answer
``` |
70,682 | <p>I am looking for details of the VTable structure, order and contents, and the location of the vtable pointers within objects. </p>
<p>Ideally, this will cover single inheritance, multiple inheritance, and virtual inheritance.</p>
<p>References to external documentation would also be appreciated</p>
<p>Documentation of GCC 4.0x class layout is <a href="http://www.cse.wustl.edu/~mdeters/seminar/fall2005/mi.html#virtual" rel="noreferrer">here</a> and the Itanium, and more broadly GNU, ABI layout documents are <a href="http://www.codesourcery.com/public/cxx-abi/abi.html#general" rel="noreferrer">here</a>. </p>
| [
{
"answer_id": 25674843,
"author": "GlGuru",
"author_id": 497840,
"author_profile": "https://Stackoverflow.com/users/497840",
"pm_score": -1,
"selected": false,
"text": "<p>Most of the compiler implementations that I have seen just \"embed\" the base object into the derived object. It be... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8516/"
] | I am looking for details of the VTable structure, order and contents, and the location of the vtable pointers within objects.
Ideally, this will cover single inheritance, multiple inheritance, and virtual inheritance.
References to external documentation would also be appreciated
Documentation of GCC 4.0x class layout is [here](http://www.cse.wustl.edu/~mdeters/seminar/fall2005/mi.html#virtual) and the Itanium, and more broadly GNU, ABI layout documents are [here](http://www.codesourcery.com/public/cxx-abi/abi.html#general). | A virtual table is generally treated as an array of function pointers, although compilers are free to put data pointers (in MI and VI scenarios, or to typeinfos), integers (for fixups), or sentinel elements (such as NULL pointers) into it as well. The layout is generally compiler-specific (or ABI-specific where multiple C++ compilers share an ABI), but stable provided the classes being compiled have stable interfaces (otherwise you'd have to recompile your code all the time, and that's a drag). There are also additional tables that are needed to handle corner cases involving virtual and multiple inheritance, and to make sure that virtual calls during derived class construction behave as the Standard says they should under those circumstances (those are what the VTTs and construction tables in the output below are for).
As to the specific case of GCC 4.x: the `-fdump-class-hierarchy` switch indeed acts as described (and then some). I tested it on [Coliru](http://coliru.stacked-crooked.com/a/16d53eb062d38bec) using the sample code below:
```
struct Base
{
virtual ~Base() {}
virtual void f() = 0;
};
struct OtherBase
{
virtual ~OtherBase() {}
virtual void g() {}
};
struct Derived: public Base
{
virtual ~Derived() {}
virtual void f() {}
};
struct MultiplyDerived: public Base, public OtherBase
{
virtual ~MultiplyDerived() {}
virtual void f() {}
virtual void g() {}
};
struct OtherDerived: public Base
{
virtual ~OtherDerived() {}
virtual void f() {}
};
struct DiamondDerived: public Derived, public OtherDerived
{
virtual ~DiamondDerived() {}
virtual void f() {}
};
struct VirtuallyDerived: virtual public Base
{
virtual ~VirtuallyDerived() {}
virtual void f() {}
};
struct OtherVirtuallyDerived: virtual public Base
{
virtual ~OtherVirtuallyDerived() {}
virtual void f() {}
};
struct VirtuallyDiamondDerived: public VirtuallyDerived, public OtherVirtuallyDerived
{
virtual ~VirtuallyDiamondDerived() {}
virtual void f() {}
};
struct DoublyVirtuallyDiamondDerived: virtual public VirtuallyDerived, virtual public OtherVirtuallyDerived
{
virtual ~DoublyVirtuallyDiamondDerived() {}
virtual void f() {}
};
struct MixedVirtuallyDerived: virtual public Base, public OtherBase
{
virtual ~MixedVirtuallyDerived() {}
};
struct MixedVirtuallyDiamondDerived: public VirtuallyDerived, public MixedVirtuallyDerived
{
virtual ~MixedVirtuallyDiamondDerived() {}
virtual void f() {}
virtual void g() {}
};
struct VirtuallyMultiplyDerived: virtual public Base, virtual public OtherBase
{
virtual ~VirtuallyMultiplyDerived() {}
};
struct OtherVirtuallyMultiplyDerived: virtual public Base, virtual public OtherBase
{
virtual ~OtherVirtuallyMultiplyDerived() {}
};
struct MultiplyVirtuallyDiamondDerived: public VirtuallyMultiplyDerived, public OtherVirtuallyMultiplyDerived
{
virtual ~MultiplyVirtuallyDiamondDerived() {}
virtual void f() {}
virtual void g() {}
};
```
and received from G++ (mangled name guide: TI's are typeinfos, TV's are vtables, and Th's and Tv's are thunks used to make correct virtual calls in the presence of multiple and/or virtual inheritance):
```
Vtable for Base
Base::_ZTV4Base: 5u entries
0 (int (*)(...))0
8 (int (*)(...))(& _ZTI4Base)
16 0u
24 0u
32 (int (*)(...))__cxa_pure_virtual
Class Base
size=8 align=8
base size=8 base align=8
Base (0x0x7fd42c0355a0) 0 nearly-empty
vptr=((& Base::_ZTV4Base) + 16u)
Vtable for OtherBase
OtherBase::_ZTV9OtherBase: 5u entries
0 (int (*)(...))0
8 (int (*)(...))(& _ZTI9OtherBase)
16 (int (*)(...))OtherBase::~OtherBase
24 (int (*)(...))OtherBase::~OtherBase
32 (int (*)(...))OtherBase::g
Class OtherBase
size=8 align=8
base size=8 base align=8
OtherBase (0x0x7fd42c035600) 0 nearly-empty
vptr=((& OtherBase::_ZTV9OtherBase) + 16u)
Vtable for Derived
Derived::_ZTV7Derived: 5u entries
0 (int (*)(...))0
8 (int (*)(...))(& _ZTI7Derived)
16 (int (*)(...))Derived::~Derived
24 (int (*)(...))Derived::~Derived
32 (int (*)(...))Derived::f
Class Derived
size=8 align=8
base size=8 base align=8
Derived (0x0x7fd42c02d138) 0 nearly-empty
vptr=((& Derived::_ZTV7Derived) + 16u)
Base (0x0x7fd42c035660) 0 nearly-empty
primary-for Derived (0x0x7fd42c02d138)
Vtable for MultiplyDerived
MultiplyDerived::_ZTV15MultiplyDerived: 11u entries
0 (int (*)(...))0
8 (int (*)(...))(& _ZTI15MultiplyDerived)
16 (int (*)(...))MultiplyDerived::~MultiplyDerived
24 (int (*)(...))MultiplyDerived::~MultiplyDerived
32 (int (*)(...))MultiplyDerived::f
40 (int (*)(...))MultiplyDerived::g
48 (int (*)(...))-8
56 (int (*)(...))(& _ZTI15MultiplyDerived)
64 (int (*)(...))MultiplyDerived::_ZThn8_N15MultiplyDerivedD1Ev
72 (int (*)(...))MultiplyDerived::_ZThn8_N15MultiplyDerivedD0Ev
80 (int (*)(...))MultiplyDerived::_ZThn8_N15MultiplyDerived1gEv
Class MultiplyDerived
size=16 align=8
base size=16 base align=8
MultiplyDerived (0x0x7fd42c04aaf0) 0
vptr=((& MultiplyDerived::_ZTV15MultiplyDerived) + 16u)
Base (0x0x7fd42c0356c0) 0 nearly-empty
primary-for MultiplyDerived (0x0x7fd42c04aaf0)
OtherBase (0x0x7fd42c035720) 8 nearly-empty
vptr=((& MultiplyDerived::_ZTV15MultiplyDerived) + 64u)
Vtable for OtherDerived
OtherDerived::_ZTV12OtherDerived: 5u entries
0 (int (*)(...))0
8 (int (*)(...))(& _ZTI12OtherDerived)
16 (int (*)(...))OtherDerived::~OtherDerived
24 (int (*)(...))OtherDerived::~OtherDerived
32 (int (*)(...))OtherDerived::f
Class OtherDerived
size=8 align=8
base size=8 base align=8
OtherDerived (0x0x7fd42c02d1a0) 0 nearly-empty
vptr=((& OtherDerived::_ZTV12OtherDerived) + 16u)
Base (0x0x7fd42c035780) 0 nearly-empty
primary-for OtherDerived (0x0x7fd42c02d1a0)
Vtable for DiamondDerived
DiamondDerived::_ZTV14DiamondDerived: 10u entries
0 (int (*)(...))0
8 (int (*)(...))(& _ZTI14DiamondDerived)
16 (int (*)(...))DiamondDerived::~DiamondDerived
24 (int (*)(...))DiamondDerived::~DiamondDerived
32 (int (*)(...))DiamondDerived::f
40 (int (*)(...))-8
48 (int (*)(...))(& _ZTI14DiamondDerived)
56 (int (*)(...))DiamondDerived::_ZThn8_N14DiamondDerivedD1Ev
64 (int (*)(...))DiamondDerived::_ZThn8_N14DiamondDerivedD0Ev
72 (int (*)(...))DiamondDerived::_ZThn8_N14DiamondDerived1fEv
Class DiamondDerived
size=16 align=8
base size=16 base align=8
DiamondDerived (0x0x7fd42c0625b0) 0
vptr=((& DiamondDerived::_ZTV14DiamondDerived) + 16u)
Derived (0x0x7fd42c02d208) 0 nearly-empty
primary-for DiamondDerived (0x0x7fd42c0625b0)
Base (0x0x7fd42c0357e0) 0 nearly-empty
primary-for Derived (0x0x7fd42c02d208)
OtherDerived (0x0x7fd42c02d270) 8 nearly-empty
vptr=((& DiamondDerived::_ZTV14DiamondDerived) + 56u)
Base (0x0x7fd42c035840) 8 nearly-empty
primary-for OtherDerived (0x0x7fd42c02d270)
Vtable for VirtuallyDerived
VirtuallyDerived::_ZTV16VirtuallyDerived: 8u entries
0 0u
8 0u
16 0u
24 (int (*)(...))0
32 (int (*)(...))(& _ZTI16VirtuallyDerived)
40 (int (*)(...))VirtuallyDerived::~VirtuallyDerived
48 (int (*)(...))VirtuallyDerived::~VirtuallyDerived
56 (int (*)(...))VirtuallyDerived::f
VTT for VirtuallyDerived
VirtuallyDerived::_ZTT16VirtuallyDerived: 2u entries
0 ((& VirtuallyDerived::_ZTV16VirtuallyDerived) + 40u)
8 ((& VirtuallyDerived::_ZTV16VirtuallyDerived) + 40u)
Class VirtuallyDerived
size=8 align=8
base size=8 base align=8
VirtuallyDerived (0x0x7fd42c02d2d8) 0 nearly-empty
vptridx=0u vptr=((& VirtuallyDerived::_ZTV16VirtuallyDerived) + 40u)
Base (0x0x7fd42c0358a0) 0 nearly-empty virtual
primary-for VirtuallyDerived (0x0x7fd42c02d2d8)
vptridx=8u vbaseoffset=-40
Vtable for OtherVirtuallyDerived
OtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived: 8u entries
0 0u
8 0u
16 0u
24 (int (*)(...))0
32 (int (*)(...))(& _ZTI21OtherVirtuallyDerived)
40 (int (*)(...))OtherVirtuallyDerived::~OtherVirtuallyDerived
48 (int (*)(...))OtherVirtuallyDerived::~OtherVirtuallyDerived
56 (int (*)(...))OtherVirtuallyDerived::f
VTT for OtherVirtuallyDerived
OtherVirtuallyDerived::_ZTT21OtherVirtuallyDerived: 2u entries
0 ((& OtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived) + 40u)
8 ((& OtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived) + 40u)
Class OtherVirtuallyDerived
size=8 align=8
base size=8 base align=8
OtherVirtuallyDerived (0x0x7fd42c02d340) 0 nearly-empty
vptridx=0u vptr=((& OtherVirtuallyDerived::_ZTV21OtherVirtuallyDerived) + 40u)
Base (0x0x7fd42c035900) 0 nearly-empty virtual
primary-for OtherVirtuallyDerived (0x0x7fd42c02d340)
vptridx=8u vbaseoffset=-40
Vtable for VirtuallyDiamondDerived
VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived: 16u entries
0 0u
8 0u
16 0u
24 (int (*)(...))0
32 (int (*)(...))(& _ZTI23VirtuallyDiamondDerived)
40 (int (*)(...))VirtuallyDiamondDerived::~VirtuallyDiamondDerived
48 (int (*)(...))VirtuallyDiamondDerived::~VirtuallyDiamondDerived
56 (int (*)(...))VirtuallyDiamondDerived::f
64 18446744073709551608u
72 18446744073709551608u
80 18446744073709551608u
88 (int (*)(...))-8
96 (int (*)(...))(& _ZTI23VirtuallyDiamondDerived)
104 (int (*)(...))VirtuallyDiamondDerived::_ZThn8_N23VirtuallyDiamondDerivedD1Ev
112 (int (*)(...))VirtuallyDiamondDerived::_ZThn8_N23VirtuallyDiamondDerivedD0Ev
120 (int (*)(...))VirtuallyDiamondDerived::_ZThn8_N23VirtuallyDiamondDerived1fEv
Construction vtable for VirtuallyDerived (0x0x7fd42c02d3a8 instance) in VirtuallyDiamondDerived
VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived0_16VirtuallyDerived: 8u entries
0 0u
8 0u
16 0u
24 (int (*)(...))0
32 (int (*)(...))(& _ZTI16VirtuallyDerived)
40 0u
48 0u
56 (int (*)(...))VirtuallyDerived::f
Construction vtable for OtherVirtuallyDerived (0x0x7fd42c02d410 instance) in VirtuallyDiamondDerived
VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived8_21OtherVirtuallyDerived: 15u entries
0 18446744073709551608u
8 0u
16 0u
24 (int (*)(...))0
32 (int (*)(...))(& _ZTI21OtherVirtuallyDerived)
40 0u
48 0u
56 (int (*)(...))OtherVirtuallyDerived::f
64 8u
72 8u
80 (int (*)(...))8
88 (int (*)(...))(& _ZTI21OtherVirtuallyDerived)
96 0u
104 0u
112 (int (*)(...))OtherVirtuallyDerived::_ZTv0_n32_N21OtherVirtuallyDerived1fEv
VTT for VirtuallyDiamondDerived
VirtuallyDiamondDerived::_ZTT23VirtuallyDiamondDerived: 7u entries
0 ((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 40u)
8 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)
16 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)
24 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 40u)
32 ((& VirtuallyDiamondDerived::_ZTC23VirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 96u)
40 ((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 40u)
48 ((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 104u)
Class VirtuallyDiamondDerived
size=16 align=8
base size=16 base align=8
VirtuallyDiamondDerived (0x0x7fd42c07e460) 0
vptridx=0u vptr=((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 40u)
VirtuallyDerived (0x0x7fd42c02d3a8) 0 nearly-empty
primary-for VirtuallyDiamondDerived (0x0x7fd42c07e460)
subvttidx=8u
Base (0x0x7fd42c035960) 0 nearly-empty virtual
primary-for VirtuallyDerived (0x0x7fd42c02d3a8)
vptridx=40u vbaseoffset=-40
OtherVirtuallyDerived (0x0x7fd42c02d410) 8 nearly-empty
lost-primary
subvttidx=24u vptridx=48u vptr=((& VirtuallyDiamondDerived::_ZTV23VirtuallyDiamondDerived) + 104u)
Base (0x0x7fd42c035960) alternative-path
Vtable for DoublyVirtuallyDiamondDerived
DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived: 18u entries
0 8u
8 0u
16 0u
24 0u
32 0u
40 (int (*)(...))0
48 (int (*)(...))(& _ZTI29DoublyVirtuallyDiamondDerived)
56 (int (*)(...))DoublyVirtuallyDiamondDerived::~DoublyVirtuallyDiamondDerived
64 (int (*)(...))DoublyVirtuallyDiamondDerived::~DoublyVirtuallyDiamondDerived
72 (int (*)(...))DoublyVirtuallyDiamondDerived::f
80 18446744073709551608u
88 18446744073709551608u
96 18446744073709551608u
104 (int (*)(...))-8
112 (int (*)(...))(& _ZTI29DoublyVirtuallyDiamondDerived)
120 (int (*)(...))DoublyVirtuallyDiamondDerived::_ZTv0_n24_N29DoublyVirtuallyDiamondDerivedD1Ev
128 (int (*)(...))DoublyVirtuallyDiamondDerived::_ZTv0_n24_N29DoublyVirtuallyDiamondDerivedD0Ev
136 (int (*)(...))DoublyVirtuallyDiamondDerived::_ZTv0_n32_N29DoublyVirtuallyDiamondDerived1fEv
Construction vtable for VirtuallyDerived in DoublyVirtuallyDiamondDerived
DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived0_16VirtuallyDerived: 8u entries
0 0u
8 0u
16 0u
24 (int (*)(...))0
32 (int (*)(...))(& _ZTI16VirtuallyDerived)
40 0u
48 0u
56 (int (*)(...))VirtuallyDerived::f
Construction vtable for OtherVirtuallyDerived in DoublyVirtuallyDiamondDerived
DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived8_21OtherVirtuallyDerived: 15u entries
0 18446744073709551608u
8 0u
16 0u
24 (int (*)(...))0
32 (int (*)(...))(& _ZTI21OtherVirtuallyDerived)
40 0u
48 0u
56 (int (*)(...))OtherVirtuallyDerived::f
64 8u
72 8u
80 (int (*)(...))8
88 (int (*)(...))(& _ZTI21OtherVirtuallyDerived)
96 0u
104 0u
112 (int (*)(...))OtherVirtuallyDerived::_ZTv0_n32_N21OtherVirtuallyDerived1fEv
VTT for DoublyVirtuallyDiamondDerived
DoublyVirtuallyDiamondDerived::_ZTT29DoublyVirtuallyDiamondDerived: 8u entries
0 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u)
8 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u)
16 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u)
24 ((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 120u)
32 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)
40 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)
48 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 40u)
56 ((& DoublyVirtuallyDiamondDerived::_ZTC29DoublyVirtuallyDiamondDerived8_21OtherVirtuallyDerived) + 96u)
Class DoublyVirtuallyDiamondDerived
size=16 align=8
base size=8 base align=8
DoublyVirtuallyDiamondDerived (0x0x7fd42c07ea10) 0 nearly-empty
vptridx=0u vptr=((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 56u)
VirtuallyDerived (0x0x7fd42c02d478) 0 nearly-empty virtual
primary-for DoublyVirtuallyDiamondDerived (0x0x7fd42c07ea10)
subvttidx=32u vptridx=8u vbaseoffset=-48
Base (0x0x7fd42c035a80) 0 nearly-empty virtual
primary-for VirtuallyDerived (0x0x7fd42c02d478)
vptridx=16u vbaseoffset=-40
OtherVirtuallyDerived (0x0x7fd42c02d4e0) 8 nearly-empty virtual
lost-primary
subvttidx=48u vptridx=24u vbaseoffset=-56 vptr=((& DoublyVirtuallyDiamondDerived::_ZTV29DoublyVirtuallyDiamondDerived) + 120u)
Base (0x0x7fd42c035a80) alternative-path
Vtable for MixedVirtuallyDerived
MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived: 13u entries
0 8u
8 (int (*)(...))0
16 (int (*)(...))(& _ZTI21MixedVirtuallyDerived)
24 0u
32 0u
40 (int (*)(...))OtherBase::g
48 0u
56 18446744073709551608u
64 (int (*)(...))-8
72 (int (*)(...))(& _ZTI21MixedVirtuallyDerived)
80 0u
88 0u
96 (int (*)(...))__cxa_pure_virtual
VTT for MixedVirtuallyDerived
MixedVirtuallyDerived::_ZTT21MixedVirtuallyDerived: 2u entries
0 ((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 24u)
8 ((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 80u)
Class MixedVirtuallyDerived
size=16 align=8
base size=8 base align=8
MixedVirtuallyDerived (0x0x7fd42c07eee0) 0 nearly-empty
vptridx=0u vptr=((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 24u)
Base (0x0x7fd42c035c60) 8 nearly-empty virtual
vptridx=8u vbaseoffset=-24 vptr=((& MixedVirtuallyDerived::_ZTV21MixedVirtuallyDerived) + 80u)
OtherBase (0x0x7fd42c035cc0) 0 nearly-empty
primary-for MixedVirtuallyDerived (0x0x7fd42c07eee0)
Vtable for MixedVirtuallyDiamondDerived
MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived: 15u entries
0 0u
8 0u
16 0u
24 (int (*)(...))0
32 (int (*)(...))(& _ZTI28MixedVirtuallyDiamondDerived)
40 (int (*)(...))MixedVirtuallyDiamondDerived::~MixedVirtuallyDiamondDerived
48 (int (*)(...))MixedVirtuallyDiamondDerived::~MixedVirtuallyDiamondDerived
56 (int (*)(...))MixedVirtuallyDiamondDerived::f
64 (int (*)(...))MixedVirtuallyDiamondDerived::g
72 18446744073709551608u
80 (int (*)(...))-8
88 (int (*)(...))(& _ZTI28MixedVirtuallyDiamondDerived)
96 (int (*)(...))MixedVirtuallyDiamondDerived::_ZThn8_N28MixedVirtuallyDiamondDerivedD1Ev
104 (int (*)(...))MixedVirtuallyDiamondDerived::_ZThn8_N28MixedVirtuallyDiamondDerivedD0Ev
112 (int (*)(...))MixedVirtuallyDiamondDerived::_ZThn8_N28MixedVirtuallyDiamondDerived1gEv
Construction vtable for VirtuallyDerived (0x0x7fd42c02d750 instance) in MixedVirtuallyDiamondDerived
MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived0_16VirtuallyDerived: 8u entries
0 0u
8 0u
16 0u
24 (int (*)(...))0
32 (int (*)(...))(& _ZTI16VirtuallyDerived)
40 0u
48 0u
56 (int (*)(...))VirtuallyDerived::f
Construction vtable for MixedVirtuallyDerived (0x0x7fd42c0b5380 instance) in MixedVirtuallyDiamondDerived
MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived8_21MixedVirtuallyDerived: 13u entries
0 18446744073709551608u
8 (int (*)(...))0
16 (int (*)(...))(& _ZTI21MixedVirtuallyDerived)
24 0u
32 0u
40 (int (*)(...))OtherBase::g
48 0u
56 8u
64 (int (*)(...))8
72 (int (*)(...))(& _ZTI21MixedVirtuallyDerived)
80 0u
88 0u
96 (int (*)(...))__cxa_pure_virtual
VTT for MixedVirtuallyDiamondDerived
MixedVirtuallyDiamondDerived::_ZTT28MixedVirtuallyDiamondDerived: 7u entries
0 ((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 40u)
8 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)
16 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived0_16VirtuallyDerived) + 40u)
24 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived8_21MixedVirtuallyDerived) + 24u)
32 ((& MixedVirtuallyDiamondDerived::_ZTC28MixedVirtuallyDiamondDerived8_21MixedVirtuallyDerived) + 80u)
40 ((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 40u)
48 ((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 96u)
Class MixedVirtuallyDiamondDerived
size=16 align=8
base size=16 base align=8
MixedVirtuallyDiamondDerived (0x0x7fd42c0b5310) 0
vptridx=0u vptr=((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 40u)
VirtuallyDerived (0x0x7fd42c02d750) 0 nearly-empty
primary-for MixedVirtuallyDiamondDerived (0x0x7fd42c0b5310)
subvttidx=8u
Base (0x0x7fd42c035d20) 0 nearly-empty virtual
primary-for VirtuallyDerived (0x0x7fd42c02d750)
vptridx=40u vbaseoffset=-40
MixedVirtuallyDerived (0x0x7fd42c0b5380) 8 nearly-empty
subvttidx=24u vptridx=48u vptr=((& MixedVirtuallyDiamondDerived::_ZTV28MixedVirtuallyDiamondDerived) + 96u)
Base (0x0x7fd42c035d20) alternative-path
OtherBase (0x0x7fd42c035d80) 8 nearly-empty
primary-for MixedVirtuallyDerived (0x0x7fd42c0b5380)
Vtable for VirtuallyMultiplyDerived
VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived: 16u entries
0 8u
8 0u
16 0u
24 0u
32 (int (*)(...))0
40 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived)
48 0u
56 0u
64 (int (*)(...))__cxa_pure_virtual
72 0u
80 18446744073709551608u
88 (int (*)(...))-8
96 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived)
104 0u
112 0u
120 (int (*)(...))OtherBase::g
VTT for VirtuallyMultiplyDerived
VirtuallyMultiplyDerived::_ZTT24VirtuallyMultiplyDerived: 3u entries
0 ((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 48u)
8 ((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 48u)
16 ((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 104u)
Class VirtuallyMultiplyDerived
size=16 align=8
base size=8 base align=8
VirtuallyMultiplyDerived (0x0x7fd42c0b59a0) 0 nearly-empty
vptridx=0u vptr=((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 48u)
Base (0x0x7fd42c035e40) 0 nearly-empty virtual
primary-for VirtuallyMultiplyDerived (0x0x7fd42c0b59a0)
vptridx=8u vbaseoffset=-40
OtherBase (0x0x7fd42c035ea0) 8 nearly-empty virtual
vptridx=16u vbaseoffset=-48 vptr=((& VirtuallyMultiplyDerived::_ZTV24VirtuallyMultiplyDerived) + 104u)
Vtable for OtherVirtuallyMultiplyDerived
OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived: 16u entries
0 8u
8 0u
16 0u
24 0u
32 (int (*)(...))0
40 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived)
48 0u
56 0u
64 (int (*)(...))__cxa_pure_virtual
72 0u
80 18446744073709551608u
88 (int (*)(...))-8
96 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived)
104 0u
112 0u
120 (int (*)(...))OtherBase::g
VTT for OtherVirtuallyMultiplyDerived
OtherVirtuallyMultiplyDerived::_ZTT29OtherVirtuallyMultiplyDerived: 3u entries
0 ((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 48u)
8 ((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 48u)
16 ((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 104u)
Class OtherVirtuallyMultiplyDerived
size=16 align=8
base size=8 base align=8
OtherVirtuallyMultiplyDerived (0x0x7fd42c0b5d90) 0 nearly-empty
vptridx=0u vptr=((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 48u)
Base (0x0x7fd42c035f00) 0 nearly-empty virtual
primary-for OtherVirtuallyMultiplyDerived (0x0x7fd42c0b5d90)
vptridx=8u vbaseoffset=-40
OtherBase (0x0x7fd42c035f60) 8 nearly-empty virtual
vptridx=16u vbaseoffset=-48 vptr=((& OtherVirtuallyMultiplyDerived::_ZTV29OtherVirtuallyMultiplyDerived) + 104u)
Vtable for MultiplyVirtuallyDiamondDerived
MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived: 26u entries
0 16u
8 0u
16 0u
24 0u
32 (int (*)(...))0
40 (int (*)(...))(& _ZTI31MultiplyVirtuallyDiamondDerived)
48 (int (*)(...))MultiplyVirtuallyDiamondDerived::~MultiplyVirtuallyDiamondDerived
56 (int (*)(...))MultiplyVirtuallyDiamondDerived::~MultiplyVirtuallyDiamondDerived
64 (int (*)(...))MultiplyVirtuallyDiamondDerived::f
72 (int (*)(...))MultiplyVirtuallyDiamondDerived::g
80 8u
88 18446744073709551608u
96 18446744073709551608u
104 18446744073709551608u
112 (int (*)(...))-8
120 (int (*)(...))(& _ZTI31MultiplyVirtuallyDiamondDerived)
128 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZThn8_N31MultiplyVirtuallyDiamondDerivedD1Ev
136 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZThn8_N31MultiplyVirtuallyDiamondDerivedD0Ev
144 0u
152 18446744073709551600u
160 18446744073709551600u
168 (int (*)(...))-16
176 (int (*)(...))(& _ZTI31MultiplyVirtuallyDiamondDerived)
184 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZTv0_n24_N31MultiplyVirtuallyDiamondDerivedD1Ev
192 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZTv0_n24_N31MultiplyVirtuallyDiamondDerivedD0Ev
200 (int (*)(...))MultiplyVirtuallyDiamondDerived::_ZTv0_n32_N31MultiplyVirtuallyDiamondDerived1gEv
Construction vtable for VirtuallyMultiplyDerived (0x0x7fd42bcdf230 instance) in MultiplyVirtuallyDiamondDerived
MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived: 16u entries
0 16u
8 0u
16 0u
24 0u
32 (int (*)(...))0
40 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived)
48 0u
56 0u
64 (int (*)(...))__cxa_pure_virtual
72 0u
80 18446744073709551600u
88 (int (*)(...))-16
96 (int (*)(...))(& _ZTI24VirtuallyMultiplyDerived)
104 0u
112 0u
120 (int (*)(...))OtherBase::g
Construction vtable for OtherVirtuallyMultiplyDerived (0x0x7fd42bcdf2a0 instance) in MultiplyVirtuallyDiamondDerived
MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived: 23u entries
0 8u
8 18446744073709551608u
16 18446744073709551608u
24 0u
32 (int (*)(...))0
40 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived)
48 0u
56 0u
64 (int (*)(...))__cxa_pure_virtual
72 0u
80 8u
88 (int (*)(...))8
96 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived)
104 0u
112 0u
120 (int (*)(...))__cxa_pure_virtual
128 0u
136 18446744073709551608u
144 (int (*)(...))-8
152 (int (*)(...))(& _ZTI29OtherVirtuallyMultiplyDerived)
160 0u
168 0u
176 (int (*)(...))OtherBase::g
VTT for MultiplyVirtuallyDiamondDerived
MultiplyVirtuallyDiamondDerived::_ZTT31MultiplyVirtuallyDiamondDerived: 10u entries
0 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 48u)
8 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived) + 48u)
16 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived) + 48u)
24 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived0_24VirtuallyMultiplyDerived) + 104u)
32 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived) + 48u)
40 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived) + 104u)
48 ((& MultiplyVirtuallyDiamondDerived::_ZTC31MultiplyVirtuallyDiamondDerived8_29OtherVirtuallyMultiplyDerived) + 160u)
56 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 48u)
64 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 184u)
72 ((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 128u)
Class MultiplyVirtuallyDiamondDerived
size=24 align=8
base size=16 base align=8
MultiplyVirtuallyDiamondDerived (0x0x7fd42bcdf1c0) 0
vptridx=0u vptr=((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 48u)
VirtuallyMultiplyDerived (0x0x7fd42bcdf230) 0 nearly-empty
primary-for MultiplyVirtuallyDiamondDerived (0x0x7fd42bcdf1c0)
subvttidx=8u
Base (0x0x7fd42bce2000) 0 nearly-empty virtual
primary-for VirtuallyMultiplyDerived (0x0x7fd42bcdf230)
vptridx=56u vbaseoffset=-40
OtherBase (0x0x7fd42bce2060) 16 nearly-empty virtual
vptridx=64u vbaseoffset=-48 vptr=((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 184u)
OtherVirtuallyMultiplyDerived (0x0x7fd42bcdf2a0) 8 nearly-empty
lost-primary
subvttidx=32u vptridx=72u vptr=((& MultiplyVirtuallyDiamondDerived::_ZTV31MultiplyVirtuallyDiamondDerived) + 128u)
Base (0x0x7fd42bce2000) alternative-path
OtherBase (0x0x7fd42bce2060) alternative-path
``` |
70,689 | <p>What is an efficient way to implement a singleton design pattern in Java?</p>
| [
{
"answer_id": 70737,
"author": "Neil Burroughs",
"author_id": 5166,
"author_profile": "https://Stackoverflow.com/users/5166",
"pm_score": 6,
"selected": false,
"text": "<p>Make sure that you really need it. Do a google search for "singleton anti-pattern" to see some arguments ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11581/"
] | What is an efficient way to implement a singleton design pattern in Java? | Use an enum:
```
public enum Foo {
INSTANCE;
}
```
Joshua Bloch explained this approach in his [Effective Java Reloaded](http://sites.google.com/site/io/effective-java-reloaded) talk at Google I/O 2008: [link to video](http://www.youtube.com/watch?v=pi_I7oD_uGI#t=28m50s). Also see slides 30-32 of his presentation ([effective\_java\_reloaded.pdf](https://14b1424d-a-62cb3a1a-s-sites.googlegroups.com/site/io/effective-java-reloaded/effective_java_reloaded.pdf?attachauth=ANoY7crKCOet2NEUGW7RV1XfM-Jn4z8YJhs0qJM11OhLRnFW_JbExkJtvJ3UJvTE40dhAciyWcRIeGJ-n3FLGnMOapHShHINh8IY05YViOJoZWzaohMtM-s4HCi5kjREagi8awWtcYD0_6G7GhKr2BndToeqLk5sBhZcQfcYIyAE5A4lGNosDCjODcBAkJn8EuO6572t2wU1LMSEUgjvqcf4I-Fp6VDhDvih_XUEmL9nuVJQynd2DRpxyuNH1SpJspEIdbLw-WWZ&attredirects=0)):
>
> ### The Right Way to Implement a Serializable Singleton
>
>
>
> ```
> public enum Elvis {
> INSTANCE;
> private final String[] favoriteSongs =
> { "Hound Dog", "Heartbreak Hotel" };
> public void printFavorites() {
> System.out.println(Arrays.toString(favoriteSongs));
> }
> }
>
> ```
>
>
**Edit:** An [online portion of "Effective Java"](http://www.ddj.com/java/208403883?pgno=3) says:
>
> "This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, **a single-element enum type is the best way to implement a singleton**."
>
>
> |
70,694 | <p>I am trying to create a Task Scheduler task to start my SQL Server 2005 instance every morning, because something stops it every night. This is a temporary solution until I can diagnose the stoppage.</p>
<p>I created a task to run under my admin user, and to start the program, <em>cmd</em> with the arguments <em>/c net start mssqlserver</em>. When I manually run the command, in a console under my admin user, it runs, but when I try to manually execute the task, it logs the following message, and the service remains stopped:</p>
<p><em>action "C:\Windows\system32\cmd.EXE" with return code 2</em>.</p>
<p>Any suggestions?</p>
| [
{
"answer_id": 70737,
"author": "Neil Burroughs",
"author_id": 5166,
"author_profile": "https://Stackoverflow.com/users/5166",
"pm_score": 6,
"selected": false,
"text": "<p>Make sure that you really need it. Do a google search for "singleton anti-pattern" to see some arguments ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] | I am trying to create a Task Scheduler task to start my SQL Server 2005 instance every morning, because something stops it every night. This is a temporary solution until I can diagnose the stoppage.
I created a task to run under my admin user, and to start the program, *cmd* with the arguments */c net start mssqlserver*. When I manually run the command, in a console under my admin user, it runs, but when I try to manually execute the task, it logs the following message, and the service remains stopped:
*action "C:\Windows\system32\cmd.EXE" with return code 2*.
Any suggestions? | Use an enum:
```
public enum Foo {
INSTANCE;
}
```
Joshua Bloch explained this approach in his [Effective Java Reloaded](http://sites.google.com/site/io/effective-java-reloaded) talk at Google I/O 2008: [link to video](http://www.youtube.com/watch?v=pi_I7oD_uGI#t=28m50s). Also see slides 30-32 of his presentation ([effective\_java\_reloaded.pdf](https://14b1424d-a-62cb3a1a-s-sites.googlegroups.com/site/io/effective-java-reloaded/effective_java_reloaded.pdf?attachauth=ANoY7crKCOet2NEUGW7RV1XfM-Jn4z8YJhs0qJM11OhLRnFW_JbExkJtvJ3UJvTE40dhAciyWcRIeGJ-n3FLGnMOapHShHINh8IY05YViOJoZWzaohMtM-s4HCi5kjREagi8awWtcYD0_6G7GhKr2BndToeqLk5sBhZcQfcYIyAE5A4lGNosDCjODcBAkJn8EuO6572t2wU1LMSEUgjvqcf4I-Fp6VDhDvih_XUEmL9nuVJQynd2DRpxyuNH1SpJspEIdbLw-WWZ&attredirects=0)):
>
> ### The Right Way to Implement a Serializable Singleton
>
>
>
> ```
> public enum Elvis {
> INSTANCE;
> private final String[] favoriteSongs =
> { "Hound Dog", "Heartbreak Hotel" };
> public void printFavorites() {
> System.out.println(Arrays.toString(favoriteSongs));
> }
> }
>
> ```
>
>
**Edit:** An [online portion of "Effective Java"](http://www.ddj.com/java/208403883?pgno=3) says:
>
> "This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, **a single-element enum type is the best way to implement a singleton**."
>
>
> |
70,732 | <p>Lasty, I tried to implements an hybrid structure in Java, something that looks like:</p>
<pre><code>public class MapOfSet<K, V extends HasKey<K>> implements Set<V>, Map<K, Set<V>>
</code></pre>
<p>Where HasKey is the following interface:</p>
<pre><code>public interface HasKey<K> {
public K getKey();
}
</code></pre>
<p>Unfortunately, there are some conflicts between methos signature of the Set interface and the Map interface in Java. I've finally chosen to implements only the Set interface and to add the Map method without implementing this interface.</p>
<p>Do you see a nicer solution?</p>
<p>In response to the first comments, here is my goal:</p>
<blockquote>
<p>Have a set structure and be able to efficiently access to a subset of values of this set, corresponding to a given key value.
At the beginning I instantiated a map and a set, but I tried to joined the two structures to optimize performances.</p>
</blockquote>
| [
{
"answer_id": 70760,
"author": "Avi",
"author_id": 1605,
"author_profile": "https://Stackoverflow.com/users/1605",
"pm_score": 0,
"selected": false,
"text": "<p>I would say that something that is meant to be sometimes used as a Map and sometimes as a Set should implement Map, since that... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1730/"
] | Lasty, I tried to implements an hybrid structure in Java, something that looks like:
```
public class MapOfSet<K, V extends HasKey<K>> implements Set<V>, Map<K, Set<V>>
```
Where HasKey is the following interface:
```
public interface HasKey<K> {
public K getKey();
}
```
Unfortunately, there are some conflicts between methos signature of the Set interface and the Map interface in Java. I've finally chosen to implements only the Set interface and to add the Map method without implementing this interface.
Do you see a nicer solution?
In response to the first comments, here is my goal:
>
> Have a set structure and be able to efficiently access to a subset of values of this set, corresponding to a given key value.
> At the beginning I instantiated a map and a set, but I tried to joined the two structures to optimize performances.
>
>
> | Perhaps you could add more information which operations do you really want. I guess you want to create a set which automatically groups their elements by a key, right? The question is which operations do you want to be able to have? How are elements added to the Set? Can elements be deleted by removing them from a grouped view? My proposal would be an interface like that:
```
public interface GroupedSet<K, V extends HasKey<K>> extends Set<V>{
Set<V> havingKey(K k);
}
```
If you want to be able to use the Set as map you can add another method
```
Map<K,Set<V>> asMap();
```
That avoids the use of multiple interface inheritance and the resulting problems. |
70,758 | <p>I know you can put <% if %> statements in the ItemTemplate to hide controls but the column is still there.
You cannot put <% %> statements into the LayoutTemplate which is where the column headings are declared, hence the problem.
Does anyone know of a better way?</p>
| [
{
"answer_id": 70955,
"author": "Magnus Johansson",
"author_id": 3584,
"author_profile": "https://Stackoverflow.com/users/3584",
"pm_score": 0,
"selected": false,
"text": "<p>You can always set the column width to 0 (zero) if you don't find a better way.</p>\n"
},
{
"answer_id": ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10186/"
] | I know you can put <% if %> statements in the ItemTemplate to hide controls but the column is still there.
You cannot put <% %> statements into the LayoutTemplate which is where the column headings are declared, hence the problem.
Does anyone know of a better way? | Here's another solution that I just did, seeing that I understand what you want to do:
**Here's your ASCX / ASPX**
```
<asp:ListView ID="ListView1" runat="server" DataSourceID="MyDataSource" ItemPlaceholderID="itemPlaceHolder" OnDataBound="ListView1_DataBound">
<LayoutTemplate>
<table border="1">
<tr>
<td>Name</td>
<td>Age</td>
<td runat="server" id="tdIsSuperCool">IsSuperCool</td>
</tr>
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("Name") %></td>
<td><%# Eval("Age") %></td>
<td runat="server" id="myCol" visible='<%# (bool)Eval("IsSuperCool") %>'>true</td>
</tr>
</ItemTemplate>
</asp:ListView>
<asp:ObjectDataSource
ID="MyDataSource"
runat="server"
DataObjectTypeName="BusinessLogicLayer.Thing"
SelectMethod="SelectThings"
TypeName="BusinessLogicLayer.MyObjectDataSource" />
```
**Here's the code behind**
```
/// <summary>
/// Handles the DataBound event of the ListView1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void ListView1_DataBound(object sender, EventArgs e)
{
ListView1.FindControl("tdIsSuperCool").Visible = false;
}
```
Do whatever you want in the databound. Because the column is now runat server, and you're handling the DataBound of the control, when you do ListView1.FindControl("tdIsSuperCool") you're in the Layout template so that works like a champ.
Put whatever business logic that you want to control the visibility of the td and you're good. |
70,773 | <p>What are the pros / cons of using <code>pthread_cond_wait</code> or using a semaphore ?
I am waiting for a state change like this :</p>
<pre><code>pthread_mutex_lock(&cam->video_lock);
while(cam->status == WAIT_DISPLAY) {
pthread_cond_wait(&cam->video_cond, &cam->video_lock);
}
pthread_mutex_unlock(&cam->video_lock);
</code></pre>
<p>Using a properly initialised semaphore, I think I could do it like this :</p>
<pre><code>while(cam->status == WAIT_DISPLAY) {
sem_wait(&some_semaphore);
}
</code></pre>
<p>What are the pros and cons of each method ?</p>
| [
{
"answer_id": 70924,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 0,
"selected": false,
"text": "<p>In your second snippet, you're getting the lock multitude of times, never releasing it.</p>\n\n<p>In general, the state y... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11589/"
] | What are the pros / cons of using `pthread_cond_wait` or using a semaphore ?
I am waiting for a state change like this :
```
pthread_mutex_lock(&cam->video_lock);
while(cam->status == WAIT_DISPLAY) {
pthread_cond_wait(&cam->video_cond, &cam->video_lock);
}
pthread_mutex_unlock(&cam->video_lock);
```
Using a properly initialised semaphore, I think I could do it like this :
```
while(cam->status == WAIT_DISPLAY) {
sem_wait(&some_semaphore);
}
```
What are the pros and cons of each method ? | A semaphore is suited cleanly to a producer-consumer model, although it has other uses. Your program logic is responsible for ensuring that the right number of posts are made for the number of waits. If you post a semaphore and nobody is waiting on it yet, then when they do wait they continue immediately. If your problem is such that it can be explained in terms of the count value of a semaphore, then it should be easy to solve with a semaphore.
A condition variable is a bit more forgiving in some respects. You can for example use cond\_broadcast to wake up all waiters, without the producer knowing how many there are. And if you cond\_signal a condvar with nobody waiting on it then nothing happens. This is good if you don't know whether there's going to be a listener interested. It is also why the listener should always check the state with the mutex held before waiting - if they don't then they can miss a signal and not wake up until the next one (which could be never).
So a condition variable is suitable for notifying interested parties that state has changed: you acquire the mutex, change the state, signal (or broadcast) the condvar and release the mutex. If this describes your problem you're in condvar territory. If different listeners are interested in different states you can just broadcast and they'll each in turn wake up, figure out whether they've found the state they want, and if not wait again.
It's very gnarly indeed to attempt this sort of thing with a mutex and a semaphore. The problem comes when you want to take the mutex, check some state, then wait on the semaphore for changes. Unless you can atomically release the mutex and wait on the semaphore (which in pthreads you can't), you end up waiting on the semaphore while holding the mutex. This blocks the mutex, meaning that others can't take it to make the change you care about. So you will be tempted to add another mutex in a way which depends on your specific requirements. And maybe another semaphore. The result is generally incorrect code with harmful race conditions.
Condition variables escape this problem, because calling cond\_wait automatically releases the mutex, freeing it for use by others. The mutex is regained before cond\_wait returns.
IIRC it is possible to implement a kind of condvar using only semaphores, but if the mutex you're implementing to go with the condvar is required to have trylock, then it's a serious head-scratcher, and timed waits are out. Not recommended. So don't assume that anything you can do with a condvar can be done with semaphores. Plus of course mutexes can have nice behaviours that semaphores lack, principally priority-inversion avoidance. |
70,779 | <p>I need to be able to quickly convert an image (inside a rails controller) so that the hosting company using managing our application can quickly test at any time to ensure that rmagick is not only successfully installed, but can be called throgh the rails stiack, what is the quickest clean code I can use to do this?</p>
| [
{
"answer_id": 70932,
"author": "tomafro",
"author_id": 7126,
"author_profile": "https://Stackoverflow.com/users/7126",
"pm_score": 0,
"selected": false,
"text": "<p>I'd log on to the server and try out your code in script/console. This will still go through the rails stack, but will al... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7473/"
] | I need to be able to quickly convert an image (inside a rails controller) so that the hosting company using managing our application can quickly test at any time to ensure that rmagick is not only successfully installed, but can be called throgh the rails stiack, what is the quickest clean code I can use to do this? | I wanted to do this so that I can easily hit it with a web browser, as I'm deployng to managed servers, which I do not have shell access onto (for increased security).
So this is what I did
```
class DiagnosticsController < ApplicationController
require 'RMagick'
def rmagick
images_path = "public/images"
file_name = "rmagick_generated_thumb.jpg"
file_path = images_path + "/"+ file_name
File.delete file_path if File.exists? file_path
img = Magick::Image.read("lib/sample_images/magic.jpg").first
thumb = img.scale(0.25)
@path = file_name
thumb.write file_path
end
end #------
```
and then in rmagick.html.erb
```
<%= image_tag @path %>
```
Now I can hit the controller, and if I see an image, I know rmagic is installed. |
70,782 | <p>How to get a file's creation date or file size, for example this Hello.jpg at <a href="http://www.mywebsite.com/now/Hello.jpg(note" rel="nofollow noreferrer">http://www.mywebsite.com/now/Hello.jpg(note</a>: This URL does not exist)? The purpose of this question is to make my application re-download the files from the any website when it has detected that the website has an updated version of the files and the files in my local folder are out of date. Any ideas?</p>
| [
{
"answer_id": 70803,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": true,
"text": "<p>If you use the HEAD request it will send the headers for the resource, there you can check the cache control header... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | How to get a file's creation date or file size, for example this Hello.jpg at <http://www.mywebsite.com/now/Hello.jpg(note>: This URL does not exist)? The purpose of this question is to make my application re-download the files from the any website when it has detected that the website has an updated version of the files and the files in my local folder are out of date. Any ideas? | If you use the HEAD request it will send the headers for the resource, there you can check the cache control headers which will tell you if the resource has been modified, last modification time, size (content-length) and date.
```
$ telnet www.google.com 80
Trying 216.239.59.103...
Connected to www.l.google.com.
Escape character is '^]'.
HEAD /intl/en_ALL/images/logo.gif HTTP/1.0
HTTP/1.0 200 OK
Content-Type: image/gif
Last-Modified: Wed, 07 Jun 2006 19:38:24 GMT
Expires: Sun, 17 Jan 2038 19:14:07 GMT
Cache-Control: public
Date: Tue, 16 Sep 2008 09:45:42 GMT
Server: gws
Content-Length: 8558
Connection: Close
Connection closed by foreign host.
```
Note that you'll probably have to decorate this basic and easy approach with many heuristics depending on the craziness of each webserver's admin, as each can send whatever headers they like. If they do not provide caching headers (Last-Modified, Expires, Cache-Control) nor Content-Length nor etag, you'd be stuck with redownloading it to test. |
70,797 | <p>How do I have a Python script that a) can accept user input and how do I make it b) read in arguments if run from the command line?</p>
| [
{
"answer_id": 70814,
"author": "lbz",
"author_id": 11530,
"author_profile": "https://Stackoverflow.com/users/11530",
"pm_score": 9,
"selected": false,
"text": "<pre><code>var = raw_input(\"Please enter something: \")\nprint \"you entered\", var\n</code></pre>\n\n<p>Or for Python 3:</p>\... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | How do I have a Python script that a) can accept user input and how do I make it b) read in arguments if run from the command line? | To read user input you can try [the `cmd` module](https://docs.python.org/dev/library/cmd.html) for easily creating a mini-command line interpreter (with help texts and autocompletion) and [`raw_input`](https://docs.python.org/2/library/functions.html#raw_input) ([`input`](https://docs.python.org/dev/library/functions.html#input) for Python 3+) for reading a line of text from the user.
```
text = raw_input("prompt") # Python 2
text = input("prompt") # Python 3
```
Command line inputs are in `sys.argv`. Try this in your script:
```
import sys
print (sys.argv)
```
There are two modules for parsing command line options: [~~`optparse`~~](https://docs.python.org/dev/library/optparse.html) (deprecated since Python 2.7, use [`argparse`](https://docs.python.org/dev/library/argparse.html) instead) and [`getopt`](https://docs.python.org/dev/library/getopt.html). If you just want to input files to your script, behold the power of [`fileinput`](https://docs.python.org/dev/library/fileinput.html).
The [Python library reference](https://docs.python.org/dev/library/) is your friend. |
70,842 | <p>How should I run another program from within my <code>C</code> program? I need to be able to write data into <code>STDIN</code> of the launched program (and maybe read from it's <code>STDOUT</code>)</p>
<p>I am not sure if this is a standard C function. I need the solution that should work under Linux.</p>
| [
{
"answer_id": 70848,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 5,
"selected": true,
"text": "<p>You want to use <code>popen</code>. It gives you a unidirectional pipe with which you can access stdin and stdout of the ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6974/"
] | How should I run another program from within my `C` program? I need to be able to write data into `STDIN` of the launched program (and maybe read from it's `STDOUT`)
I am not sure if this is a standard C function. I need the solution that should work under Linux. | You want to use `popen`. It gives you a unidirectional pipe with which you can access stdin and stdout of the program.
popen is standard on modern unix and unix-like OS, of which Linux is one :-)
Type
```
man popen
```
in a terminal to read more about it.
**EDIT**
Whether `popen` produces unidirectional or bidirectional pipes depends on the implementation. In [Linux](https://manpages.debian.org/jessie/manpages-dev/popen.3.en.html) and [OpenBSD](http://man.openbsd.org/OpenBSD-current/man3/popen.3), `popen` produces unidirectional pipes, which are read-only or write-only. On [OS X](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/popen.3.html), [FreeBSD](https://www.freebsd.org/cgi/man.cgi?query=popen&apropos=0&sektion=0&manpath=FreeBSD+11.0-RELEASE+and+Ports&arch=default&format=html) and [NetBSD](http://netbsd.gw.com/cgi-bin/man-cgi?popen++NetBSD-current) `popen` produces bidirectional pipes. |
70,850 | <p>What advantage, if any, is provided by formatting C code as follows:</p>
<pre><code>while(lock_file(lockdir)==0)
{
count++;
if(count==20)
{
fprintf(stderr,"Can't lock dir %s\n",lockdir);
exit(1);
}
sleep(3);
}
if(rmdir(serverdir)!=0)
{
switch(errno)
{
case EEXIST:
fprintf(stderr,"Server dir %s not empty\n",serverdir);
break;
default:
fprintf(stderr,"Can't delete dir %s\n",serverdir);
}
exit(1);
}
unlock_file(lockdir);
</code></pre>
<p>versus something more typical such as</p>
<pre><code>while(lock_file(lockdir)==0) {
count++;
if(count==20) {
fprintf(stderr,"Can't lock dir %s\n",lockdir);
exit(1);
}
sleep(3);
}
if(rmdir(serverdir)!=0) {
switch(errno) {
case EEXIST:
fprintf(stderr,"Server dir %s not empty\n",serverdir);
break;
default:
fprintf(stderr,"Can't delete dir %s\n",serverdir);
}
exit(1);
}
unlock_file(lockdir);
</code></pre>
<p>I just find the top version difficult to read and to get the indenting level correct for statements outside of a long block, especially for longs blocks containing several nested blocks.</p>
<p>Only advantage I can see is just to be different and leave your fingerprints on code that you've written.</p>
<p>I notice vim formatting would have to be hand-rolled to handle the top case.</p>
| [
{
"answer_id": 70862,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 3,
"selected": false,
"text": "<p>Nothing. Indentation and other coding standards are a matter of preference.</p>\n"
},
{
"answer_id": 70863,
"a... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2974/"
] | What advantage, if any, is provided by formatting C code as follows:
```
while(lock_file(lockdir)==0)
{
count++;
if(count==20)
{
fprintf(stderr,"Can't lock dir %s\n",lockdir);
exit(1);
}
sleep(3);
}
if(rmdir(serverdir)!=0)
{
switch(errno)
{
case EEXIST:
fprintf(stderr,"Server dir %s not empty\n",serverdir);
break;
default:
fprintf(stderr,"Can't delete dir %s\n",serverdir);
}
exit(1);
}
unlock_file(lockdir);
```
versus something more typical such as
```
while(lock_file(lockdir)==0) {
count++;
if(count==20) {
fprintf(stderr,"Can't lock dir %s\n",lockdir);
exit(1);
}
sleep(3);
}
if(rmdir(serverdir)!=0) {
switch(errno) {
case EEXIST:
fprintf(stderr,"Server dir %s not empty\n",serverdir);
break;
default:
fprintf(stderr,"Can't delete dir %s\n",serverdir);
}
exit(1);
}
unlock_file(lockdir);
```
I just find the top version difficult to read and to get the indenting level correct for statements outside of a long block, especially for longs blocks containing several nested blocks.
Only advantage I can see is just to be different and leave your fingerprints on code that you've written.
I notice vim formatting would have to be hand-rolled to handle the top case. | The top example is know as "Whitesmiths style". [Wikipedia's entry on Indent Styles](http://en.wikipedia.org/wiki/Indent_style) explains several styles along with their advantages and disadvantages. |
70,855 | <p>Is there a realistic way of implementing a multi-threaded model in PHP whether truly, or just simulating it. Some time back it was suggested that you could force the operating system to load another instance of the PHP executable and handle other simultaneous processes.</p>
<p>The problem with this is that when the PHP code finished executing the PHP instance remains in memory because there is no way to kill it from within PHP. So if you are simulating several threads you can imagine whats going to happen. So I am still looking for a way multi-threading can be done or simulated effectively from within PHP. Any ideas?</p>
| [
{
"answer_id": 71043,
"author": "J.D. Fitz.Gerald",
"author_id": 11542,
"author_profile": "https://Stackoverflow.com/users/11542",
"pm_score": 4,
"selected": false,
"text": "<p>While you can't thread, you do have some degree of process control in php. The two function sets that are usefu... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11190/"
] | Is there a realistic way of implementing a multi-threaded model in PHP whether truly, or just simulating it. Some time back it was suggested that you could force the operating system to load another instance of the PHP executable and handle other simultaneous processes.
The problem with this is that when the PHP code finished executing the PHP instance remains in memory because there is no way to kill it from within PHP. So if you are simulating several threads you can imagine whats going to happen. So I am still looking for a way multi-threading can be done or simulated effectively from within PHP. Any ideas? | Multi-threading is possible in php
==================================
Yes you can do multi-threading in PHP with [pthreads](https://github.com/krakjoe/pthreads)
From [the PHP documentation](http://www.php.net/manual/en/intro.pthreads.php):
>
> pthreads is an object-orientated API that provides all of the tools needed for multi-threading in PHP. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Threaded objects.
>
>
> **Warning**:
> The pthreads extension cannot be used in a web server environment. Threading in PHP should therefore remain to CLI-based applications only.
>
>
>
**Simple Test**
```
#!/usr/bin/php
<?php
class AsyncOperation extends Thread {
public function __construct($arg) {
$this->arg = $arg;
}
public function run() {
if ($this->arg) {
$sleep = mt_rand(1, 10);
printf('%s: %s -start -sleeps %d' . "\n", date("g:i:sa"), $this->arg, $sleep);
sleep($sleep);
printf('%s: %s -finish' . "\n", date("g:i:sa"), $this->arg);
}
}
}
// Create a array
$stack = array();
//Initiate Multiple Thread
foreach ( range("A", "D") as $i ) {
$stack[] = new AsyncOperation($i);
}
// Start The Threads
foreach ( $stack as $t ) {
$t->start();
}
?>
```
First Run
```
12:00:06pm: A -start -sleeps 5
12:00:06pm: B -start -sleeps 3
12:00:06pm: C -start -sleeps 10
12:00:06pm: D -start -sleeps 2
12:00:08pm: D -finish
12:00:09pm: B -finish
12:00:11pm: A -finish
12:00:16pm: C -finish
```
Second Run
```
12:01:36pm: A -start -sleeps 6
12:01:36pm: B -start -sleeps 1
12:01:36pm: C -start -sleeps 2
12:01:36pm: D -start -sleeps 1
12:01:37pm: B -finish
12:01:37pm: D -finish
12:01:38pm: C -finish
12:01:42pm: A -finish
```
**Real World Example**
```
error_reporting(E_ALL);
class AsyncWebRequest extends Thread {
public $url;
public $data;
public function __construct($url) {
$this->url = $url;
}
public function run() {
if (($url = $this->url)) {
/*
* If a large amount of data is being requested, you might want to
* fsockopen and read using usleep in between reads
*/
$this->data = file_get_contents($url);
} else
printf("Thread #%lu was not provided a URL\n", $this->getThreadId());
}
}
$t = microtime(true);
$g = new AsyncWebRequest(sprintf("http://www.google.com/?q=%s", rand() * 10));
/* starting synchronization */
if ($g->start()) {
printf("Request took %f seconds to start ", microtime(true) - $t);
while ( $g->isRunning() ) {
echo ".";
usleep(100);
}
if ($g->join()) {
printf(" and %f seconds to finish receiving %d bytes\n", microtime(true) - $t, strlen($g->data));
} else
printf(" and %f seconds to finish, request failed\n", microtime(true) - $t);
}
``` |
70,880 | <p>Say I have the following C++:</p>
<pre><code>char *p = new char[cb];
SOME_STRUCT *pSS = (SOME_STRUCT *) p;
delete pSS;
</code></pre>
<p>Is this safe according to the C++ standard? Do I need to cast back to a <code>char*</code> and then use <code>delete[]</code>? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it guaranteed to be safe?</p>
| [
{
"answer_id": 70904,
"author": "Daniel James",
"author_id": 2434,
"author_profile": "https://Stackoverflow.com/users/2434",
"pm_score": 3,
"selected": false,
"text": "<p>No, it's undefined behaviour - a compiler could plausibly do something different, and as the C++ FAQ entry that <a hr... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446/"
] | Say I have the following C++:
```
char *p = new char[cb];
SOME_STRUCT *pSS = (SOME_STRUCT *) p;
delete pSS;
```
Is this safe according to the C++ standard? Do I need to cast back to a `char*` and then use `delete[]`? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it guaranteed to be safe? | It's not guaranteed to be safe. Here's a relevant link in the C++ FAQ lite:
[16.13] Can I drop the `[]` when deleting array of some built-in type (`char`, `int`, etc.)?
[http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.13](https://isocpp.org/wiki/faq/freestore-mgmt#delete-array-built-ins) |
70,947 | <p>I have a workbook with 20 different pivot tables. Is there any easy way to find all the pivot tables and refresh them in VBA?</p>
| [
{
"answer_id": 70976,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 9,
"selected": true,
"text": "<p>Yes.</p>\n\n<pre><code>ThisWorkbook.RefreshAll\n</code></pre>\n\n<p>Or, if your Excel version is old enough,</p>\n\n<pre><c... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8418/"
] | I have a workbook with 20 different pivot tables. Is there any easy way to find all the pivot tables and refresh them in VBA? | Yes.
```
ThisWorkbook.RefreshAll
```
Or, if your Excel version is old enough,
```
Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
For Each Pivot in Sheet.PivotTables
Pivot.RefreshTable
Pivot.Update
Next
Next
``` |
70,956 | <p>Is there a good way to exclude certain pages from using a HTTP module?</p>
<p>I have an application that uses a custom HTTP module to validate a session. The HTTPModule is set up like this in web config:</p>
<pre><code><system.web>
<!-- ... -->
<httpModules>
<add name="SessionValidationModule"
type="SessionValidationModule, SomeNamespace" />
</httpModules>
</system.web>
</code></pre>
<p>To exclude the module from the page, I tried doing this (without success):</p>
<pre><code><location path="ToBeExcluded">
<system.web>
<!-- ... -->
<httpModules>
<remove name="SessionValidationModule" />
</httpModules>
</system.web>
</location>
</code></pre>
<p>Any thoughts?</p>
| [
{
"answer_id": 71790,
"author": "Crob",
"author_id": 2460,
"author_profile": "https://Stackoverflow.com/users/2460",
"pm_score": 5,
"selected": true,
"text": "<p>You could use an HTTPHandler instead of an HTTPModule. Handlers let you specify a path when you declare them in Web.Config. ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6308/"
] | Is there a good way to exclude certain pages from using a HTTP module?
I have an application that uses a custom HTTP module to validate a session. The HTTPModule is set up like this in web config:
```
<system.web>
<!-- ... -->
<httpModules>
<add name="SessionValidationModule"
type="SessionValidationModule, SomeNamespace" />
</httpModules>
</system.web>
```
To exclude the module from the page, I tried doing this (without success):
```
<location path="ToBeExcluded">
<system.web>
<!-- ... -->
<httpModules>
<remove name="SessionValidationModule" />
</httpModules>
</system.web>
</location>
```
Any thoughts? | You could use an HTTPHandler instead of an HTTPModule. Handlers let you specify a path when you declare them in Web.Config.
```
<add verb="*" path="/validate/*.aspx" type="Handler,Assembly"/>
```
If you must use an HTTPModule, you could just check the path of the request and if it's one to be excluded, bypass the validation. |
70,964 | <p>Originally I am looking for a solution in Actionscript. The point of this question is the algorithm, which detects the exact Minute, when a clock has to switch the Daylight Saving Time. </p>
<p>So for example between the 25th and the 31th of October we have to check, if the actual date is a sunday, it is before or after 2 o'clock...</p>
| [
{
"answer_id": 154765,
"author": "Benno Richters",
"author_id": 3565,
"author_profile": "https://Stackoverflow.com/users/3565",
"pm_score": 2,
"selected": false,
"text": "<p>There is no real algorithm for dealing with Daylight Saving Time. Basically every country can decide for themselve... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Originally I am looking for a solution in Actionscript. The point of this question is the algorithm, which detects the exact Minute, when a clock has to switch the Daylight Saving Time.
So for example between the 25th and the 31th of October we have to check, if the actual date is a sunday, it is before or after 2 o'clock... | There is no real algorithm for dealing with Daylight Saving Time. Basically every country can decide for themselves when -and if- DST starts and ends. The only thing we can do as developers is using some sort of table to look it up. Most computer languages integrate such a table in the language.
In Java you could use the `inDaylightTime` method of the [TimeZone](http://java.sun.com/javase/6/docs/api/java/util/TimeZone.html) class. If you want to know the exact date and time when DST starts or ends in a certain year, I would recommend to use [Joda Time](http://joda-time.sourceforge.net/). I can't see a clean way of finding this out using just the standard libraries.
The following program is an example: (Note that it could give unexpected results if a certain time zone does not have DST for a certain year)
```
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
public class App {
public static void main(String[] args) {
DateTimeZone dtz = DateTimeZone.forID("Europe/Amsterdam");
System.out.println(startDST(dtz, 2008));
System.out.println(endDST(dtz, 2008));
}
public static DateTime startDST(DateTimeZone zone, int year) {
return new DateTime(zone.nextTransition(new DateTime(year, 1, 1, 0, 0, 0, 0, zone).getMillis()));
}
public static DateTime endDST(DateTimeZone zone, int year) {
return new DateTime(zone.previousTransition(new DateTime(year + 1, 1, 1, 0, 0, 0, 0, zone).getMillis()));
}
}
``` |
70,992 | <p>Relating to my <a href="https://stackoverflow.com/questions/48733/javahibernate-jpa-designing-the-server-data-reload">earlier question</a>, I want to ensure all the child objects are loaded as I have a multiple threads that may need to access the data (and thus avoid lazy loading exceptions). I understand the way to do this is to use the "fetch" keyword in the query (EJB QL). Like this:</p>
<pre><code>select distinct o from Order o left join fetch o.orderLines
</code></pre>
<p>Assuming a model with an <code>Order</code> class which has a set of <code>OrderLines</code> in it.</p>
<p>My question is that the "distinct" keyword seems to be needed as otherwise I seem to get back an <code>Order</code> for each <code>OrderLine</code>. Am I doing the right thing?</p>
<p>Perhaps more importantly, is there a way to pull in all child objects, no matter how deep? We have around 10-15 classes and for the server we will need everything loaded... I was avoiding using <code>FetchType.EAGER</code> as that meant its always eager and in particular the web front end loads everything - but perhaps that is the way to go - is that what you do? I seem to remember us trying this before and then getting really slow webpages - but perhaps that means we should be using a second-level cache?</p>
| [
{
"answer_id": 71172,
"author": "Jeremy",
"author_id": 4419,
"author_profile": "https://Stackoverflow.com/users/4419",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not sure about using the fetch keyword in your EJBQL, you might be getting it confused with the annotation...</p>\n\n<p... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/48310/"
] | Relating to my [earlier question](https://stackoverflow.com/questions/48733/javahibernate-jpa-designing-the-server-data-reload), I want to ensure all the child objects are loaded as I have a multiple threads that may need to access the data (and thus avoid lazy loading exceptions). I understand the way to do this is to use the "fetch" keyword in the query (EJB QL). Like this:
```
select distinct o from Order o left join fetch o.orderLines
```
Assuming a model with an `Order` class which has a set of `OrderLines` in it.
My question is that the "distinct" keyword seems to be needed as otherwise I seem to get back an `Order` for each `OrderLine`. Am I doing the right thing?
Perhaps more importantly, is there a way to pull in all child objects, no matter how deep? We have around 10-15 classes and for the server we will need everything loaded... I was avoiding using `FetchType.EAGER` as that meant its always eager and in particular the web front end loads everything - but perhaps that is the way to go - is that what you do? I seem to remember us trying this before and then getting really slow webpages - but perhaps that means we should be using a second-level cache? | Changing the annotation is a bad idea IMO. As it can't be changed to lazy at runtime. Better to make everything lazy, and fetch as needed.
I'm not sure I understand your problem without mappings. Left join fetch should be all you need for the use case you describe. Of course you'll get back an order for every orderline if orderline has an order as its parent. |
70,993 | <p>We all know the various ways of testing OO systems. However, it looks like I'll be going to do a project where I'll be dealing with PLC ladder logic (don't ask :/), and I was wondering if there's a good way of testing the validity of the system.</p>
<p>The only way I see so far is simply constructing a huge table with all known states of the system and which output states that generates. This would do for simple 'if input A is on, turn output B on' cases. I don't think this will work for more complicated constructions though.</p>
| [
{
"answer_id": 71105,
"author": "jbdavid",
"author_id": 6314,
"author_profile": "https://Stackoverflow.com/users/6314",
"pm_score": 4,
"selected": true,
"text": "<p>The verification of \"logical\" systems in the IC design arena is known as \"Design Verification\", which is the process of... | 2008/09/16 | [
"https://Stackoverflow.com/questions/70993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/909/"
] | We all know the various ways of testing OO systems. However, it looks like I'll be going to do a project where I'll be dealing with PLC ladder logic (don't ask :/), and I was wondering if there's a good way of testing the validity of the system.
The only way I see so far is simply constructing a huge table with all known states of the system and which output states that generates. This would do for simple 'if input A is on, turn output B on' cases. I don't think this will work for more complicated constructions though. | The verification of "logical" systems in the IC design arena is known as "Design Verification", which is the process of ensuring that the system you design in hardware (RTL) implements the desired functionality.
Ladder logic can be transformed to one of the modern HDL's like Verilog..
transform each ladder
```
|---|R15|---+---|/R16|---------(R18)--------|
| |
|---|R12|---+
```
to an expression like
```
always @(*) R18 = !R16 && ( R15 | R12);
```
or you could use an assign statement
```
assign R18 = R16 && (R15 | R12);
```
a latching relay
```
assign R18 = (set condition) || R18 && !(break condition);
```
Then use a free verilog simulator like [Icarus](http://www.icarus.com/eda/verilog/) to develop a testbench and test your system.
Make sure you're testcases give good CODE coverage of your logic! And If your ladder editing software gives you decent naming capabilities, use them, rather than Rnn.
(Note: in Ladder Logic for PLC convention, Rnn is for internal relays, while, Xnn is an input and Ynn is an output, as can be quickly gleaned from one of the online tutorials.
Verilog will be an easier language to develop your tests and testbenches in!
It may be helpful to program in some unit delays.
Sorry, I have never looked for ladder logic to/from verilog translators..
but ladder logic in my day was only just being put into a computer for programming PLC's - most of the relay systems I used were REAL Relays, wired into the cabinets!!
Good luck.
jbd
There are a couple of ladder logic editors (with simultors) available for free..
here is one that runs on windows supposedly:
<http://cq.cx/ladder.pl> |
71,000 | <p>I'm trying to create a Zip file from .Net that can be read from Java code.</p>
<p>I've used SharpZipLib to create the Zip file but also if the file generated is valid according to the CheckZip function of the #ZipLib library and can be successfully uncompressed via WinZip or WinRar I always get an error when trying to uncompress it using the Java.Utils.Zip class in Java.</p>
<p>Problem seems to be in the wrong header written by SharpZipLib, I've also posted a question on the SharpDevelop forum but with no results (see <a href="http://community.sharpdevelop.net/forums/t/8272.aspx" rel="nofollow noreferrer">http://community.sharpdevelop.net/forums/t/8272.aspx</a> for info) but with no result.</p>
<p>Has someone a code sample of compressing a Zip file with .Net and de-compressing it with the Java.Utils.Zip class?</p>
<p>Regards
Massimo</p>
| [
{
"answer_id": 71060,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>Can't help with SharpZipLib, but you can try to create zip file using <a href=\"http://msdn.microsoft.com/en-us/library/system... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11673/"
] | I'm trying to create a Zip file from .Net that can be read from Java code.
I've used SharpZipLib to create the Zip file but also if the file generated is valid according to the CheckZip function of the #ZipLib library and can be successfully uncompressed via WinZip or WinRar I always get an error when trying to uncompress it using the Java.Utils.Zip class in Java.
Problem seems to be in the wrong header written by SharpZipLib, I've also posted a question on the SharpDevelop forum but with no results (see <http://community.sharpdevelop.net/forums/t/8272.aspx> for info) but with no result.
Has someone a code sample of compressing a Zip file with .Net and de-compressing it with the Java.Utils.Zip class?
Regards
Massimo | I have used [DotNetZip library](http://www.codeplex.com/DotNetZip) and it seems to work properly. Typical code:
```
using (ZipFile zipFile = new ZipFile())
{
zipFile.AddDirectory(sourceFolderPath);
zipFile.Save(archiveFolderName);
}
``` |
71,022 | <p>How do you return 1 value per row of the max of several columns:</p>
<p><strong>TableName</strong></p>
<pre><code>[Number, Date1, Date2, Date3, Cost]
</code></pre>
<p>I need to return something like this:</p>
<pre><code>[Number, Most_Recent_Date, Cost]
</code></pre>
<p>Query?</p>
| [
{
"answer_id": 71045,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 9,
"selected": true,
"text": "<p>This is an old answer and broken in many way.</p>\n<p>See <a href=\"https://stackoverflow.com/a/6871572/194653\">htt... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11703/"
] | How do you return 1 value per row of the max of several columns:
**TableName**
```
[Number, Date1, Date2, Date3, Cost]
```
I need to return something like this:
```
[Number, Most_Recent_Date, Cost]
```
Query? | This is an old answer and broken in many way.
See <https://stackoverflow.com/a/6871572/194653> which has way more upvotes and works with sql server 2008+ and handles nulls, etc.
**Original but problematic answer**:
Well, you can use the CASE statement:
```
SELECT
CASE
WHEN Date1 >= Date2 AND Date1 >= Date3 THEN Date1
WHEN Date2 >= Date1 AND Date2 >= Date3 THEN Date2
WHEN Date3 >= Date1 AND Date3 >= Date2 THEN Date3
ELSE Date1
END AS MostRecentDate
``` |
71,030 | <p>I'm aware I can add maven repositories for fetching dependencies in ~/.m2/settings.xml. But is it possible to add a repository using command line, something like:</p>
<pre><code>mvn install -Dmaven.repository=http://example.com/maven2
</code></pre>
<p>The reason I want to do this is because I'm using a continuous integration tool where I have full control over the command line options it uses to call maven, but managing the settings.xml for the user that runs the integration tool is a bit of a hassle.</p>
| [
{
"answer_id": 71132,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 3,
"selected": false,
"text": "<p>I am not sure if you can do it using the command line. You can on the other hand add repositories in the <strong>po... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113/"
] | I'm aware I can add maven repositories for fetching dependencies in ~/.m2/settings.xml. But is it possible to add a repository using command line, something like:
```
mvn install -Dmaven.repository=http://example.com/maven2
```
The reason I want to do this is because I'm using a continuous integration tool where I have full control over the command line options it uses to call maven, but managing the settings.xml for the user that runs the integration tool is a bit of a hassle. | You can do this but you're probably better off doing it in the POM as others have said.
On the command line you can specify a property for the local repository, and another repository for the remote repositories. The remote repository will have all default settings though
The example below specifies two remote repositories and a custom local repository.
```
mvn package -Dmaven.repo.remote=http://www.ibiblio.org/maven/,http://myrepo
-Dmaven.repo.local="c:\test\repo"
``` |
71,074 | <p>I can make Firefox not display the ugly dotted focus outlines on <b>links</b> with this:</p>
<pre class="lang-css prettyprint-override"><code>a:focus {
outline: none;
}
</code></pre>
<p>But how can I do this for <code><button></code> tags as well? When I do this:</p>
<pre class="lang-css prettyprint-override"><code>button:focus {
outline: none;
}
</code></pre>
<p>the buttons still have the dotted focus outline when I click on them.</p>
<p>(and yes, I know this is a usability issue, but I would like to provide my own focus hints which are appropriate to the design instead of ugly grey dots)</p>
| [
{
"answer_id": 71251,
"author": "Vitaly Sharovatov",
"author_id": 6647,
"author_profile": "https://Stackoverflow.com/users/6647",
"pm_score": 3,
"selected": false,
"text": "<p>There's no way to remove these dotted focus in Firefox using CSS.</p>\n\n<p>If you have access to the computers ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] | I can make Firefox not display the ugly dotted focus outlines on **links** with this:
```css
a:focus {
outline: none;
}
```
But how can I do this for `<button>` tags as well? When I do this:
```css
button:focus {
outline: none;
}
```
the buttons still have the dotted focus outline when I click on them.
(and yes, I know this is a usability issue, but I would like to provide my own focus hints which are appropriate to the design instead of ugly grey dots) | ```css
button::-moz-focus-inner {
border: 0;
}
``` |
71,108 | <p>Under what circumstances might you want to use multiple indirection (that is, a chain of pointers as in <code>Foo **</code>) in C++?</p>
| [
{
"answer_id": 71143,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "<p>IMO most common usage is to pass reference to pointer variable</p>\n\n<pre><code>void test(int ** var)\n{\n ...\n}\n\nint *foo... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11575/"
] | Under what circumstances might you want to use multiple indirection (that is, a chain of pointers as in `Foo **`) in C++? | Most common usage as @aku pointed out is to allow a change to a pointer parameter to be visible after the function returns.
```
#include <iostream>
using namespace std;
struct Foo {
int a;
};
void CreateFoo(Foo** p) {
*p = new Foo();
(*p)->a = 12;
}
int main(int argc, char* argv[])
{
Foo* p = NULL;
CreateFoo(&p);
cout << p->a << endl;
delete p;
return 0;
}
```
This will print
```
12
```
But there are several other useful usages as in the following example to iterate an array of strings and print them to the standard output.
```
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
const char* words[] = { "first", "second", NULL };
for (const char** p = words; *p != NULL; ++p) {
cout << *p << endl;
}
return 0;
}
``` |
71,118 | <p>I have developed a simple page using JQuery. It works fine in almost all browsers (i.e. Firefox, IE, Chrome) but whenever the page is opened in IE, it prompts Javascript error like,</p>
<pre><code>'guid' is null or not an object on line 1834
</code></pre>
<p>Do you have any idea ?</p>
| [
{
"answer_id": 71269,
"author": "Wouter Lievens",
"author_id": 7927,
"author_profile": "https://Stackoverflow.com/users/7927",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe you're using the parentNode or parentElement property? There are some issues with that in IE vs other browser... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/959/"
] | I have developed a simple page using JQuery. It works fine in almost all browsers (i.e. Firefox, IE, Chrome) but whenever the page is opened in IE, it prompts Javascript error like,
```
'guid' is null or not an object on line 1834
```
Do you have any idea ? | Thanks guys for your messages.
The error was on my part. For hover event, I was not passing function for "out". Therefore the handler was passed as undefined in jQuery.event function and that causing error for statement ,
if ( !handler.guid )
written at 1834 line of jquery-1.2.6.js file.
While using I thought that out handler is not mandatory to specify, but I guess I am wrong.
Strangely, FF / Chrome does not prompt error but IE does :) which is bit different than what it used to be.
Regards,
Jatan |
71,151 | <p>Using the Python Documentation I found the <a href="http://docs.python.org/lib/module-HTMLParser.html" rel="noreferrer">HTML parser</a> but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page).</p>
| [
{
"answer_id": 71161,
"author": "1077",
"author_id": 10776,
"author_profile": "https://Stackoverflow.com/users/10776",
"pm_score": 5,
"selected": true,
"text": "<p>Try:</p>\n\n<pre><code>import HTMLParser\n</code></pre>\n\n<p>In Python 3.0, the HTMLParser module has been renamed to html.... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | Using the Python Documentation I found the [HTML parser](http://docs.python.org/lib/module-HTMLParser.html) but I have no idea which library to import to use it, how do I find this out (bearing in mind it doesn't say on the page). | Try:
```
import HTMLParser
```
In Python 3.0, the HTMLParser module has been renamed to html.parser
you can check about this [here](http://docs.python.org/library/htmlparser.html)
Python 3.0
```
import html.parser
```
Python 2.2 and above
```
import HTMLParser
``` |
71,157 | <p>I may have this completely wrong, but my understanding is that the --standalone compiler option tells the compiler to include the F# core and other dependencies in the exe, so that you can run it on another machine without installing any 'runtime'.</p>
<p>However, I can't get this to work in the CTP - it doesn't even seem to change the size of the output file (docs I've read say about 1M extra).</p>
<p>"Google may know, but if it does, it ain't telling, or I'm not looking in the right place"</p>
<p><strong>UPDATE:</strong></p>
<p>It seems to work with latest CTP <a href="http://www.microsoft.com/downloads/details.aspx?familyid=61ad6924-93ad-48dc-8c67-60f7e7803d3c&displaylang=en" rel="nofollow noreferrer">update 1.9.6.2</a></p>
<p><strong>UPDATE2:</strong></p>
<p>I have since experienced another error: </p>
<pre><code>FSC(0,0): error FS0191: could not resolve assembly Microsoft.Build.Utilities.
</code></pre>
<p>If you get errors like this when trying to compile --standalone, you need to explicitly include them as references in your project.</p>
| [
{
"answer_id": 71200,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>F# manual: <a href=\"http://research.microsoft.com/fsharp/manual/compiler.aspx#Standalone\" rel=\"nofollow noreferrer\">Static... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11410/"
] | I may have this completely wrong, but my understanding is that the --standalone compiler option tells the compiler to include the F# core and other dependencies in the exe, so that you can run it on another machine without installing any 'runtime'.
However, I can't get this to work in the CTP - it doesn't even seem to change the size of the output file (docs I've read say about 1M extra).
"Google may know, but if it does, it ain't telling, or I'm not looking in the right place"
**UPDATE:**
It seems to work with latest CTP [update 1.9.6.2](http://www.microsoft.com/downloads/details.aspx?familyid=61ad6924-93ad-48dc-8c67-60f7e7803d3c&displaylang=en)
**UPDATE2:**
I have since experienced another error:
```
FSC(0,0): error FS0191: could not resolve assembly Microsoft.Build.Utilities.
```
If you get errors like this when trying to compile --standalone, you need to explicitly include them as references in your project. | Answer from MS:
*There is a CTP update 1.9.6.2 that fixed some --standalone bugs.*
I'm reinstalling now...
UPDATE:
Works for me - so the my accepted answer is **download CTP update 1.9.6.2**. |
71,180 | <p>How can I find the last row that contains data in a specific column and on a specific sheet?</p>
| [
{
"answer_id": 71197,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": -1,
"selected": false,
"text": "<pre><code>Function LastRow(rng As Range) As Long\n Dim iRowN As Long\n Dim iRowI As Long\n Dim iColN As Integer\... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8418/"
] | How can I find the last row that contains data in a specific column and on a specific sheet? | How about:
```
Function GetLastRow(strSheet, strColumn) As Long
Dim MyRange As Range
Set MyRange = Worksheets(strSheet).Range(strColumn & "1")
GetLastRow = Cells(Rows.Count, MyRange.Column).End(xlUp).Row
End Function
```
Regarding a comment, this will return the row number of the last cell even when only a single cell in the last row has data:
```
Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
``` |
71,257 | <p>How do I suspend a whole process (like the Process Explorer does when I click Suspend) in C#.</p>
<p>I'm starting the Process with Process.Start, and on a certain event, I want to suspend the process to be able to do some investigation on a "snapshot" of it.</p>
| [
{
"answer_id": 71290,
"author": "Dave Moore",
"author_id": 6996,
"author_profile": "https://Stackoverflow.com/users/6996",
"pm_score": 1,
"selected": false,
"text": "<p>See this CodeProject article for the win32 basics : <a href=\"http://www.codeproject.com/KB/threads/pausep.aspx\" rel=\... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9632/"
] | How do I suspend a whole process (like the Process Explorer does when I click Suspend) in C#.
I'm starting the Process with Process.Start, and on a certain event, I want to suspend the process to be able to do some investigation on a "snapshot" of it. | Here's my suggestion:
```
[Flags]
public enum ThreadAccess : int
{
TERMINATE = (0x0001),
SUSPEND_RESUME = (0x0002),
GET_CONTEXT = (0x0008),
SET_CONTEXT = (0x0010),
SET_INFORMATION = (0x0020),
QUERY_INFORMATION = (0x0040),
SET_THREAD_TOKEN = (0x0080),
IMPERSONATE = (0x0100),
DIRECT_IMPERSONATION = (0x0200)
}
[DllImport("kernel32.dll")]
static extern IntPtr OpenThread(ThreadAccess dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll")]
static extern uint SuspendThread(IntPtr hThread);
[DllImport("kernel32.dll")]
static extern int ResumeThread(IntPtr hThread);
[DllImport("kernel32", CharSet = CharSet.Auto,SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);
private static void SuspendProcess(int pid)
{
var process = Process.GetProcessById(pid); // throws exception if process does not exist
foreach (ProcessThread pT in process.Threads)
{
IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
if (pOpenThread == IntPtr.Zero)
{
continue;
}
SuspendThread(pOpenThread);
CloseHandle(pOpenThread);
}
}
public static void ResumeProcess(int pid)
{
var process = Process.GetProcessById(pid);
if (process.ProcessName == string.Empty)
return;
foreach (ProcessThread pT in process.Threads)
{
IntPtr pOpenThread = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)pT.Id);
if (pOpenThread == IntPtr.Zero)
{
continue;
}
var suspendCount = 0;
do
{
suspendCount = ResumeThread(pOpenThread);
} while (suspendCount > 0);
CloseHandle(pOpenThread);
}
}
``` |
71,309 | <p>for example this code</p>
<pre><code>var html = "<p>This text is <a href=#> good</a></p>";
var newNode = Builder.node('div',{className: 'test'},[html]);
$('placeholder').update(newNode);
</code></pre>
<p>casues the p and a tags to be shown, how do I prevent them from being escaped?</p>
| [
{
"answer_id": 71371,
"author": "Leo Lännenmäki",
"author_id": 2451,
"author_profile": "https://Stackoverflow.com/users/2451",
"pm_score": 3,
"selected": true,
"text": "<p>The last parameter to Builder.node is \"Array, List of other nodes to be appended as children\" according to the <a ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6892/"
] | for example this code
```
var html = "<p>This text is <a href=#> good</a></p>";
var newNode = Builder.node('div',{className: 'test'},[html]);
$('placeholder').update(newNode);
```
casues the p and a tags to be shown, how do I prevent them from being escaped? | The last parameter to Builder.node is "Array, List of other nodes to be appended as children" according to the [Wiki](http://github.com/madrobby/scriptaculous/wikis/builder). So when you pass it a string it is treated like text.
You could use:
```
var a = Builder.node('div').update("<a href='#'>foo</a>")
```
Where the link is text or:
```
var a = Builder.node('div', {'class':'cool'},
[Builder.node('div', {'class': 'another_div'})]
);
```
And you could use just Prototypes [new Element()](http://www.prototypejs.org/api/element) (Available as of version 1.6).
```
var a = new Element('div').insert(
new Element('div', {'class': 'inner_div'}).update("Text in the inner div")
);
``` |
71,323 | <p>I'm trying to replace each <code>,</code> in the current file by a new line:</p>
<pre><code>:%s/,/\n/g
</code></pre>
<p>But it inserts what looks like a <code>^@</code> instead of an actual newline. The file is not in DOS mode or anything.</p>
<p>What should I do?</p>
<p>If you are curious, like me, check the question <em><a href="https://stackoverflow.com/questions/71417/why-is-r-a-newline-for-vim">Why is \r a newline for Vim?</a></em> as well.</p>
| [
{
"answer_id": 71334,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 13,
"selected": true,
"text": "<h2>Use <code>\\r</code> instead of <code>\\n</code>.</h2>\n<p>Substituting by <code>\\n</code> inserts a null charact... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
] | I'm trying to replace each `,` in the current file by a new line:
```
:%s/,/\n/g
```
But it inserts what looks like a `^@` instead of an actual newline. The file is not in DOS mode or anything.
What should I do?
If you are curious, like me, check the question *[Why is \r a newline for Vim?](https://stackoverflow.com/questions/71417/why-is-r-a-newline-for-vim)* as well. | Use `\r` instead of `\n`.
-------------------------
Substituting by `\n` inserts a null character into the text. To get a newline, use `\r`. When *searching* for a newline, you’d still use `\n`, however. This asymmetry is due to the fact that `\n` and `\r` [do slightly different things](http://vim.wikia.com/wiki/Search_and_replace):
`\n` matches an end of line (newline), whereas `\r` matches a carriage return. On the other hand, in substitutions `\n` inserts a null character whereas `\r` inserts a newline (more precisely, it’s treated as the input `CR`). Here’s a small, non-interactive example to illustrate this, using the Vim command line feature (in other words, you can copy and paste the following into a terminal to run it). `xxd` shows a hexdump of the resulting file.
```
echo bar > test
(echo 'Before:'; xxd test) > output.txt
vim test '+s/b/\n/' '+s/a/\r/' +wq
(echo 'After:'; xxd test) >> output.txt
more output.txt
```
```
Before:
0000000: 6261 720a bar.
After:
0000000: 000a 720a ..r.
```
In other words, `\n` has inserted the byte 0x00 into the text; `\r` has inserted the byte 0x0a. |
71,328 | <p>I have PHP configured so that magic quotes are on and register globals are off.</p>
<p>I do my best to always call htmlentities() for anything I am outputing that is derived from user input.</p>
<p>I also occasionally seach my database for common things used in xss attached such as...</p>
<pre><code><script
</code></pre>
<p>What else should I be doing and how can I make sure that the things I am trying to do are <strong>always</strong> done.</p>
| [
{
"answer_id": 71358,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>Escaping all user input is enough for most sites. Also make sure that session IDs don't end up in the URL so they c... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4012/"
] | I have PHP configured so that magic quotes are on and register globals are off.
I do my best to always call htmlentities() for anything I am outputing that is derived from user input.
I also occasionally seach my database for common things used in xss attached such as...
```
<script
```
What else should I be doing and how can I make sure that the things I am trying to do are **always** done. | Escaping input is not the best you can do for successful XSS prevention. Also output must be escaped. If you use Smarty template engine, you may use `|escape:'htmlall'` modifier to convert all sensitive characters to HTML entities (I use own `|e` modifier which is alias to the above).
My approach to input/output security is:
* store user input not modified (no HTML escaping on input, only DB-aware escaping done via PDO prepared statements)
* escape on output, depending on what output format you use (e.g. HTML and JSON need different escaping rules) |
71,413 | <p>Given a table of votes (users vote for a choice, and must supply an email address):</p>
<pre><code>votes
--
id: int
choice: int
timestamp: timestamp
ip: varchar
email: varchar
</code></pre>
<p>What's the best way to count "unique" votes (a user being a unique combination of email + ip) given the constraint they may only vote <em>twice</em> per hour?</p>
<p>It's possible to count the number of hours between first and last vote and determine the maximum number of allowed votes for that timeframe, but that allows users to compress all their votes into say, a single hour-long window, and still have them counted.</p>
<p>I realize anonymous online voting is inherently flawed, but I'm not sure how to do this with SQL. Should I be using an external script or whatever instead? (For each choice, for each email+ip pair, get a vote, calculate the next +1h timestamp, count/discard/tally votes, move on to the next hour, etc...)</p>
| [
{
"answer_id": 71430,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 2,
"selected": false,
"text": "<p>Something like </p>\n\n<pre><code>select email, ip, count(choice)\nfrom votes\ngroup by email, ip, datepart(hour, timest... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Given a table of votes (users vote for a choice, and must supply an email address):
```
votes
--
id: int
choice: int
timestamp: timestamp
ip: varchar
email: varchar
```
What's the best way to count "unique" votes (a user being a unique combination of email + ip) given the constraint they may only vote *twice* per hour?
It's possible to count the number of hours between first and last vote and determine the maximum number of allowed votes for that timeframe, but that allows users to compress all their votes into say, a single hour-long window, and still have them counted.
I realize anonymous online voting is inherently flawed, but I'm not sure how to do this with SQL. Should I be using an external script or whatever instead? (For each choice, for each email+ip pair, get a vote, calculate the next +1h timestamp, count/discard/tally votes, move on to the next hour, etc...) | Something like
```
select email, ip, count(choice)
from votes
group by email, ip, datepart(hour, timestamp)
```
If I understand correctly |
71,416 | <p>I'm trying to do something like the following:</p>
<pre><code>enum E;
void Foo(E e);
enum E {A, B, C};
</code></pre>
<p>which the compiler rejects. I've had a quick look on Google and the consensus seems to be "you can't do it", but I can't understand why. Can anyone explain?</p>
<p>Clarification 2: I'm doing this as I have private methods in a class that take said enum, and I do not want the enum's values exposed - so, for example, I do not want anyone to know that E is defined as</p>
<pre><code>enum E {
FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X
}
</code></pre>
<p>as project X is not something I want my users to know about.</p>
<p>So, I wanted to forward declare the enum so I could put the private methods in the header file, declare the enum internally in the cpp, and distribute the built library file and header to people.</p>
<p>As for the compiler - it's GCC.</p>
| [
{
"answer_id": 71428,
"author": "prakash",
"author_id": 123,
"author_profile": "https://Stackoverflow.com/users/123",
"pm_score": 1,
"selected": false,
"text": "<p>It seems it can not be forward-declared in GCC!</p>\n<p>An interesting discussion is <a href=\"http://bytes.com/forum/thread... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11437/"
] | I'm trying to do something like the following:
```
enum E;
void Foo(E e);
enum E {A, B, C};
```
which the compiler rejects. I've had a quick look on Google and the consensus seems to be "you can't do it", but I can't understand why. Can anyone explain?
Clarification 2: I'm doing this as I have private methods in a class that take said enum, and I do not want the enum's values exposed - so, for example, I do not want anyone to know that E is defined as
```
enum E {
FUNCTIONALITY_NORMAL, FUNCTIONALITY_RESTRICTED, FUNCTIONALITY_FOR_PROJECT_X
}
```
as project X is not something I want my users to know about.
So, I wanted to forward declare the enum so I could put the private methods in the header file, declare the enum internally in the cpp, and distribute the built library file and header to people.
As for the compiler - it's GCC. | The reason the enum can't be forward declared is that, without knowing the values, the compiler can't know the storage required for the enum variable. C++ compilers are allowed to specify the actual storage space based on the size necessary to contain all the values specified. If all that is visible is the forward declaration, the translation unit can't know what storage size has been chosen – it could be a `char`, or an `int`, or something else.
---
From Section 7.2.5 of the ISO C++ Standard:
>
> The *underlying type* of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than `int` unless the value of an enumerator cannot fit in an `int` or `unsigned int`. If the *enumerator-list* is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value of `sizeof()` applied to an enumeration type, an object of enumeration type, or an enumerator, is the value of `sizeof()` applied to the underlying type.
>
>
>
Since the *caller* to the function must know the sizes of the parameters to correctly set up the call stack, the number of enumerations in an enumeration list must be known before the function prototype.
Update:
In C++0X, a syntax for forward declaring enum types has been proposed and accepted. You can see the proposal at *[Forward declaration of enumerations (rev.3)](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2764.pdf)* |
71,417 | <p>From question <em><a href="https://stackoverflow.com/questions/71323/how-to-replace-a-character-for-a-newline-in-vim">How to replace a character for a newline in Vim?</a></em>. You have to use \r when replacing text for a newline, like this</p>
<pre><code>:%s/%/\r/g
</code></pre>
<p>But when replacing end of lines and newlines for a character, you can do it like:</p>
<pre><code>:%s/\n/%/g
</code></pre>
<p>What section of the manual documents these behaviors, and what's the reasoning behind them?</p>
| [
{
"answer_id": 71531,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 6,
"selected": false,
"text": "<h3><a href=\"http://vimdoc.sf.net/htmldoc/pattern.html#NL-used-for-Nul\" rel=\"noreferrer\"><code>:help NL-used-... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
] | From question *[How to replace a character for a newline in Vim?](https://stackoverflow.com/questions/71323/how-to-replace-a-character-for-a-newline-in-vim)*. You have to use \r when replacing text for a newline, like this
```
:%s/%/\r/g
```
But when replacing end of lines and newlines for a character, you can do it like:
```
:%s/\n/%/g
```
What section of the manual documents these behaviors, and what's the reasoning behind them? | From [vim docs on patterns](http://vimdoc.sourceforge.net/htmldoc/pattern.html#/%5Cr):
>
> `\r` matches <CR>
>
>
> `\n` matches an end-of-line -
> When matching in a string instead of
> buffer text a literal newline
> character is matched.
>
>
> |
71,419 | <p>I've heard many programmers, particularly Delphi programmers scorn the use of 'with'. </p>
<p>I thought it made programs run faster (only one reference to parent object) and that it was easier to read the code if used sensibly (less than a dozen lines of code and no nesting).</p>
<p>Here's an example:</p>
<pre><code>procedure TBitmap32.FillRectS(const ARect: TRect; Value: TColor32);
begin
with ARect do FillRectS(Left, Top, Right, Bottom, Value);
end;
</code></pre>
<p>I like using <code>with</code>. What's wrong with me?</p>
| [
{
"answer_id": 71432,
"author": "Ralph M. Rickenbach",
"author_id": 4549416,
"author_profile": "https://Stackoverflow.com/users/4549416",
"pm_score": 2,
"selected": false,
"text": "<p>I do not like it because it makes debbuging a hassle. You cannot read the value of a variable or the lik... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11781/"
] | I've heard many programmers, particularly Delphi programmers scorn the use of 'with'.
I thought it made programs run faster (only one reference to parent object) and that it was easier to read the code if used sensibly (less than a dozen lines of code and no nesting).
Here's an example:
```
procedure TBitmap32.FillRectS(const ARect: TRect; Value: TColor32);
begin
with ARect do FillRectS(Left, Top, Right, Bottom, Value);
end;
```
I like using `with`. What's wrong with me? | One annoyance with using with is that the debugger can't handle it. So it makes debugging more difficult.
A bigger problem is that it is less easy to read the code. Especially if the with statement is a bit longer.
```
procedure TMyForm.ButtonClick(...)
begin
with OtherForm do begin
Left := 10;
Top := 20;
CallThisFunction;
end;
end;
```
Which Form's CallThisFunction will be called? Self (TMyForm) or OtherForm? You can't know without checking if OtherForm has a CallThisFunction method.
And the biggest problem is that you can make bugs easy without even knowing it. What if both TMyForm and OtherForm have a CallThisFunction, but it's private. You might expect/want the OtherForm.CallThisFunction to be called, but it really is not. The compiler would have warned you if you didn't use the with, but now it doesn't.
Using multiple objects in the with multiplies the problems. See <http://blog.marcocantu.com/blog/with_harmful.html> |
71,423 | <p>I want to disable the selection of certain rows in a datagridview.</p>
<p>It must be possible to remove the select property for one or more datagridview rows in a datagridview shown in a winform. The goal is that the user can't select certain rows. (depending on a condition)</p>
<p>Thankx,</p>
| [
{
"answer_id": 71665,
"author": "szevvy",
"author_id": 11437,
"author_profile": "https://Stackoverflow.com/users/11437",
"pm_score": 5,
"selected": true,
"text": "<p>If SelectionMode is FullRowSelect, then you'll need to override SetSelectedRowCore for that DataGridView, and not call the... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4392/"
] | I want to disable the selection of certain rows in a datagridview.
It must be possible to remove the select property for one or more datagridview rows in a datagridview shown in a winform. The goal is that the user can't select certain rows. (depending on a condition)
Thankx, | If SelectionMode is FullRowSelect, then you'll need to override SetSelectedRowCore for that DataGridView, and not call the base SetSelectedRowCore for rows you don't want selected.
If SelectionMode is not FullRowSelect, you'll want to additionally override SetSelectedCellCore (and not call the base SetSelectedCellCore for rows you don't want selected), as SetSelectedRowCore will only kick in if you click the row header and not an individual cell.
Here's an example:
```
public class MyDataGridView : DataGridView
{
protected override void SetSelectedRowCore(int rowIndex, bool selected)
{
if (selected && WantRowSelection(rowIndex))
{
base.SetSelectedRowCore(rowIndex, selected);
}
}
protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool selected)
{
if (selected && WantRowSelection(rowIndex))
{
base.SetSelectedRowCore(rowIndex, selected);
}
}
bool WantRowSelection(int rowIndex)
{
//return true if you want the row to be selectable, false otherwise
}
}
```
If you're using WinForms, crack open your designer.cs for the relevant form, and change the declaration of your DataGridView instance to use this new class instead of DataGridView, and also replace the this.blahblahblah = new System.Windows.Forms.DataGridView() to point to the new class. |
71,440 | <p>I have a UserControl in my Asp.net project that has a public property. I do not want this property to show up in the Visual Studio Property Window when a user highlights an instance of the UserControl in the IDE. What attribute (or other method) should I use to prevent it from showing up?</p>
<pre><code>class MyControl : System.Web.UI.UserControl {
// Attribute to prevent property from showing in VS Property Window?
public bool SampleProperty { get; set; }
// other stuff
}
</code></pre>
| [
{
"answer_id": 71454,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 5,
"selected": true,
"text": "<p>Use the following attribute ...</p>\n\n<pre><code>using System.ComponentModel;\n\n[Browsable(false)]\npublic bool Sampl... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51/"
] | I have a UserControl in my Asp.net project that has a public property. I do not want this property to show up in the Visual Studio Property Window when a user highlights an instance of the UserControl in the IDE. What attribute (or other method) should I use to prevent it from showing up?
```
class MyControl : System.Web.UI.UserControl {
// Attribute to prevent property from showing in VS Property Window?
public bool SampleProperty { get; set; }
// other stuff
}
``` | Use the following attribute ...
```
using System.ComponentModel;
[Browsable(false)]
public bool SampleProperty { get; set; }
```
In VB.net, this [will be](https://stackoverflow.com/questions/71440/set-a-usercontrol-property-to-not-show-up-in-vs-properties-window#71481):
```
<System.ComponentModel.Browsable(False)>
``` |
71,468 | <p>Does anybody know of a tool to test OCSP responses? Preferably, something that can be used from a Windows Command-line and/or can be included (easily) in a Java/python program </p>
| [
{
"answer_id": 71674,
"author": "Alexey Feldgendler",
"author_id": 10682,
"author_profile": "https://Stackoverflow.com/users/10682",
"pm_score": 1,
"selected": false,
"text": "<p>The newpki client claims to be able to do that.\n<a href=\"http://www.newpki.org/\" rel=\"nofollow noreferrer... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Does anybody know of a tool to test OCSP responses? Preferably, something that can be used from a Windows Command-line and/or can be included (easily) in a Java/python program | Looking a bit more, I think I've found some answers:
a) OpenSSL at the rescue:
```
openssl ocsp -whatever
```
For more info, <http://www.openssl.org/docs/apps/ocsp.html>
b) <http://www.openvalidation.org/> is another way of testing a cert. And via its links, I got to:
* <http://security.polito.it/tools/ocsp/>
* Ascertia OCSP Client tool (<http://www.ascertia.com/products/ocsptool/>)
* Ascertia OCSP Crusher tool (an OCSP load generator) (<http://www.ascertia.com/products/ocspCrusher/>)
Thanks to all the answers! |
71,469 | <p>Let's assume we've got the following Java code:</p>
<pre><code>public class Maintainer {
private Map<Enum, List<Listener>> map;
public Maintainer() {
this.map = new java.util.ConcurrentHashMap<Enum, List<Listener>>();
}
public void addListener( Listener listener, Enum eventType ) {
List<Listener> listeners;
if( ( listeners = map.get( eventType ) ) == null ) {
listeners = new java.util.concurrent.CopyOnWriteArrayList<Listener>();
map.put( eventType, listeners );
}
listeners.add( listener );
}
}
</code></pre>
<p>This code snippet is nothing but a bit improved listener pattern where each listener is telling what type of event it is interested in, and the provided method maintains a concurrent map of these relationships.</p>
<p>Initially, I wanted this method to be called via my own annotation framework, but bumped into a brick wall of various annotation limitations (e.g. you can't have <em>java.lang.Enum</em> as annotation param, also there's a set of various classloader issues) therefore decided to use Spring.</p>
<p>Could anyone tell me how do I Spring_ify_ this? What I want to achive is:<br>
1. Define <em>Maintainer</em> class as a Spring bean.<br>
2. Make it so that all sorts of listeners would be able to register themselves to <em>Maintainer</em> via XML by using <em>addListener</em> method. Spring doc nor Google are very generous in examples.</p>
<p>Is there a way to achieve this easily?</p>
| [
{
"answer_id": 71504,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>What would be wrong with doing something like the following:</p>\n\n<p>Defining a 'Maintainer' interface with the addListener... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7345/"
] | Let's assume we've got the following Java code:
```
public class Maintainer {
private Map<Enum, List<Listener>> map;
public Maintainer() {
this.map = new java.util.ConcurrentHashMap<Enum, List<Listener>>();
}
public void addListener( Listener listener, Enum eventType ) {
List<Listener> listeners;
if( ( listeners = map.get( eventType ) ) == null ) {
listeners = new java.util.concurrent.CopyOnWriteArrayList<Listener>();
map.put( eventType, listeners );
}
listeners.add( listener );
}
}
```
This code snippet is nothing but a bit improved listener pattern where each listener is telling what type of event it is interested in, and the provided method maintains a concurrent map of these relationships.
Initially, I wanted this method to be called via my own annotation framework, but bumped into a brick wall of various annotation limitations (e.g. you can't have *java.lang.Enum* as annotation param, also there's a set of various classloader issues) therefore decided to use Spring.
Could anyone tell me how do I Spring\_ify\_ this? What I want to achive is:
1. Define *Maintainer* class as a Spring bean.
2. Make it so that all sorts of listeners would be able to register themselves to *Maintainer* via XML by using *addListener* method. Spring doc nor Google are very generous in examples.
Is there a way to achieve this easily? | What would be wrong with doing something like the following:
Defining a 'Maintainer' interface with the addListener(Listener, Enum) method.
Create a DefaultMaintainer class (as above) which implements Maintainer.
Then, in each Listener class, 'inject' the Maintainer interface (constructor injection might be a good choice). The listener can then register itself with the Maintainer.
other than that, I'm not 100% clear on exactly what your difficulty is with Spring at the moment! :) |
71,478 | <p>Is it possible in <code>PHP (as it is in C++)</code> to declare a <code>class method</code> OUTSIDE the <code>class definition?</code></p>
| [
{
"answer_id": 71502,
"author": "Silver Dragon",
"author_id": 9440,
"author_profile": "https://Stackoverflow.com/users/9440",
"pm_score": 1,
"selected": false,
"text": "<p>No. </p>\n\n<p>You can extend previously declared classes, though, if that helps.</p>\n"
},
{
"answer_id": 7... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Is it possible in `PHP (as it is in C++)` to declare a `class method` OUTSIDE the `class definition?` | No, as of PHP 5.2. However, you may use `__call` magic method to forward call to arbitrary function or method.
```
class A {
public function __call($method, $args) {
if ($method == 'foo') {
return call_user_func_array('bar', $args);
}
}
}
function bar($x) {
echo $x;
}
$a = new A();
$a->foo('12345'); // will result in calling bar('12345')
```
In PHP 5.4 there is support for *traits*. Trait is an implementation of method(s) that cannot be instantiated as standalone object. Instead, trait can be used to extend class with contained implementation. Learn more on Traits [here](http://www.stefan-marr.de/artikel/rfc-traits-for-php.html). |
71,518 | <p>I just tried FxCop. It does detect unused private methods, but not unused public. Is there a custom rule that I can download, plug-in that will detect public methods that aren't called from within the same assembly?</p>
| [
{
"answer_id": 71538,
"author": "Loofer",
"author_id": 5552,
"author_profile": "https://Stackoverflow.com/users/5552",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.ndepend.com/\" rel=\"nofollow noreferrer\">NDepend</a> is your friend for this kind of thing</p>\n"
... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9328/"
] | I just tried FxCop. It does detect unused private methods, but not unused public. Is there a custom rule that I can download, plug-in that will detect public methods that aren't called from within the same assembly? | Corey, my answer of using FxCop had assumed you were interested in removing unused private members, however to solve the problem with other cases you can try using [NDepend](http://www.ndepend.com/). Here is some CQL to detect unused public members (adapted from an article listed below):
```
// <Name>Potentially unused methods</Name>
WARN IF Count > 0 IN SELECT METHODS WHERE
MethodCa == 0 AND // Ca=0 -> No Afferent Coupling -> The method
// is not used in the context of this
// application.
IsPublic AND // Check for unused public methods
!IsEntryPoint AND // Main() method is not used by-design.
!IsExplicitInterfaceImpl AND // The IL code never explicitely calls
// explicit interface methods implementation.
!IsClassConstructor AND // The IL code never explicitely calls class
// constructors.
!IsFinalizer // The IL code never explicitely calls
// finalizers.
```
Source: [Patrick Smacchia's "Code metrics on Coupling, Dead Code, Design flaws and Re-engineering](http://codebetter.com/blogs/patricksmacchia/archive/2008/02/15/code-metrics-on-coupling-dead-code-design-flaws-and-re-engineering.aspx). The article also goes over detecting dead fields and types.
*(EDIT: made answer more understandable)*
---
EDIT 11th June 2012: *Explain new NDepend facilities concerning unused code. Disclaimer: I am one of the developer of this tool.*
Since NDepend v4 released in May 2012, the tool proposes to write [Code Rule over LINQ Query (CQLinq)](http://codebetter.com/blogs/patricksmacchia/archive/2008/02/15/code-metrics-on-coupling-dead-code-design-flaws-and-re-engineering.aspx). Around [200 default code rules](http://www.ndepend.com/DefaultRules/webframe.html) are proposed, 3 of them being dedicated to *unused/dead code* detection:
* [Potentially dead Types](http://www.ndepend.com/DefaultRules/webframe.html?Q_Potentially_dead_Types.html) (hence detect unused class, struct, interface, delegate...)
* **[Potentially dead Methods](http://www.ndepend.com/DefaultRules/webframe.html?Q_Potentially_dead_Methods.html)** (hence detect unused method, ctor, property getter/setter...)
* [Potentially dead Fields](http://www.ndepend.com/DefaultRules/webframe.html?Q_Potentially_dead_Fields.html)
These CQLinq code rules are more powerful than the previous CQL ones. If you click these 3 links above toward the source code of these rules, you'll see that the ones concerning types and methods are a bit complex. This is because they detect not only unused types and methods, but also types and methods used *only* by unused dead types and methods (recursive).
This is *static analysis*, hence the prefix *Potentially* in the rule names. If a code element is used *only* through reflection, these rules might consider it as unused which is not the case.
In addition to using these 3 rules, I'd advise measuring code coverage by tests and striving for having full coverage. Often, you'll see that code that cannot be covered by tests, is actually *unused/dead* code that can be safely discarded. This is especially useful in complex algorithms where it is not clear if a branch of code is reachable or not. |
71,534 | <p>I hope I haven't painted myself into a corner. I've gotten what seems to be most of the way through implementing a Makefile and I can't get the last bit to work. I hope someone here can suggest a technique to do what I'm trying to do.</p>
<p>I have what I'll call "bills of materials" in version controlled files in a source repository and I build something like:</p>
<pre><code>make VER=x
</code></pre>
<p>I want my Makefile to use $(VER) as a tag to retrieve a BOM from the repository, generate a dependency file to include in the Makefile, rescan including that dependency, and then build the product. </p>
<p>More generally, my Makefile may have several targets -- A, B, C, etc. -- and I can build different versions of each so I might do:</p>
<pre><code>make A VER=x
make B VER=y
make C VER=z
</code></pre>
<p>and the dependency file includes information about all three targets.</p>
<p>However, creating the dependency file is somewhat expensive so if I do:</p>
<pre><code>make A VER=x
...make source (not BOM) changes...
make A VER=x
</code></pre>
<p>I'd really like the Makefile to not regenerate the dependency. And just to make things as complicated as possible, I might do:</p>
<pre><code>make A VER=x
.. change version x of A's BOM and check it in
make A VER=x
</code></pre>
<p>so I need to regenerate the dependency on the second build.</p>
<p>The check out messes up the timestamps used to regenerate the dependencies so I think I need a way for the dependency file to depend not on the BOM but on some indication that the BOM changed.</p>
<p>What I've come to is making the BOM checkout happen in a .PHONY target (so it always gets checked out) and keeping track of the contents of the last checkout in a ".sig" file (if the signature file is missing or the contents are different than the signature of the new file, then the BOM changed), and having the dependency generation depend on the signatures). At the top of my Makefile, I have some setup:</p>
<pre><code>BOMS = $(addsuffix .bom,$(MAKECMDGOALS)
SIGS = $(subst .bom,.sig,$(BOMS))
DEP = include.d
-include $(DEP)
</code></pre>
<p>And it seems I always need to do:</p>
<pre><code>.PHONY: $(BOMS)
$(BOMS):
...checkout TAG=$(VER) $@
</code></pre>
<p>But, as noted above, if i do just that, and continue:</p>
<pre><code>$(DEP) : $(BOMS)
... recreate dependency
</code></pre>
<p>Then the dependency gets updated every time I invoke make. So I try:</p>
<pre><code>$(DEP) : $(SIGS)
... recreate dependency
</code></pre>
<p>and</p>
<pre><code>$(BOMS):
...checkout TAG=$(VER) $@
...if $(subst .bom,.sig,$@) doesn't exist
... create signature file
...else
... if new signature is different from file contents
... update signature file
... endif
...endif
</code></pre>
<p>But the dependency generation doesn't get tripped when the signature changes. I think it's because because $(SIGS) isn't a target, so make doesn't notice when the $(BOMS) rule updates a signature.</p>
<p>I tried creating a .sig:.bom rule and managing the timestamps of the checked out BOM with touch but that didn't work.</p>
<p>Someone suggested something like:</p>
<pre><code>$(DEP) : $(SIGS)
... recreate dependency
$(BOMS) : $(SIGS)
...checkout TAG=$(VER) $@
$(SIGS) :
...if $(subst .bom,.sig,$(BOMS)) doesn't exist
... create it
...else
... if new signature is different from file contents
... update signature file
... endif
...endif
</code></pre>
<p>but how can the BOM depend on the SIG when the SIG is created from the BOM? As I read that it says, "create the SIG from the BOM and if the SIG is newer than the BOM then checkout the BOM". How do I bootstrap that process? Where does the first BOM come from?</p>
| [
{
"answer_id": 71623,
"author": "mbyrne215",
"author_id": 5241,
"author_profile": "https://Stackoverflow.com/users/5241",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not a make expert, but I would try have $(BOMS) depend on $(SIGS), and making the $(SIGS) target execute the if/else... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7685/"
] | I hope I haven't painted myself into a corner. I've gotten what seems to be most of the way through implementing a Makefile and I can't get the last bit to work. I hope someone here can suggest a technique to do what I'm trying to do.
I have what I'll call "bills of materials" in version controlled files in a source repository and I build something like:
```
make VER=x
```
I want my Makefile to use $(VER) as a tag to retrieve a BOM from the repository, generate a dependency file to include in the Makefile, rescan including that dependency, and then build the product.
More generally, my Makefile may have several targets -- A, B, C, etc. -- and I can build different versions of each so I might do:
```
make A VER=x
make B VER=y
make C VER=z
```
and the dependency file includes information about all three targets.
However, creating the dependency file is somewhat expensive so if I do:
```
make A VER=x
...make source (not BOM) changes...
make A VER=x
```
I'd really like the Makefile to not regenerate the dependency. And just to make things as complicated as possible, I might do:
```
make A VER=x
.. change version x of A's BOM and check it in
make A VER=x
```
so I need to regenerate the dependency on the second build.
The check out messes up the timestamps used to regenerate the dependencies so I think I need a way for the dependency file to depend not on the BOM but on some indication that the BOM changed.
What I've come to is making the BOM checkout happen in a .PHONY target (so it always gets checked out) and keeping track of the contents of the last checkout in a ".sig" file (if the signature file is missing or the contents are different than the signature of the new file, then the BOM changed), and having the dependency generation depend on the signatures). At the top of my Makefile, I have some setup:
```
BOMS = $(addsuffix .bom,$(MAKECMDGOALS)
SIGS = $(subst .bom,.sig,$(BOMS))
DEP = include.d
-include $(DEP)
```
And it seems I always need to do:
```
.PHONY: $(BOMS)
$(BOMS):
...checkout TAG=$(VER) $@
```
But, as noted above, if i do just that, and continue:
```
$(DEP) : $(BOMS)
... recreate dependency
```
Then the dependency gets updated every time I invoke make. So I try:
```
$(DEP) : $(SIGS)
... recreate dependency
```
and
```
$(BOMS):
...checkout TAG=$(VER) $@
...if $(subst .bom,.sig,$@) doesn't exist
... create signature file
...else
... if new signature is different from file contents
... update signature file
... endif
...endif
```
But the dependency generation doesn't get tripped when the signature changes. I think it's because because $(SIGS) isn't a target, so make doesn't notice when the $(BOMS) rule updates a signature.
I tried creating a .sig:.bom rule and managing the timestamps of the checked out BOM with touch but that didn't work.
Someone suggested something like:
```
$(DEP) : $(SIGS)
... recreate dependency
$(BOMS) : $(SIGS)
...checkout TAG=$(VER) $@
$(SIGS) :
...if $(subst .bom,.sig,$(BOMS)) doesn't exist
... create it
...else
... if new signature is different from file contents
... update signature file
... endif
...endif
```
but how can the BOM depend on the SIG when the SIG is created from the BOM? As I read that it says, "create the SIG from the BOM and if the SIG is newer than the BOM then checkout the BOM". How do I bootstrap that process? Where does the first BOM come from? | Make is very bad at being able to detect actual file changes, as opposed to just updated timestamps.
It sounds to me that the root of the problem is that the bom-checkout always modifies the timestamp of the bom, causing the dependencies to be regenerated. I would probably try to solve this problem instead -- try to checkout the bom without messing up the timestamp. A wrapper script around the checkout tool might do the trick; first checkout the bom to a temporary file, compare it to the already checked out version, and replace it only if the new one is different.
If you're not strictly bound to using make, there are other tools which are much better at detecting actual file changes (SCons, for example). |
71,561 | <p>In a web interface, I've got a text field. When user enters text and accepts with enter, application performs an action.</p>
<p>I wanted to test the behavior with Selenium. Unfortunately, invoking 'keypress' with chr(13) insert representation of the character into the field.</p>
<p>Is there a way other then submitting the form? I'd like to mimic intended user interaction, without any shortcuts...</p>
| [
{
"answer_id": 71580,
"author": "Scott Gowell",
"author_id": 6943,
"author_profile": "https://Stackoverflow.com/users/6943",
"pm_score": 0,
"selected": false,
"text": "<p>Though I haven't tested this I imagine you can use \"\\r\\n\" appended to a string to simulate a new line. If not loo... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9622/"
] | In a web interface, I've got a text field. When user enters text and accepts with enter, application performs an action.
I wanted to test the behavior with Selenium. Unfortunately, invoking 'keypress' with chr(13) insert representation of the character into the field.
Is there a way other then submitting the form? I'd like to mimic intended user interaction, without any shortcuts... | This Java code works for me:
```
selenium.keyDown(id, "\\13");
```
Notice the escape. You probably need something like chr(\13) |
71,562 | <p>We're using SQL Server 2005 in a project. The users of the system have the ability to search some objects by using 'keywords'. The way we implement this is by creating a full-text catalog for the significant columns in each table that may contain these 'keywords' and then using CONTAINS to search for the keywords the user inputs in the search box in that index. </p>
<p>So, for example, let say you have the Movie object, and you want to let the user search for keywords in the title and body of the article, then we'd index both the Title and Plot column, and then do something like:</p>
<pre><code>SELECT * FROM Movies WHERE CONTAINS(Title, keywords) OR CONTAINS(Plot, keywords)
</code></pre>
<p>(It's actually a bit more advanced than that, but nothing terribly complex)</p>
<p>Some users are adding numbers to their search, so for example they want to find 'Terminator 2'. The problem here is that, as far as I know, by default SQL Server won't index short words, thus doing a search like this:</p>
<pre><code>SELECT * FROM Movies WHERE CONTAINS(Title, '"Terminator 2"')
</code></pre>
<p>is actually equivalent to doing this:</p>
<pre><code>SELECT * FROM Movies WHERE CONTAINS(Title, '"Terminator"') <-- notice the missing '2'
</code></pre>
<p>and we are getting a plethora of spurious results.</p>
<p>Is there a way to force SQL Server to index small words? Preferably, I'd rather index only <em>numbers</em> like 1, 2, 21, etc. I don't know where to define the indexing criteria, or even if it's possible to be as specific as that.</p>
<hr>
<p>Well, I did that, removed the "noise-words" from the list, and now the behaviour is a bit different, but still not what you'd expect. </p>
<p>A search won't for "Terminator 2" (I'm just making this up, my employer might not be really happy if I disclose what we are doing... anyway, the terms are a bit different but the principle the same), I don't get <em>anything</em>, but I know there are objects containing the two words.</p>
<p>Maybe I'm doing something wrong? I removed all numbers 1 ... 9 from my noise configuration for ENG, ENU and NEU (neutral), regenerated the indexes, and tried the search.</p>
| [
{
"answer_id": 71604,
"author": "Darren Gosbell",
"author_id": 11860,
"author_profile": "https://Stackoverflow.com/users/11860",
"pm_score": 3,
"selected": true,
"text": "<p>These \"small words\" are considered \"noise words\" by the full text index. You can customize the list of noise w... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2384/"
] | We're using SQL Server 2005 in a project. The users of the system have the ability to search some objects by using 'keywords'. The way we implement this is by creating a full-text catalog for the significant columns in each table that may contain these 'keywords' and then using CONTAINS to search for the keywords the user inputs in the search box in that index.
So, for example, let say you have the Movie object, and you want to let the user search for keywords in the title and body of the article, then we'd index both the Title and Plot column, and then do something like:
```
SELECT * FROM Movies WHERE CONTAINS(Title, keywords) OR CONTAINS(Plot, keywords)
```
(It's actually a bit more advanced than that, but nothing terribly complex)
Some users are adding numbers to their search, so for example they want to find 'Terminator 2'. The problem here is that, as far as I know, by default SQL Server won't index short words, thus doing a search like this:
```
SELECT * FROM Movies WHERE CONTAINS(Title, '"Terminator 2"')
```
is actually equivalent to doing this:
```
SELECT * FROM Movies WHERE CONTAINS(Title, '"Terminator"') <-- notice the missing '2'
```
and we are getting a plethora of spurious results.
Is there a way to force SQL Server to index small words? Preferably, I'd rather index only *numbers* like 1, 2, 21, etc. I don't know where to define the indexing criteria, or even if it's possible to be as specific as that.
---
Well, I did that, removed the "noise-words" from the list, and now the behaviour is a bit different, but still not what you'd expect.
A search won't for "Terminator 2" (I'm just making this up, my employer might not be really happy if I disclose what we are doing... anyway, the terms are a bit different but the principle the same), I don't get *anything*, but I know there are objects containing the two words.
Maybe I'm doing something wrong? I removed all numbers 1 ... 9 from my noise configuration for ENG, ENU and NEU (neutral), regenerated the indexes, and tried the search. | These "small words" are considered "noise words" by the full text index. You can customize the list of noise words. This [blog post](http://arcanecode.wordpress.com/2008/05/29/creating-and-customizing-noise-words-in-sql-server-2005-full-text-search/) provides more details. You need to repopulate your full text index when you change the noise words file. |
71,565 | <p>If I have the following:</p>
<pre><code>Public Class Product
Public Id As Integer
Public Name As String
Public AvailableColours As List(Of Colour)
Public AvailableSizes As List(Of Size)
End Class
</code></pre>
<p>and I want to get a list of products from the database and display them on a page along with their available sizes and colours, should I </p>
<ol>
<li>have one method (GetProducts()) which makes use of a single view that joins the relevant tables, that then loops through each row and creates the objects as required? Or…</li>
<li>have several methods which are responsible only for creating one object each? eg. GetProducts(), GetAvailableColoursForProduct(id), etc</li>
</ol>
<p>I'm currently doing a) but as I add other other properties (multiple images, optional tassels, etc) the code is getting very messy (having to check that this isn't the same product as the previous row, has this colour already been added, etc) so I'm tempted to go with b) however, this will really ramp up the number of round trips to the database.</p>
| [
{
"answer_id": 71606,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Personally, I'd get more data from the database through fewer methods and then bind the UI against only those parts of the d... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/984/"
] | If I have the following:
```
Public Class Product
Public Id As Integer
Public Name As String
Public AvailableColours As List(Of Colour)
Public AvailableSizes As List(Of Size)
End Class
```
and I want to get a list of products from the database and display them on a page along with their available sizes and colours, should I
1. have one method (GetProducts()) which makes use of a single view that joins the relevant tables, that then loops through each row and creates the objects as required? Or…
2. have several methods which are responsible only for creating one object each? eg. GetProducts(), GetAvailableColoursForProduct(id), etc
I'm currently doing a) but as I add other other properties (multiple images, optional tassels, etc) the code is getting very messy (having to check that this isn't the same product as the previous row, has this colour already been added, etc) so I'm tempted to go with b) however, this will really ramp up the number of round trips to the database. | You're probably best off benchmarking both and finding out. I've seen situations where just doing multiple queries (MySQL likes this) is faster than JOINs and one big slow query that takes a lot memory and causes the DB server to thrash. I say benchmark because it's going to depend on your database server, how much memory and concurrent connections it has, sizes of your tables, how your indexes are optimized and the size of your typical recordsets. JOINs on large unindexed columns are very expensive (so you should either not do them or add indexes).
You will probably also learn a bit more/be more satisfied in the end if you write at least a little of both implementations (you don't need to write the methods, just a bunch of test queries) and then benchmark, vs. just going with one or the other. The trickiest (but important) part of testing though is simulating concurrent users hitting the DB at the same time -- realistic production memory and cpu load.
Keep in mind you are dealing with 2 issues: One is the DBA issue, how do I make it fastest and most efficient. The second is the programmer who wants pretty, maintainable code. (b) makes your code more readable and extensible than just having giant queries with complicated JOINs, so you may decide to prefer it over (a) as long as it isn't drastically slower. |
71,578 | <p>I have a database in ISO-8859-2 format, but I need to create XML in UTF-8. This means that I must encode the database before prinitng in UTF-8. I know very little about ASP.Net, so I'm hoping someone can help.</p>
<p>In PHP I would do something like this:</p>
<pre><code>db_connect();
mysql_query("SET NAMES 'UTF8'");
mysql_query("SET character_set_client='UTF8'");
</code></pre>
<p>This is my ASP.Net code for database connection:</p>
<pre><code> 'CONNECTION TO DATABASE
dim dbconn,sql,dbcomm
dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Server.MapPath("../baze/test.mdb"))
dbconn.Open()
sql="SELECT * FROM nekretnine, tipovinekretnina WHERE nekretnine.idtipnekretnine = tipovinekretnina.idtipnekretnine ORDER BY nekretnine.idnekretnine"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
while dbread.Read()
</code></pre>
<p>Where and how do I encode to UTF-8?</p>
| [
{
"answer_id": 71639,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 1,
"selected": false,
"text": "<p>The .NET Framework's internal string type is UTF-16. All database access will convert to UTF-16 so that you can view ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205368/"
] | I have a database in ISO-8859-2 format, but I need to create XML in UTF-8. This means that I must encode the database before prinitng in UTF-8. I know very little about ASP.Net, so I'm hoping someone can help.
In PHP I would do something like this:
```
db_connect();
mysql_query("SET NAMES 'UTF8'");
mysql_query("SET character_set_client='UTF8'");
```
This is my ASP.Net code for database connection:
```
'CONNECTION TO DATABASE
dim dbconn,sql,dbcomm
dbconn=New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & Server.MapPath("../baze/test.mdb"))
dbconn.Open()
sql="SELECT * FROM nekretnine, tipovinekretnina WHERE nekretnine.idtipnekretnine = tipovinekretnina.idtipnekretnine ORDER BY nekretnine.idnekretnine"
dbcomm=New OleDbCommand(sql,dbconn)
dbread=dbcomm.ExecuteReader()
while dbread.Read()
```
Where and how do I encode to UTF-8? | Assuming you have a value string in `str`, this is the pure-.NET way of doing this.
```
var encoding = System.Text.Encoding.GetEncoding("iso-8859-2");
var bytes = System.Text.Encoding.Convert(encoding, System.Text.Encoding.Default, encoding.GetBytes(str));
var newString = System.Text.Encoding.Default.GetString(bytes);
``` |
71,585 | <p>Since generics were introduced, Class is parametrized, so that List.class produces Class<List>. This is clear.</p>
<p>What I am not able to figure out is how to get a instance of Class of type which is parametrized itself, i.e. Class<List<String>>. Like in this snippet:</p>
<pre><code>public class GenTest {
static <T> T instantiate(Class<T> clazz) throws Exception {
return clazz.newInstance();
}
public static void main(String[] args) throws Exception {
// Is there a way to avoid waring on the line below
// without using @SuppressWarnings("unchecked")?
// ArrayList.class is Class<ArrayList>, but I would like to
// pass in Class<ArrayList<String>>
ArrayList<String> l = GenTest.instantiate(ArrayList.class);
}
}
</code></pre>
<p>I run into variations of this problem quite often and I still don't know, if I just miss something, or if there is really no better way. Thanks for suggestions.</p>
| [
{
"answer_id": 71753,
"author": "Avi",
"author_id": 1605,
"author_profile": "https://Stackoverflow.com/users/1605",
"pm_score": 4,
"selected": true,
"text": "<p>The Class class is a run-time representation of a type. Since parametrized types undergo type erasure at runtime, the class obj... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7135/"
] | Since generics were introduced, Class is parametrized, so that List.class produces Class<List>. This is clear.
What I am not able to figure out is how to get a instance of Class of type which is parametrized itself, i.e. Class<List<String>>. Like in this snippet:
```
public class GenTest {
static <T> T instantiate(Class<T> clazz) throws Exception {
return clazz.newInstance();
}
public static void main(String[] args) throws Exception {
// Is there a way to avoid waring on the line below
// without using @SuppressWarnings("unchecked")?
// ArrayList.class is Class<ArrayList>, but I would like to
// pass in Class<ArrayList<String>>
ArrayList<String> l = GenTest.instantiate(ArrayList.class);
}
}
```
I run into variations of this problem quite often and I still don't know, if I just miss something, or if there is really no better way. Thanks for suggestions. | The Class class is a run-time representation of a type. Since parametrized types undergo type erasure at runtime, the class object for Class would be the same as for Class<List<Integer>> and Class<List<String>>.
The reason you cannot instantiate them using the .class notation is that this is a special syntax used for class literals. The [Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.8.2) specifically forbids this syntax when the type is parametrized, which is why List<String>.class is not allowed. |
71,590 | <p>With this code I can show an animated gif while the server script is running:</p>
<pre><code>function calculateTotals() {
$('#results').load('getResults.php', null, showStatusFinished);
showLoadStatus();
}
function showLoadStatus() {
$('#status').html('');
}
function showStatusFinished() {
$('#status').html('Finished.');
}
</code></pre>
<p>However, I would like to display a status of how far along the script is, e.g. "Processing line 342 of 20000..." and have it count up until it is finished.</p>
<p>How can I do that? I can make a server-script which constantly contains the updated information but where do I put the command to read this, say, every second?</p>
| [
{
"answer_id": 71648,
"author": "squadette",
"author_id": 7754,
"author_profile": "https://Stackoverflow.com/users/7754",
"pm_score": 0,
"selected": false,
"text": "<p>Your server-side script should somehow keep its progress somewhere on server (file, field in database, memcached, etc.).... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] | With this code I can show an animated gif while the server script is running:
```
function calculateTotals() {
$('#results').load('getResults.php', null, showStatusFinished);
showLoadStatus();
}
function showLoadStatus() {
$('#status').html('');
}
function showStatusFinished() {
$('#status').html('Finished.');
}
```
However, I would like to display a status of how far along the script is, e.g. "Processing line 342 of 20000..." and have it count up until it is finished.
How can I do that? I can make a server-script which constantly contains the updated information but where do I put the command to read this, say, every second? | After reading your comments to Andrew's answer.
You would read the status like this:
```
function getStatus() {
$.getJSON("/status.php",{"session":0, "requestID":12345},
function(data) { //data is the returned JSON object from the server {name:"value"}
setStatus(data.status);
window.setTimeout("getStatus()",intervalInMS)
});
}
```
Using this method you can open several simultaneous XHR request on the server.
all your status.php as to output is :
```
{"status":"We are done row 1040/45983459"}
```
You can however output as many information you want in the response and to process it accordingly (feeding a progress bar for example or performing an animation..)
For more information on $.getJSON see <http://docs.jquery.com/Ajax/jQuery.getJSON> |
71,599 | <p>I've downloaded the IKVM sources (<a href="http://www.ikvm.net/" rel="nofollow noreferrer">http://www.ikvm.net/</a>) from <a href="http://sourceforge.net/cvs/?group_id=69637" rel="nofollow noreferrer">http://sourceforge.net/cvs/?group_id=69637</a></p>
<p>Now I'm trying to get it to build in Visual Studio 2008 and am stuck. Does anyone know of documentation of how to build the thing, or could even give me pointers?</p>
<p>I've tried opening the ikvm8.sln, which opens all the projects, but trying to build the solution leads to a bunch of "type or namespace could not be found" errors.</p>
<p>As you can probably guess I'm no Visual Studio expert, but rather am used to working with Java in Eclipse.</p>
<p>So again, I'm looking for either: step-by-step instructions or a link to documentation on how to build IKVM in Visual Studio.</p>
<p>Let me know if you need any more info. Thanks for any help!</p>
<p><strong>Edit:</strong> I've also tried a manual "MsBuild.exe IKVM8.sln", but also get a bunch of:</p>
<pre><code>JniInterface.cs(30,12): error CS0234: The type or namespace name 'Internal' does not exist in the namespace 'IKVM' (a
re you missing an assembly reference?)
JniInterface.cs(175,38): error CS0246: The type or namespace name 'ClassLoaderWrapper' could not be found (are you mi
ssing a using directive or an assembly reference?)
JniInterface.cs(175,13): error CS0246: The type or namespace name 'ClassLoaderWrapper' could not be found (are you mi
ssing a using directive or an assembly reference?)
</code></pre>
<p><strong>Edit #2</strong>: I noticed a "ikvm.build" file so I downloaded and ran nant on the folder, which got me a step further. A few things start to build successfully, unfortunately I now get the following error:</p>
<p>ikvm-native-win32:</p>
<pre><code> [mkdir] Creating directory 'C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\Release'.
[cl] Compiling 2 files to 'C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\Release'.
BUILD FAILED
C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\native.build(17,10):
'cl' failed to start.
The system cannot find the file specified
Total time: 0.2 seconds.
</code></pre>
<p><strong>Edit #3</strong>: OK solved that by putting <code>cl.exe</code> in the path, still getting other errors though. <strong><em>Note this is all for building it on the console e.g. with Nant. Is there no way to get it to build in Visual Studio? That would be sad...</em></strong></p>
<p><strong>Edit #4</strong>: Next step was installing GNU classpath 0.95, and now it looks like I need a specific OpenJDK installation... Linux AMD64?!</p>
<pre><code> [exec] javac: file not found: ..\..\openjdk6-b12\control\build\linux-amd64\gensrc\com\sun\accessibility\internal\resources\accessibility.java
[exec] Usage: javac <options> <source files>
[exec] use -help for a list of possible options
</code></pre>
<p><strong>Edit #5</strong>: Got an answer from the author. See below or at <a href="http://weblog.ikvm.net/CommentView.aspx?guid=7e91b51d-6f84-4485-b61f-ea9e068a5fcf" rel="nofollow noreferrer">http://weblog.ikvm.net/CommentView.aspx?guid=7e91b51d-6f84-4485-b61f-ea9e068a5fcf</a> Let's see if it works...</p>
<p><strong>Edit #6</strong> As I feared, next problem: "cannot open windows.h", see separate question <a href="https://stackoverflow.com/questions/80788/fatal-error-c1083-cannot-open-include-file-windowsh-no-such-file-or-directory">here</a>.</p>
<p><strong>Final Edit: Found Solution!</strong> After getting the Platform SDK folders in the Lib and Path environment variables, the solution I described below worked for me.</p>
| [
{
"answer_id": 71744,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know that this would do it for you but can you try building from the command line?</p>\n\n<p>msbuild _... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] | I've downloaded the IKVM sources (<http://www.ikvm.net/>) from <http://sourceforge.net/cvs/?group_id=69637>
Now I'm trying to get it to build in Visual Studio 2008 and am stuck. Does anyone know of documentation of how to build the thing, or could even give me pointers?
I've tried opening the ikvm8.sln, which opens all the projects, but trying to build the solution leads to a bunch of "type or namespace could not be found" errors.
As you can probably guess I'm no Visual Studio expert, but rather am used to working with Java in Eclipse.
So again, I'm looking for either: step-by-step instructions or a link to documentation on how to build IKVM in Visual Studio.
Let me know if you need any more info. Thanks for any help!
**Edit:** I've also tried a manual "MsBuild.exe IKVM8.sln", but also get a bunch of:
```
JniInterface.cs(30,12): error CS0234: The type or namespace name 'Internal' does not exist in the namespace 'IKVM' (a
re you missing an assembly reference?)
JniInterface.cs(175,38): error CS0246: The type or namespace name 'ClassLoaderWrapper' could not be found (are you mi
ssing a using directive or an assembly reference?)
JniInterface.cs(175,13): error CS0246: The type or namespace name 'ClassLoaderWrapper' could not be found (are you mi
ssing a using directive or an assembly reference?)
```
**Edit #2**: I noticed a "ikvm.build" file so I downloaded and ran nant on the folder, which got me a step further. A few things start to build successfully, unfortunately I now get the following error:
ikvm-native-win32:
```
[mkdir] Creating directory 'C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\Release'.
[cl] Compiling 2 files to 'C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\Release'.
BUILD FAILED
C:\Documents and Settings\...\My Documents\ikvm\ikvm\native\native.build(17,10):
'cl' failed to start.
The system cannot find the file specified
Total time: 0.2 seconds.
```
**Edit #3**: OK solved that by putting `cl.exe` in the path, still getting other errors though. ***Note this is all for building it on the console e.g. with Nant. Is there no way to get it to build in Visual Studio? That would be sad...***
**Edit #4**: Next step was installing GNU classpath 0.95, and now it looks like I need a specific OpenJDK installation... Linux AMD64?!
```
[exec] javac: file not found: ..\..\openjdk6-b12\control\build\linux-amd64\gensrc\com\sun\accessibility\internal\resources\accessibility.java
[exec] Usage: javac <options> <source files>
[exec] use -help for a list of possible options
```
**Edit #5**: Got an answer from the author. See below or at <http://weblog.ikvm.net/CommentView.aspx?guid=7e91b51d-6f84-4485-b61f-ea9e068a5fcf> Let's see if it works...
**Edit #6** As I feared, next problem: "cannot open windows.h", see separate question [here](https://stackoverflow.com/questions/80788/fatal-error-c1083-cannot-open-include-file-windowsh-no-such-file-or-directory).
**Final Edit: Found Solution!** After getting the Platform SDK folders in the Lib and Path environment variables, the solution I described below worked for me. | OK just got the following reply from the author: <http://weblog.ikvm.net/CommentView.aspx?guid=7e91b51d-6f84-4485-b61f-ea9e068a5fcf>
>
> If you want to build from cvs, you're on your own. However, you can more easily build from source if you use an official release.
>
>
> If you download ikvm-0.36.0.11.zip, classpath-0.95-stripped.zip and openjdk-b13-stripped.zip from SourceForge (the last two are under the ikvm 0.36.0.5 release) you have all the sources that are needed.
>
>
> Now you'll have to open a Visual Studio 2008 Command Prompt (i.e. one that has cl.exe and peverify in the path).
>
>
> Then in the ikvm root directory, do a "nant clean" followed by "nant". That should build the whole project. After you done that, you should be able to build in Visual Studio (debug target only), but you may need to repair the assembly references in the projects (unless you have ikvm installed in c:\ikvm).
>
>
> Regards,
> Jeroen
>
>
>
**Edit**: After making sure the Platform SDK folders were in the Path and Lib environment variables, this worked for me. Thanks, Jeroen! |
71,608 | <p>How do you set up your .NET development tree? I use a structure like this:</p>
<pre><code>-projectname
--config (where I put the configuration files)
--doc (where I put all the document concerning the project: e-mails, documentation)
--tools (all the tools I use: Nunit, Moq)
--lib (all the libraries used by the solution: ninject or autofac)
--src
---app (sourcefiles)
---test (unittests)
solutionfile.sln
build.csproj
</code></pre>
<p>The sign "-" marks directories.</p>
<p>I think it's very important to have a good structure on this stuff. You should be able to get the source code from the source control system and then build the solution without opening Visual Studio or installing any third party libraries. </p>
<p>Any thoughts on this?</p>
| [
{
"answer_id": 71676,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 3,
"selected": false,
"text": "<p>Check out these other StackOverflow questions...</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/16... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4093/"
] | How do you set up your .NET development tree? I use a structure like this:
```
-projectname
--config (where I put the configuration files)
--doc (where I put all the document concerning the project: e-mails, documentation)
--tools (all the tools I use: Nunit, Moq)
--lib (all the libraries used by the solution: ninject or autofac)
--src
---app (sourcefiles)
---test (unittests)
solutionfile.sln
build.csproj
```
The sign "-" marks directories.
I think it's very important to have a good structure on this stuff. You should be able to get the source code from the source control system and then build the solution without opening Visual Studio or installing any third party libraries.
Any thoughts on this? | We use a very similar layout as covered in JP Boodhoo's blog post titled [Directory Structure For Projects](http://blog.developwithpassion.com/2007/10/01/directory-structure-for-projects/). |
71,625 | <p>I have just found a static nested interface in our code-base.</p>
<pre><code>class Foo {
public static interface Bar {
/* snip */
}
/* snip */
}
</code></pre>
<p>I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:</p>
<p>What are the semantics behind a static interface? What would change, if I remove the <code>static</code>? Why would anyone do this?</p>
| [
{
"answer_id": 71654,
"author": "Clinton Dreisbach",
"author_id": 6262,
"author_profile": "https://Stackoverflow.com/users/6262",
"pm_score": 3,
"selected": false,
"text": "<p>An inner interface has to be static in order to be accessed. The interface isn't associated with instances of th... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870/"
] | I have just found a static nested interface in our code-base.
```
class Foo {
public static interface Bar {
/* snip */
}
/* snip */
}
```
I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:
What are the semantics behind a static interface? What would change, if I remove the `static`? Why would anyone do this? | The static keyword in the above example is redundant (a nested interface is automatically "static") and can be removed with no effect on semantics; I would recommend it be removed. The same goes for "public" on interface methods and "public final" on interface fields - the modifiers are redundant and just add clutter to the source code.
Either way, the developer is simply declaring an interface named Foo.Bar. There is no further association with the enclosing class, except that code which cannot access Foo will not be able to access Foo.Bar either. (From source code - bytecode or reflection can access Foo.Bar even if Foo is package-private!)
It is acceptable style to create a nested interface this way if you expect it to be used only from the outer class, so that you do not create a new top-level name. For example:
```
public class Foo {
public interface Bar {
void callback();
}
public static void registerCallback(Bar bar) {...}
}
// ...elsewhere...
Foo.registerCallback(new Foo.Bar() {
public void callback() {...}
});
``` |
71,643 | <p>Currently I monitoring a particular file with a simple shell one-liner:</p>
<pre><code>filesize=$(ls -lah somefile | awk '{print $5}')
</code></pre>
<p>I'm aware that Perl has some nice modules to deal with Excel files so the idea is to, let's say, run that check daily, perhaps with cron, and write the result on a spreadsheet for further statistical use.</p>
| [
{
"answer_id": 71668,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 3,
"selected": false,
"text": "<p>You can use <a href=\"http://p3rl.org/-X\" rel=\"nofollow noreferrer\">the <code>-s</code> operator</a> to obt... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6992/"
] | Currently I monitoring a particular file with a simple shell one-liner:
```
filesize=$(ls -lah somefile | awk '{print $5}')
```
I'm aware that Perl has some nice modules to deal with Excel files so the idea is to, let's say, run that check daily, perhaps with cron, and write the result on a spreadsheet for further statistical use. | You can check the size of the file using the -s operator.
```
use strict;
use warnings;
use File::Slurp qw(read_file write_file);
use Spreadsheet::ParseExcel;
use Spreadsheet::ParseExcel::SaveParser;
use Spreadsheet::WriteExcel;
my $file = 'path_to_file';
my $size_file = 'path_to_file_keeping_the_size';
my $excel_file = 'path_to_excel_file.xls';
my $current_size = -s $file;
my $old_size = 0;
if (-e $size_file) {
$old_size = read_file($size_file);
}
if ($old_size new;
my $excel = $parser->Parse($excel_file);
my $row = 1;
$row++ while $excel->{Worksheet}[0]->{Cells}[$row][0];
$excel->AddCell(0, $row, 0, scalar(localtime));
$excel->AddCell(0, $row, 1, $current_size);
my $workbook = $excel->SaveAs($excel_file);
$workbook->close;
} else {
my $workbook = Spreadsheet::WriteExcel->new($excel_file);
my $worksheet = $workbook->add_worksheet();
$worksheet->write(0, 0, 'Date');
$worksheet->write(0, 1, 'Size');
$worksheet->write(1, 0, scalar(localtime));
$worksheet->write(1, 1, $current_size);
$workbook->close;
}
}
write_file($size_file, $current_size);
```
A simple way to write Excel files would be using
[Spreadsheet::Write](http://search.cpan.org/dist/Spreadsheet-Write/).
but if you need to update an existing Excel file you should look into
[Spreadsheet::ParseExcel](http://search.cpan.org/dist/Spreadsheet-ParseExcel/). |
71,692 | <p>I'm building small web site in Java (Spring MVC with JSP views) and am trying to find best solution for making and including few reusable modules (like "latest news" "upcoming events"...).</p>
<p>So the question is: Portlets, tiles or some other technology?</p>
| [
{
"answer_id": 71737,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 2,
"selected": false,
"text": "<p>Tiles can be a pain. Vast improvement over what came before (i.e. nothing), but rather limiting. </p>\n\n<p><a href=\"http... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11890/"
] | I'm building small web site in Java (Spring MVC with JSP views) and am trying to find best solution for making and including few reusable modules (like "latest news" "upcoming events"...).
So the question is: Portlets, tiles or some other technology? | If you are using Spring MVC, then I would recommend using Portlets. In Spring, portlets are just lightweight controllers since they are only responsible for a fragment of the whole page, and are very easy to write. If you are using Spring 2.5, then you can enjoy all the benefits of the new annotation support, and they fit nicely in the whole Spring application with dependency injection and the other benefits of using Spring.
A portlet controller is pretty much the same as a servlet controller, here is a simple example:
```
@RequestMapping("VIEW")
@Controller
public class NewsPortlet {
private NewsService newsService;
@Autowired
public NewsPortlet(NewsService newsService) {
this.newsService = newsService;
}
@RequestMapping(method = RequestMethod.GET)
public String view(Model model) {
model.addAttribute(newsService.getLatests(10));
return "news";
}
}
```
Here, a NewsService will be automatically injected into the controller. The view method adds a List object to the model, which will be available as ${newsList} in the JSP. Spring will look for a view named news.jsp based on the return value of the method. The RequestMapping tells Spring that this contoller is for the VIEW mode of the portlet.
The XML configuration only needs to specify where the view and controllers are located:
```
<!-- look for controllers and services here -->
<context:component-scan base-package="com.example.news"/>
<!-- look for views here -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/news/"/>
<property name="suffix" value=".jsp"/>
</bean>
```
If you want to simply embed the portlets in your existing application, the you can bundle a portlet container, such as [eXo](http://www.exoplatform.com), [Sun](https://portlet-container.dev.java.net/), or [Apache](http://portals.apache.org/pluto/). If you want to build your application as a set of portlets, the you might want to consider a full blown portlal solution, such as [Liferay Portal](http://liferay.com). |
71,694 | <p>Is there an api to bring the vista side bar to the front (Win+Space) programatically and to do the reverse (send it to the back ground).</p>
| [
{
"answer_id": 71785,
"author": "Cory",
"author_id": 11870,
"author_profile": "https://Stackoverflow.com/users/11870",
"pm_score": 1,
"selected": false,
"text": "<p>Probably using SetWindowPos you can change it to be placed the top / bottom of the z-order or even as the top-most window. ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11930/"
] | Is there an api to bring the vista side bar to the front (Win+Space) programatically and to do the reverse (send it to the back ground). | Probably using SetWindowPos you can change it to be placed the top / bottom of the z-order or even as the top-most window. You would need to find the handle to the sidebar using FindWindow or an application like WinSpy.
But after that something like.
Sets the window on top, but not top most.
```
SetWindowPos(sidebarHandle, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NORESIZE);
```
Sets the window at the bottom.
```
SetWindowPos(sidebarHandle, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NORESIZE);
```
This is my best guess on achieving what you asked, hopefully it helps. |
71,766 | <p>In Delphi, I want to be able to create an private object that's associated with a class, and access it from all instances of that class. In Java, I'd use:</p>
<pre><code>public class MyObject {
private static final MySharedObject mySharedObjectInstance = new MySharedObject();
}
</code></pre>
<p>Or, if MySharedObject needed more complicated initialization, in Java I could instantiate and initialize it in a static initializer block.</p>
<p>(You might have guessed... I know my Java but I'm rather new to Delphi...)</p>
<p>Anyway, I don't want to instantiate a new MySharedObject each time I create an instance of MyObject, but I do want a MySharedObject to be accessible from each instance of MyObject. (It's actually logging that has spurred me to try to figure this out - I'm using Log4D and I want to store a TLogLogger as a class variable for each class that has logging functionality.)</p>
<p>What's the neatest way to do something like this in Delphi?</p>
| [
{
"answer_id": 71811,
"author": "CL.",
"author_id": 11654,
"author_profile": "https://Stackoverflow.com/users/11654",
"pm_score": 0,
"selected": false,
"text": "<p>Before version 7, Delphi didn't have static variables, you'd have to use a global variable.</p>\n\n<p>To make it as private ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11961/"
] | In Delphi, I want to be able to create an private object that's associated with a class, and access it from all instances of that class. In Java, I'd use:
```
public class MyObject {
private static final MySharedObject mySharedObjectInstance = new MySharedObject();
}
```
Or, if MySharedObject needed more complicated initialization, in Java I could instantiate and initialize it in a static initializer block.
(You might have guessed... I know my Java but I'm rather new to Delphi...)
Anyway, I don't want to instantiate a new MySharedObject each time I create an instance of MyObject, but I do want a MySharedObject to be accessible from each instance of MyObject. (It's actually logging that has spurred me to try to figure this out - I'm using Log4D and I want to store a TLogLogger as a class variable for each class that has logging functionality.)
What's the neatest way to do something like this in Delphi? | Here is how I'll do that using a class variable, a class procedure and an initialization block:
```
unit MyObject;
interface
type
TMyObject = class
private
class var FLogger : TLogLogger;
public
class procedure SetLogger(value:TLogLogger);
class procedure FreeLogger;
end;
implementation
class procedure TMyObject.SetLogger(value:TLogLogger);
begin
// sanity checks here
FLogger := Value;
end;
class procedure TMyObject.FreeLogger;
begin
if assigned(FLogger) then
FLogger.Free;
end;
initialization
TMyObject.SetLogger(TLogLogger.Create);
finalization
TMyObject.FreeLogger;
end.
``` |
71,775 | <p>I have to read data from some files and insert the data into different tables in a database. Is Unix shell script powerful enough to do the job?</p>
<p>Is it easy to do the job in shell script or should I go about doing this in Java?</p>
| [
{
"answer_id": 71789,
"author": "Josti",
"author_id": 11231,
"author_profile": "https://Stackoverflow.com/users/11231",
"pm_score": 0,
"selected": false,
"text": "<p>Can't test it right now, but something like:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>echo \"INSERT INTO f... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] | I have to read data from some files and insert the data into different tables in a database. Is Unix shell script powerful enough to do the job?
Is it easy to do the job in shell script or should I go about doing this in Java? | If the data you are trying to import is in a reasonable format -- comma-delimited, for example -- and your database server has reasonable command line utilities, this should be no problem. MySQL has the "mysqlimport" command-line tool that will accept various arguments describing the format of the file:
```sh
mysqlimport \
--fields-terminated-by=, \
--ignore-lines=1 \
--fields-optionally-enclosed-by='"' < datafile.txt
```
Passing the data through perl/sed/awk one-liners can help with getting it in the proper format, and the shell script can easily handle prompting for filenames, handling arguments, etc.
Using the various command-line tools provided by Unix is the entire point of bash scripting. Perl, mysql, etc. are all part of that toolkit. |
71,776 | <p>I have 16,000 jpg's from a webcan screeb grabber that I let run for a year pointing into the back year. I want to find a way to grab every 4th image so that I can then put them into another directory so I can later turn them into a movie. Is there a simple bash script or other way under linux that I can do this.</p>
<p>They are named like so......</p>
<p>frame-44558.jpg</p>
<p>frame-44559.jpg</p>
<p>frame-44560.jpg</p>
<p>frame-44561.jpg</p>
<p>Thanks from a newb needing help.</p>
<hr>
<p>Seems to have worked.
Couple of errors in my origonal post. There were actually 280,000 images and the naming was.
/home/baldy/Desktop/webcamimages/webcam_2007-05-29_163405.jpg
/home/baldy/Desktop/webcamimages/webcam_2007-05-29_163505.jpg
/home/baldy/Desktop/webcamimages/webcam_2007-05-29_163605.jpg</p>
<p>I ran.
cp $(ls | awk '{nr++; if (nr % 10 == 0) print $0}') ../newdirectory/</p>
<p>Which appears to have copied the images. 70-900 per day from the looks of it.</p>
<p>Now I'm running
mencoder mf://*.jpg -mf w=640:h=480:fps=30:type=jpg -ovc lavc -lavcopts vcodec=msmpeg4v2 -nosound -o ../output-msmpeg4v2.avi</p>
<p>I'll let you know how the movie works out.</p>
<p>UPDATE: Movie did not work.
Only has images from 2007 in it even though the directory has 2008 as well.
webcam_2008-02-17_101403.jpg webcam_2008-03-27_192205.jpg
webcam_2008-02-17_102403.jpg webcam_2008-03-27_193205.jpg
webcam_2008-02-17_103403.jpg webcam_2008-03-27_194205.jpg
webcam_2008-02-17_104403.jpg webcam_2008-03-27_195205.jpg</p>
<p>How can I modify my mencoder line so that it uses all the images?</p>
| [
{
"answer_id": 71798,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 1,
"selected": false,
"text": "<p>An easy way in perl (probably easily adaptable to bash) is to glob the filenames in an array then get the sequence number and re... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11950/"
] | I have 16,000 jpg's from a webcan screeb grabber that I let run for a year pointing into the back year. I want to find a way to grab every 4th image so that I can then put them into another directory so I can later turn them into a movie. Is there a simple bash script or other way under linux that I can do this.
They are named like so......
frame-44558.jpg
frame-44559.jpg
frame-44560.jpg
frame-44561.jpg
Thanks from a newb needing help.
---
Seems to have worked.
Couple of errors in my origonal post. There were actually 280,000 images and the naming was.
/home/baldy/Desktop/webcamimages/webcam\_2007-05-29\_163405.jpg
/home/baldy/Desktop/webcamimages/webcam\_2007-05-29\_163505.jpg
/home/baldy/Desktop/webcamimages/webcam\_2007-05-29\_163605.jpg
I ran.
cp $(ls | awk '{nr++; if (nr % 10 == 0) print $0}') ../newdirectory/
Which appears to have copied the images. 70-900 per day from the looks of it.
Now I'm running
mencoder mf://\*.jpg -mf w=640:h=480:fps=30:type=jpg -ovc lavc -lavcopts vcodec=msmpeg4v2 -nosound -o ../output-msmpeg4v2.avi
I'll let you know how the movie works out.
UPDATE: Movie did not work.
Only has images from 2007 in it even though the directory has 2008 as well.
webcam\_2008-02-17\_101403.jpg webcam\_2008-03-27\_192205.jpg
webcam\_2008-02-17\_102403.jpg webcam\_2008-03-27\_193205.jpg
webcam\_2008-02-17\_103403.jpg webcam\_2008-03-27\_194205.jpg
webcam\_2008-02-17\_104403.jpg webcam\_2008-03-27\_195205.jpg
How can I modify my mencoder line so that it uses all the images? | One simple way is:
```
$ touch a b c d e f g h i j k l m n o p q r s t u v w x y z
$ mv $(ls | awk '{nr++; if (nr % 4 == 0) print $0}') destdir
``` |
71,788 | <p>I'm writing an Emacs major mode for an APL dialect I use at work. I've gotten
basic font locking to work, and after setting comment-start and
comment-start-skip, comment/uncomment region and fill paragraph also
work.</p>
<p>However, comment blocks often contain javadoc style comments and i
would like fill-paragraph to avoid glueing together lines starting
with such commands.</p>
<p>If I have this (\ instead of javadoc @):</p>
<pre><code># This is a comment that is long and should be wrapped.
# \arg Description of argument
# \ret Description of return value
</code></pre>
<p>M-q gives me:</p>
<pre><code># This is a comment that is long and
# should be wrapped. \arg Description
# of argument \ret Description of
# return value
</code></pre>
<p>But I want:</p>
<pre><code># This is a comment that is long and
# should be wrapped.
# \arg Description of argument
# \ret Description of return value
</code></pre>
<p>I've tried setting up paragraph-start and paragraph-separate to
appropriate values, but fill-paragraph still doesn't work inside a
comment block. If I remove the comment markers, M-q works as I want
to, so the regexp I use for paragraph-start seems to work.</p>
<p>Do I have to write a custom fill-paragraph for my major
mode? cc-mode has one that handles cases like this, but it's really
complex, I'd like to avoid it if possible. </p>
| [
{
"answer_id": 72637,
"author": "Allen",
"author_id": 6043,
"author_profile": "https://Stackoverflow.com/users/6043",
"pm_score": 1,
"selected": false,
"text": "<p>There's other modes that have less complex functions used for <code>fill-paragraph-function</code>. Browsing through my inst... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11978/"
] | I'm writing an Emacs major mode for an APL dialect I use at work. I've gotten
basic font locking to work, and after setting comment-start and
comment-start-skip, comment/uncomment region and fill paragraph also
work.
However, comment blocks often contain javadoc style comments and i
would like fill-paragraph to avoid glueing together lines starting
with such commands.
If I have this (\ instead of javadoc @):
```
# This is a comment that is long and should be wrapped.
# \arg Description of argument
# \ret Description of return value
```
M-q gives me:
```
# This is a comment that is long and
# should be wrapped. \arg Description
# of argument \ret Description of
# return value
```
But I want:
```
# This is a comment that is long and
# should be wrapped.
# \arg Description of argument
# \ret Description of return value
```
I've tried setting up paragraph-start and paragraph-separate to
appropriate values, but fill-paragraph still doesn't work inside a
comment block. If I remove the comment markers, M-q works as I want
to, so the regexp I use for paragraph-start seems to work.
Do I have to write a custom fill-paragraph for my major
mode? cc-mode has one that handles cases like this, but it's really
complex, I'd like to avoid it if possible. | The problem was that the paragraph-start regexp has to match the entire line to work, including the actual comment character. The following elisp works for the example I gave:
```
(setq paragraph-start "^\\s-*\\#\\s-*\\\\\\(arg\\|ret\\).*$")
```
Here a page that has an example regexp for php-mode that does this:
<http://barelyenough.org/blog/2006/10/nicer-phpdoc-comments/> |
71,817 | <p>The problem: I have a class which contains a template method <code>execute</code> which calls another method <code>_execute</code>. Subclasses are supposed to overwrite <code>_execute</code> to implement some specific functionality. This functionality should be documented in the docstring of <code>_execute</code>.
Advanced users can create their own subclasses to extend the library. However, another user dealing with such a subclass should only use <code>execute</code>, so he won't see the correct docstring if he uses <code>help(execute)</code>.</p>
<p>Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of <code>execute</code> is automatically replaced with that of <code>_execute</code>. Any ideas how this might be done?</p>
<p>I was thinking of metaclasses to do this, to make this completely transparent to the user.</p>
| [
{
"answer_id": 72126,
"author": "John Montgomery",
"author_id": 5868,
"author_profile": "https://Stackoverflow.com/users/5868",
"pm_score": 0,
"selected": false,
"text": "<p>Well the doc-string is stored in <code>__doc__</code> so it wouldn't be too hard to re-assign it based on the doc-... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11992/"
] | The problem: I have a class which contains a template method `execute` which calls another method `_execute`. Subclasses are supposed to overwrite `_execute` to implement some specific functionality. This functionality should be documented in the docstring of `_execute`.
Advanced users can create their own subclasses to extend the library. However, another user dealing with such a subclass should only use `execute`, so he won't see the correct docstring if he uses `help(execute)`.
Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of `execute` is automatically replaced with that of `_execute`. Any ideas how this might be done?
I was thinking of metaclasses to do this, to make this completely transparent to the user. | Well, if you don't mind copying the original method in the subclass, you can use the following technique.
```
import new
def copyfunc(func):
return new.function(func.func_code, func.func_globals, func.func_name,
func.func_defaults, func.func_closure)
class Metaclass(type):
def __new__(meta, name, bases, attrs):
for key in attrs.keys():
if key[0] == '_':
skey = key[1:]
for base in bases:
original = getattr(base, skey, None)
if original is not None:
copy = copyfunc(original)
copy.__doc__ = attrs[key].__doc__
attrs[skey] = copy
break
return type.__new__(meta, name, bases, attrs)
class Class(object):
__metaclass__ = Metaclass
def execute(self):
'''original doc-string'''
return self._execute()
class Subclass(Class):
def _execute(self):
'''sub-class doc-string'''
pass
``` |
71,820 | <p>I need a function called <code>SizeOfPipe()</code> which should return the size of a pipe - I only want to know how much data is in the pipe and not actually read data off the pipe itself. </p>
<p>I thought the following code would work:</p>
<pre><code>fseek (pPipe, 0 , SEEK_END);
*pBytes = ftell (pPipe);
rewind (pPipe);
</code></pre>
<p>but <code>fseek()</code> doesn't work on file descriptors. Another option would be to read the pipe then write the data back but would like to avoid this if possible. Any suggestions?</p>
| [
{
"answer_id": 71870,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 2,
"selected": false,
"text": "<p>It's not in general possible to know the amount of data you can read from a pipe just from the pipe handle alone. The... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I need a function called `SizeOfPipe()` which should return the size of a pipe - I only want to know how much data is in the pipe and not actually read data off the pipe itself.
I thought the following code would work:
```
fseek (pPipe, 0 , SEEK_END);
*pBytes = ftell (pPipe);
rewind (pPipe);
```
but `fseek()` doesn't work on file descriptors. Another option would be to read the pipe then write the data back but would like to avoid this if possible. Any suggestions? | Depending on your unix implementation ioctl/FIONREAD might do the trick
```
err = ioctl(pipedesc, FIONREAD, &bytesAvailable);
```
Unless this returns the error code for "invalid argument" (or any other error) bytesAvailable contains the amount of data available for unblocking read operations at that time. |
71,853 | <p>I'm using an Xml field in my Sql Server database table. I'm trying to search a word using the XQuery <strong>contains</strong> method but it seems to search <strong>only</strong> in case sensitive mode. The lower method isn't implemented on Sql Server XQuery implementation also.
¿Is there a simple solution to this problem?</p>
| [
{
"answer_id": 71908,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p><em><a href=\"http://www.google.ru/search?complete=1&hl=en&newwindow=1&client=firefox-a&rls=org.mozilla%3Aen-U... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm using an Xml field in my Sql Server database table. I'm trying to search a word using the XQuery **contains** method but it seems to search **only** in case sensitive mode. The lower method isn't implemented on Sql Server XQuery implementation also.
¿Is there a simple solution to this problem? | If you're using SQL Server 2005, I'm afraid you're out of luck.
If you're using SQL Server 2008, you can use the upper-case function like this :
```
DECLARE @x xml = N'abcDEF!@4';
SELECT @x.value('fn:upper-case(/text()[1])', 'nvarchar(10)');
```
Here's a link on MSDN for the upper-case syntax and a couple search examples :
<http://msdn.microsoft.com/en-us/library/cc645590.aspx> |
71,864 | <p>I want to delete all but the 4 newest directories in my parent directory. How would you do this in Bash?</p>
| [
{
"answer_id": 71891,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 4,
"selected": true,
"text": "<pre><code>ls -atrd */ | head --lines=-4 | xargs rm -rf\n</code></pre>\n\n<p><strong>Edit:</strong> added 'a' argument ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12015/"
] | I want to delete all but the 4 newest directories in my parent directory. How would you do this in Bash? | ```
ls -atrd */ | head --lines=-4 | xargs rm -rf
```
**Edit:** added 'a' argument to ls |
71,913 | <p>Here is a sample from Kernighan & Ritchie's "The C Programming Language":</p>
<pre><code>int getline(char s[], int lim)
{
int c, i = 0;
while (--lim > 0; && (c=getchar()) !=EOF && c !='\n')
{
s[i++] = c;
}
if (c =='\n')
{
s[i++] = c;
}
s[i] = '\0';
return i;
}
</code></pre>
<p>Why do we should check if <code>c != '\n'</code>, despite we use <code>s[i++] = c</code> after that?</p>
| [
{
"answer_id": 71935,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You do that just to exit the while loop on new line. Else you would have to check it in while body and use break.</p>\n"
}... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11972/"
] | Here is a sample from Kernighan & Ritchie's "The C Programming Language":
```
int getline(char s[], int lim)
{
int c, i = 0;
while (--lim > 0; && (c=getchar()) !=EOF && c !='\n')
{
s[i++] = c;
}
if (c =='\n')
{
s[i++] = c;
}
s[i] = '\0';
return i;
}
```
Why do we should check if `c != '\n'`, despite we use `s[i++] = c` after that? | The functions reads characters from the standard input until either EOF or a newline characters is found.
The second check ensures that the only newline character is put into the char array. EOF shouldn't occur in a proper c-string. Also, if the character isn't newline that means that we might have filled up our c-string, in which case we shouldn't put any more characters into it.
Notice we still append the '\0'. We've ensured that theres still room for one more character in our c-string, as we use the pre-fix decrementor, which evaluates before the comparison. |
71,932 | <p>I'm missing the boat on something here, kids. This keeps rearing its head and I don't know what's going on with it, so I hope my homeys here can help.</p>
<p>When working in Silverlight, when I create bindings in my c# code, they never hold up when the application is running. The declarative bindings from my xaml seem ok, but I'm doing something wrong when I create my bindings in C#. I'm hoping that there is something blindingly obvious I'm missing. Here's a typical binding that gets crushed:</p>
<pre><code>TextBlock tb = new TextBlock();
Binding b = new Binding("FontSize");
b.Source = this;
tb.SetBinding(TextBlock.FontSizeProperty, b);
</code></pre>
| [
{
"answer_id": 72129,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I've just tried the exact code you just posted and it worked fine, with some changes. I believe the problem is the element y... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93/"
] | I'm missing the boat on something here, kids. This keeps rearing its head and I don't know what's going on with it, so I hope my homeys here can help.
When working in Silverlight, when I create bindings in my c# code, they never hold up when the application is running. The declarative bindings from my xaml seem ok, but I'm doing something wrong when I create my bindings in C#. I'm hoping that there is something blindingly obvious I'm missing. Here's a typical binding that gets crushed:
```
TextBlock tb = new TextBlock();
Binding b = new Binding("FontSize");
b.Source = this;
tb.SetBinding(TextBlock.FontSizeProperty, b);
``` | It looks like as of Silverlight 3.1, at least, this is no longer an issue. I can't reproduce it, at any rate. |
71,944 | <p>I am using <code><input type="file" id="fileUpload" runat="server"></code> to upload a file in an ASP.NET application. I would like to limit the file type of the upload (example: limit to .xls or .xlsx file extensions). </p>
<p>Both JavaScript or server-side validation are OK (as long as the server side validation would take place before the files are being uploaded - there could be some very large files uploaded, so any validation needs to take place before the actual files are uploaded).</p>
| [
{
"answer_id": 71987,
"author": "Chris Roberts",
"author_id": 475,
"author_profile": "https://Stackoverflow.com/users/475",
"pm_score": 1,
"selected": false,
"text": "<p>Well - you won't be able to do it server-side on post-back as the file will get submitted (uploaded) during the post-b... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51/"
] | I am using `<input type="file" id="fileUpload" runat="server">` to upload a file in an ASP.NET application. I would like to limit the file type of the upload (example: limit to .xls or .xlsx file extensions).
Both JavaScript or server-side validation are OK (as long as the server side validation would take place before the files are being uploaded - there could be some very large files uploaded, so any validation needs to take place before the actual files are uploaded). | Seems like you are going to have limited options since you want the check to occur before the upload. I think the best you are going to get is to use javascript to validate the extension of the file. You could build a hash of valid extensions and then look to see if the extension of the file being uploaded existed in the hash.
HTML:
```
<input type="file" name="FILENAME" size="20" onchange="check_extension(this.value,"upload");"/>
<input type="submit" id="upload" name="upload" value="Attach" disabled="disabled" />
```
Javascript:
```
var hash = {
'xls' : 1,
'xlsx' : 1,
};
function check_extension(filename,submitId) {
var re = /\..+$/;
var ext = filename.match(re);
var submitEl = document.getElementById(submitId);
if (hash[ext]) {
submitEl.disabled = false;
return true;
} else {
alert("Invalid filename, please select another file");
submitEl.disabled = true;
return false;
}
}
``` |
71,959 | <p>I have my own class inside the file "Particles.h" and the class's implementation is inside "Particles.cpp"</p>
<p>I want the file "Load.h" to recognize my classes inside there, so I've added the line</p>
<pre><code>#include "Particles.h"
</code></pre>
<p>and the file doesn't recognize it and in the past everything was OK (I haven't made any changes inside that class).</p>
<p>What should I do?</p>
| [
{
"answer_id": 71984,
"author": "mrgroucho",
"author_id": 10870,
"author_profile": "https://Stackoverflow.com/users/10870",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like your include path - the list of directories that the compiler scans in order to locate files that you #... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have my own class inside the file "Particles.h" and the class's implementation is inside "Particles.cpp"
I want the file "Load.h" to recognize my classes inside there, so I've added the line
```
#include "Particles.h"
```
and the file doesn't recognize it and in the past everything was OK (I haven't made any changes inside that class).
What should I do? | It sounds like your include path - the list of directories that the compiler scans in order to locate files that you #include - is set incorrectly. Which compiler are you using? |
71,985 | <p>How can I copy a line 10 times easily in Emacs? I can't find a copy-line shortcut or function. I can use C-aC-spcC-eM-w to laboriously copy the line but how can I then paste it more than once?</p>
<p>Any ideas before I go and write my own functions.</p>
| [
{
"answer_id": 72008,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 0,
"selected": false,
"text": "<p>You will want to kill the line: C-a C-k, and then C-y or ?</p>\n"
},
{
"answer_id": 72039,
"author": "ljs",
... | 2008/09/16 | [
"https://Stackoverflow.com/questions/71985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9831/"
] | How can I copy a line 10 times easily in Emacs? I can't find a copy-line shortcut or function. I can use C-aC-spcC-eM-w to laboriously copy the line but how can I then paste it more than once?
Any ideas before I go and write my own functions. | **Copying**:
If you frequently work with lines, you might want to make copy (`kill-ring-save`) and cut (`kill-region`) work on lines when no region is selected:
```
(defadvice kill-ring-save (before slickcopy activate compile)
"When called interactively with no active region, copy a single line instead."
(interactive
(if mark-active (list (region-beginning) (region-end))
(list (line-beginning-position)
(line-beginning-position 2)))))
(defadvice kill-region (before slickcut activate compile)
"When called interactively with no active region, kill a single line instead."
(interactive
(if mark-active (list (region-beginning) (region-end))
(list (line-beginning-position)
(line-beginning-position 2)))))
```
Then you can copy the line with just M-w.
**Pasting**:
Often a prefix argument just performs an action multiple times, so you'd expect C-u 10 C-y to work, but in this case C-y uses its argument to mean which element of the kill-ring to "yank" (paste). The only solution I can think of is what kronoz says: record a macro with C-x ( C-y C-x ) and then let the argument of C-u go to `kmacro-end-and-call-macro` instead (that's C-u 9 C-x e or even just C-9 C-x e or M-9 C-x e).
**Another way**:
You can also just stay in `M-x viper-mode` and use yy10p :) |
72,010 | <p>Given the following example, why do I have to explicitly use the statement <code>b->A::DoSomething()</code> rather than just <code>b->DoSomething()</code>?</p>
<p>Shouldn't the compiler's overload resolution figure out which method I'm talking about?</p>
<p>I'm using Microsoft VS 2005. (Note: using virtual doesn't help in this case.)</p>
<pre><code>class A
{
public:
int DoSomething() {return 0;};
};
class B : public A
{
public:
int DoSomething(int x) {return 1;};
};
int main()
{
B* b = new B();
b->A::DoSomething(); //Why this?
//b->DoSomething(); //Why not this? (Gives compiler error.)
delete b;
return 0;
}
</code></pre>
| [
{
"answer_id": 72075,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "<p>The two “overloads” aren't in the same scope. By default, the compiler only considers the smallest possible name sco... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12083/"
] | Given the following example, why do I have to explicitly use the statement `b->A::DoSomething()` rather than just `b->DoSomething()`?
Shouldn't the compiler's overload resolution figure out which method I'm talking about?
I'm using Microsoft VS 2005. (Note: using virtual doesn't help in this case.)
```
class A
{
public:
int DoSomething() {return 0;};
};
class B : public A
{
public:
int DoSomething(int x) {return 1;};
};
int main()
{
B* b = new B();
b->A::DoSomething(); //Why this?
//b->DoSomething(); //Why not this? (Gives compiler error.)
delete b;
return 0;
}
``` | The two “overloads” aren't in the same scope. By default, the compiler only considers the smallest possible name scope until it finds a name match. Argument matching is done *afterwards*. In your case this means that the compiler sees `B::DoSomething`. It then tries to match the argument list, which fails.
One solution would be to pull down the overload from `A` into `B`'s scope:
```
class B : public A {
public:
using A::DoSomething;
// …
}
``` |
72,014 | <p>What are some important practices to follow when creating a .NET assembly that is going to be embedded to SQL Server 2005?</p>
<p>I am brand new to this, and I've found that there are significant method attributes like:</p>
<pre><code>[SqlFunction(FillRowMethodName = "FillRow", TableDefinition = "letter nchar(1)")]
</code></pre>
<p>I'm also looking for common pitfalls to avoid, etc.</p>
| [
{
"answer_id": 72113,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 3,
"selected": true,
"text": "<p>Some that I remember:</p>\n\n<ul>\n<li>Keep its usage to a minimum, only use it when T-SQL proved too complex.</li>\n<li>Av... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11947/"
] | What are some important practices to follow when creating a .NET assembly that is going to be embedded to SQL Server 2005?
I am brand new to this, and I've found that there are significant method attributes like:
```
[SqlFunction(FillRowMethodName = "FillRow", TableDefinition = "letter nchar(1)")]
```
I'm also looking for common pitfalls to avoid, etc. | Some that I remember:
* Keep its usage to a minimum, only use it when T-SQL proved too complex.
* Avoid pointers/cursors at all costs because a for loop is so easily abusable in CLR context.
* Only use the SQL-Server native data types unless totally necessary.
Can't remember where I've found the information, but those are some that I do remember.
Basically, only use it when declarative T-SQL is too complex or is impossible to do (such as registry editing etc.). |
72,048 | <p>I admit I know enough about COM and IE architecture only to be dangerous. I have a working C# .NET ActiveX control similar to this:</p>
<pre><code>using System;
using System.Runtime.InteropServices;
using BrowseUI;
using mshtml;
using SHDocVw;
using Microsoft.Win32;
namespace CTI
{
public interface CTIActiveXInterface
{
[DispId(1)]
string GetMsg();
}
[ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual)]
public class CTIActiveX : CTIActiveXInterface
{
/*** Where can I get a reference to SHDocVw.WebBrowser? *****/
SHDocVw.WebBrowser browser;
public string GetMsg()
{
return "foo";
}
}
}
</code></pre>
<p>I registered and created a type library using regasm:</p>
<pre><code>regasm CTIActiveX.dll /tlb:CTIActiveXNet.dll /codebase
</code></pre>
<p>And can successfully instantiate this in javascript:</p>
<pre><code>var CTIAX = new ActiveXObject("CTI.CTIActiveX");
alert(CTIAX.GetMsg());
</code></pre>
<p>How can I get a reference to the client site (browser window) within CTIActiveX? I have done this in a BHO by implementing IObjectWithSite, but I don't think this is the correct approach for an ActiveX control. If I implement any interface (I mean COM interface like IObjectWithSite) on CTIActiveX when I try to instantiate in Javascript I get an error that the object does not support automation.</p>
| [
{
"answer_id": 75086,
"author": "jlew",
"author_id": 7450,
"author_profile": "https://Stackoverflow.com/users/7450",
"pm_score": 2,
"selected": false,
"text": "<p>First, your interface needs ComVisible(true) in order to be seen by the calling script (this is probably causing the error). ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I admit I know enough about COM and IE architecture only to be dangerous. I have a working C# .NET ActiveX control similar to this:
```
using System;
using System.Runtime.InteropServices;
using BrowseUI;
using mshtml;
using SHDocVw;
using Microsoft.Win32;
namespace CTI
{
public interface CTIActiveXInterface
{
[DispId(1)]
string GetMsg();
}
[ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual)]
public class CTIActiveX : CTIActiveXInterface
{
/*** Where can I get a reference to SHDocVw.WebBrowser? *****/
SHDocVw.WebBrowser browser;
public string GetMsg()
{
return "foo";
}
}
}
```
I registered and created a type library using regasm:
```
regasm CTIActiveX.dll /tlb:CTIActiveXNet.dll /codebase
```
And can successfully instantiate this in javascript:
```
var CTIAX = new ActiveXObject("CTI.CTIActiveX");
alert(CTIAX.GetMsg());
```
How can I get a reference to the client site (browser window) within CTIActiveX? I have done this in a BHO by implementing IObjectWithSite, but I don't think this is the correct approach for an ActiveX control. If I implement any interface (I mean COM interface like IObjectWithSite) on CTIActiveX when I try to instantiate in Javascript I get an error that the object does not support automation. | First, your interface needs ComVisible(true) in order to be seen by the calling script (this is probably causing the error).
Second, add a .NETreference in your project to "Microsoft.mshtml". This will import the COM interfaces for various IE-related things (windows, HTML documents, etc.)
Then, you need to add a property of type IHtmlDocument2 to your interface:
```
IHtmlDocument2 Document { set; }
```
...implement it in your class:
```
public IHtmlDocument2 Document
{
set { _doc = value;}
}
```
...call it from script
```
CTIAX.Document = document;
```
...once you have stored a reference to the document, you can use it at will to get to the window, other frames, or any part of the HTML DOM that you wish. |
72,057 | <p>I would like to have a Guile script, which implements functions, which output test result messages according to the TAP protocol.</p>
| [
{
"answer_id": 72272,
"author": "Omer Zak",
"author_id": 11886,
"author_profile": "https://Stackoverflow.com/users/11886",
"pm_score": 2,
"selected": false,
"text": "<p>The following script, to be named guiletap.scm, implements the frequently-needed functions for using the TAP protocol w... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11886/"
] | I would like to have a Guile script, which implements functions, which output test result messages according to the TAP protocol. | The following script, to be named guiletap.scm, implements the frequently-needed functions for using the TAP protocol when running tests.
```
; Define functions for running Guile-written tests under the TAP protocol.
; Copyright © 2008 by Omer Zak
; Released under the GNU LGPL 2.1 or (at your option) any later version.
;;;
;;; To invoke it:
;;; (use-modules (guiletap))
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-module (guiletap))
(export plan)
(export ok)
(export bail_out)
(export diag)
(export is_ok)
(use-modules (ice-9 format))
; n is the number of tests.
(define plan
(lambda (n) (display (format "1..~d~%" n))))
; n - test number
; testdesc - test descriptor
; res - result which is #f at failure, other at success.
(define ok
(lambda (n testdesc res)
(if (not res)(display "not "))
(display (format "ok ~d - ~a~%" n testdesc))))
; testdesc - test descriptor
(define bail_out
(lambda (testdesc)
(display (format "Bail out! - ~a~%" testdesc))))
; diagmsg - diagnostic message
(define diag
(lambda (diagmsg)
(display (format "# ~a~%" diagmsg))))
; n - test number
; testdesc - test descriptor
; expres - expected test result
; actres - actual test result
(define is_ok
(lambda (n testdesc expres actres)
(ok n testdesc (equal? expres actres))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; !!! TODO:
; !!! To be implemented also:
; plan_no_plan
; plan_skip_all [REASON]
;
; is RESULT EXPECTED [NAME]
; isnt RESULT EXPECTED [NAME]
; like RESULT PATTERN [NAME]
; unlike RESULT PATTERN [NAME]
; pass [NAME]
; fail [NAME]
;
; skip CONDITION [REASON] [NB_TESTS=1]
; Specify TODO mode by setting $TODO:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; End of guiletap.scm
``` |
72,070 | <p>I'm executing stored procedures using SET FMTONLY ON, in order to emulate what our code generator does. However, it seems that the results are cached when executed like this, as I'm still getting a <em>Conversion failed</em> error from a proc that I have just dropped! This happens even when I execute the proc without SET FMTONLY ON.</p>
<p>Can anyone please tell me what's going on here?</p>
| [
{
"answer_id": 72094,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li><p>This sounds like a client-side error. Do you get the same message when running through SQL Management St... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] | I'm executing stored procedures using SET FMTONLY ON, in order to emulate what our code generator does. However, it seems that the results are cached when executed like this, as I'm still getting a *Conversion failed* error from a proc that I have just dropped! This happens even when I execute the proc without SET FMTONLY ON.
Can anyone please tell me what's going on here? | Some statements will still be executed, even with **`SET FMTONLY ON`**. You "Conversion failed" error could be from something as simple as a `set variable` statement in the stored proc. For example, this returns the metadata for the first query, but throws an exception when it runs the last statement:
```
SET FMTONLY on
select 1 as a
declare @a int
set @a = 'a'
```
As for running a dropped procedure, that's a new one to me. SQL Server uses the system tables to determine the object to execute, so it doesn't matter if the execution plan is cached for that object. If you drop it, it is deleted from the system tables, and should never be executable. Could you please query sysobjects (or sys.objects) just before you execute the procedure? I expect you'll find that you haven't dropped it. |
72,090 | <p>I'm trying to modify my GreaseMonkey script from firing on window.onload to window.DOMContentLoaded, but this event never fires.</p>
<p>I'm using FireFox 2.0.0.16 / GreaseMonkey 0.8.20080609</p>
<p><a href="https://stackoverflow.com/questions/59205/enhancing-stackoverflow-user-experience">This</a> is the full script that I'm trying to modify, changing:</p>
<pre><code>window.addEventListener ("load", doStuff, false);
</code></pre>
<p>to</p>
<pre><code>window.addEventListener ("DOMContentLoaded", doStuff, false);
</code></pre>
| [
{
"answer_id": 72245,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 6,
"selected": true,
"text": "<p>So I googled <a href=\"http://www.google.com/search?q=greasemonkey%20dom%20ready\" rel=\"noreferrer\">greasemonkey dom r... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/394/"
] | I'm trying to modify my GreaseMonkey script from firing on window.onload to window.DOMContentLoaded, but this event never fires.
I'm using FireFox 2.0.0.16 / GreaseMonkey 0.8.20080609
[This](https://stackoverflow.com/questions/59205/enhancing-stackoverflow-user-experience) is the full script that I'm trying to modify, changing:
```
window.addEventListener ("load", doStuff, false);
```
to
```
window.addEventListener ("DOMContentLoaded", doStuff, false);
``` | So I googled [greasemonkey dom ready](http://www.google.com/search?q=greasemonkey%20dom%20ready) and the [first result](http://www.sitepoint.com/article/beat-website-greasemonkey/) seemed to say that the greasemonkey script is actually running at "DOM ready" so you just need to remove the onload call and run the script straight away.
I removed the *`window.addEventListener ("load", function() {`* and *`}, false);`* wrapping and it worked perfectly. It's **much** more responsive this way, the page appears straight away with your script applied to it and all the unseen questions highlighted, no flicker at all. And there was much rejoicing.... yea. |
72,098 | <p>When using MediaWiki's markup language, the only thing that I hate is creating numbered lists. The only way I know to create a list is to do something like this:</p>
<pre><code>#Item1
#Item2
</code></pre>
<p>However, if I want to add spaces or some other text between those lines, the numbering gets lost. For example, the following will create text that has two number one items:</p>
<pre><code>#Item1
Somestuff
#Item2
</code></pre>
<p>Is there any way around this, or should I just use bullet points instead? I noticed just now that the stackoverflow system does not allow numbering like this, you have to do it all manually.</p>
| [
{
"answer_id": 72140,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 5,
"selected": false,
"text": "<p>Like this:</p>\n\n<pre><code>#Item1\n#:Somestuff\n#Item2\n</code></pre>\n"
},
{
"answer_id": 72222,
"author": ... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | When using MediaWiki's markup language, the only thing that I hate is creating numbered lists. The only way I know to create a list is to do something like this:
```
#Item1
#Item2
```
However, if I want to add spaces or some other text between those lines, the numbering gets lost. For example, the following will create text that has two number one items:
```
#Item1
Somestuff
#Item2
```
Is there any way around this, or should I just use bullet points instead? I noticed just now that the stackoverflow system does not allow numbering like this, you have to do it all manually. | Like this:
```
#Item1
#:Somestuff
#Item2
``` |
72,103 | <p>I'm using a winforms webbrowser control to display some content in a windows forms app. I'm using the DocumentText property to write the generated HTML. That part is working spectacularly. Now I want to use some images in the markup. (I also would prefer to use linked CSS and JavaScript, however, that can be worked around by just embedding it.)</p>
<p>I have been googling over the course of several days and can't seem to find an answer to the title question. </p>
<p>I tried using a relative reference: the app exe is in the bin\debug. The images live in the "Images" directory at the root of the project. I've set the images to be copied to the output directory on compile, so they end up in bin\debug\Images*. So I then use a reference like this "Images..." thinking it will be relative to the exe. However, when I look at the image properties in the embedded browser window, I see the image URL to be "about:blankImages/*". Everything seems to be relative to "about:blank" when HTML is written to the control. Lacking a location context, I can't figure out what to use for a relative file resource reference.</p>
<p>I poked around the properties of the control to see if there is a way to set something to fix this. I created a blank html page, and pointed the browser at it using the "Navigate()" method, using the full local path to the file. This worked fine with the browser reporting the local "file:///..." path to the blank page. Then I again wrote to the browser, this time using Document.Write(). Again, the browser now reports "about:blank" as the URL.</p>
<p>Short of writing the dynamic HTML results to a real file, is there no other way to reference a file resource?</p>
<p>I am going to try one last thing: constructing absolute file paths to the images and writing those to the HTML. My HTML is being generated using an XSL transform of a serialized object's XML so I'll need to play with some XSL parameters which will take a little extra time as I'm not that familiar with them.</p>
| [
{
"answer_id": 72339,
"author": "Ken Wootton",
"author_id": 7357,
"author_profile": "https://Stackoverflow.com/users/7357",
"pm_score": 4,
"selected": true,
"text": "<p>Here's what we do, although I should mention that we use a custom web browser to remove such things as the ability to r... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5496/"
] | I'm using a winforms webbrowser control to display some content in a windows forms app. I'm using the DocumentText property to write the generated HTML. That part is working spectacularly. Now I want to use some images in the markup. (I also would prefer to use linked CSS and JavaScript, however, that can be worked around by just embedding it.)
I have been googling over the course of several days and can't seem to find an answer to the title question.
I tried using a relative reference: the app exe is in the bin\debug. The images live in the "Images" directory at the root of the project. I've set the images to be copied to the output directory on compile, so they end up in bin\debug\Images\*. So I then use a reference like this "Images..." thinking it will be relative to the exe. However, when I look at the image properties in the embedded browser window, I see the image URL to be "about:blankImages/\*". Everything seems to be relative to "about:blank" when HTML is written to the control. Lacking a location context, I can't figure out what to use for a relative file resource reference.
I poked around the properties of the control to see if there is a way to set something to fix this. I created a blank html page, and pointed the browser at it using the "Navigate()" method, using the full local path to the file. This worked fine with the browser reporting the local "file:///..." path to the blank page. Then I again wrote to the browser, this time using Document.Write(). Again, the browser now reports "about:blank" as the URL.
Short of writing the dynamic HTML results to a real file, is there no other way to reference a file resource?
I am going to try one last thing: constructing absolute file paths to the images and writing those to the HTML. My HTML is being generated using an XSL transform of a serialized object's XML so I'll need to play with some XSL parameters which will take a little extra time as I'm not that familiar with them. | Here's what we do, although I should mention that we use a custom web browser to remove such things as the ability to right-click and see the good old IE context menu:
```
public class HtmlFormatter
{
/// <summary>
/// Indicator that this is a URI referencing the local
/// file path.
/// </summary>
public static readonly string FILE_URL_PREFIX =
"file://";
/// <summary>
/// The path separator for HTML paths.
/// </summary>
public const string PATH_SEPARATOR = "/";
}
// We need to add the proper paths to each image source
// designation that match where they are being placed on disk.
String html = HtmlFormatter.ReplaceImagePath(
myHtml,
HtmlFormatter.FILE_URL_PREFIX + ApplicationPath.FullAppPath +
HtmlFormatter.PATH_SEPARATOR);
```
Basically, you need to have an image path that has a file URI, e.g.
```
<img src="file://ApplicationPath/images/myImage.gif">
``` |
72,116 | <p>I understand about race conditions and how with multiple threads accessing the same variable, updates made by one can be ignored and overwritten by others, but what if each thread is writing the same value (not different values) to the same variable; can even this cause problems? Could this code:</p>
<p>GlobalVar.property = 11;</p>
<p>(assuming that property will never be assigned anything other than 11), cause problems if multiple threads execute it at the same time?</p>
| [
{
"answer_id": 72147,
"author": "Laurie Young",
"author_id": 7473,
"author_profile": "https://Stackoverflow.com/users/7473",
"pm_score": 1,
"selected": false,
"text": "<p>I would expect the result to be undetermined. As in it would vary from compiler to complier, langauge to language and... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I understand about race conditions and how with multiple threads accessing the same variable, updates made by one can be ignored and overwritten by others, but what if each thread is writing the same value (not different values) to the same variable; can even this cause problems? Could this code:
GlobalVar.property = 11;
(assuming that property will never be assigned anything other than 11), cause problems if multiple threads execute it at the same time? | The problem comes when you read that state back, and do something about it. Writing is a red herring - it is true that as long as this is a single word most environments guarantee the write will be atomic, but that doesn't mean that a larger piece of code that includes this fragment is thread-safe. Firstly, presumably your global variable contained a different value to begin with - otherwise if you know it's always the same, why is it a variable? Second, presumably you eventually **read** this value back again?
The issue is that presumably, you are writing to this bit of shared state for a reason - to signal that something has occurred? This is where it falls down: when you have no locking constructs, there is no implied order of memory accesses at all. It's hard to point to what's wrong here because your example doesn't actually contain the **use** of the variable, so here's a trivialish example in neutral C-like syntax:
```
int x = 0, y = 0;
//thread A does:
x = 1;
y = 2;
if (y == 2)
print(x);
//thread B does, at the same time:
if (y == 2)
print(x);
```
Thread A will always print 1, but it's completely valid for thread B to print 0. The order of operations in thread A is only required to be observable from code executing in thread A - thread B is allowed to see any combination of the state. The writes to x and y may not actually happen in order.
This can happen even on single-processor systems, where most people do not expect this kind of reordering - your compiler may reorder it for you. On SMP even if the compiler doesn't reorder things, the memory writes may be reordered between the caches of the separate processors.
If that doesn't seem to answer it for you, include more detail of your example in the question. Without the use of the variable it's impossible to definitively say whether such a usage is safe or not. |
72,121 | <p>Let me use the following example to explain my question:</p>
<pre class="lang-csharp prettyprint-override"><code>public string ExampleFunction(string Variable) {
return something;
}
string WhatIsMyName = "Hello World";
string Hello = ExampleFunction(WhatIsMyName);
</code></pre>
<p>When I pass the variable <code>WhatIsMyName</code> to the <code>ExampleFunction</code>, I want to be able to get a string of the <em>original</em> variable's name. Perhaps something like:</p>
<pre class="lang-csharp prettyprint-override"><code>Variable.OriginalName.ToString() // == "WhatIsMyName"
</code></pre>
<p>Is there any way to do this?</p>
| [
{
"answer_id": 72139,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": -1,
"selected": true,
"text": "<p><strong>No.</strong> I don't think so.</p>\n<p>The variable name that you use is for your convenience and readability. The c... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] | Let me use the following example to explain my question:
```csharp
public string ExampleFunction(string Variable) {
return something;
}
string WhatIsMyName = "Hello World";
string Hello = ExampleFunction(WhatIsMyName);
```
When I pass the variable `WhatIsMyName` to the `ExampleFunction`, I want to be able to get a string of the *original* variable's name. Perhaps something like:
```csharp
Variable.OriginalName.ToString() // == "WhatIsMyName"
```
Is there any way to do this? | **No.** I don't think so.
The variable name that you use is for your convenience and readability. The compiler doesn't need it & just chucks it out if I'm not mistaken.
If it helps, you could define a new class called `NamedParameter` with attributes `Name` and `Param`. You then pass this object around as parameters. |
72,125 | <p>Lets say that you have websites www.xyz.com and www.abc.com.</p>
<p>Lets say that a user goes to www.abc.com and they get authenticated through the normal ASP .NET membership provider. </p>
<p>Then, from that site, they get sent to (redirection, linked, whatever works) site www.xyz.com, and the intent of site www.abc.com was to pass that user to the other site as the status of isAuthenticated, so that the site www.xyz.com does not ask for the credentials of said user again.</p>
<p>What would be needed for this to work? I have some constraints on this though, the user databases are completely separate, it is not internal to an organization, in all regards, it is like passing from stackoverflow.com to google as authenticated, it is that separate in nature. A link to a relevant article will suffice.</p>
| [
{
"answer_id": 72149,
"author": "Marc Gear",
"author_id": 6563,
"author_profile": "https://Stackoverflow.com/users/6563",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure what you'd use for .NET but ordinarily I'd use <a href=\"http://www.danga.com/memcached/\" rel=\"nofollow noref... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952/"
] | Lets say that you have websites www.xyz.com and www.abc.com.
Lets say that a user goes to www.abc.com and they get authenticated through the normal ASP .NET membership provider.
Then, from that site, they get sent to (redirection, linked, whatever works) site www.xyz.com, and the intent of site www.abc.com was to pass that user to the other site as the status of isAuthenticated, so that the site www.xyz.com does not ask for the credentials of said user again.
What would be needed for this to work? I have some constraints on this though, the user databases are completely separate, it is not internal to an organization, in all regards, it is like passing from stackoverflow.com to google as authenticated, it is that separate in nature. A link to a relevant article will suffice. | Try using FormAuthentication by setting the web.config authentication section like so:
```
<authentication mode="Forms">
<forms name=".ASPXAUTH" requireSSL="true"
protection="All"
enableCrossAppRedirects="true" />
</authentication>
```
Generate a machine key. Example: [Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS ...](https://blogs.msdn.microsoft.com/amb/2012/07/31/easiest-way-to-generate-machinekey/)
When posting to the other application the authentication ticket is passed as a hidden field. While reading the post from the first app, the second app will read the encrypted ticket and authenticate the user. Here's an example of the page that passes that posts the field:
.aspx:
```
<form id="form1" runat="server">
<div>
<p><asp:Button ID="btnTransfer" runat="server" Text="Go" PostBackUrl="http://otherapp/" /></p>
<input id="hdnStreetCred" runat="server" type="hidden" />
</div>
</form>
```
code-behind:
```
protected void Page_Load(object sender, EventArgs e)
{
FormsIdentity cIdentity = Page.User.Identity as FormsIdentity;
if (cIdentity != null)
{
this.hdnStreetCred.ID = FormsAuthentication.FormsCookieName;
this.hdnStreetCred.Value = FormsAuthentication.Encrypt(((FormsIdentity)User.Identity).Ticket);
}
}
```
Also see the cross app form authentication section in Chapter 5 of this [book](http://www.wrox.com/WileyCDA/WroxTitle/Professional-ASP-NET-2-0-Security-Membership-and-Role-Management.productCd-0764596985.html) from Wrox. It recommends answers like the ones above in addition to providing a homebrew SSO solution. |
72,151 | <p>I'm using OLEDB provider for ADO.Net connecting to an Oracle database. In my loop, I am doing an insert:</p>
<pre><code>insert into ps_tl_compleave_tbl values('2626899', 0, TO_DATE('01/01/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '52', TO_DATE('01/01/2002', 'MM/DD/YYYY'), 16.000000, 24.000)insert into ps_tl_compleave_tbl values('4327142', 0, TO_DATE('03/23/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '51', TO_DATE('03/23/2002', 'MM/DD/YYYY'), 0.000000, 0.000)
</code></pre>
<p>The first insert succeeds but the second one gives an error:</p>
<pre><code>ORA-00933: SQL command not properly ended
</code></pre>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 72165,
"author": "metadave",
"author_id": 7237,
"author_profile": "https://Stackoverflow.com/users/7237",
"pm_score": 2,
"selected": false,
"text": "<p>semi colon after the first insert?</p>\n"
},
{
"answer_id": 72170,
"author": "ShoeLace",
"author_id": 382... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10589/"
] | I'm using OLEDB provider for ADO.Net connecting to an Oracle database. In my loop, I am doing an insert:
```
insert into ps_tl_compleave_tbl values('2626899', 0, TO_DATE('01/01/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '52', TO_DATE('01/01/2002', 'MM/DD/YYYY'), 16.000000, 24.000)insert into ps_tl_compleave_tbl values('4327142', 0, TO_DATE('03/23/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '51', TO_DATE('03/23/2002', 'MM/DD/YYYY'), 0.000000, 0.000)
```
The first insert succeeds but the second one gives an error:
```
ORA-00933: SQL command not properly ended
```
What am I doing wrong? | To me it seems you're missing a `;` between the two statements:
`insert into ps_tl_compleave_tbl values('2626899', 0, TO_DATE('01/01/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '52', TO_DATE('01/01/2002', 'MM/DD/YYYY'), 16.000000, 24.000)`
**`;`**
`insert into ps_tl_compleave_tbl values('4327142', 0, TO_DATE('03/23/2002', 'MM/DD/YYYY'), 'LTKN', 'LTKN', '51', TO_DATE('03/23/2002', 'MM/DD/YYYY'), 0.000000, 0.000)`
**`;`**
Try adding the `;` and let us know. |
72,153 | <p>How can I construct a MSBuild ItemGroup to exclude .svn directories and all files within (recursively). I've got:</p>
<pre><code><ItemGroup>
<LibraryFiles Include="$(LibrariesReleaseDir)\**\*.*" Exclude=".svn" />
</ItemGroup>
</code></pre>
<p>At the moment, but this does not exclude anything!</p>
| [
{
"answer_id": 72536,
"author": "Kieran Benton",
"author_id": 5777,
"author_profile": "https://Stackoverflow.com/users/5777",
"pm_score": 7,
"selected": true,
"text": "<p>Thanks for your help, managed to sort it as follows:</p>\n\n<pre><code><ItemGroup>\n <LibraryFiles Inclu... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5777/"
] | How can I construct a MSBuild ItemGroup to exclude .svn directories and all files within (recursively). I've got:
```
<ItemGroup>
<LibraryFiles Include="$(LibrariesReleaseDir)\**\*.*" Exclude=".svn" />
</ItemGroup>
```
At the moment, but this does not exclude anything! | Thanks for your help, managed to sort it as follows:
```
<ItemGroup>
<LibraryFiles Include="$(LibrariesReleaseDir)\**\*.*"
Exclude="$(LibrariesReleaseDir)\**\.svn\**" />
</ItemGroup>
```
Turns out the pattern matching basically runs on files, so you have to exclude everything BELOW the `.svn` directories (`.svn\\**`) for MSBuild to exclude the `.svn` directory itself. |
72,167 | <p>How do I find out which sound files the user has configured in the control panel?</p>
<p>Example: I want to play the sound for "Device connected".</p>
<p>Which API can be used to query the control panel sound settings?</p>
<p>I see that there are some custom entries made by third party programs in the control panel dialog, so there has to be a way for these programs to communicate with the global sound settings.</p>
<p>Edit: Thank you. I did not know that PlaySound also just played appropriate sound file when specifying the name of the registry entry.</p>
<p>To play the "Device Conntected" sound:</p>
<pre><code>::PlaySound( TEXT("DeviceConnect"), NULL, SND_ALIAS|SND_ASYNC );
</code></pre>
| [
{
"answer_id": 72250,
"author": "titanae",
"author_id": 2387,
"author_profile": "https://Stackoverflow.com/users/2387",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"https://learn.microsoft.com/en-us/previous-versions/ms712879(v=vs.85)\" rel=\"nofollow noreferrer\"><code>PlaySou... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1810/"
] | How do I find out which sound files the user has configured in the control panel?
Example: I want to play the sound for "Device connected".
Which API can be used to query the control panel sound settings?
I see that there are some custom entries made by third party programs in the control panel dialog, so there has to be a way for these programs to communicate with the global sound settings.
Edit: Thank you. I did not know that PlaySound also just played appropriate sound file when specifying the name of the registry entry.
To play the "Device Conntected" sound:
```
::PlaySound( TEXT("DeviceConnect"), NULL, SND_ALIAS|SND_ASYNC );
``` | [`PlaySound`](https://learn.microsoft.com/en-us/previous-versions/ms712879(v=vs.85)) is the API.
Also see [Play System Sounds](https://learn.microsoft.com/en-us/windows/win32/multimedia/using-playsound-to-play-system-sounds). |
72,176 | <p>While there are 100 ways to solve the conversion problem, I am focusing on performance.</p>
<p>Give that the string only contains binary data, what is the fastest method, in terms of performance, of converting that data to a byte[] (not char[]) under C#?</p>
<p>Clarification: This is not ASCII data, rather binary data that happens to be in a string.</p>
| [
{
"answer_id": 72191,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.text.utf8encoding.getbytes.aspx\" rel=\"nofollow noreferrer\">UT... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12113/"
] | While there are 100 ways to solve the conversion problem, I am focusing on performance.
Give that the string only contains binary data, what is the fastest method, in terms of performance, of converting that data to a byte[] (not char[]) under C#?
Clarification: This is not ASCII data, rather binary data that happens to be in a string. | I'm not sure ASCIIEncoding.GetBytes is going to do it, because it only supports the [range 0x0000 to 0x007F](https://learn.microsoft.com/en-us/dotnet/api/system.text.asciiencoding).
You tell the string contains only bytes. But a .NET string is an array of chars, and 1 char is 2 bytes (because a .NET stores strings as UTF16). So you can either have two situations for storing the bytes 0x42 and 0x98:
1. The string was an ANSI string and contained bytes and is converted to an unicode string, thus the bytes will be 0x00 0x42 0x00 0x98. (The string is stored as 0x0042 and 0x0098)
2. The string was just a byte array which you typecasted or just recieved to an string and thus became the following bytes 0x42 0x98. (The string is stored as 0x9842)
In the first situation on the result would be 0x42 and 0x3F (ascii for "B?"). The second situation would result in 0x3F (ascii for "?"). This is logical, because the chars are outside of the valid ascii range and the encoder does not know what to do with those values.
So i'm wondering why it's a string with bytes?
* Maybe it contains a byte encoded as a string (for instance [Base64](https://en.wikipedia.org/wiki/Base64))?
* Maybe you should start with an char array or a byte array?
If you realy do have situation 2 and you want to get the bytes out of it you should use the [UnicodeEncoding.GetBytes](https://learn.microsoft.com/en-us/dotnet/api/system.text.unicodeencoding.getbytes) call. Because that will return 0x42 and 0x98.
If you'd like to go from a char array to byte array, the fastest way would be Marshaling.. But that's not really nice, and uses double memory.
```
public Byte[] ConvertToBytes(Char[] source)
{
Byte[] result = new Byte[source.Length * sizeof(Char)];
IntPtr tempBuffer = Marshal.AllocHGlobal(result.Length);
try
{
Marshal.Copy(source, 0, tempBuffer, source.Length);
Marshal.Copy(tempBuffer, result, 0, result.Length);
}
finally
{
Marshal.FreeHGlobal(tempBuffer);
}
return result;
}
``` |
72,198 | <p>This seemed like an easy thing to do. I just wanted to pop up a text window and display two columns of data -- a description on the left side and a corresponding value displayed on the right side. I haven't worked with Forms much so I just grabbed the first control that seemed appropriate, a TextBox. I thought using tabs would be an easy way to create the second column, but I discovered things just don't work that well.</p>
<p>There seems to be two problems with the way I tried to do this (see below). First, I read on numerous websites that the MeasureString function isn't very precise due to how complex fonts are, with kerning issues and all. The second is that I have no idea what the TextBox control is using as its StringFormat underneath.</p>
<p>Anyway, the result is that I invariably end up with items in the right column that are off by a tab. I suppose I could roll my own text window and do everything myself, but gee, isn't there a simple way to do this?</p>
<pre><code> TextBox textBox = new TextBox();
textBox.Font = new Font("Calibri", 11);
textBox.Dock = DockStyle.Fill;
textBox.Multiline = true;
textBox.WordWrap = false;
textBox.ScrollBars = ScrollBars.Vertical;
Form form = new Form();
form.Text = "Recipe";
form.Size = new Size(400, 600);
form.FormBorderStyle = FormBorderStyle.Sizable;
form.StartPosition = FormStartPosition.CenterScreen;
form.Controls.Add(textBox);
Graphics g = form.CreateGraphics();
float targetWidth = 230;
foreach (PropertyInfo property in properties)
{
string text = String.Format("{0}:\t", Description);
while (g.MeasureString(text,textBox.Font).Width < targetWidth)
text += "\t";
textBox.AppendText(text + value.ToString() + "\n");
}
g.Dispose();
form.ShowDialog();
</code></pre>
| [
{
"answer_id": 72282,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": -1,
"selected": false,
"text": "<p>Don't the text boxes allow HTML usage? If that is the case, just use HTML to format the text into a table. Other... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12058/"
] | This seemed like an easy thing to do. I just wanted to pop up a text window and display two columns of data -- a description on the left side and a corresponding value displayed on the right side. I haven't worked with Forms much so I just grabbed the first control that seemed appropriate, a TextBox. I thought using tabs would be an easy way to create the second column, but I discovered things just don't work that well.
There seems to be two problems with the way I tried to do this (see below). First, I read on numerous websites that the MeasureString function isn't very precise due to how complex fonts are, with kerning issues and all. The second is that I have no idea what the TextBox control is using as its StringFormat underneath.
Anyway, the result is that I invariably end up with items in the right column that are off by a tab. I suppose I could roll my own text window and do everything myself, but gee, isn't there a simple way to do this?
```
TextBox textBox = new TextBox();
textBox.Font = new Font("Calibri", 11);
textBox.Dock = DockStyle.Fill;
textBox.Multiline = true;
textBox.WordWrap = false;
textBox.ScrollBars = ScrollBars.Vertical;
Form form = new Form();
form.Text = "Recipe";
form.Size = new Size(400, 600);
form.FormBorderStyle = FormBorderStyle.Sizable;
form.StartPosition = FormStartPosition.CenterScreen;
form.Controls.Add(textBox);
Graphics g = form.CreateGraphics();
float targetWidth = 230;
foreach (PropertyInfo property in properties)
{
string text = String.Format("{0}:\t", Description);
while (g.MeasureString(text,textBox.Font).Width < targetWidth)
text += "\t";
textBox.AppendText(text + value.ToString() + "\n");
}
g.Dispose();
form.ShowDialog();
``` | If you want, you can translate this VB.Net code to C#. The theory here is that you change the size of a tab in the control.
```
Private Declare Function SendMessage _
Lib "user32" Alias "SendMessageA" _
(ByVal handle As IntPtr, ByVal wMsg As Integer, _
ByVal wParam As Integer, ByRef lParam As Integer) As Integer
Private Sub SetTabStops(ByVal ctlTextBox As TextBox)
Const EM_SETTABSTOPS As Integer = &HCBS
Dim tabs() As Integer = {20, 40, 80}
SendMessage(ctlTextBox.Handle, EM_SETTABSTOPS, _
tabs.Length, tabs(0))
End Sub
```
I converted a version to C# for you, too. Tested and working in VS2005.
Add this using statement to your form:
```
using System.Runtime.InteropServices;
```
Put this right after the class declaration:
```
private const int EM_SETTABSTOPS = 0x00CB;
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, int[] lParam);
```
Call this method when you want to set the tabstops:
```
private void SetTabStops(TextBox ctlTextBox)
{
const int EM_SETTABSTOPS = 203;
int[] tabs = { 100, 40, 80 };
SendMessage(textBox1.Handle, EM_SETTABSTOPS, tabs.Length, tabs);
}
```
To use it, here is all I did:
```
private void Form1_Load(object sender, EventArgs e)
{
SetTabStops(textBox1);
textBox1.Text = "Hi\tWorld";
}
``` |
72,204 | <p>Has anyone used <a href="http://www.ayende.com/Blog/archive/2007/09/03/Rhino-Igloo-ndash-MVC-Framework-for-Web-Forms.aspx" rel="nofollow noreferrer">Rhino igloo</a> in a non-trivial project? I am curious if it's worth, what are its drawbacks, does it enhance testability a lot, is it easy to use. How would you compare it to a pure MVC framework (ASP.NET MVC)? Please share the experience.</p>
| [
{
"answer_id": 72282,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": -1,
"selected": false,
"text": "<p>Don't the text boxes allow HTML usage? If that is the case, just use HTML to format the text into a table. Other... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1801/"
] | Has anyone used [Rhino igloo](http://www.ayende.com/Blog/archive/2007/09/03/Rhino-Igloo-ndash-MVC-Framework-for-Web-Forms.aspx) in a non-trivial project? I am curious if it's worth, what are its drawbacks, does it enhance testability a lot, is it easy to use. How would you compare it to a pure MVC framework (ASP.NET MVC)? Please share the experience. | If you want, you can translate this VB.Net code to C#. The theory here is that you change the size of a tab in the control.
```
Private Declare Function SendMessage _
Lib "user32" Alias "SendMessageA" _
(ByVal handle As IntPtr, ByVal wMsg As Integer, _
ByVal wParam As Integer, ByRef lParam As Integer) As Integer
Private Sub SetTabStops(ByVal ctlTextBox As TextBox)
Const EM_SETTABSTOPS As Integer = &HCBS
Dim tabs() As Integer = {20, 40, 80}
SendMessage(ctlTextBox.Handle, EM_SETTABSTOPS, _
tabs.Length, tabs(0))
End Sub
```
I converted a version to C# for you, too. Tested and working in VS2005.
Add this using statement to your form:
```
using System.Runtime.InteropServices;
```
Put this right after the class declaration:
```
private const int EM_SETTABSTOPS = 0x00CB;
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr h, int msg, int wParam, int[] lParam);
```
Call this method when you want to set the tabstops:
```
private void SetTabStops(TextBox ctlTextBox)
{
const int EM_SETTABSTOPS = 203;
int[] tabs = { 100, 40, 80 };
SendMessage(textBox1.Handle, EM_SETTABSTOPS, tabs.Length, tabs);
}
```
To use it, here is all I did:
```
private void Form1_Load(object sender, EventArgs e)
{
SetTabStops(textBox1);
textBox1.Text = "Hi\tWorld";
}
``` |
72,220 | <p>I'm a Java-developer toying with Ruby, and loving it. I have understood that because of Ruby's metaprogramming facilities my unit-tests become much cleaner and I don't need nasty mocking frameworks. I have a class which needs the <code>File</code> class's services and in my test I don't want to touch my real filesystem. In Java I would use some virtual file system for easier "seams" to pass fake-objects in but in Ruby that's obviously overkill. What I come up seems already really nice compared to the Java-world. In my class under test I have an optional constructor parameter: </p>
<pre><code>def initialize(file_class=File)
</code></pre>
<p>When I need to open files within my class, I can then do this:</p>
<pre><code>@file_class.open(filename)
</code></pre>
<p>And the call goes to either the real File-class, or in case of my unit-test, it goes to a fake-class which doesn't touch the filesystem. I know there must be a better way to do this with metaprogramming?</p>
| [
{
"answer_id": 72248,
"author": "Brian Phillips",
"author_id": 7230,
"author_profile": "https://Stackoverflow.com/users/7230",
"pm_score": 4,
"selected": false,
"text": "<p>Mocha (<a href=\"http://mocha.rubyforge.org/\" rel=\"noreferrer\">http://mocha.rubyforge.org/</a>) is a very good m... | 2008/09/16 | [
"https://Stackoverflow.com/questions/72220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4110/"
] | I'm a Java-developer toying with Ruby, and loving it. I have understood that because of Ruby's metaprogramming facilities my unit-tests become much cleaner and I don't need nasty mocking frameworks. I have a class which needs the `File` class's services and in my test I don't want to touch my real filesystem. In Java I would use some virtual file system for easier "seams" to pass fake-objects in but in Ruby that's obviously overkill. What I come up seems already really nice compared to the Java-world. In my class under test I have an optional constructor parameter:
```
def initialize(file_class=File)
```
When I need to open files within my class, I can then do this:
```
@file_class.open(filename)
```
And the call goes to either the real File-class, or in case of my unit-test, it goes to a fake-class which doesn't touch the filesystem. I know there must be a better way to do this with metaprogramming? | Mocha (<http://mocha.rubyforge.org/>) is a very good mocking library for ruby. Depending on what you're actually wanting to test (i.e. if you want to just fake out the File.new call to avoid the file system dependency or if you want to verify that the correct arguments are passed into File.new) you could do something like this:
```
require 'mocha'
mock_file_obj = mock("My Mock File") do
stubs(:some_instance_method).returns("foo")
end
File.stubs(:new).with(is_a(String)).returns(mock_file_obj)
``` |