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 |
|---|---|---|---|---|---|---|
47,309 | <p>I'm trying to install <a href="http://godi.camlcity.org/godi/index.html" rel="noreferrer">GODI</a> on linux (Ubuntu). It's a library management tool for the ocaml language. I've actually installed this before --twice, but awhile ago-- with no issues --that I can remember-- but this time I just can't figure out what I'm missing.</p>
<pre><code>$ ./bootstrap --prefix /home/nlucaroni/godi
$ ./bootstrap_stage2
.: 1: godi_confdir: not found
Error: Command fails with code 2: /bin/sh
Failure!
</code></pre>
<p>I had added the proper directories to the path, and they show up with a quick <code>echo $path</code>, and <code>godi_confdir</code> reported as being:</p>
<pre><code> /home/nlucaroni/godi/etc
</code></pre>
<p>(...and the directory exists, with the godi.conf file present). So, I can't figure out why <code>./bootstrap_stage2</code> isn't working.</p>
| [
{
"answer_id": 47655,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 2,
"selected": false,
"text": "<p>What is the output of <code>which godi_confdir</code>?</p>\n\n<p>P.S. I remember having this exact same problem, but ... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/157/"
] | I'm trying to install [GODI](http://godi.camlcity.org/godi/index.html) on linux (Ubuntu). It's a library management tool for the ocaml language. I've actually installed this before --twice, but awhile ago-- with no issues --that I can remember-- but this time I just can't figure out what I'm missing.
```
$ ./bootstrap --prefix /home/nlucaroni/godi
$ ./bootstrap_stage2
.: 1: godi_confdir: not found
Error: Command fails with code 2: /bin/sh
Failure!
```
I had added the proper directories to the path, and they show up with a quick `echo $path`, and `godi_confdir` reported as being:
```
/home/nlucaroni/godi/etc
```
(...and the directory exists, with the godi.conf file present). So, I can't figure out why `./bootstrap_stage2` isn't working. | Hey Chris, I just figured it out. Silly mistake.
It was just a permission issue, running everything from `/tmp/` worked fine --well after enabling `GODI_BASEPKG_PCRE` in `godi.conf`. I had been running it from my home directory, you forget simple things like that at 3:00am.
--
Actually I'm having another problem. Installing `conf-opengl-6`:
GODI can't seen to find the `GL/gl.h` file, though I can --you can see that it is `Checking the suggestion`.
```
> ===> Configuring for conf-opengl-6
> Checking the suggestion
> Include=/usr/include/GL/gl.h Library=/<GLU+GL>
> Checking /usr:
> Include=/usr/include/GL/gl.h Library=/usr/lib/<GLU+GL>
> Checking /usr:
> Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/<GLU+GL>
> Checking /usr/local:
> Include=/usr/local/include/GL/gl.h Library=/usr/local/lib/<GLU+GL>
> Exception: Failure "Cannot find library".
> Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1022: Command returned with non-zero exit code
> Error: Exec error: File /home/nlucaroni/godi/build/conf/conf-opengl/./../../mk/bsd.pkg.mk, line 1375: Command returned with non-zero exit code
### Error: Command fails with code 1: godi_console
```
*edit* - Ok, this is fixed too... just needed GLU, weird since the test configuration option said everything was fine. |
47,329 | <p>I'm implementing a custom control and in this control I need to write a bunch of links to the current page, each one with a different query parameter. I need to keep existing query string intact, and add (or modify the value of ) an extra query item (eg. "page"):</p>
<pre><code>"Default.aspx?page=1"
"Default.aspx?page=2"
"Default.aspx?someother=true&page=2"
</code></pre>
<p>etc.</p>
<p>Is there a simple helper method that I can use in the Render method ... uhmm ... like:</p>
<pre><code>Page.ClientScript.SomeURLBuilderMethodHere(this,"page","1");
Page.ClientScript.SomeURLBuilderMethodHere(this,"page","2");
</code></pre>
<p>That will take care of generating a correct URL, maintain existing query string items and not create duplicates eg. page=1&page=2&page=3?</p>
<p>Rolling up my own seems like such an unappealing task.</p>
| [
{
"answer_id": 47344,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 2,
"selected": true,
"text": "<p>I'm afraid I don't know of any built-in method for this, we use this method that takes the querystring and sets parame... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3263/"
] | I'm implementing a custom control and in this control I need to write a bunch of links to the current page, each one with a different query parameter. I need to keep existing query string intact, and add (or modify the value of ) an extra query item (eg. "page"):
```
"Default.aspx?page=1"
"Default.aspx?page=2"
"Default.aspx?someother=true&page=2"
```
etc.
Is there a simple helper method that I can use in the Render method ... uhmm ... like:
```
Page.ClientScript.SomeURLBuilderMethodHere(this,"page","1");
Page.ClientScript.SomeURLBuilderMethodHere(this,"page","2");
```
That will take care of generating a correct URL, maintain existing query string items and not create duplicates eg. page=1&page=2&page=3?
Rolling up my own seems like such an unappealing task. | I'm afraid I don't know of any built-in method for this, we use this method that takes the querystring and sets parameters
```
/// <summary>
/// Set a parameter value in a query string. If the parameter is not found in the passed in query string,
/// it is added to the end of the query string
/// </summary>
/// <param name="queryString">The query string that is to be manipulated</param>
/// <param name="paramName">The name of the parameter</param>
/// <param name="paramValue">The value that the parameter is to be set to</param>
/// <returns>The query string with the parameter set to the new value.</returns>
public static string SetParameter(string queryString, string paramName, object paramValue)
{
//create the regex
//match paramname=*
//string regex = String.Format(@"{0}=[^&]*", paramName);
string regex = @"([&?]{0,1})" + String.Format(@"({0}=[^&]*)", paramName);
RegexOptions options = RegexOptions.RightToLeft;
// Querystring has parameters...
if (Regex.IsMatch(queryString, regex, options))
{
queryString = Regex.Replace(queryString, regex, String.Format("$1{0}={1}", paramName, paramValue));
}
else
{
// If no querystring just return the Parameter Key/Value
if (queryString == String.Empty)
{
return String.Format("{0}={1}", paramName, paramValue);
}
else
{
// Append the new parameter key/value to the end of querystring
queryString = String.Format("{0}&{1}={2}", queryString, paramName, paramValue);
}
}
return queryString;
}
```
Obviously you could use the QueryString `NameValueCollection` property of the URI object to make looking up the values easier, but we wanted to be able to parse any querystring. |
47,338 | <p>I have a problem with a sample routing with the preview 5 of asp.net mvc.</p>
<p>In the AccountController I have 2 actions: </p>
<pre><code>public ActionResult Delete()
public ActionResult Delete(string username)
</code></pre>
<p>While trying to look for Account/Delete or Account/Delete?username=davide the ControllerActionInvoker throws a exception saying that Delete request is ambiguous between my tow actions methods.</p>
<p>The default route in the global.asax hasn't been changed.</p>
<p>Shouldn't the action invoker understand what's the method to call looking in the parameters list?</p>
<p>Using the preview 4 I hadn't these kind of problem performing the same operation.</p>
<p>Any idea?</p>
| [
{
"answer_id": 47375,
"author": "berko",
"author_id": 4884,
"author_profile": "https://Stackoverflow.com/users/4884",
"pm_score": 0,
"selected": false,
"text": "<p>I can't say for sure why this is happening. But you might want to consider only having the Delete(string username) action an... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1812/"
] | I have a problem with a sample routing with the preview 5 of asp.net mvc.
In the AccountController I have 2 actions:
```
public ActionResult Delete()
public ActionResult Delete(string username)
```
While trying to look for Account/Delete or Account/Delete?username=davide the ControllerActionInvoker throws a exception saying that Delete request is ambiguous between my tow actions methods.
The default route in the global.asax hasn't been changed.
Shouldn't the action invoker understand what's the method to call looking in the parameters list?
Using the preview 4 I hadn't these kind of problem performing the same operation.
Any idea? | Solution found!
With the introduction of the ActionNameAttribute, it's now necessary to filter manually which method to call depending on the request. This is done by the ActionSelectionAttribute.
Full explanation here: <http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx> |
47,363 | <p>What is the command to list all triggers in a MySQL database?</p>
| [
{
"answer_id": 47364,
"author": "Harry",
"author_id": 4704,
"author_profile": "https://Stackoverflow.com/users/4704",
"pm_score": 9,
"selected": true,
"text": "<p>The command for listing all triggers is:</p>\n\n<pre><code>show triggers;\n</code></pre>\n\n<p>or you can access the <code>IN... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4704/"
] | What is the command to list all triggers in a MySQL database? | The command for listing all triggers is:
```
show triggers;
```
or you can access the `INFORMATION_SCHEMA` table directly by:
```
select trigger_schema, trigger_name, action_statement
from information_schema.triggers
```
* You can do this from version 5.0.10 onwards.
* More information about the [`TRIGGERS` table is here](http://dev.mysql.com/doc/refman/5.0/en/triggers-table.html). |
47,374 | <p>Part of the web application I'm working on is an area displaying messages from management to 1...n users. I have a DataAccess project that contains the LINQ to SQL classes, and a website project that is the UI. My database looks like this:</p>
<p>User -> MessageDetail <- Message <- MessageCategory</p>
<p>MessageDetail is a join table that also contains an IsRead flag.</p>
<p>The list of messages is grouped by category. I have two nested ListView controls on the page -- One outputs the group name, while a second one nested inside that is bound to MessageDetails and outputs the messages themselves. In the code-behind for the page listing the messages I have the following code:</p>
<pre><code>protected void MessageListDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
var db = new DataContext();
// parse the input strings from the web form
int categoryIDFilter;
DateTime dateFilter;
string catFilterString = MessagesCategoryFilter.SelectedValue;
string dateFilterString = MessagesDateFilter.SelectedValue;
// TryParse will return default values if parsing is unsuccessful (i.e. if "all" is selected"):
// DateTime.MinValue for dates, 0 for int
DateTime.TryParse(dateFilterString, out dateFilter);
Int32.TryParse(catFilterString, out categoryIDFilter);
bool showRead = MessagesReadFilter.Checked;
var messages =
from detail in db.MessageDetails
where detail.UserID == (int)Session["UserID"]
where detail.Message.IsPublished
where detail.Message.MessageCategoryID == categoryIDFilter || (categoryIDFilter == 0)
where dateFilter == detail.Message.PublishDate.Value.Date || (dateFilter == DateTime.MinValue)
// is unread, showRead filter is on, or message was marked read today
where detail.IsRead == false || showRead || detail.ReadDate.Value.Date == DateTime.Today
orderby detail.Message.PublishDate descending
group detail by detail.Message.MessageCategory into categories
orderby categories.Key.Name
select new
{
MessageCategory = categories.Key,
MessageDetails = categories.Select(d => d)
};
e.Result = messages;
}
</code></pre>
<p>This code <em>works</em>, but sticking a huge LINQ statement like this in the code-behind for a LinqDataSource control just doesn't sit right with me. </p>
<p>It seems like I'm still coding queries into the user interface, only now it's LINQ instead of SQL. However, I feel that building another layer between the L2S classes and the UI would cut back on some of the flexibility of LINQ. Isn't the whole point to reduce the amount of code you write to fetch data?</p>
<p>Is there some possible middle ground I'm not seeing, or am I just misunderstanding the way LINQ to SQL is supposed to be used? Advice would be greatly appreciated.</p>
| [
{
"answer_id": 47383,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>Regardless of LINQ, I think that mixing presentation code with database-relaed code is not a good idea. I would create a simpl... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4160/"
] | Part of the web application I'm working on is an area displaying messages from management to 1...n users. I have a DataAccess project that contains the LINQ to SQL classes, and a website project that is the UI. My database looks like this:
User -> MessageDetail <- Message <- MessageCategory
MessageDetail is a join table that also contains an IsRead flag.
The list of messages is grouped by category. I have two nested ListView controls on the page -- One outputs the group name, while a second one nested inside that is bound to MessageDetails and outputs the messages themselves. In the code-behind for the page listing the messages I have the following code:
```
protected void MessageListDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
var db = new DataContext();
// parse the input strings from the web form
int categoryIDFilter;
DateTime dateFilter;
string catFilterString = MessagesCategoryFilter.SelectedValue;
string dateFilterString = MessagesDateFilter.SelectedValue;
// TryParse will return default values if parsing is unsuccessful (i.e. if "all" is selected"):
// DateTime.MinValue for dates, 0 for int
DateTime.TryParse(dateFilterString, out dateFilter);
Int32.TryParse(catFilterString, out categoryIDFilter);
bool showRead = MessagesReadFilter.Checked;
var messages =
from detail in db.MessageDetails
where detail.UserID == (int)Session["UserID"]
where detail.Message.IsPublished
where detail.Message.MessageCategoryID == categoryIDFilter || (categoryIDFilter == 0)
where dateFilter == detail.Message.PublishDate.Value.Date || (dateFilter == DateTime.MinValue)
// is unread, showRead filter is on, or message was marked read today
where detail.IsRead == false || showRead || detail.ReadDate.Value.Date == DateTime.Today
orderby detail.Message.PublishDate descending
group detail by detail.Message.MessageCategory into categories
orderby categories.Key.Name
select new
{
MessageCategory = categories.Key,
MessageDetails = categories.Select(d => d)
};
e.Result = messages;
}
```
This code *works*, but sticking a huge LINQ statement like this in the code-behind for a LinqDataSource control just doesn't sit right with me.
It seems like I'm still coding queries into the user interface, only now it's LINQ instead of SQL. However, I feel that building another layer between the L2S classes and the UI would cut back on some of the flexibility of LINQ. Isn't the whole point to reduce the amount of code you write to fetch data?
Is there some possible middle ground I'm not seeing, or am I just misunderstanding the way LINQ to SQL is supposed to be used? Advice would be greatly appreciated. | All your LINQ querys should be in a **business logic class**, no change from older methodologies like ADO.
If you are a **purist** you should always return List(of T) from your methods in the business class, in fact, the datacontext should only be visible to the business classes.
Then you can manipulate the list in the user interface.
If you are a **pragmatist**, you can return a IQueryable object and make some manipulations in the user interface. |
47,400 | <p>With the code, forms and data inside the same database I am wondering what are the best practices to design a suite of tests for a Microsoft Access application (say for Access 2007).</p>
<p>One of the main issues with testing forms is that only a few controls have a <code>hwnd</code> handle and other controls only get one they have focus, which makes automation quite opaque since you cant get a list of controls on a form to act on.</p>
<p>Any experience to share?</p>
| [
{
"answer_id": 47404,
"author": "Knox",
"author_id": 4873,
"author_profile": "https://Stackoverflow.com/users/4873",
"pm_score": 2,
"selected": false,
"text": "<p>I would design the application to have as much work as possible done in queries and in vba subroutines so that your testing c... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3811/"
] | With the code, forms and data inside the same database I am wondering what are the best practices to design a suite of tests for a Microsoft Access application (say for Access 2007).
One of the main issues with testing forms is that only a few controls have a `hwnd` handle and other controls only get one they have focus, which makes automation quite opaque since you cant get a list of controls on a form to act on.
Any experience to share? | 1. Write Testable Code
======================
First, stop writing business logic into your Form's code behind. That's not the place for it. It can't be properly tested there. In fact, you really shouldn't have to test your form itself at all. It should be a dead dumb simple view that responds to User Interaction and then delegates responsibility for responding to those actions to another class that ***is*** testable.
How do you do that? Familiarizing yourself with the [Model-View-Controller pattern](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) is a good start.

It can't be done *perfectly* in VBA due to the fact that we get either events or interfaces, never both, but you can get pretty close. Consider this simple form that has a text box and a button.

In the form's code behind, we'll wrap the TextBox's value in a public property and re-raise any events we're interested in.
```
Public Event OnSayHello()
Public Event AfterTextUpdate()
Public Property Let Text(value As String)
Me.TextBox1.value = value
End Property
Public Property Get Text() As String
Text = Me.TextBox1.value
End Property
Private Sub SayHello_Click()
RaiseEvent OnSayHello
End Sub
Private Sub TextBox1_AfterUpdate()
RaiseEvent AfterTextUpdate
End Sub
```
Now we need a model to work with. Here I've created a new class module named `MyModel`. Here lies the code we'll put under test. Note that it naturally shares a similar structure as our view.
```
Private mText As String
Public Property Let Text(value As String)
mText = value
End Property
Public Property Get Text() As String
Text = mText
End Property
Public Function Reversed() As String
Dim result As String
Dim length As Long
length = Len(mText)
Dim i As Long
For i = 0 To length - 1
result = result + Mid(mText, (length - i), 1)
Next i
Reversed = result
End Function
Public Sub SayHello()
MsgBox Reversed()
End Sub
```
Finally, our controller wires it all together. The controller listens for form events and communicates changes to the model and triggers the model's routines.
```
Private WithEvents view As Form_Form1
Private model As MyModel
Public Sub Run()
Set model = New MyModel
Set view = New Form_Form1
view.Visible = True
End Sub
Private Sub view_AfterTextUpdate()
model.Text = view.Text
End Sub
Private Sub view_OnSayHello()
model.SayHello
view.Text = model.Reversed()
End Sub
```
Now this code can be run from any other module. For the purposes of this example, I've used a standard module. I highly encourage you to build this yourself using the code I've provided and see it function.
```
Private controller As FormController
Public Sub Run()
Set controller = New FormController
controller.Run
End Sub
```
---
So, that's great and all ***but what does it have to do with testing?!*** Friend, it has ***everything*** to do with testing. What we've done is make our code *testable*. In the example I've provided, there is no reason what-so-ever to even try to test the GUI. The only thing we really need to test is the `model`. That's where all of the real logic is.
So, on to step two.
2. Choose a Unit Testing Framework
==================================
There aren't a lot of options here. Most frameworks require installing COM Add-ins, lots of boiler plate, weird syntax, writing tests as comments, etc. That's why I got involved in [building one myself](https://github.com/rubberduck-vba/Rubberduck), so this part of my answer isn't impartial, but I'll try to give a fair summary of what's available.
1. [AccUnit](http://accunit.access-codelib.net/)
* Works only in Access.
* Requires you to write tests as a strange hybrid of comments and code. (no intellisense for the comment part.
* There ***is*** a graphical interface to help you write those strange looking tests though.
* The project has not seen any updates since 2013.
2. [VB Lite Unit](http://vb-lite-unit.sourceforge.net/)
I can't say I've personally used it. It's out there, but hasn't seen an update since 2005.
3. [xlUnit](http://xlvbadevtools.codeplex.com/)
xlUnit isn't awful, but it's not good either. It's clunky and there's lots of boiler plate code. It's the best of the worst, but it doesn't work in Access. So, that's out.
4. Build your own framework
I've [been there and done that](https://codereview.stackexchange.com/questions/62781/unit-testing-in-vba). It's probably more than most people want to get into, but it is completely possible to build a Unit Testing framework in Native VBA code.
5. [Rubberduck VBE Add-In's Unit Testing Framework](https://github.com/rubberduck-vba/Rubberduck/wiki/Unit-Testing)
*Disclaimer: I'm one of the co-devs*.
I'm biased, but this is by far my favorite of the bunch.
* Little to no boiler plate code.
* Intellisense is available.
* The project is active.
* More documentation than most of these projects.
* It works in most of the major office applications, not just Access.
* It is, unfortunately, a COM Add-In, so it has to be installed onto your machine.
3. Start writing tests
======================
So, back to our code from section 1. The only code that we *really* needed to test was the `MyModel.Reversed()` function. So, let's take a look at what that test could look like. (Example given uses Rubberduck, but it's a simple test and could translate into the framework of your choice.)
```
'@TestModule
Private Assert As New Rubberduck.AssertClass
'@TestMethod
Public Sub ReversedReversesCorrectly()
Arrange:
Dim model As New MyModel
Const original As String = "Hello"
Const expected As String = "olleH"
Dim actual As String
model.Text = original
Act:
actual = model.Reversed
Assert:
Assert.AreEqual expected, actual
End Sub
```
Guidelines for Writing Good Tests
---------------------------------
1. Only test one thing at a time.
2. Good tests only fail when there is a bug introduced into the system or the requirements have changed.
3. Don't include external dependencies such as databases and file systems. These external dependencies can make tests fail for reasons outside of your control. Secondly, they slow your tests down. If your tests are slow, you won't run them.
4. Use test names that describe what the test is testing. Don't worry if it gets long. It's most important that it is descriptive.
---
I know that answer was a little long, and late, but hopefully it helps some people get started in writing unit tests for their VBA code. |
47,402 | <p>Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.</p>
<p>Example input and output:</p>
<pre><code>>>> reverse_words("this is a string")
'string a is this'
</code></pre>
<p>It should be O(N) time and O(1) space (<code>split()</code> and pushing on / popping off the stack are not allowed).</p>
<p>The puzzle is taken from <a href="http://halcyon.usc.edu/~kiran/msqs.html#programming" rel="noreferrer" title="Microsoft Interview Questions">here</a>.</p>
| [
{
"answer_id": 47416,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>In pseudo code:</p>\n\n<pre><code>reverse input string\nreverse each word (you will need to find word boundaries)\n</code></pr... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4279/"
] | Given an array of characters which forms a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.
Example input and output:
```
>>> reverse_words("this is a string")
'string a is this'
```
It should be O(N) time and O(1) space (`split()` and pushing on / popping off the stack are not allowed).
The puzzle is taken from [here](http://halcyon.usc.edu/~kiran/msqs.html#programming "Microsoft Interview Questions"). | A solution in C/C++:
```cpp
void swap(char* str, int i, int j){
char t = str[i];
str[i] = str[j];
str[j] = t;
}
void reverse_string(char* str, int length){
for(int i=0; i<length/2; i++){
swap(str, i, length-i-1);
}
}
void reverse_words(char* str){
int l = strlen(str);
//Reverse string
reverse_string(str,strlen(str));
int p=0;
//Find word boundaries and reverse word by word
for(int i=0; i<l; i++){
if(str[i] == ' '){
reverse_string(&str[p], i-p);
p=i+1;
}
}
//Finally reverse the last word.
reverse_string(&str[p], l-p);
}
```
This should be O(n) in time and O(1) in space.
Edit: Cleaned it up a bit.
The first pass over the string is obviously O(n/2) = O(n). The second pass is O(n + combined length of all words / 2) = O(n + n/2) = O(n), which makes this an O(n) algorithm. |
47,413 | <p>It's common to have a table where for example the the fields are account, value, and time. What's the best design pattern for retrieving the last value for each account? Unfortunately the last keyword in a grouping gives you the last physical record in the database, not the last record by any sorting. Which means IMHO it should never be used. The two clumsy approaches I use are either a subquery approach or a secondary query to determine the last record, and then joining to the table to find the value. Isn't there a more elegant approach?</p>
| [
{
"answer_id": 47431,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 2,
"selected": true,
"text": "<p>The subquery option sounds best to me, something like the following psuedo-sql. It may be possible/necessary to optimize it vi... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4873/"
] | It's common to have a table where for example the the fields are account, value, and time. What's the best design pattern for retrieving the last value for each account? Unfortunately the last keyword in a grouping gives you the last physical record in the database, not the last record by any sorting. Which means IMHO it should never be used. The two clumsy approaches I use are either a subquery approach or a secondary query to determine the last record, and then joining to the table to find the value. Isn't there a more elegant approach? | The subquery option sounds best to me, something like the following psuedo-sql. It may be possible/necessary to optimize it via a join, that will depend on the capabilities of the SQL engine.
```
select *
from table
where account+time in (select account+max(time)
from table
group by account
order by time)
``` |
47,433 | <p>Consider the following 2 queries:</p>
<pre><code>select tblA.a,tblA.b,tblA.c,tblA.d
from tblA
where tblA.a not in (select tblB.a from tblB)
select tblA.a,tblA.b,tblA.c,tblA.d
from tblA left outer join tblB
on tblA.a = tblB.a where tblB.a is null
</code></pre>
<p>Which will perform better? My assumption is that in general the join will be better except in cases where the subselect returns a very small result set.</p>
| [
{
"answer_id": 47439,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>From my observations, MSSQL server produces same query plan for these queries.</p>\n"
},
{
"answer_id": 47448,
"au... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292/"
] | Consider the following 2 queries:
```
select tblA.a,tblA.b,tblA.c,tblA.d
from tblA
where tblA.a not in (select tblB.a from tblB)
select tblA.a,tblA.b,tblA.c,tblA.d
from tblA left outer join tblB
on tblA.a = tblB.a where tblB.a is null
```
Which will perform better? My assumption is that in general the join will be better except in cases where the subselect returns a very small result set. | RDBMSs "rewrite" queries to optimize them, so it depends on system you're using, and I would guess they end up giving the same performance on most "good" databases.
I suggest picking the one that is clearer and easier to maintain, for my money, that's the first one. It's much easier to debug the subquery as it can be run independently to check for sanity. |
47,447 | <p>I am trying to create a horizontal menu with the elements represented by <code><span></code>'s. The menu itself (parent <code><div></code>) has a fixed width, but the elements number is always different.</p>
<p>I would like to have child <code><span></code>'s of the same width, independently of how many of them are there.</p>
<p>What I've done so far: added a <code>float: left;</code> style for every span and specified its percentage width (percents are more or less fine, as the server knows at the time of the page generation, how many menu items are there and could divide 100% by this number). This works, except for the case when we have a division remainder (like for 3 elements), in this case I have a one-pixel hole to the right of the parent <code><div></code>, and if I rounding the percents up, the last menu element is wrapped. I also don't really like style generation on the fly, but if there's no other solution, it's fine.</p>
<p>What else could I try?</p>
<p>It seems like this is a very common problem, however googling for "child elements of the same width" didn't help.</p>
| [
{
"answer_id": 47465,
"author": "Xian",
"author_id": 4642,
"author_profile": "https://Stackoverflow.com/users/4642",
"pm_score": 2,
"selected": false,
"text": "<p>If you have a fixed width container, then you are losing some of the effectiveness of a percentage width child span.</p>\n\n<... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3894/"
] | I am trying to create a horizontal menu with the elements represented by `<span>`'s. The menu itself (parent `<div>`) has a fixed width, but the elements number is always different.
I would like to have child `<span>`'s of the same width, independently of how many of them are there.
What I've done so far: added a `float: left;` style for every span and specified its percentage width (percents are more or less fine, as the server knows at the time of the page generation, how many menu items are there and could divide 100% by this number). This works, except for the case when we have a division remainder (like for 3 elements), in this case I have a one-pixel hole to the right of the parent `<div>`, and if I rounding the percents up, the last menu element is wrapped. I also don't really like style generation on the fly, but if there's no other solution, it's fine.
What else could I try?
It seems like this is a very common problem, however googling for "child elements of the same width" didn't help. | You might try a table with a fixed table layout. It should calculate the column widths without concerning itself with the cell contents.
```css
table.ClassName {
table-layout: fixed
}
``` |
47,475 | <p>If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names?</p>
<p>ie </p>
<pre><code>[Test]
public void ShouldValidateUserNameIsLessThan100Characters() {}
</code></pre>
<p>verse </p>
<pre><code>[Test]
public void UserNameTestValidation1() {}
</code></pre>
| [
{
"answer_id": 47477,
"author": "zappan",
"author_id": 4723,
"author_profile": "https://Stackoverflow.com/users/4723",
"pm_score": 1,
"selected": false,
"text": "<p>i wouldn't put conditions that test needs to meet in the name, because conditions may change in time. in your example, i'd ... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4642/"
] | If unit-test names can become outdated over time and if you consider that the test itself is the most important thing, then is it important to choose wise test names?
ie
```
[Test]
public void ShouldValidateUserNameIsLessThan100Characters() {}
```
verse
```
[Test]
public void UserNameTestValidation1() {}
``` | The name of any method should make it clear what it does.
IMO, your first suggestion is a bit long and the second one isn't informative enough. Also it's probably a bad idea to put "100" in the name, as that's very likely to change. What about:
```
public void validateUserNameLength()
```
If the test changes, the name should be updated accordingly. |
47,487 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/30170/avoiding-repeated-constants-in-css">Avoiding repeated constants in CSS</a> </p>
</blockquote>
<p>We have some "theme colors" that are reused in our CSS sheet.</p>
<p>Is there a way to set a variable and then reuse it?</p>
<p>E.g.</p>
<pre><code>.css
OurColor: Blue
H1 {
color:OurColor;
}
</code></pre>
| [
{
"answer_id": 47490,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>CSS doesn't offer any such thing. The only solution is to write a preprocessing script that is either run manually ... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4906/"
] | >
> **Possible Duplicate:**
>
> [Avoiding repeated constants in CSS](https://stackoverflow.com/questions/30170/avoiding-repeated-constants-in-css)
>
>
>
We have some "theme colors" that are reused in our CSS sheet.
Is there a way to set a variable and then reuse it?
E.g.
```
.css
OurColor: Blue
H1 {
color:OurColor;
}
``` | There's no requirement that all styles for a selector reside in a single rule, and a single rule can apply to multiple selectors... so *flip it around*:
```
/* Theme color: text */
H1, P, TABLE, UL
{ color: blue; }
/* Theme color: emphasis */
B, I, STRONG, EM
{ color: #00006F; }
/* ... */
/* Theme font: header */
H1, H2, H3, H4, H5, H6
{ font-family: Comic Sans MS; }
/* ... */
/* H1-specific styles */
H1
{
font-size: 2em;
margin-bottom: 1em;
}
```
This way, you avoid repeating styles that are *conceptually* the same, while also making it clear which parts of the document they affect.
Note the emphasis on "conceptually" in that last sentence... This just came up in the comments, so I'm gonna expand on it a bit, since I've seen people making this same mistake over and over again for years - predating even the existence of CSS: **two attributes sharing the same value does not necessarily mean they represent the same *concept***. The sky may appear red in the evening, and so do tomatoes - but the sky and the tomato are not red for the same reason, and their colors *will* vary over time independently. By the same token, just because you happen to have two elements in your stylesheet that are given the same color, or size or positioning does not mean they will *always* share these values. A naive designer who uses grouping (as described here) or a variable processor such as SASS or LESS to avoid *value* repetition risks making future changes to styling incredibly error-prone; always focus on the *contextual meaning* of styles when looking to reduce repetition, ignoring their *current values*. |
47,519 | <p>I have a fairly standards compliant XHTML+CSS site that looks great on all browsers on PC and Mac. The other day I saw it on FF3 on Linux and the letter spacing was slightly larger, throwing everything out of whack and causing unwanted wrapping and clipping of text. The CSS in question has</p>
<pre><code>font-size: 11px;
font-family: Arial, Helvetica, sans-serif;
</code></pre>
<p>I know it's going with the generic sans-serif, whatever that maps to. If I add the following, the text scrunches up enough to be close to what I get on the other platforms:</p>
<pre><code>letter-spacing: -1.5px;
</code></pre>
<p>but this would involve some nasty server-side OS sniffing. If there's a pure CSS solution to this I'd love to hear it.</p>
<p>The system in question is Ubuntu 7.04 but that is irrelevant as I'm looking to fix it for at least the majority of, if not all, Linux users. Of course asking the user to install a font is not an option!</p>
| [
{
"answer_id": 47523,
"author": "thekidder",
"author_id": 1631,
"author_profile": "https://Stackoverflow.com/users/1631",
"pm_score": 0,
"selected": false,
"text": "<p>I find the easiest way to solve font sizing problems between browsers is to simply leave room for error. Make divs sligh... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3206/"
] | I have a fairly standards compliant XHTML+CSS site that looks great on all browsers on PC and Mac. The other day I saw it on FF3 on Linux and the letter spacing was slightly larger, throwing everything out of whack and causing unwanted wrapping and clipping of text. The CSS in question has
```
font-size: 11px;
font-family: Arial, Helvetica, sans-serif;
```
I know it's going with the generic sans-serif, whatever that maps to. If I add the following, the text scrunches up enough to be close to what I get on the other platforms:
```
letter-spacing: -1.5px;
```
but this would involve some nasty server-side OS sniffing. If there's a pure CSS solution to this I'd love to hear it.
The system in question is Ubuntu 7.04 but that is irrelevant as I'm looking to fix it for at least the majority of, if not all, Linux users. Of course asking the user to install a font is not an option! | Sizing/spacing differences are usually difficult to catch. What you can do is create a Linux-specific CSS file that will contain these values adjusted for Linux, then do a simple JS-based detect to inject that CSS if the User agent is a Linux one.
This is probably not the cleanest approach, but it will work, and with the least intrusion into your otherwise clean HTML/CSS. |
47,521 | <p>Here is a sample code to retrieve data from a database using the yield keyword that I found in a few place while googling around :</p>
<pre><code>public IEnumerable<object> ExecuteSelect(string commandText)
{
using (IDbConnection connection = CreateConnection())
{
using (IDbCommand cmd = CreateCommand(commandText, connection))
{
connection.Open();
using (IDbDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
yield return reader["SomeField"];
}
}
connection.Close();
}
}
}
</code></pre>
<p>Am I correct in thinking that in this sample code, the connection would not be closed if we do not iterate over the whole datareader ? </p>
<p>Here is an example that would not close the connection, if I understand yield correctly..</p>
<pre><code>foreach(object obj in ExecuteSelect(commandText))
{
break;
}
</code></pre>
<p>For a db connection that might not be catastrophic, I suppose the GC would clean it up eventually, but what if instead of a connection it was a more critical resource?</p>
| [
{
"answer_id": 47529,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>Connection will be closed automatically since you're using it inside \"using\" block.</p>\n"
},
{
"answer_id": 47699,
... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4789/"
] | Here is a sample code to retrieve data from a database using the yield keyword that I found in a few place while googling around :
```
public IEnumerable<object> ExecuteSelect(string commandText)
{
using (IDbConnection connection = CreateConnection())
{
using (IDbCommand cmd = CreateCommand(commandText, connection))
{
connection.Open();
using (IDbDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
{
yield return reader["SomeField"];
}
}
connection.Close();
}
}
}
```
Am I correct in thinking that in this sample code, the connection would not be closed if we do not iterate over the whole datareader ?
Here is an example that would not close the connection, if I understand yield correctly..
```
foreach(object obj in ExecuteSelect(commandText))
{
break;
}
```
For a db connection that might not be catastrophic, I suppose the GC would clean it up eventually, but what if instead of a connection it was a more critical resource? | The Iterator that the compiler synthesises implements `IDisposable`, which `foreach` calls when the `foreach` loop is exited.
The Iterator's `Dispose()` method will clean up the `using` statements on early exit.
As long as you use the iterator in a `foreach` loop, `using()` block, or call the `Dispose()` method in some other way, the cleanup of the Iterator will happen. |
47,535 | <p>Updating an old ASP/Access site for a client - I need SQL to add a column to an existing table and set a default value. Doesn't work - any ideas?</p>
<p>This works fine</p>
<pre><code>ALTER TABLE documents ADD COLUMN membersOnly NUMBER
</code></pre>
<p>I want this to work:</p>
<pre><code>ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0
</code></pre>
<p>Have googled and seen instructions for default values work for other field types but I want to add number. Thanks!</p>
| [
{
"answer_id": 47552,
"author": "zappan",
"author_id": 4723,
"author_profile": "https://Stackoverflow.com/users/4723",
"pm_score": 4,
"selected": true,
"text": "<p>Tools -> Options -> Tables/Queries -> (At the bottom right:) Sql Server Compatible Syntax - turn option on for this... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137/"
] | Updating an old ASP/Access site for a client - I need SQL to add a column to an existing table and set a default value. Doesn't work - any ideas?
This works fine
```
ALTER TABLE documents ADD COLUMN membersOnly NUMBER
```
I want this to work:
```
ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0
```
Have googled and seen instructions for default values work for other field types but I want to add number. Thanks! | Tools -> Options -> Tables/Queries -> (At the bottom right:) Sql Server Compatible Syntax - turn option on for this database.
then you can execute your query:
```
ALTER TABLE documents ADD COLUMN membersOnly NUMBER DEFAULT 0
``` |
47,589 | <p>I'm dealing with a MySQL table that defines the JobName column as UNIQUE. If somebody tries to save a new Job to the database using a JobName that is already in the database, MySQL throws a warning.</p>
<p>I would like to be able to detect this warning, just like an error, in my PHP script and deal with it appropriately. Ideally I would like to know what kind of warning MySQL has thrown so that I can branch the code to handle it.</p>
<p>Is this possible? If not, is it because MySQL doesn't have this ability, PHP doesn't have this ability, or both?</p>
| [
{
"answer_id": 47597,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 2,
"selected": false,
"text": "<p>First, you should <a href=\"http://us.php.net/error_reporting\" rel=\"nofollow noreferrer\">turn warnings off</a> so tha... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2056/"
] | I'm dealing with a MySQL table that defines the JobName column as UNIQUE. If somebody tries to save a new Job to the database using a JobName that is already in the database, MySQL throws a warning.
I would like to be able to detect this warning, just like an error, in my PHP script and deal with it appropriately. Ideally I would like to know what kind of warning MySQL has thrown so that I can branch the code to handle it.
Is this possible? If not, is it because MySQL doesn't have this ability, PHP doesn't have this ability, or both? | For warnings to be "flagged" to PHP natively would require changes to the mysql/mysqli driver, which is obviously beyond the scope of this question. Instead you're going to have to basically check every query you make on the database for warnings:
```
$warningCountResult = mysql_query("SELECT @@warning_count");
if ($warningCountResult) {
$warningCount = mysql_fetch_row($warningCountResult );
if ($warningCount[0] > 0) {
//Have warnings
$warningDetailResult = mysql_query("SHOW WARNINGS");
if ($warningDetailResult ) {
while ($warning = mysql_fetch_assoc($warningDetailResult) {
//Process it
}
}
}//Else no warnings
}
```
Obviously this is going to be hideously expensive to apply en-mass, so you might need to carefully think about when and how warnings may arise (which may lead you to refactor to eliminate them).
For reference, [MySQL SHOW WARNINGS](http://dev.mysql.com/doc/refman/5.0/en/show-warnings.html)
Of course, you could dispense with the initial query for the `SELECT @@warning_count`, which would save you a query per execution, but I included it for pedantic completeness. |
47,591 | <p>Specifically, I am looking to use CA on properties of types other than </p>
<ul>
<li>integers and doubles</li>
<li>CGRect, CGPoint, CGSize, and CGAffineTransform structures</li>
<li>CATransform3D data structures</li>
<li>CGColor and CGImage references</li>
</ul>
<p>and in objects other than CALayers or NSViews</p>
| [
{
"answer_id": 48564,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Well, it seems I cannot do that. What I should be doing is [subclassing NSAnimation](<a href=\"https://developer.apple.com/l... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Specifically, I am looking to use CA on properties of types other than
* integers and doubles
* CGRect, CGPoint, CGSize, and CGAffineTransform structures
* CATransform3D data structures
* CGColor and CGImage references
and in objects other than CALayers or NSViews | If you can do the changes yourself and the class you use is custom, you might want to add a setProgress:(float) f method to your class and use CA to animate it, then modify the desired properties as needed as a function of f.
Just do a
```
[[someObject animator] setValue:[NSNumber numberWithFloat:1.0] forKeyPath:@"someCustomProperty.progress"];
```
or if the object doesn't have an animator, create the correct CAAnimation yourself. |
47,605 | <p>Assuming String a and b:</p>
<pre><code>a += b
a = a.concat(b)
</code></pre>
<p>Under the hood, are they the same thing?</p>
<p>Here is concat decompiled as reference. I'd like to be able to decompile the <code>+</code> operator as well to see what that does.</p>
<pre><code>public String concat(String s) {
int i = s.length();
if (i == 0) {
return this;
}
else {
char ac[] = new char[count + i];
getChars(0, count, ac, 0);
s.getChars(0, i, ac, count);
return new String(0, count + i, ac);
}
}
</code></pre>
| [
{
"answer_id": 47615,
"author": "Niyaz",
"author_id": 184,
"author_profile": "https://Stackoverflow.com/users/184",
"pm_score": 2,
"selected": false,
"text": "<p>The <strong>+ operator</strong> can work between a string and a string, char, integer, double or float data type value. It jus... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292/"
] | Assuming String a and b:
```
a += b
a = a.concat(b)
```
Under the hood, are they the same thing?
Here is concat decompiled as reference. I'd like to be able to decompile the `+` operator as well to see what that does.
```
public String concat(String s) {
int i = s.length();
if (i == 0) {
return this;
}
else {
char ac[] = new char[count + i];
getChars(0, count, ac, 0);
s.getChars(0, i, ac, count);
return new String(0, count + i, ac);
}
}
``` | No, not quite.
Firstly, there's a slight difference in semantics. If `a` is `null`, then `a.concat(b)` throws a `NullPointerException` but `a+=b` will treat the original value of `a` as if it were `null`. Furthermore, the `concat()` method only accepts `String` values while the `+` operator will silently convert the argument to a String (using the `toString()` method for objects). So the `concat()` method is more strict in what it accepts.
To look under the hood, write a simple class with `a += b;`
```
public class Concat {
String cat(String a, String b) {
a += b;
return a;
}
}
```
Now disassemble with `javap -c` (included in the Sun JDK). You should see a listing including:
```
java.lang.String cat(java.lang.String, java.lang.String);
Code:
0: new #2; //class java/lang/StringBuilder
3: dup
4: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V
7: aload_1
8: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
11: aload_2
12: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
15: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/ String;
18: astore_1
19: aload_1
20: areturn
```
So, `a += b` is the equivalent of
```
a = new StringBuilder()
.append(a)
.append(b)
.toString();
```
The `concat` method should be faster. However, with more strings the `StringBuilder` method wins, at least in terms of performance.
The source code of `String` and `StringBuilder` (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final `String`. In practice memory allocation is surprisingly fast.
**Update:** As Pawel Adamski notes, performance has changed in more recent HotSpot. `javac` still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing `System.identityHashCode` (not `String.hashCode`) shows the `StringBuffer` code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From [@lukaseder](https://twitter.com/lukaseder), [a list of HotSpot JVM intrinsics](https://gist.github.com/apangin/7a9b7062a4bd0cd41fcc). |
47,612 | <p>I've got a C# class with a <code>Dispose</code> function via <code>IDisposable</code>. It's intended to be used inside a <code>using</code> block so the expensive resource it handles can be released right away.</p>
<p>The problem is that a bug occurred when an exception was thrown before <code>Dispose</code> was called, and the programmer neglected to use <code>using</code> or <code>finally</code>.</p>
<p>In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use <code>using</code>.</p>
<p>Is there any way to for a <code>using</code> block to be automatically used in C#?</p>
<p>Many thanks.</p>
<p>UPDATE:</p>
<p>I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.</p>
<p>Here's the bug I found, reduced to the essentials...</p>
<pre><code>try
{
PleaseDisposeMe a = new PleaseDisposeMe();
throw new Exception();
a.Dispose();
}
catch (Exception ex)
{
Log(ex);
}
// This next call will throw a time-out exception unless the GC
// runs a.Dispose in time.
PleaseDisposeMe b = new PleaseDisposeMe();
</code></pre>
<p>Using <code>FXCop</code> is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?</p>
| [
{
"answer_id": 47617,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 2,
"selected": false,
"text": "<pre><code>~ClassName()\n{\n}\n</code></pre>\n\n<p>EDIT (bold):</p>\n\n<p>If will get called when the object is moved out... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3568/"
] | I've got a C# class with a `Dispose` function via `IDisposable`. It's intended to be used inside a `using` block so the expensive resource it handles can be released right away.
The problem is that a bug occurred when an exception was thrown before `Dispose` was called, and the programmer neglected to use `using` or `finally`.
In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use `using`.
Is there any way to for a `using` block to be automatically used in C#?
Many thanks.
UPDATE:
I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.
Here's the bug I found, reduced to the essentials...
```
try
{
PleaseDisposeMe a = new PleaseDisposeMe();
throw new Exception();
a.Dispose();
}
catch (Exception ex)
{
Log(ex);
}
// This next call will throw a time-out exception unless the GC
// runs a.Dispose in time.
PleaseDisposeMe b = new PleaseDisposeMe();
```
Using `FXCop` is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone? | Unfortunately there isn't any way to do this directly in the code. If this is an issue in house, there are various code analysis solutions that could catch these sort of problems. Have you looked into FxCop? I think that this will catch these situations and in all cases where IDisposable objects might be left hanging. If it is a component that people are using outside of your organization and you can't require FxCop, then documentation is really your only recourse :).
Edit: In the case of finalizers, this doesn't really guarantee when the finalization will happen. So this may be a solution for you but it depends on the situation. |
47,658 | <p>I am writing a coding standards document for a team of about 15 developers with a project load of between 10 and 15 projects a year. Amongst other sections (which I may post here as I get to them) I am writing a section on code formatting. So to start with, I think it is wise that, for whatever reason, we establish some basic, consistent code formatting/naming standards.</p>
<p>I've looked at roughly 10 projects written over the last 3 years from this team and I'm, obviously, finding a pretty wide range of styles. Contractors come in and out and at times, and sometimes even double the team size.</p>
<p>I am looking for a few suggestions for code formatting and naming standards that have really paid off ... but that can also really be justified. I think consistency and shared-patterns go a long way to making the code more maintainable ... but, are there other things I ought to consider when defining said standards?</p>
<ul>
<li><p>How do you lineup parenthesis? Do you follow the same parenthesis guidelines when dealing with classes, methods, try catch blocks, switch statements, if else blocks, etc.</p></li>
<li><p>Do you line up fields on a column? Do you notate/prefix private variables with an underscore? Do you follow any naming conventions to make it easier to find particulars in a file? How do you order the members of your class?</p></li>
</ul>
<p>What about suggestions for namespaces, packaging or source code folder/organization standards? I tend to start with something like:</p>
<pre><code><com|org|...>.<company>.<app>.<layer>.<function>.ClassName
</code></pre>
<p>I'm curious to see if there are other, more accepted, practices than what I am accustomed to -- before I venture off dictating these standards. Links to standards already published online would be great too -- even though I've done a bit of that already.</p>
| [
{
"answer_id": 47664,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 1,
"selected": false,
"text": "<p>It obviously varies depending on languages and technologies. By the look of your example name space I am going to guess java... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4910/"
] | I am writing a coding standards document for a team of about 15 developers with a project load of between 10 and 15 projects a year. Amongst other sections (which I may post here as I get to them) I am writing a section on code formatting. So to start with, I think it is wise that, for whatever reason, we establish some basic, consistent code formatting/naming standards.
I've looked at roughly 10 projects written over the last 3 years from this team and I'm, obviously, finding a pretty wide range of styles. Contractors come in and out and at times, and sometimes even double the team size.
I am looking for a few suggestions for code formatting and naming standards that have really paid off ... but that can also really be justified. I think consistency and shared-patterns go a long way to making the code more maintainable ... but, are there other things I ought to consider when defining said standards?
* How do you lineup parenthesis? Do you follow the same parenthesis guidelines when dealing with classes, methods, try catch blocks, switch statements, if else blocks, etc.
* Do you line up fields on a column? Do you notate/prefix private variables with an underscore? Do you follow any naming conventions to make it easier to find particulars in a file? How do you order the members of your class?
What about suggestions for namespaces, packaging or source code folder/organization standards? I tend to start with something like:
```
<com|org|...>.<company>.<app>.<layer>.<function>.ClassName
```
I'm curious to see if there are other, more accepted, practices than what I am accustomed to -- before I venture off dictating these standards. Links to standards already published online would be great too -- even though I've done a bit of that already. | First find a automated code-formatter that works with your language. Reason: Whatever the document says, people will inevitably break the rules. It's much easier to run code through a formatter than to nit-pick in a code review.
If you're using a language with an existing standard (e.g. Java, C#), it's easiest to use it, or at least start with it as a first draft. Sun put a lot of thought into their formatting rules; you might as well take advantage of it.
In any case, remember that much research has shown that varying things like brace position and whitespace use has no measurable effect on productivity or understandability or prevalence of bugs. Just having *any* standard is the key. |
47,683 | <p>We have a Java listener that reads text messages off of a queue in JBossMQ. If we have to reboot JBoss, the listener will not reconnect and start reading messages again. We just get messages in the listener's log file every 2 minutes saying it can't connect. Is there something we're not setting in our code or in JBossMQ? I'm new to JMS so any help will be greatly appreciated. Thanks.</p>
| [
{
"answer_id": 47963,
"author": "Todd",
"author_id": 3803,
"author_profile": "https://Stackoverflow.com/users/3803",
"pm_score": 4,
"selected": true,
"text": "<p>You should implement in your client code javax.jms.ExceptionListener. You will need a method called onException. When the cl... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47683",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3098/"
] | We have a Java listener that reads text messages off of a queue in JBossMQ. If we have to reboot JBoss, the listener will not reconnect and start reading messages again. We just get messages in the listener's log file every 2 minutes saying it can't connect. Is there something we're not setting in our code or in JBossMQ? I'm new to JMS so any help will be greatly appreciated. Thanks. | You should implement in your client code javax.jms.ExceptionListener. You will need a method called onException. When the client's connection is lost, you should get a JMSException, and this method will be called automatically. The only thing you have to look out for is if you are intentionally disconnecting from JBossMQ-- that will also throw an exception.
Some code might look like this:
```
public void onException (JMSException jsme)
{
if (!closeRequested)
{
this.disconnect();
this.establishConnection(connectionProps, queueName, uname, pword, clientID, messageSelector);
}
else
{
//Client requested close so do not try to reconnect
}
}
```
In your "establishConnection" code, you would then implement a `while(!initialized)` construct that contains a try/catch inside of it. Until you are sure you have connected and subscribed properly, stay inside the while loop catching all JMS/Naming/etc. exceptions.
We've used this method for years with JBossMQ and it works great. We have never had a problem with our JMS clients not reconnecting after bouncing JBossMQ or losing our network connection. |
47,701 | <p>I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? </p>
<p>Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :)</p>
| [
{
"answer_id": 47744,
"author": "Henk",
"author_id": 4613,
"author_profile": "https://Stackoverflow.com/users/4613",
"pm_score": 0,
"selected": false,
"text": "<p>What platform are you attempting this on? Most debuggers allow you to attach to a running process by using the process id.\nY... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process?
Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all :) | Yeah, gdb is good for lower level debugging.
You can change threads with the *thread* command.
e.g
```
(gdb) thr 2
[Switching to thread 2 (process 6159 thread 0x3f1b)]
(gdb) backtrace
....
```
You could also check out Python specific debuggers like [Winpdb](http://winpdb.org/about/), or [pydb](http://bashdb.sourceforge.net/pydb/). Both platform independent. |
47,752 | <p>Anyone have a quick method for de-duplicating a generic List in C#?</p>
| [
{
"answer_id": 47755,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 6,
"selected": false,
"text": "<p>Sort it, then check two and two next to each others, as the duplicates will clump together.</p>\n\n<p>Something lik... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] | Anyone have a quick method for de-duplicating a generic List in C#? | Perhaps you should consider using a [HashSet](http://msdn.microsoft.com/en-us/library/bb359438.aspx).
From the MSDN link:
```
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
HashSet<int> evenNumbers = new HashSet<int>();
HashSet<int> oddNumbers = new HashSet<int>();
for (int i = 0; i < 5; i++)
{
// Populate numbers with just even numbers.
evenNumbers.Add(i * 2);
// Populate oddNumbers with just odd numbers.
oddNumbers.Add((i * 2) + 1);
}
Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);
DisplaySet(evenNumbers);
Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count);
DisplaySet(oddNumbers);
// Create a new HashSet populated with even numbers.
HashSet<int> numbers = new HashSet<int>(evenNumbers);
Console.WriteLine("numbers UnionWith oddNumbers...");
numbers.UnionWith(oddNumbers);
Console.Write("numbers contains {0} elements: ", numbers.Count);
DisplaySet(numbers);
}
private static void DisplaySet(HashSet<int> set)
{
Console.Write("{");
foreach (int i in set)
{
Console.Write(" {0}", i);
}
Console.WriteLine(" }");
}
}
/* This example produces output similar to the following:
* evenNumbers contains 5 elements: { 0 2 4 6 8 }
* oddNumbers contains 5 elements: { 1 3 5 7 9 }
* numbers UnionWith oddNumbers...
* numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 }
*/
``` |
47,762 | <p>I have a webapp development problem that I've developed one solution for, but am trying to find other ideas that might get around some performance issues I'm seeing.</p>
<p>problem statement: </p>
<ul>
<li>a user enters several keywords/tokens</li>
<li>the application searches for matches to the tokens</li>
<li>need one result for each token
<ul>
<li>ie, if an entry has 3 tokens, i need the entry id 3 times</li>
</ul></li>
<li>rank the results
<ul>
<li>assign X points for token match</li>
<li>sort the entry ids based on points</li>
<li>if point values are the same, use date to sort results</li>
</ul></li>
</ul>
<p>What I want to be able to do, but have not figured out, is to send 1 query that returns something akin to the results of an in(), but returns a duplicate entry id for each token matches for each entry id checked.</p>
<p>Is there a better way to do this than what I'm doing, of using multiple, individual queries running one query per token? If so, what's the easiest way to implement those?</p>
<p><strong>edit</strong><br>
I've already tokenized the entries, so, for example, "see spot run" has an entry id of 1, and three tokens, 'see', 'spot', 'run', and those are in a separate token table, with entry ids relevant to them so the table might look like this:</p>
<pre><code>'see', 1
'spot', 1
'run', 1
'run', 2
'spot', 3
</code></pre>
| [
{
"answer_id": 47796,
"author": "Robin Barnes",
"author_id": 1349865,
"author_profile": "https://Stackoverflow.com/users/1349865",
"pm_score": 4,
"selected": true,
"text": "<p>you could achive this in one query using 'UNION ALL' in MySQL.</p>\n\n<p>Just loop through the tokens in PHP cre... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4418/"
] | I have a webapp development problem that I've developed one solution for, but am trying to find other ideas that might get around some performance issues I'm seeing.
problem statement:
* a user enters several keywords/tokens
* the application searches for matches to the tokens
* need one result for each token
+ ie, if an entry has 3 tokens, i need the entry id 3 times
* rank the results
+ assign X points for token match
+ sort the entry ids based on points
+ if point values are the same, use date to sort results
What I want to be able to do, but have not figured out, is to send 1 query that returns something akin to the results of an in(), but returns a duplicate entry id for each token matches for each entry id checked.
Is there a better way to do this than what I'm doing, of using multiple, individual queries running one query per token? If so, what's the easiest way to implement those?
**edit**
I've already tokenized the entries, so, for example, "see spot run" has an entry id of 1, and three tokens, 'see', 'spot', 'run', and those are in a separate token table, with entry ids relevant to them so the table might look like this:
```
'see', 1
'spot', 1
'run', 1
'run', 2
'spot', 3
``` | you could achive this in one query using 'UNION ALL' in MySQL.
Just loop through the tokens in PHP creating a UNION ALL for each token:
e.g if the tokens are 'x', 'y' and 'z' your query may look something like this
```
SELECT * FROM `entries`
WHERE token like "%x%" union all
SELECT * FROM `entries`
WHERE token like "%y%" union all
SELECT * FROM `entries`
WHERE token like "%z%" ORDER BY score ect...
```
The order clause should operate on the entire result set as one, which is what you need.
In terms of performance it won't be all that fast (I'm guessing), however with databases the main overhead in terms of speed is often sending the query to the database engine from PHP and receiving the results. With this technique this only happens once instead of once per token, so performance will increase, I just don't know if it'll be enough. |
47,780 | <p>I have an inherited project that uses a build script (not make) to build and link the project with various libraries.</p>
<p>When it performs a build I would like to parse the build output to determine what and where the actual static libraries being linked into the final executable are and where are they coming from.</p>
<p>The script is compiling and linking with GNU tools.</p>
| [
{
"answer_id": 47805,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 0,
"selected": false,
"text": "<p>Static libraries, that makes life more difficult in this regard. In case of dynamic libraries you could just have ... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] | I have an inherited project that uses a build script (not make) to build and link the project with various libraries.
When it performs a build I would like to parse the build output to determine what and where the actual static libraries being linked into the final executable are and where are they coming from.
The script is compiling and linking with GNU tools. | You might try using the `nm` tool. Given the right options, it will look at a binary (archive or linked image) and tell you what objects were linked into it.
Actually, here's a one-liner I use at work:
```
#!/bin/sh
nm -Ag $* | sed 's/^.*\/\(.*\.a\):/\1/' | sort -k 3 | grep -v ' U '
```
to find the culprits for undefined symbols. Just chop off the last grep expression and it should pretty much give you what you want. |
47,786 | <p>Simple one really. In SQL, if I want to search a text field for a couple of characters, I can do:</p>
<pre><code>SELECT blah FROM blah WHERE blah LIKE '%text%'
</code></pre>
<p>The documentation for App Engine makes no mention of how to achieve this, but surely it's a common enough problem?</p>
| [
{
"answer_id": 47811,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 7,
"selected": true,
"text": "<p>BigTable, which is the database back end for App Engine, will scale to millions of records. Due to this, App Engine will... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366/"
] | Simple one really. In SQL, if I want to search a text field for a couple of characters, I can do:
```
SELECT blah FROM blah WHERE blah LIKE '%text%'
```
The documentation for App Engine makes no mention of how to achieve this, but surely it's a common enough problem? | BigTable, which is the database back end for App Engine, will scale to millions of records. Due to this, App Engine will not allow you to do any query that will result in a table scan, as performance would be dreadful for a well populated table.
In other words, every query must use an index. This is why you can only do `=`, `>` and `<` queries. (In fact you can also do `!=` but the API does this using a a combination of `>` and `<` queries.) This is also why the development environment monitors all the queries you do and automatically adds any missing indexes to your `index.yaml` file.
There is no way to index for a `LIKE` query so it's simply not available.
Have a watch of [this Google IO session](http://sites.google.com/site/io/under-the-covers-of-the-google-app-engine-datastore) for a much better and more detailed explanation of this. |
47,789 | <p>When should you use generator expressions and when should you use list comprehensions in Python?</p>
<pre><code># Generator expression
(x*2 for x in range(256))
# List comprehension
[x*2 for x in range(256)]
</code></pre>
| [
{
"answer_id": 47792,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 7,
"selected": false,
"text": "<p>Use list comprehensions when the result needs to be iterated over multiple times, or where speed is paramount. Use g... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | When should you use generator expressions and when should you use list comprehensions in Python?
```
# Generator expression
(x*2 for x in range(256))
# List comprehension
[x*2 for x in range(256)]
``` | [John's answer](https://stackoverflow.com/a/47792/4518341) is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work:
```
def gen():
return (something for something in get_some_stuff())
print gen()[:2] # generators don't support indexing or slicing
print [5,6] + gen() # generators can't be added to lists
```
Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension.
Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code. |
47,801 | <p>I am trying to create a web application using Pylons and the resources on the web point to the <a href="http://pylonsbook.com/alpha1/authentication_and_authorization" rel="noreferrer">PylonsBook</a> page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?</p>
<p>I tried downloading the <a href="http://pypi.python.org/pypi/SimpleSiteTemplate/" rel="noreferrer">SimpleSiteTemplate</a> from the cheeseshop but wasn't able to run the setup-app command. It throws up an error:</p>
<pre><code> File "/home/cnu/env/lib/python2.5/site-packages/SQLAlchemy-0.4.7-py2.5.egg/sqlalchemy/schema.py", line 96, in __call__
table = metadata.tables[key]
AttributeError: 'module' object has no attribute 'tables'
</code></pre>
<p>I use Pylons 0.9.7rc1, SQLAlchemy 0.4.7, Authkit 0.4.</p>
| [
{
"answer_id": 52136,
"author": "elarson",
"author_id": 5434,
"author_profile": "https://Stackoverflow.com/users/5434",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think AuthKit is actively maintained anymore. It does use the Paste (<a href=\"http://pythonpaste.org\" rel=\"nofo... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | I am trying to create a web application using Pylons and the resources on the web point to the [PylonsBook](http://pylonsbook.com/alpha1/authentication_and_authorization) page which isn't of much help. I want authentication and authorisation and is there anyway to setup Authkit to work easily with Pylons?
I tried downloading the [SimpleSiteTemplate](http://pypi.python.org/pypi/SimpleSiteTemplate/) from the cheeseshop but wasn't able to run the setup-app command. It throws up an error:
```
File "/home/cnu/env/lib/python2.5/site-packages/SQLAlchemy-0.4.7-py2.5.egg/sqlalchemy/schema.py", line 96, in __call__
table = metadata.tables[key]
AttributeError: 'module' object has no attribute 'tables'
```
I use Pylons 0.9.7rc1, SQLAlchemy 0.4.7, Authkit 0.4. | Ok, another update on the subject. It seems that the cheeseshop template is broken. I've followed the chapter you linked in the post and it seems that authkit is working fine. There are some caveats:
1. sqlalchemy has to be in 0.5 version
2. authkit has to be the dev version from svn (easy\_install authkit==dev)
I managed to get it working fine. |
47,824 | <p>Using core jQuery, how do you remove all the options of a select box, then add one option and select it?</p>
<p>My select box is the following.</p>
<pre><code><Select id="mySelect" size="9"> </Select>
</code></pre>
<p>EDIT: The following code was helpful with chaining. However, (in Internet Explorer) <code>.val('whatever')</code> did not select the option that was added. (I did use the same 'value' in both <code>.append</code> and <code>.val</code>.)</p>
<pre><code>$('#mySelect').find('option').remove().end()
.append('<option value="whatever">text</option>').val('whatever');
</code></pre>
<p>EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. <code>.focus()</code> was closer, but the option did not appear selected like it does with <code>.selected= "true"</code>. Nothing is wrong with my existing code - I am just trying to learn jQuery.</p>
<pre><code>var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";
</code></pre>
<p>EDIT: selected answer was close to what I needed. This worked for me:</p>
<pre><code>$('#mySelect').children().remove().end()
.append('<option selected value="whatever">text</option>') ;
</code></pre>
<p>But both answers led me to my final solution..</p>
| [
{
"answer_id": 47829,
"author": "Matt",
"author_id": 2338,
"author_profile": "https://Stackoverflow.com/users/2338",
"pm_score": 12,
"selected": true,
"text": "<pre><code>$('#mySelect')\n .find('option')\n .remove()\n .end()\n .append('<option value=\"whatever\">text<... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] | Using core jQuery, how do you remove all the options of a select box, then add one option and select it?
My select box is the following.
```
<Select id="mySelect" size="9"> </Select>
```
EDIT: The following code was helpful with chaining. However, (in Internet Explorer) `.val('whatever')` did not select the option that was added. (I did use the same 'value' in both `.append` and `.val`.)
```
$('#mySelect').find('option').remove().end()
.append('<option value="whatever">text</option>').val('whatever');
```
EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. `.focus()` was closer, but the option did not appear selected like it does with `.selected= "true"`. Nothing is wrong with my existing code - I am just trying to learn jQuery.
```
var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";
```
EDIT: selected answer was close to what I needed. This worked for me:
```
$('#mySelect').children().remove().end()
.append('<option selected value="whatever">text</option>') ;
```
But both answers led me to my final solution.. | ```
$('#mySelect')
.find('option')
.remove()
.end()
.append('<option value="whatever">text</option>')
.val('whatever')
;
``` |
47,833 | <p>I know you can look at the row.count or tables.count, but are there other ways to tell if a dataset is empty?</p>
| [
{
"answer_id": 47839,
"author": "Joe Ratzer",
"author_id": 4092,
"author_profile": "https://Stackoverflow.com/users/4092",
"pm_score": 3,
"selected": false,
"text": "<p>What's wrong with</p>\n\n<p>(aDataSet.Tables.Count == 0)</p>\n\n<p>?</p>\n"
},
{
"answer_id": 47840,
"autho... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445815/"
] | I know you can look at the row.count or tables.count, but are there other ways to tell if a dataset is empty? | I would suggest something like:-
```
bool nonEmptyDataSet = dataSet != null &&
(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any();
```
**Edits:** I have significantly cleaned up the code after due consideration, I think this is much cleaner. Many thanks to Keith for the inspiration regarding the use of .Any().
In line with Keith's suggestion, here is an extension method version of this approach:-
```
public static class ExtensionMethods {
public static bool IsEmpty(this DataSet dataSet) {
return dataSet == null ||
!(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any();
}
}
```
Note, as Keith rightly corrected me on in the comments of his post, this method will work even when the data set is null. |
47,837 | <p>I'm struggling to find the right terminology here, but if you have jQuery object...</p>
<pre><code>$('#MyObject')
</code></pre>
<p>...is it possible to extract the base element? Meaning, the equivalent of this:</p>
<pre><code>document.getElementById('MyObject')
</code></pre>
| [
{
"answer_id": 47844,
"author": "VolkerK",
"author_id": 4833,
"author_profile": "https://Stackoverflow.com/users/4833",
"pm_score": 7,
"selected": true,
"text": "<p>Yes, use <code>.get(index)</code>. According to the <a href=\"https://api.jquery.com/get/#get1\" rel=\"nofollow noreferrer... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1923/"
] | I'm struggling to find the right terminology here, but if you have jQuery object...
```
$('#MyObject')
```
...is it possible to extract the base element? Meaning, the equivalent of this:
```
document.getElementById('MyObject')
``` | Yes, use `.get(index)`. According to the [documentation](https://api.jquery.com/get/#get1):
>
> The `.get()` method grants access to the DOM nodes underlying each jQuery object.
>
>
> |
47,849 | <p>I'm trying to refer to a drive whose letter may change. I'd like to refer to it by its label (e.g., MyLabel (v:) within a Batch File. It can be referred to by V:\ . I'd like to refer to it by MyLabel.</p>
<p>(This was posted on Experts Echange for a month with no answer. Let's see how fast SO answers it )</p>
| [
{
"answer_id": 47856,
"author": "VolkerK",
"author_id": 4833,
"author_profile": "https://Stackoverflow.com/users/4833",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the WMI query language for that.\nTake a look at <a href=\"http://msdn.microsoft.com/en-us/library/aa394592(VS... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4906/"
] | I'm trying to refer to a drive whose letter may change. I'd like to refer to it by its label (e.g., MyLabel (v:) within a Batch File. It can be referred to by V:\ . I'd like to refer to it by MyLabel.
(This was posted on Experts Echange for a month with no answer. Let's see how fast SO answers it ) | This bat file will give you the drive letter from a drive label:
```
Option Explicit
Dim num, args, objWMIService, objItem, colItems
set args = WScript.Arguments
num = args.Count
if num <> 1 then
WScript.Echo "Usage: CScript DriveFromLabel.vbs <label>"
WScript.Quit 1
end if
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk")
For Each objItem in colItems
If strcomp(objItem.VolumeName, args.Item(0), 1) = 0 Then
Wscript.Echo objItem.Name
End If
Next
WScript.Quit 0
```
Run it as:
```
cscript /nologo DriveFromLabel.vbs label
``` |
47,862 | <p>I'm loading a <strong><em>SQL Server 2000</em></strong> database into my new <strong><em>SQL Server 2005</em></strong> <strong><em>instance</em></strong>. <strong><em>As expected, the full-text catalogs don't come with it.</strong> <strong>How can I rebuild them?</em></strong></p>
<p>Right-clicking my full text catalogs and hitting "<strong><em>rebuild indexes</em></strong>" just hangs for hours and hours without doing anything, so it doesn't appear to be that simple...</p>
| [
{
"answer_id": 47900,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": true,
"text": "<p>Try it using SQL.</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms189520%28SQL.90%29.aspx\" rel=... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2590/"
] | I'm loading a ***SQL Server 2000*** database into my new ***SQL Server 2005*** ***instance***. ***As expected, the full-text catalogs don't come with it.*** **How can I rebuild them?**
Right-clicking my full text catalogs and hitting "***rebuild indexes***" just hangs for hours and hours without doing anything, so it doesn't appear to be that simple... | Try it using SQL.
* [CREATE FULLTEXT CATALOG](http://msdn.microsoft.com/en-us/library/ms189520%28SQL.90%29.aspx)
* [ALTER FULLTEXT CATALOG](http://msdn.microsoft.com/en-us/library/ms176095%28SQL.90%29.aspx)
Here's an example from Microsoft.
```
--Change to accent insensitive
USE AdventureWorks;
GO
ALTER FULLTEXT CATALOG ftCatalog
REBUILD WITH ACCENT_SENSITIVITY=OFF;
GO
-- Check Accentsensitivity
SELECT FULLTEXTCATALOGPROPERTY('ftCatalog', 'accentsensitivity');
GO
--Returned 0, which means the catalog is not accent sensitive.
``` |
47,864 | <p>ValidateEvents is a great ASP.net function, but the Yellow Screen of Death is not so nice. I found a way how to handle the HttpRequestValidationException gracefully <a href="http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html" rel="nofollow noreferrer">here</a>, but that does not work with ASP.net AJAX properly.</p>
<p>Basically, I got an UpdatePanel with a TextBox and a Button, and when the user types in HTML into the Textbox, a JavaScript Popup with a Error message saying not to modify the Response pops up.</p>
<p>So I wonder what is the best way to handle HttpRequestValidationException gracefully? For "normal" requests I would like to just display an error message, but when it's an AJAX Request i'd like to throw the request away and return something to indicate an error, so that my frontend page can react on it?</p>
| [
{
"answer_id": 48831,
"author": "Sara Chipps",
"author_id": 4140,
"author_profile": "https://Stackoverflow.com/users/4140",
"pm_score": 0,
"selected": false,
"text": "<p>hmmmm, it seems you would need to find some sort of JavaScript to check for html input or a client side validator. </p... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | ValidateEvents is a great ASP.net function, but the Yellow Screen of Death is not so nice. I found a way how to handle the HttpRequestValidationException gracefully [here](http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html), but that does not work with ASP.net AJAX properly.
Basically, I got an UpdatePanel with a TextBox and a Button, and when the user types in HTML into the Textbox, a JavaScript Popup with a Error message saying not to modify the Response pops up.
So I wonder what is the best way to handle HttpRequestValidationException gracefully? For "normal" requests I would like to just display an error message, but when it's an AJAX Request i'd like to throw the request away and return something to indicate an error, so that my frontend page can react on it? | Found it and [blogged about it](http://www.stum.de/2008/09/08/gracefully-handling-httprequestvalidationexception-with-aspnet-ajax/). Basically, the EndRequestHandler and the args.set\_errorHandled are our friends here.
```
<script type="text/javascript" language="javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
if (args.get_error() != undefined)
{
var errorMessage;
if (args.get_response().get_statusCode() == '200')
{
errorMessage = args.get_error().message;
}
else
{
// Error occurred somewhere other than the server page.
errorMessage = 'An unspecified error occurred. ';
}
args.set_errorHandled(true);
$get('<%= this.newsletterLabel.ClientID %>').innerHTML = errorMessage;
}
}
</script>
``` |
47,882 | <p>What is a magic number?</p>
<p>Why should it be avoided?</p>
<p>Are there cases where it's appropriate?</p>
| [
{
"answer_id": 47885,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 4,
"selected": false,
"text": "<p>A magic number is a sequence of characters at the start of a file format, or protocol exchange. This number serves... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
] | What is a magic number?
Why should it be avoided?
Are there cases where it's appropriate? | A magic number is a direct usage of a number in the code.
For example, if you have (in Java):
```java
public class Foo {
public void setPassword(String password) {
// don't do this
if (password.length() > 7) {
throw new InvalidArgumentException("password");
}
}
}
```
This should be refactored to:
```java
public class Foo {
public static final int MAX_PASSWORD_SIZE = 7;
public void setPassword(String password) {
if (password.length() > MAX_PASSWORD_SIZE) {
throw new InvalidArgumentException("password");
}
}
}
```
It improves readability of the code and it's easier to maintain. Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies.
The JDK is full of examples like in `Integer`, `Character` and `Math` classes.
PS: Static analysis tools like FindBugs and PMD detects the use of magic numbers in your code and suggests the refactoring. |
47,883 | <p>I'm trying to install 'quadrupel', a library that relies on ffmpeg on Solaris x86.</p>
<p>I managed to build ffmpeg and its libraries live in /opt/gnu/lib and the includes are in /opt/gnu/include but when I try to build quadrupel, it can't find the ffmpeg headers.</p>
<p>What flags/configuration is required to include those two directories in the proper search paths for libraries and includes? I'm not much of a Makefile hacker.</p>
| [
{
"answer_id": 47913,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 2,
"selected": true,
"text": "<p>You can override the path by setting the environmental variable LD_LIBRARY_PATH. However I would suggest changing the system ... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/555/"
] | I'm trying to install 'quadrupel', a library that relies on ffmpeg on Solaris x86.
I managed to build ffmpeg and its libraries live in /opt/gnu/lib and the includes are in /opt/gnu/include but when I try to build quadrupel, it can't find the ffmpeg headers.
What flags/configuration is required to include those two directories in the proper search paths for libraries and includes? I'm not much of a Makefile hacker. | You can override the path by setting the environmental variable LD\_LIBRARY\_PATH. However I would suggest changing the system paths as well so you don't have to change the library path for all users. This can be done using crel.
```
crle -l -c /var/ld/ld.config -l /usr/lib:/usr/local/lib:/opt/gnu/lib
```
For the includes just add -I/opt/gnu/include to your CFLAGS variable. |
47,919 | <p>I'm used to doing all my coding in one C file. However, I'm working on a project large enough that it becomes impractical to do so. I've been #including them together but I've run into cases where I'm #including some files multiple times, etc. I've heard of .h files, but I'm not sure what their function is (or why having 2 files is better than 1).</p>
<p>What strategies should I use for organizing my code? Is it possible to separate "public" functions from "private" ones for a particular file?</p>
<p><a href="https://stackoverflow.com/questions/47878/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data">This</a> question precipitated my inquiry. The tea.h file makes no reference to the tea.c file. Does the compiler "know" that every .h file has a corresponding .c file?</p>
| [
{
"answer_id": 47928,
"author": "Andrew",
"author_id": 826,
"author_profile": "https://Stackoverflow.com/users/826",
"pm_score": 3,
"selected": false,
"text": "<p>Try to make each .c focus on a particular area of functionality. Use the corresponding .h file to declare those functions.</p... | 2008/09/06 | [
"https://Stackoverflow.com/questions/47919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
] | I'm used to doing all my coding in one C file. However, I'm working on a project large enough that it becomes impractical to do so. I've been #including them together but I've run into cases where I'm #including some files multiple times, etc. I've heard of .h files, but I'm not sure what their function is (or why having 2 files is better than 1).
What strategies should I use for organizing my code? Is it possible to separate "public" functions from "private" ones for a particular file?
[This](https://stackoverflow.com/questions/47878/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data) question precipitated my inquiry. The tea.h file makes no reference to the tea.c file. Does the compiler "know" that every .h file has a corresponding .c file? | You should regard .h files as **interface files** of your .c file. Every .c file represents a module with a certain amount of functionality. If functions in a .c file are used by other modules (i.e. other .c files) put the function prototype in the .h interface file. By including the interface file in your original modules .c file and every other .c file you need the function in, you make this function available to other modules.
If you only need a function in a certain .c file (not in any other module), declare its scope static. This means it can only be called from within the c file it is defined in.
Same goes for variables that are used across multiple modules. They should go in the header file and there they have to marked with the keyword 'extern'. Note: For functions the keyword 'extern' is optional. Functions are always considered 'extern'.
The inclusion guards in header files help to not include the same header file multiple times.
For example:
Module1.c:
```
#include "Module1.h"
static void MyLocalFunction(void);
static unsigned int MyLocalVariable;
unsigned int MyExternVariable;
void MyExternFunction(void)
{
MyLocalVariable = 1u;
/* Do something */
MyLocalFunction();
}
static void MyLocalFunction(void)
{
/* Do something */
MyExternVariable = 2u;
}
```
Module1.h:
```
#ifndef __MODULE1.H
#define __MODULE1.H
extern unsigned int MyExternVariable;
void MyExternFunction(void);
#endif
```
Module2.c
```
#include "Module.1.h"
static void MyLocalFunction(void);
static void MyLocalFunction(void)
{
MyExternVariable = 1u;
MyExternFunction();
}
``` |
47,975 | <p>More out of interest than anything else, but can you compile a DirectX app under linux?</p>
<p>Obviously there's no official SDK, but I was thinking it might be possible with wine.</p>
<p>Presumably wine has an implementation of the DirectX interface in order to run games? Is it possible to link against that? (edit: This is called winelib)</p>
<p>Failing that, maybe a mingw cross compiler with the app running under wine.</p>
<p>Half answered my own question here, but wondered if anyone had heard of anything like this being done?</p>
| [
{
"answer_id": 47978,
"author": "Nicholas",
"author_id": 2658,
"author_profile": "https://Stackoverflow.com/users/2658",
"pm_score": 0,
"selected": false,
"text": "<p>There is currently no way to compile DirectX code to directly target Linux. You would build your application like you nor... | 2008/09/07 | [
"https://Stackoverflow.com/questions/47975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4949/"
] | More out of interest than anything else, but can you compile a DirectX app under linux?
Obviously there's no official SDK, but I was thinking it might be possible with wine.
Presumably wine has an implementation of the DirectX interface in order to run games? Is it possible to link against that? (edit: This is called winelib)
Failing that, maybe a mingw cross compiler with the app running under wine.
Half answered my own question here, but wondered if anyone had heard of anything like this being done? | I've had some luck with this. I've managed to compile [this simple Direct3D example](http://www.directxtutorial.com/Tutorial9/B-Direct3DBasics/dx9B5.aspx).
I used winelib for this (wine-dev package on Ubuntu). Thanks to [alastair](https://stackoverflow.com/users/9554/alastair) for pointing me to winelib.
I modified the source slightly to convert the wchars to chars (1 on line 52, 2 on line 55, by removing the L before the string literals). There may be a way around this, but this got it up and running.
I then compiled the source with the following:
```
wineg++ -ld3d9 -ld3dx9 triangle.cpp
```
This generates an a.out.exe.so binary, as well as an a.out script to run it under wine. |
47,981 | <p>How do I set, clear, and toggle a bit?</p>
| [
{
"answer_id": 47990,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 13,
"selected": true,
"text": "<h1>Setting a bit</h1>\n<p>Use the bitwise OR operator (<code>|</code>) to set a bit.</p>\n<pre><code>number |= 1UL <<... | 2008/09/07 | [
"https://Stackoverflow.com/questions/47981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] | How do I set, clear, and toggle a bit? | Setting a bit
=============
Use the bitwise OR operator (`|`) to set a bit.
```
number |= 1UL << n;
```
That will set the `n`th bit of `number`. `n` should be zero, if you want to set the `1`st bit and so on upto `n-1`, if you want to set the `n`th bit.
Use `1ULL` if `number` is wider than `unsigned long`; promotion of `1UL << n` doesn't happen until after evaluating `1UL << n` where it's undefined behaviour to shift by more than the width of a `long`. The same applies to all the rest of the examples.
Clearing a bit
==============
Use the bitwise AND operator (`&`) to clear a bit.
```
number &= ~(1UL << n);
```
That will clear the `n`th bit of `number`. You must invert the bit string with the bitwise NOT operator (`~`), then AND it.
Toggling a bit
==============
The XOR operator (`^`) can be used to toggle a bit.
```
number ^= 1UL << n;
```
That will toggle the `n`th bit of `number`.
Checking a bit
==============
You didn't ask for this, but I might as well add it.
To check a bit, shift the number n to the right, then bitwise AND it:
```
bit = (number >> n) & 1U;
```
That will put the value of the `n`th bit of `number` into the variable `bit`.
Changing the *n*th bit to *x*
=============================
Setting the `n`th bit to either `1` or `0` can be achieved with the following on a 2's complement C++ implementation:
```
number ^= (-x ^ number) & (1UL << n);
```
Bit `n` will be set if `x` is `1`, and cleared if `x` is `0`. If `x` has some other value, you get garbage. `x = !!x` will booleanize it to 0 or 1.
To make this independent of 2's complement negation behaviour (where `-1` has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation.
```
number ^= (-(unsigned long)x ^ number) & (1UL << n);
```
or
```
unsigned long newbit = !!x; // Also booleanize to force 0 or 1
number ^= (-newbit ^ number) & (1UL << n);
```
It's generally a good idea to use unsigned types for portable bit manipulation.
or
```
number = (number & ~(1UL << n)) | (x << n);
```
`(number & ~(1UL << n))` will clear the `n`th bit and `(x << n)` will set the `n`th bit to `x`.
It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like [the community wiki answer further down](https://stackoverflow.com/a/263738/52074)) or some sort of encapsulation. |
48,009 | <p>What are the performance, security, or "other" implications of using the following form to declare a new class instance in PHP</p>
<pre><code><?php
$class_name = 'SomeClassName';
$object = new $class_name;
?>
</code></pre>
<p>This is a contrived example, but I've seen this form used in Factories (OOP) to avoid having a big if/switch statement.</p>
<p>Problems that come immediately to mind are </p>
<ol>
<li><s>You lose the ability to pass arguments into a constructor</s> (LIES. Thanks Jeremy)</li>
<li>Smells like eval(), with all the security concerns it brings to the table (but not necessarily the performance concerns?)</li>
</ol>
<p>What other implications are there, or what search engine terms other than "Rank PHP Hackery" can someone use to research this?</p>
| [
{
"answer_id": 48035,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "<p>It looks you can still pass arguments to the constructor, here's my test code:</p>\n\n<pre><code><?php\n\nclass Test ... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4668/"
] | What are the performance, security, or "other" implications of using the following form to declare a new class instance in PHP
```
<?php
$class_name = 'SomeClassName';
$object = new $class_name;
?>
```
This is a contrived example, but I've seen this form used in Factories (OOP) to avoid having a big if/switch statement.
Problems that come immediately to mind are
1. ~~You lose the ability to pass arguments into a constructor~~ (LIES. Thanks Jeremy)
2. Smells like eval(), with all the security concerns it brings to the table (but not necessarily the performance concerns?)
What other implications are there, or what search engine terms other than "Rank PHP Hackery" can someone use to research this? | One of the issues with the resolving at run time is that you make it really hard for the opcode caches (like APC). Still, for now, doing something like you describe in your question is a valid way if you need a certain amount of indirection when instanciating stuff.
As long as you don't do something like
```
$classname = 'SomeClassName';
for ($x = 0; $x < 100000; $x++){
$object = new $classname;
}
```
you are probably fine :-)
(my point being: Dynamically looking up a class here and then doesn't hurt. If you do it often, it will).
Also, be sure that $classname can never be set from the outside - you'd want to have some control over what exact class you will be instantiating. |
48,053 | <p>I read somewhere once that the modulus operator is inefficient on small embedded devices like 8 bit micro-controllers that do not have integer division instruction. Perhaps someone can confirm this but I thought the difference is 5-10 time slower than with an integer division operation.</p>
<p>Is there another way to do this other than keeping a counter variable and manually overflowing to 0 at the mod point?<p></p>
<pre><code>const int FIZZ = 6;
for(int x = 0; x < MAXCOUNT; x++)
{
if(!(x % FIZZ)) print("Fizz\n"); // slow on some systems
}
</code></pre>
<p>vs:</p>
<p>The way I am currently doing it:</p>
<pre><code>const int FIZZ = 6;
int fizzcount = 1;
for(int x = 1; x < MAXCOUNT; x++)
{
if(fizzcount >= FIZZ)
{
print("Fizz\n");
fizzcount = 0;
}
}
</code></pre>
| [
{
"answer_id": 48058,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 1,
"selected": false,
"text": "<p>In the embedded world, the \"modulus\" operations you need to do are often the ones that break down nicely into bit o... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] | I read somewhere once that the modulus operator is inefficient on small embedded devices like 8 bit micro-controllers that do not have integer division instruction. Perhaps someone can confirm this but I thought the difference is 5-10 time slower than with an integer division operation.
Is there another way to do this other than keeping a counter variable and manually overflowing to 0 at the mod point?
```
const int FIZZ = 6;
for(int x = 0; x < MAXCOUNT; x++)
{
if(!(x % FIZZ)) print("Fizz\n"); // slow on some systems
}
```
vs:
The way I am currently doing it:
```
const int FIZZ = 6;
int fizzcount = 1;
for(int x = 1; x < MAXCOUNT; x++)
{
if(fizzcount >= FIZZ)
{
print("Fizz\n");
fizzcount = 0;
}
}
``` | Ah, the joys of bitwise arithmetic. A side effect of many division routines is the modulus - so in few cases should division actually be faster than modulus. I'm interested to see the source you got this information from. Processors with multipliers have interesting division routines using the multiplier, but you can get from division result to modulus with just another two steps (multiply and subtract) so it's still comparable. If the processor has a built in division routine you'll likely see it also provides the remainder.
Still, there is a small branch of number theory devoted to [Modular Arithmetic](http://en.wikibooks.org/wiki/Discrete_mathematics/Modular_arithmetic) which requires study if you really want to understand how to optimize a modulus operation. Modular arithmatic, for instance, is very handy for generating [magic squares](http://www.math.utah.edu/~carlson/mathcircles/magic.pdf).
So, in that vein, here's a [very low level look](http://piclist.org/techref/postbot.asp?by=time&id=piclist/2006/08/03/065022a) at the math of modulus for an example of x, which should show you how simple it can be compared to division:
---
Maybe a better way to think about the problem is in terms of number
bases and modulo arithmetic. For example, your goal is to compute DOW
mod 7 where DOW is the 16-bit representation of the day of the
week. You can write this as:
```
DOW = DOW_HI*256 + DOW_LO
DOW%7 = (DOW_HI*256 + DOW_LO) % 7
= ((DOW_HI*256)%7 + (DOW_LO % 7)) %7
= ((DOW_HI%7 * 256%7) + (DOW_LO%7)) %7
= ((DOW_HI%7 * 4) + (DOW_LO%7)) %7
```
Expressed in this manner, you can separately compute the modulo 7
result for the high and low bytes. Multiply the result for the high by
4 and add it to the low and then finally compute result modulo 7.
Computing the mod 7 result of an 8-bit number can be performed in a
similar fashion. You can write an 8-bit number in octal like so:
```
X = a*64 + b*8 + c
```
Where a, b, and c are 3-bit numbers.
```
X%7 = ((a%7)*(64%7) + (b%7)*(8%7) + c%7) % 7
= (a%7 + b%7 + c%7) % 7
= (a + b + c) % 7
```
since `64%7 = 8%7 = 1`
Of course, a, b, and c are
```
c = X & 7
b = (X>>3) & 7
a = (X>>6) & 7 // (actually, a is only 2-bits).
```
The largest possible value for `a+b+c` is `7+7+3 = 17`. So, you'll need
one more octal step. The complete (untested) C version could be
written like:
```
unsigned char Mod7Byte(unsigned char X)
{
X = (X&7) + ((X>>3)&7) + (X>>6);
X = (X&7) + (X>>3);
return X==7 ? 0 : X;
}
```
I spent a few moments writing a PIC version. The actual implementation
is slightly different than described above
```
Mod7Byte:
movwf temp1 ;
andlw 7 ;W=c
movwf temp2 ;temp2=c
rlncf temp1,F ;
swapf temp1,W ;W= a*8+b
andlw 0x1F
addwf temp2,W ;W= a*8+b+c
movwf temp2 ;temp2 is now a 6-bit number
andlw 0x38 ;get the high 3 bits == a'
xorwf temp2,F ;temp2 now has the 3 low bits == b'
rlncf WREG,F ;shift the high bits right 4
swapf WREG,F ;
addwf temp2,W ;W = a' + b'
; at this point, W is between 0 and 10
addlw -7
bc Mod7Byte_L2
Mod7Byte_L1:
addlw 7
Mod7Byte_L2:
return
```
Here's a liitle routine to test the algorithm
```
clrf x
clrf count
TestLoop:
movf x,W
RCALL Mod7Byte
cpfseq count
bra fail
incf count,W
xorlw 7
skpz
xorlw 7
movwf count
incfsz x,F
bra TestLoop
passed:
```
Finally, for the 16-bit result (which I have not tested), you could
write:
```
uint16 Mod7Word(uint16 X)
{
return Mod7Byte(Mod7Byte(X & 0xff) + Mod7Byte(X>>8)*4);
}
```
Scott
--- |
48,070 | <p>We are trying to lighten our page load as much as possible. Since ViewState can sometimes swell up to 100k of the page, I'd love to completely eliminate it.</p>
<p>I'd love to hear some techniques other people have used to move ViewState to a custom provider.</p>
<p>That said, a few caveats:</p>
<ul>
<li>We serve on average 2 Million unique visitors per hour.</li>
<li>Because of this, Database reads have been a serious issue in performance, so I don't want to store ViewState in the database.</li>
<li>We also are behind a load balancer, so any solution has to work with the user bouncing from machine to machine per postback.</li>
</ul>
<p>Ideas?</p>
| [
{
"answer_id": 48082,
"author": "Erick Sgarbi",
"author_id": 4171,
"author_profile": "https://Stackoverflow.com/users/4171",
"pm_score": 2,
"selected": false,
"text": "<p>I have tested many ways to remove the load of view state from the page and between all hacks and some software out th... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | We are trying to lighten our page load as much as possible. Since ViewState can sometimes swell up to 100k of the page, I'd love to completely eliminate it.
I'd love to hear some techniques other people have used to move ViewState to a custom provider.
That said, a few caveats:
* We serve on average 2 Million unique visitors per hour.
* Because of this, Database reads have been a serious issue in performance, so I don't want to store ViewState in the database.
* We also are behind a load balancer, so any solution has to work with the user bouncing from machine to machine per postback.
Ideas? | How do you handle Session State? There is a built-in "store the viewstate in the session state" provider. If you are storing the session state in some fast, out of proc system, that might be the best option for the viewstate.
edit: to do this add the following code to the your Page classes / global page base class
```
protected override PageStatePersister PageStatePersister {
get { return new SessionPageStatePersister(this); }
}
```
Also... this is by no means a perfect (or even good) solution to a large viewstate. As always, minimize the size of the viewstate as much as possible. However, the SessionPageStatePersister is relatively intelligent and avoids storing an unbounded number of viewstates per session as well as avoids storing only a single viewstate per session. |
48,094 | <p>So I have a pointer to an array of pointers. If I delete it like this:</p>
<pre><code>delete [] PointerToPointers;
</code></pre>
<p>Will that delete all the pointed to pointers as well? If not, do I have to loop over all of the pointers and delete them as well, or is there an easier way to do it? My google-fu doesn't seem to give me any good answers to this question.</p>
<p>(And yeah, I know I need to use a vector. This is one of those "catch up on C++" type assignments in school.)</p>
| [
{
"answer_id": 48095,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 1,
"selected": false,
"text": "<p>I think you're going to have to loop over I'm afraid.</p>\n"
},
{
"answer_id": 48098,
"author": "Jeffrey",... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] | So I have a pointer to an array of pointers. If I delete it like this:
```
delete [] PointerToPointers;
```
Will that delete all the pointed to pointers as well? If not, do I have to loop over all of the pointers and delete them as well, or is there an easier way to do it? My google-fu doesn't seem to give me any good answers to this question.
(And yeah, I know I need to use a vector. This is one of those "catch up on C++" type assignments in school.) | Yes you have to loop over the pointers, deleting individually.
Reason: What if other code had pointers to the objects in your array? The C++ compiler doesn't know if that's true or not, so you have to be explicit.
For an "easier way," two suggestions: (1) Make a subroutine for this purpose so at least you won't have to write the code more than once. (2) Use the "smart pointer" design paradigm where you hold an array of objects with reference-counters, then the objects are deleted when the objects are no longer referenced by any code. |
48,124 | <p>How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?</p>
| [
{
"answer_id": 48125,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 8,
"selected": true,
"text": "<p>First make a string with all your possible characters:</p>\n\n<pre><code> $characters = 'abcdefghijklmnopqrstuvwxyz012345... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] | How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP? | First make a string with all your possible characters:
```
$characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
```
You could also use [range()](http://php.net/range) to do this more quickly.
Then, in a loop, choose a random number and use it as the index to the `$characters` string to get a random character, and append it to your string:
```
$string = '';
$max = strlen($characters) - 1;
for ($i = 0; $i < $random_string_length; $i++) {
$string .= $characters[mt_rand(0, $max)];
}
```
`$random_string_length` is the length of the random string. |
48,126 | <p>Documentation is severely lacking on anything to do with stored procedures in mysql with PHP. I currently have a stored procedure that I call via PHP, how can I get the value of an out parameter?</p>
| [
{
"answer_id": 48161,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 5,
"selected": true,
"text": "<p>it looks like it's answered in this post:</p>\n\n<p><a href=\"http://forums.mysql.com/read.php?52,198596,198717#msg-1987... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | Documentation is severely lacking on anything to do with stored procedures in mysql with PHP. I currently have a stored procedure that I call via PHP, how can I get the value of an out parameter? | it looks like it's answered in this post:
<http://forums.mysql.com/read.php?52,198596,198717#msg-198717>
With mysqli PHP API:
Assume sproc myproc( IN i int, OUT j int ):
```
$mysqli = new mysqli( "HOST", "USR", "PWD", "DBNAME" );
$ivalue=1;
$res = $mysqli->multi_query( "CALL myproc($ivalue,@x);SELECT @x" );
if( $res ) {
$results = 0;
do {
if ($result = $mysqli->store_result()) {
printf( "<b>Result #%u</b>:<br/>", ++$results );
while( $row = $result->fetch_row() ) {
foreach( $row as $cell ) echo $cell, " ";
}
$result->close();
if( $mysqli->more_results() ) echo "<br/>";
}
} while( $mysqli->next_result() );
}
$mysqli->close();
``` |
48,198 | <p>How do I find out which process is listening on a TCP or UDP port on Windows?</p>
| [
{
"answer_id": 48199,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 13,
"selected": true,
"text": "<h1><a href=\"https://en.wikipedia.org/wiki/PowerShell\" rel=\"noreferrer\">PowerShell</a></h1>\n<h2>TCP</h2>\n<pre><code... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | How do I find out which process is listening on a TCP or UDP port on Windows? | [PowerShell](https://en.wikipedia.org/wiki/PowerShell)
======================================================
TCP
---
```
Get-Process -Id (Get-NetTCPConnection -LocalPort YourPortNumberHere).OwningProcess
```
UDP
---
```
Get-Process -Id (Get-NetUDPEndpoint -LocalPort YourPortNumberHere).OwningProcess
```
[cmd](https://en.wikipedia.org/wiki/Cmd.exe)
============================================
```
netstat -a -b
```
(Add **-n** to stop it trying to resolve hostnames, which will make it a lot faster.)
Note Dane's recommendation for [TCPView](http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx). It looks very useful!
**-a** Displays all connections and listening ports.
**-b** Displays the executable involved in creating each connection or listening port. In some cases well-known executables host multiple independent components, and in these cases the sequence of components involved in creating the connection or listening port is displayed. In this case the executable name is in [] at the bottom, on top is the component it called, and so forth until TCP/IP was reached. Note that this option can be time-consuming and will fail unless you have sufficient permissions.
**-n** Displays addresses and port numbers in numerical form.
**-o** Displays the owning process ID associated with each connection. |
48,235 | <p>I really enjoy Chrome, and the sheer exercise of helping a port would boost my knowledge-base.</p>
<p>Where do I start?</p>
<p>What are the fundamental similarities and differences between the code which will operated under Windows and Linux?</p>
<p>What skills and software do I need?</p>
<hr />
<h3>Note:</h3>
<p>The official website is Visual Studio oriented!<br />
Netbeans or Eclipse are my only options.<br />
I will not pay Microsoft to help an Open Source project.</p>
| [
{
"answer_id": 48236,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "<p>Read this article on Chrome and Open Source on Linux:</p>\n\n<p><a href=\"http://arstechnica.com/journals/linux.ars/2008/09/0... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
] | I really enjoy Chrome, and the sheer exercise of helping a port would boost my knowledge-base.
Where do I start?
What are the fundamental similarities and differences between the code which will operated under Windows and Linux?
What skills and software do I need?
---
### Note:
The official website is Visual Studio oriented!
Netbeans or Eclipse are my only options.
I will not pay Microsoft to help an Open Source project. | EDIT: (2/6/10)
A Beta version of Chrome has been released for Linux. Although it is labeled beta, it works great on my Ubuntu box. You can download it from Google:
<http://www.google.com/chrome?platform=linux>
EDIT: (5/31/09)
Since I answered this question, there have been more new developments in Chrome (actually "Chromium") for Linux: An alpha build has been released. This means it's not fully functional.
If you use Ubuntu, you're in luck: add the following lines to your /etc/apt/sources.list
```
deb http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty main
deb-src http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty main
```
Then, at the command line:
```
aptitude update
aptitude install chromium-browser
```
Don't forget to s/jaunty/yourUbuntuVersion/ if necessary. Also, you can s/aptitude/apt-get/, if you insist.
And.... **Yes**, it works. I'm typing this in my freshly installed Chromium browser right now!
The build is hosted by launchpad, and gave me some security warnings upon install, which I promptly ignored. Here's the website: <https://launchpad.net/~chromium-daily/+archive/ppa>
***The original answer:***
[Linux Build Instructions](http://code.google.com/p/chromium/wiki/LinuxBuildInstructions) |
48,239 | <p>Is there any way to get the ID of the element that fires an event?</p>
<p>I'm thinking something like:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
$("a").click(function() {
var test = caller.id;
alert(test.val());
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="starterkit/jquery.js"></script>
<form class="item" id="aaa">
<input class="title"></input>
</form>
<form class="item" id="bbb">
<input class="title"></input>
</form></code></pre>
</div>
</div>
</p>
<p>Except of course that the var <code>test</code> should contain the id <code>"aaa"</code>, if the event is fired from the first form, and <code>"bbb"</code>, if the event is fired from the second form.</p>
| [
{
"answer_id": 48242,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 6,
"selected": false,
"text": "<p>You can use <code>(this)</code> to reference the object that fired the function.</p>\n\n<p><code>'this'</code> is a <strong>D... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1090/"
] | Is there any way to get the ID of the element that fires an event?
I'm thinking something like:
```js
$(document).ready(function() {
$("a").click(function() {
var test = caller.id;
alert(test.val());
});
});
```
```html
<script type="text/javascript" src="starterkit/jquery.js"></script>
<form class="item" id="aaa">
<input class="title"></input>
</form>
<form class="item" id="bbb">
<input class="title"></input>
</form>
```
Except of course that the var `test` should contain the id `"aaa"`, if the event is fired from the first form, and `"bbb"`, if the event is fired from the second form. | In jQuery `event.target` always refers to the element that triggered the event, where `event` is the parameter passed to the function. <http://api.jquery.com/category/events/event-object/>
```
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id);
});
});
```
Note also that `this` will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as `$(this)`, e.g.:
```
$(document).ready(function() {
$("a").click(function(event) {
// this.append wouldn't work
$(this).append(" Clicked");
});
});
``` |
48,240 | <p>I am working with an API that provides bus arrival data. For every request, I get back (among other things) a list of which routes serve the stop in question. For example, if the list includes result for bus route #1, 2, and 5, then I know that those serve this stop.</p>
<p>I have a many-to-many relationship set up between Route and Stop, and I want to dynamically check and update these associations on every request. There is no "master list" of which routes serve which stops, so this seems like the best way to get this data.</p>
<p>I believe that the way I'm doing it now is very inefficient:</p>
<pre><code># routes is an array of [number, destination] that I build while iterating over the data
routes.uniq.each do |route|
number = route[0]
destination = route[1]
r = Route.find_by_number_and_destination(number, destination)
if !r
r = Route.new :number => number, :destination => destination
r.save
end
# I have to check if it already exists because I can't find a way
# to create a uniqueness constraint on the join table with 2 foreign keys
r.stops << stop unless r.stops.include? stop
end
</code></pre>
<p>Basically, I have to do 2 things for every route I find:
1) Create it if it doesn't already exist, 2) Add a relationship to the current stop if it doesn't already exist.</p>
<p>Is there a better way to do this, for example by getting a bunch of the data in memory and doing some of the processing on the app server side, in order to avoid the multitude of database calls I'm currently doing?</p>
| [
{
"answer_id": 48529,
"author": "Can Berk Güder",
"author_id": 2119,
"author_profile": "https://Stackoverflow.com/users/2119",
"pm_score": 1,
"selected": false,
"text": "<p>If I get it right, you (should) have 2 models. A Route model, and a Stop model.</p>\n\n<p>Here's how I would define... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/124/"
] | I am working with an API that provides bus arrival data. For every request, I get back (among other things) a list of which routes serve the stop in question. For example, if the list includes result for bus route #1, 2, and 5, then I know that those serve this stop.
I have a many-to-many relationship set up between Route and Stop, and I want to dynamically check and update these associations on every request. There is no "master list" of which routes serve which stops, so this seems like the best way to get this data.
I believe that the way I'm doing it now is very inefficient:
```
# routes is an array of [number, destination] that I build while iterating over the data
routes.uniq.each do |route|
number = route[0]
destination = route[1]
r = Route.find_by_number_and_destination(number, destination)
if !r
r = Route.new :number => number, :destination => destination
r.save
end
# I have to check if it already exists because I can't find a way
# to create a uniqueness constraint on the join table with 2 foreign keys
r.stops << stop unless r.stops.include? stop
end
```
Basically, I have to do 2 things for every route I find:
1) Create it if it doesn't already exist, 2) Add a relationship to the current stop if it doesn't already exist.
Is there a better way to do this, for example by getting a bunch of the data in memory and doing some of the processing on the app server side, in order to avoid the multitude of database calls I'm currently doing? | If I get it right, you (should) have 2 models. A Route model, and a Stop model.
Here's how I would define these models:
```
class Route < ActiveRecord::Base
has_and_belongs_to_many :stops
belongs_to :stop, :foreign_key => 'destination_id'
end
class Stop < ActiveRecorde::Base
has_and_belongs_to_many :routes
end
```
And here's how I would set up my tables:
```
create_table :routes do |t|
t.integer :destination_id
# Any other information you want to store about routes
end
create_table :stops do |t|
# Any other information you want to store about stops
end
create_table :routes_stops, :primary_key => [:route_id, :stop_id] do |t|
t.integer :route_id
t.integer :stop_id
end
```
Finally, here's the code I'd use:
```
# First, find all the relevant routes, just for caching.
Route.find(numbers)
r = Route.find(number)
r.destination_id = destination
r.stops << stop
```
This should use only a few SQL queries. |
48,278 | <p>I am using the webbrowser control in winforms and discovered now that background images which I apply with css are not included in the printouts.</p>
<p>Is there a way to make the webbrowser print the background of the displayed document too?</p>
<p>Edit:
Since I wanted to do this programatically, I opted for this solution:</p>
<pre><code>using Microsoft.Win32;
...
RegistryKey regKey = Registry.CurrentUser
.OpenSubKey("Software")
.OpenSubKey("Microsoft")
.OpenSubKey("Internet Explorer")
.OpenSubKey("Main");
//Get the current setting so that we can revert it after printjob
var defaultValue = regKey.GetValue("Print_Background");
regKey.SetValue("Print_Background", "yes");
//Do the printing
//Revert the registry key to the original value
regKey.SetValue("Print_Background", defaultValue);
</code></pre>
<p>Another way to handle this might be to just read the value, and notify the user to adjust this himself before printing. I have to agree that tweaking with the registry like this is not a good practice, so I am open for any suggestions.</p>
<p>Thanks for all your feedback</p>
| [
{
"answer_id": 48292,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>By default, the browser does not print background images at all. </p>\n\n<p>In Firefox</p>\n\n<pre><code>* File > Page Set... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4582/"
] | I am using the webbrowser control in winforms and discovered now that background images which I apply with css are not included in the printouts.
Is there a way to make the webbrowser print the background of the displayed document too?
Edit:
Since I wanted to do this programatically, I opted for this solution:
```
using Microsoft.Win32;
...
RegistryKey regKey = Registry.CurrentUser
.OpenSubKey("Software")
.OpenSubKey("Microsoft")
.OpenSubKey("Internet Explorer")
.OpenSubKey("Main");
//Get the current setting so that we can revert it after printjob
var defaultValue = regKey.GetValue("Print_Background");
regKey.SetValue("Print_Background", "yes");
//Do the printing
//Revert the registry key to the original value
regKey.SetValue("Print_Background", defaultValue);
```
Another way to handle this might be to just read the value, and notify the user to adjust this himself before printing. I have to agree that tweaking with the registry like this is not a good practice, so I am open for any suggestions.
Thanks for all your feedback | If you're going to go and change an important system setting, make sure to first read the current setting and restore it when you are done.
I consider this *very bad* practice in the first place, but if you must do it then be kind.
```
Registry.LocalMachine
```
Also, try changing `LocalUser` instead of `LocalMachine` - that way if your app crashes (and it will), then you'll only confounded the user, not everyone who uses the machine. |
48,288 | <p>I've been trying to understand <a href="http://msdn.microsoft.com/en-gb/library/system.diagnostics.process.mainwindowhandle.aspx" rel="nofollow noreferrer">Process.MainWindowHandle</a>.</p>
<p>According to MSDN; "The main window is the window that is created when the process is started. After initialization, other windows may be opened, including the Modal and TopLevel windows, but <em>the first window associated with the process remains the main window</em>." (Emphasis added)</p>
<p>But while debugging I noticed that MainWindowHandle seemed to change value... which I wasn't expecting, especially after consulting the documentation above.</p>
<p>To confirm the behaviour I created a standalone WinForms app with a timer to check the MainWindowHandle of the "DEVENV" (Visual Studio) process every 100ms.</p>
<p>Here's the interesting part of this test app...</p>
<pre><code> IntPtr oldHWnd = IntPtr.Zero;
void GetMainwindowHandle()
{
Process[] processes = Process.GetProcessesByName("DEVENV");
if (processes.Length!=1)
return;
IntPtr newHWnd = processes[0].MainWindowHandle;
if (newHWnd != oldHWnd)
{
oldHWnd = newHWnd;
textBox1.AppendText(processes[0].MainWindowHandle.ToString("X")+"\r\n");
}
}
private void timer1Tick(object sender, EventArgs e)
{
GetMainwindowHandle();
}
</code></pre>
<p>You can see the value of MainWindowHandle changing when you (for example) click on a drop-down menu inside VS.</p>
<p><img src="https://i.stack.imgur.com/r54iB.png" alt="MainWindowHandleMystery"></p>
<p>Perhaps I've misunderstood the documentation. </p>
<p>Can anyone shed light?</p>
| [
{
"answer_id": 48301,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "<p>Actually Process.MainWindowHandle is a handle of top-most window, it's not really the \"Main Window Handle\"</p>\n"
},
{
... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4200/"
] | I've been trying to understand [Process.MainWindowHandle](http://msdn.microsoft.com/en-gb/library/system.diagnostics.process.mainwindowhandle.aspx).
According to MSDN; "The main window is the window that is created when the process is started. After initialization, other windows may be opened, including the Modal and TopLevel windows, but *the first window associated with the process remains the main window*." (Emphasis added)
But while debugging I noticed that MainWindowHandle seemed to change value... which I wasn't expecting, especially after consulting the documentation above.
To confirm the behaviour I created a standalone WinForms app with a timer to check the MainWindowHandle of the "DEVENV" (Visual Studio) process every 100ms.
Here's the interesting part of this test app...
```
IntPtr oldHWnd = IntPtr.Zero;
void GetMainwindowHandle()
{
Process[] processes = Process.GetProcessesByName("DEVENV");
if (processes.Length!=1)
return;
IntPtr newHWnd = processes[0].MainWindowHandle;
if (newHWnd != oldHWnd)
{
oldHWnd = newHWnd;
textBox1.AppendText(processes[0].MainWindowHandle.ToString("X")+"\r\n");
}
}
private void timer1Tick(object sender, EventArgs e)
{
GetMainwindowHandle();
}
```
You can see the value of MainWindowHandle changing when you (for example) click on a drop-down menu inside VS.

Perhaps I've misunderstood the documentation.
Can anyone shed light? | @edg,
I guess it's an error in MSDN. You can clearly see in Relfector, that "Main window" check in .NET looks like:
```
private bool IsMainWindow(IntPtr handle)
{
return (!(NativeMethods.GetWindow(new HandleRef(this, handle), 4) != IntPtr.Zero)
&& NativeMethods.IsWindowVisible(new HandleRef(this, handle)));
}
```
When .NET code enumerates windows, it's pretty obvious that first visible window (i.e. top level window) will match this criteria. |
48,340 | <p>i have a wcf service that does an operation. and in this operation there could be a fault. i have stated that there could be a fault in my service contract. </p>
<p>here is the code below;</p>
<pre><code>public void Foo()
{
try
{
DoSomething(); // throws FaultException<FooFault>
}
catch (FaultException)
{
throw;
}
catch (Exception ex)
{
myProject.Exception.Throw<FooFault>(ex);
}
}
</code></pre>
<p>in service contract;</p>
<pre><code>[FaultException(typeof(FooFault))]
void Foo();
</code></pre>
<p>when a FaultException was thrown by DoSomething() method while i was running the application, firstly the exception was caught at "catch(Exception ex)" line and breaks in there. then when i pressed f5 again, it does what normally it has to. i wonder why that break exists? and if not could it be problem on publish?</p>
| [
{
"answer_id": 48345,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>Take a closer look at catched exception. Was it FaultException< FooFault> or FaultException ? There are 2 version of FaultE... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4215/"
] | i have a wcf service that does an operation. and in this operation there could be a fault. i have stated that there could be a fault in my service contract.
here is the code below;
```
public void Foo()
{
try
{
DoSomething(); // throws FaultException<FooFault>
}
catch (FaultException)
{
throw;
}
catch (Exception ex)
{
myProject.Exception.Throw<FooFault>(ex);
}
}
```
in service contract;
```
[FaultException(typeof(FooFault))]
void Foo();
```
when a FaultException was thrown by DoSomething() method while i was running the application, firstly the exception was caught at "catch(Exception ex)" line and breaks in there. then when i pressed f5 again, it does what normally it has to. i wonder why that break exists? and if not could it be problem on publish? | Are you consuming the WCF service from Silverlight? If so, a special configuration is needed to make the service return a HTTP 200 code instead of 500 in case of error. The details are here: <http://msdn.microsoft.com/en-us/library/dd470096%28VS.96%29.aspx> |
48,356 | <p>Greetings, I'm trying to find a way to 'unbind' a socket from a particular IP/Port combination. My pseudocode looks like this:</p>
<pre><code>ClassA a = new ClassA(); //(class A instantiates socket and binds it to 127.0.0.1:4567)
//do something
//...much later, a has been garbage-collected away.
ClassA aa = new ClassA(); //crash here.
</code></pre>
<p>At this point, .Net informs me that I've already got a socket bound to 127.0.0.1:4567, which is technically true. But no matter what code I put in ClassA's destructor, or no matter what functions I call on the socket (I've tried .Close() and .Disconnect(true)), the socket remains proudly bound to 127.0.0.1:4567. What do I do to be able to 'un-bind' the socket?</p>
<hr>
<p>EDIT: I'm not relying solely on garbage collection (though I tried that approach as well). I tried calling a.Close() or a.Disconnect() and only then instantiating aa; this doesn't solve the problem.</p>
<hr>
<p>EDIT: I've also tried implementing IDisposable, but the code never got there without my calling the method (which was the equivalent of earlier attempts, as the method would simply try .Close and .Disconnect). Let me try calling .Dispose directly and get back to you.</p>
<hr>
<p>EDIT (lots of edits, apologies): Implementing IDisposable and calling a.Dispose() from where 'a' loses scope doesn't work - my Dispose implementation still has to call either .Close or .Disconnect(true) (or .Shutdown(Both)) but none of those unbind the socket.</p>
<p>Any help would be appreciated!</p>
| [
{
"answer_id": 48361,
"author": "zappan",
"author_id": 4723,
"author_profile": "https://Stackoverflow.com/users/4723",
"pm_score": 0,
"selected": false,
"text": "<p>you can't rely on object being garbage collected in C# (i assume you're using c#, based on tagging) if it holds resources l... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5021/"
] | Greetings, I'm trying to find a way to 'unbind' a socket from a particular IP/Port combination. My pseudocode looks like this:
```
ClassA a = new ClassA(); //(class A instantiates socket and binds it to 127.0.0.1:4567)
//do something
//...much later, a has been garbage-collected away.
ClassA aa = new ClassA(); //crash here.
```
At this point, .Net informs me that I've already got a socket bound to 127.0.0.1:4567, which is technically true. But no matter what code I put in ClassA's destructor, or no matter what functions I call on the socket (I've tried .Close() and .Disconnect(true)), the socket remains proudly bound to 127.0.0.1:4567. What do I do to be able to 'un-bind' the socket?
---
EDIT: I'm not relying solely on garbage collection (though I tried that approach as well). I tried calling a.Close() or a.Disconnect() and only then instantiating aa; this doesn't solve the problem.
---
EDIT: I've also tried implementing IDisposable, but the code never got there without my calling the method (which was the equivalent of earlier attempts, as the method would simply try .Close and .Disconnect). Let me try calling .Dispose directly and get back to you.
---
EDIT (lots of edits, apologies): Implementing IDisposable and calling a.Dispose() from where 'a' loses scope doesn't work - my Dispose implementation still has to call either .Close or .Disconnect(true) (or .Shutdown(Both)) but none of those unbind the socket.
Any help would be appreciated! | (this is what finally got everything to work for me)
Make sure EVERY socket that the socket in A connects to has
```
socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress, true);
```
set upon being initiated. |
48,426 | <p>My gcc build toolchain produces a .map file. How do I display the memory map graphically?</p>
| [
{
"answer_id": 112078,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 6,
"selected": true,
"text": "<p>Here's the beginnings of a script in Python. It loads the map file into a list of Sections and Symbols (first half). I... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] | My gcc build toolchain produces a .map file. How do I display the memory map graphically? | Here's the beginnings of a script in Python. It loads the map file into a list of Sections and Symbols (first half). It then renders the map using HTML (or do whatever you want with the `sections` and `symbols` lists).
You can control the script by modifying these lines:
```
with open('t.map') as f:
colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E']
total_height = 32.0
```
map2html.py
```
from __future__ import with_statement
import re
class Section:
def __init__(self, address, size, segment, section):
self.address = address
self.size = size
self.segment = segment
self.section = section
def __str__(self):
return self.section+""
class Symbol:
def __init__(self, address, size, file, name):
self.address = address
self.size = size
self.file = file
self.name = name
def __str__(self):
return self.name
#===============================
# Load the Sections and Symbols
#
sections = []
symbols = []
with open('t.map') as f:
in_sections = True
for line in f:
m = re.search('^([0-9A-Fx]+)\s+([0-9A-Fx]+)\s+((\[[ 0-9]+\])|\w+)\s+(.*?)\s*$', line)
if m:
if in_sections:
sections.append(Section(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5)))
else:
symbols.append(Symbol(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5)))
else:
if len(sections) > 0:
in_sections = False
#===============================
# Gererate the HTML File
#
colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E']
total_height = 32.0
segments = set()
for s in sections: segments.add(s.segment)
segment_colors = dict()
i = 0
for s in segments:
segment_colors[s] = colors[i % len(colors)]
i += 1
total_size = 0
for s in symbols:
total_size += s.size
sections.sort(lambda a,b: a.address - b.address)
symbols.sort(lambda a,b: a.address - b.address)
def section_from_address(addr):
for s in sections:
if addr >= s.address and addr < (s.address + s.size):
return s
return None
print "<html><head>"
print " <style>a { color: black; text-decoration: none; font-family:monospace }</style>"
print "<body>"
print "<table cellspacing='1px'>"
for sym in symbols:
section = section_from_address(sym.address)
height = (total_height/total_size) * sym.size
font_size = 1.0 if height > 1.0 else height
print "<tr style='background-color:#%s;height:%gem;line-height:%gem;font-size:%gem'><td style='overflow:hidden'>" % \
(segment_colors[section.segment], height, height, font_size)
print "<a href='#%s'>%s</a>" % (sym.name, sym.name)
print "</td></tr>"
print "</table>"
print "</body></html>"
```
And here's a bad rendering of the HTML it outputs:
 |
48,432 | <p>Being relatively new to the .net game, I was wondering, has anyone had any experience of the pros / cons between the use of LINQ and what could be considered more traditional methods working with lists / collections? </p>
<p>For a specific example of a project I'm working on : a list of unique id / name pairs are being retrieved from a remote web-service.</p>
<ul>
<li>this list will change infrequently (once per day), </li>
<li>will be read-only from the point of view of the application where it is being used</li>
<li>will be stored at the application level for all requests to access</li>
</ul>
<p>Given those points, I plan to store the returned values at the application level in a singleton class.</p>
<p>My initial approach was to iterate through the list returned from the remote service and store it in a NameValueCollection in a singleton class, with methods to retrieve from the collection based on an id:</p>
<pre><code>sugarsoap soapService = new sugarsoap();
branch_summary[] branchList = soapService.getBranches();
foreach (branch_summary aBranch in branchList)
{
branchNameList.Add(aBranch.id, aBranch.name);
}
</code></pre>
<p>The alternative using LINQ is to simply add a method that works on the list directly once it has been retrieved:</p>
<pre><code>public string branchName (string branchId)
{
//branchList populated in the constructor
branch_summary bs = from b in branchList where b.id == branchId select b;
return branch_summary.name;
}
</code></pre>
<p>Is either better than the other - is there a third way? I'm open to all answers, for both approaches and both in terms of solutions that offer elegance, and those which benefit performance.</p>
| [
{
"answer_id": 48476,
"author": "Rob Stevenson-Leggett",
"author_id": 4950,
"author_profile": "https://Stackoverflow.com/users/4950",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure a singleton class is absolutely necessary, do you absolutely need global access at all times? I... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4396/"
] | Being relatively new to the .net game, I was wondering, has anyone had any experience of the pros / cons between the use of LINQ and what could be considered more traditional methods working with lists / collections?
For a specific example of a project I'm working on : a list of unique id / name pairs are being retrieved from a remote web-service.
* this list will change infrequently (once per day),
* will be read-only from the point of view of the application where it is being used
* will be stored at the application level for all requests to access
Given those points, I plan to store the returned values at the application level in a singleton class.
My initial approach was to iterate through the list returned from the remote service and store it in a NameValueCollection in a singleton class, with methods to retrieve from the collection based on an id:
```
sugarsoap soapService = new sugarsoap();
branch_summary[] branchList = soapService.getBranches();
foreach (branch_summary aBranch in branchList)
{
branchNameList.Add(aBranch.id, aBranch.name);
}
```
The alternative using LINQ is to simply add a method that works on the list directly once it has been retrieved:
```
public string branchName (string branchId)
{
//branchList populated in the constructor
branch_summary bs = from b in branchList where b.id == branchId select b;
return branch_summary.name;
}
```
Is either better than the other - is there a third way? I'm open to all answers, for both approaches and both in terms of solutions that offer elegance, and those which benefit performance. | i dont think the linq you wrote would compile, it'd have to be
```
public string branchName (string branchId)
{
//branchList populated in the constructor
branch_summary bs = (from b in branchList where b.id == branchId select b).FirstOrDefault();
return branch_summary == null ? null : branch_summary.name;
}
```
note the .FirstsOrDefault()
I'd rather use LINQ for the reason that it can be used in other places, for writing more complex filters on your data. I also think it's easier to read than NameValueCollection alternative.
that's my $0.02 |
48,458 | <p>I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is <a href="http://www.bowlsk.com" rel="noreferrer">BowlSK</a>. However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working.</p>
<p>What I have:</p>
<ul>
<li>Main Level contains:
<ul>
<li>all .py files (didn't know how to make packages work)</li>
<li>all .html templates for main level pages</li>
</ul></li>
<li>Subdirectories:
<ul>
<li>separate folders for css, images, js, etc.</li>
<li>folders that hold .html templates for subdirecty-type urls</li>
</ul></li>
</ul>
<p>Example:<br/>
<a href="http://www.bowlsk.com/" rel="noreferrer">http://www.bowlsk.com/</a> maps to HomePage (default package), template at "index.html"<br/>
<a href="http://www.bowlsk.com/games/view-series.html?series=7130" rel="noreferrer">http://www.bowlsk.com/games/view-series.html?series=7130</a> maps to ViewSeriesPage (again, default package), template at "games/view-series.html"</p>
<p>It's nasty. How do I restructure? I had 2 ideas:</p>
<ul>
<li><p>Main Folder containing: appdef, indexes, main.py?</p>
<ul>
<li>Subfolder for code. Does this have to be my first package?</li>
<li>Subfolder for templates. Folder heirarchy would match package heirarchy</li>
<li>Individual subfolders for css, images, js, etc.</li>
</ul></li>
<li><p>Main Folder containing appdef, indexes, main.py?</p>
<ul>
<li>Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage"</li>
</ul></li>
</ul>
<p>Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again.</p>
| [
{
"answer_id": 48467,
"author": "Dominic Eidson",
"author_id": 5042,
"author_profile": "https://Stackoverflow.com/users/5042",
"pm_score": 1,
"selected": false,
"text": "<p>I am not entirely up to date on the latest best practices, et cetera when it comes to code layout, but when I did m... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/96/"
] | I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is [BowlSK](http://www.bowlsk.com). However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working.
What I have:
* Main Level contains:
+ all .py files (didn't know how to make packages work)
+ all .html templates for main level pages
* Subdirectories:
+ separate folders for css, images, js, etc.
+ folders that hold .html templates for subdirecty-type urls
Example:
<http://www.bowlsk.com/> maps to HomePage (default package), template at "index.html"
<http://www.bowlsk.com/games/view-series.html?series=7130> maps to ViewSeriesPage (again, default package), template at "games/view-series.html"
It's nasty. How do I restructure? I had 2 ideas:
* Main Folder containing: appdef, indexes, main.py?
+ Subfolder for code. Does this have to be my first package?
+ Subfolder for templates. Folder heirarchy would match package heirarchy
+ Individual subfolders for css, images, js, etc.
* Main Folder containing appdef, indexes, main.py?
+ Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage"
Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again. | First, I would suggest you have a look at "[Rapid Development with Python, Django, and Google App Engine](http://sites.google.com/site/io/rapid-development-with-python-django-and-google-app-engine)"
GvR describes a general/standard project layout on page 10 of his [slide presentation](http://sites.google.com/site/io/rapid-development-with-python-django-and-google-app-engine/rapid_development_with_django_gae.pdf?attredirects=0).
Here I'll post a slightly modified version of the layout/structure from that page. I pretty much follow this pattern myself. You also mentioned you had trouble with packages. Just make sure each of your sub folders has an \_\_init\_\_.py file. It's ok if its empty.
Boilerplate files
-----------------
* These hardly vary between projects
* app.yaml: direct all non-static requests to main.py
* main.py: initialize app and send it all requests
Project lay-out
---------------
* static/\*: static files; served directly by App Engine
* myapp/\*.py: app-specific python code
+ views.py, models.py, tests.py, \_\_init\_\_.py, and more
* templates/\*.html: templates (or myapp/templates/\*.html)
Here are some code examples that may help as well:
main.py
-------
```
import wsgiref.handlers
from google.appengine.ext import webapp
from myapp.views import *
application = webapp.WSGIApplication([
('/', IndexHandler),
('/foo', FooHandler)
], debug=True)
def main():
wsgiref.handlers.CGIHandler().run(application)
```
myapp/views.py
--------------
```
import os
import datetime
import logging
import time
from google.appengine.api import urlfetch
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from models import *
class IndexHandler(webapp.RequestHandler):
def get(self):
date = "foo"
# Do some processing
template_values = {'data': data }
path = os.path.join(os.path.dirname(__file__) + '/../templates/', 'main.html')
self.response.out.write(template.render(path, template_values))
class FooHandler(webapp.RequestHandler):
def get(self):
#logging.debug("start of handler")
```
myapp/models.py
---------------
```
from google.appengine.ext import db
class SampleModel(db.Model):
```
I think this layout works great for new and relatively small to medium projects. For larger projects I would suggest breaking up the views and models to have their own sub-folders with something like:
Project lay-out
---------------
* static/: static files; served directly by App Engine
+ js/\*.js
+ images/\*.gif|png|jpg
+ css/\*.css
* myapp/: app structure
+ models/\*.py
+ views/\*.py
+ tests/\*.py
+ templates/\*.html: templates |
48,470 | <p>Whenever I use a macro in Visual Studio I get an annoying tip balloon in the system tray and an accompanying "pop" sound. It says:</p>
<blockquote>
<p>Visual Studio .NET macros</p>
<p>To stop the macro from running, double-click the spinning cassette.<br>
Click here to not show this balloon again.</p>
</blockquote>
<p>I have trouble clicking the balloon because my macro runs so quickly.</p>
<p>Is this controllable by some dialog box option?</p>
<p>(I found someone else asking this question on <a href="http://www.tech-archive.net/Archive/VisualStudio/microsoft.public.vsnet.ide/2005-11/msg00267.html" rel="noreferrer">some other site</a> but it's not answered there. I give credit here because I've copied and pasted some pieces from there.)</p>
| [
{
"answer_id": 48478,
"author": "Owen",
"author_id": 4790,
"author_profile": "https://Stackoverflow.com/users/4790",
"pm_score": 2,
"selected": false,
"text": "<p>Okay, I found a way to make the balloon clickable, and clicking it does indeed stop it from popping up again. (On the other s... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
] | Whenever I use a macro in Visual Studio I get an annoying tip balloon in the system tray and an accompanying "pop" sound. It says:
>
> Visual Studio .NET macros
>
>
> To stop the macro from running, double-click the spinning cassette.
>
> Click here to not show this balloon again.
>
>
>
I have trouble clicking the balloon because my macro runs so quickly.
Is this controllable by some dialog box option?
(I found someone else asking this question on [some other site](http://www.tech-archive.net/Archive/VisualStudio/microsoft.public.vsnet.ide/2005-11/msg00267.html) but it's not answered there. I give credit here because I've copied and pasted some pieces from there.) | This will disable the pop up:
For Visual Studio 2008:
```
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0
DWORD DontShowMacrosBalloon=6
```
For Visual Studio 2010 (the DWORD won't be there by default, use `New | DWORD value` to create it):
```
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0
DWORD DontShowMacrosBalloon=6
```
Delete the same key to re-enable it. |
48,474 | <p>I'm a beginner at rails programming, attempting to show many images on a page. Some images are to lay on top of others. To make it simple, say I want a blue square, with a red square in the upper right corner of the blue square (but not tight in the corner). I am trying to avoid compositing (with ImageMagick and similar) due to performance issues.</p>
<p>I just want to position overlapping images relative to one another.</p>
<p>As a more difficult example, imagine an odometer placed inside a larger image. For six digits, I would need to composite a million different images, or do it all on the fly, where all that is needed is to place the six images on top of the other one.</p>
| [
{
"answer_id": 48482,
"author": "Chris Bartow",
"author_id": 497,
"author_profile": "https://Stackoverflow.com/users/497",
"pm_score": 3,
"selected": false,
"text": "<p>The easy way to do it is to use background-image then just put an <img> in that element.</p>\n\n<p>The other way ... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5038/"
] | I'm a beginner at rails programming, attempting to show many images on a page. Some images are to lay on top of others. To make it simple, say I want a blue square, with a red square in the upper right corner of the blue square (but not tight in the corner). I am trying to avoid compositing (with ImageMagick and similar) due to performance issues.
I just want to position overlapping images relative to one another.
As a more difficult example, imagine an odometer placed inside a larger image. For six digits, I would need to composite a million different images, or do it all on the fly, where all that is needed is to place the six images on top of the other one. | Ok, after some time, here's what I landed on:
```css
.parent {
position: relative;
top: 0;
left: 0;
}
.image1 {
position: relative;
top: 0;
left: 0;
border: 1px red solid;
}
.image2 {
position: absolute;
top: 30px;
left: 30px;
border: 1px green solid;
}
```
```html
<div class="parent">
<img class="image1" src="https://via.placeholder.com/50" />
<img class="image2" src="https://via.placeholder.com/100" />
</div>
```
As the simplest solution. That is:
Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct. |
48,491 | <p>I have two machines, speed and mass. speed has a fast Internet connection and is running a crawler which downloads a lot of files to disk. mass has a lot of disk space. I want to move the files from speed to mass after they're done downloading. Ideally, I'd just run:</p>
<pre><code>$ rsync --remove-source-files speed:/var/crawldir .
</code></pre>
<p>but I worry that rsync will unlink a source file that hasn't finished downloading yet. (I looked at the source code and I didn't see anything protecting against this.) Any suggestions?</p>
| [
{
"answer_id": 48500,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 3,
"selected": false,
"text": "<p>How much control do you have over the download process? If you roll your own, you can have the file being downloaded... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4300/"
] | I have two machines, speed and mass. speed has a fast Internet connection and is running a crawler which downloads a lot of files to disk. mass has a lot of disk space. I want to move the files from speed to mass after they're done downloading. Ideally, I'd just run:
```
$ rsync --remove-source-files speed:/var/crawldir .
```
but I worry that rsync will unlink a source file that hasn't finished downloading yet. (I looked at the source code and I didn't see anything protecting against this.) Any suggestions? | How much control do you have over the download process? If you roll your own, you can have the file being downloaded go to a temp directory or have a temporary name until it's finished downloading, and then mv it to the correct name when it's done. If you're using third party software, then you don't have as much control, but you still might be able to do the temp directory thing. |
48,497 | <p>The following XHTML code is not working:</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="/dojotoolkit/dijit/themes/tundra/tundra.css" />
<link rel="stylesheet" type="text/css" href="/dojotoolkit/dojo/resources/dojo.css" />
<script type="text/javascript" src="/dojotoolkit/dojo/dojo.js" djConfig="parseOnLoad: true" />
<script type="text/javascript">
dojo.require("dijit.form.ValidationTextBox");
dojo.require("dojo.parser");
</script>
</head>
<body class="nihilo">
<input type="text" dojoType="dijit.form.ValidationTextBox" size="30" />
</body>
</html>
</code></pre>
<p>In Firebug I get the following error message:</p>
<blockquote>
<p>[Exception... "Component returned failure code: 0x80004003
(NS_ERROR_INVALID_POINTER) [nsIDOMNSHTMLElement.innerHTML]" nsresult:
"0x80004003 (NS_ERROR_INVALID_POINTER)" location: "JS frame ::
<a href="http://localhost:21000/dojotoolkit/dojo/dojo.js" rel="nofollow noreferrer">http://localhost:21000/dojotoolkit/dojo/dojo.js</a> :: anonymous :: line
319" data: no] <a href="http://localhost:21000/dojotoolkit/dojo/dojo.js" rel="nofollow noreferrer">http://localhost:21000/dojotoolkit/dojo/dojo.js</a> Line
319</p>
</blockquote>
<p>Any idea what is wrong?</p>
| [
{
"answer_id": 48552,
"author": "John Smithers",
"author_id": 1069,
"author_profile": "https://Stackoverflow.com/users/1069",
"pm_score": 0,
"selected": false,
"text": "<p>Well, what is dojo.js doing at line 319?</p>\n"
},
{
"answer_id": 48554,
"author": "Brian Gianforcaro",
... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4875/"
] | The following XHTML code is not working:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="/dojotoolkit/dijit/themes/tundra/tundra.css" />
<link rel="stylesheet" type="text/css" href="/dojotoolkit/dojo/resources/dojo.css" />
<script type="text/javascript" src="/dojotoolkit/dojo/dojo.js" djConfig="parseOnLoad: true" />
<script type="text/javascript">
dojo.require("dijit.form.ValidationTextBox");
dojo.require("dojo.parser");
</script>
</head>
<body class="nihilo">
<input type="text" dojoType="dijit.form.ValidationTextBox" size="30" />
</body>
</html>
```
In Firebug I get the following error message:
>
> [Exception... "Component returned failure code: 0x80004003
> (NS\_ERROR\_INVALID\_POINTER) [nsIDOMNSHTMLElement.innerHTML]" nsresult:
> "0x80004003 (NS\_ERROR\_INVALID\_POINTER)" location: "JS frame ::
> <http://localhost:21000/dojotoolkit/dojo/dojo.js> :: anonymous :: line
> 319" data: no] <http://localhost:21000/dojotoolkit/dojo/dojo.js> Line
> 319
>
>
>
Any idea what is wrong? | The problem seams to be the ending of the file...
* If I name the file [test2.html](http://www.tasix.ch/Greter/test2.html) everything works.
* If I name the file [test2.xhtml](http://www.tasix.ch/Greter/test2.xhtml) I get the error message.
The diverence between the two seams to be the Content-Type in the response header from apache.
* For .html it is Content-Type text/html; charset=ISO-8859-1
* For .xhtml it is Content-Type application/xhtml+xml |
48,521 | <p>I would like to use a component that exposes the datasource property, but instead of supplying the datasource with whole list of objects, I would like to use only simple object. Is there any way to do this ?</p>
<p>The mentioned component is DevExpress.XtraDataLayout.DataLayoutControl - this is fairly irrelevant to the question though.</p>
| [
{
"answer_id": 48522,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": true,
"text": "<p>Databinding expects an IEnumerable object, because it enumorates over it just like a foreach loop does.</p>\n\n<p>So to do ... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4694/"
] | I would like to use a component that exposes the datasource property, but instead of supplying the datasource with whole list of objects, I would like to use only simple object. Is there any way to do this ?
The mentioned component is DevExpress.XtraDataLayout.DataLayoutControl - this is fairly irrelevant to the question though. | Databinding expects an IEnumerable object, because it enumorates over it just like a foreach loop does.
So to do this, just wrap your single object in an IEnumerable.
Even this would work:
```
DataBindObject.DataSource = new List<YourObject>().Add(YourObjectInstance);
``` |
48,526 | <p>I've been looking into different web statistics programs for my site, and one promising one is <a href="http://www.hping.org/visitors/" rel="nofollow noreferrer">Visitors</a>. Unfortunately, it's a C program and I don't know how to call it from the web server. I've tried using PHP's <a href="http://us.php.net/manual/en/function.shell-exec.php" rel="nofollow noreferrer">shell_exec</a>, but my web host (<a href="https://www.nearlyfreespeech.net/" rel="nofollow noreferrer">NFSN</a>) has PHP's <a href="http://us2.php.net/features.safe-mode" rel="nofollow noreferrer">safe mode</a> on and it's giving me an error message.</p>
<p>Is there a way to execute the program within safe mode? If not, can it work with CGI? If so, how? (I've never used CGI before)</p>
| [
{
"answer_id": 48528,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>Visitors looks like a log analyzer and report generator. Its probably best setup as a chron job to create static HTML page... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
] | I've been looking into different web statistics programs for my site, and one promising one is [Visitors](http://www.hping.org/visitors/). Unfortunately, it's a C program and I don't know how to call it from the web server. I've tried using PHP's [shell\_exec](http://us.php.net/manual/en/function.shell-exec.php), but my web host ([NFSN](https://www.nearlyfreespeech.net/)) has PHP's [safe mode](http://us2.php.net/features.safe-mode) on and it's giving me an error message.
Is there a way to execute the program within safe mode? If not, can it work with CGI? If so, how? (I've never used CGI before) | I managed to solve this problem on my own. I put the following lines in a file named visitors.cgi:
```
#!/bin/sh
printf "Content-type: text/html\n\n"
exec visitors -A /home/logs/access_log
``` |
48,550 | <p>I am trying to publish an Asp.net MVC web application locally using the NAnt and MSBuild. This is what I am using for my NAnt target;</p>
<pre><code><target name="publish-artifacts-to-build">
<msbuild project="my-solution.sln" target="Publish">
<property name="Configuration" value="debug" />
<property name="OutDir" value="builds\" />
<arg line="/m:2 /tv:3.5" />
</msbuild>
</target>
</code></pre>
<p>and all I get is this as a response;</p>
<pre><code>[msbuild] Skipping unpublishable project.
</code></pre>
<p>Is it possible to publish web applications via the command line in this way?</p>
| [
{
"answer_id": 48553,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 5,
"selected": true,
"text": "<p>The \"Publish\" target you are trying to invoke is for \"OneClick\" deployment, not for publishing a website... This is why y... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4642/"
] | I am trying to publish an Asp.net MVC web application locally using the NAnt and MSBuild. This is what I am using for my NAnt target;
```
<target name="publish-artifacts-to-build">
<msbuild project="my-solution.sln" target="Publish">
<property name="Configuration" value="debug" />
<property name="OutDir" value="builds\" />
<arg line="/m:2 /tv:3.5" />
</msbuild>
</target>
```
and all I get is this as a response;
```
[msbuild] Skipping unpublishable project.
```
Is it possible to publish web applications via the command line in this way? | The "Publish" target you are trying to invoke is for "OneClick" deployment, not for publishing a website... This is why you are getting the seemingly bizarre message.
You would want to use the AspNetCompiler task, rather than the MSBuild task. See <http://msdn2.microsoft.com/en-us/library/ms164291.aspx> for more info on this task. Your "PublishDir" would correspond to the TargetPath property of the task.
[Source](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1032073&SiteID=1) |
48,555 | <p>I have a few sites on a shared host that is running Apache 2. I would like to compress the HTML, CSS and Javascript that is delivered to the browser. The host has disabled mod_deflate and mod_gzip, so these options are out. I do have PHP 5 at my disposal, though, so I could use the gzip component of that.</p>
<p>I am currently placing the following in my .htaccess file:</p>
<blockquote>
<p>php_value output_handler ob_gzhandler</p>
</blockquote>
<p>However, this only compresses the HTML and leaves out the CSS and JS.</p>
<p>Is there a reliable way of transparently compressing the output of the CSS and JS without having to change every page? I have searched Google and a number of solutions are presented, but I've yet to get one to work. If anyone could suggest a solution that they know to work, that would be very gratefully received.</p>
<p>Note, <strong>Method 2</strong> in <strong><a href="http://www.fiftyfoureleven.com/weblog/web-development/css/the-definitive-css-gzip-method" rel="noreferrer">The Definitive Post on Gzipping your CSS</a></strong> looks like a good solution, but I couldn't get it working. Has anyone else succeeded using this method?</p>
| [
{
"answer_id": 48583,
"author": "macbirdie",
"author_id": 5049,
"author_profile": "https://Stackoverflow.com/users/5049",
"pm_score": 1,
"selected": false,
"text": "<p>You can try your luck with <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html\" rel=\"nofollow noreferrer\"... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1944/"
] | I have a few sites on a shared host that is running Apache 2. I would like to compress the HTML, CSS and Javascript that is delivered to the browser. The host has disabled mod\_deflate and mod\_gzip, so these options are out. I do have PHP 5 at my disposal, though, so I could use the gzip component of that.
I am currently placing the following in my .htaccess file:
>
> php\_value output\_handler ob\_gzhandler
>
>
>
However, this only compresses the HTML and leaves out the CSS and JS.
Is there a reliable way of transparently compressing the output of the CSS and JS without having to change every page? I have searched Google and a number of solutions are presented, but I've yet to get one to work. If anyone could suggest a solution that they know to work, that would be very gratefully received.
Note, **Method 2** in **[The Definitive Post on Gzipping your CSS](http://www.fiftyfoureleven.com/weblog/web-development/css/the-definitive-css-gzip-method)** looks like a good solution, but I couldn't get it working. Has anyone else succeeded using this method? | Sorry about the delay - it's a busy week for me.
Assumptions:
* `.htaccess` is in the same file as `compress.php`
* static files to be compressed are in `static` subdirectory
I started my solution from setting the following directives in .htaccess:
```
RewriteEngine on
RewriteRule ^static/.+\.(js|ico|gif|jpg|jpeg|png|css|swf)$ compress.php [NC]
```
It's required that your provider allows you to override `mod_rewrite` options in `.htaccess` files.
Then the compress.php file itself can look like this:
```
<?php
$basedir = realpath( dirname($_SERVER['SCRIPT_FILENAME']) );
$file = realpath( $basedir . $_SERVER["REQUEST_URI"] );
if( !file_exists($file) && strpos($file, $basedir) === 0 ) {
header("HTTP/1.0 404 Not Found");
print "File does not exist.";
exit();
}
$components = split('\.', basename($file));
$extension = strtolower( array_pop($components) );
switch($extension)
{
case 'css':
$mime = "text/css";
break;
default:
$mime = "text/plain";
}
header( "Content-Type: " . $mime );
readfile($file);
```
You should of course add more mime types to the switch statement. I didn't want to make the solution dependant on the pecl `fileinfo` extension or any other magical mime type detecting libraries - this is the simplest approach.
As for securing the script - I do a translation to a real path in the file system so no hacked '../../../etc/passwd' or other shellscript file paths don't go through.
That's the
```
$basedir = realpath( dirname($_SERVER['SCRIPT_FILENAME']) );
$file = realpath( $basedir . $_SERVER["REQUEST_URI"] );
```
snippet. Although I'm pretty sure most of the paths that are in other hierarchy than $basedir will get handled by the Apache before they even reach the script.
Also I check if the resulting path is inside the script's directory tree.
Add the headers for cache control as pilif suggested and you should have a working solution to your problem. |
48,567 | <p>I wrote a simple Windows Forms program in C#. I want to be able to input a windows user name and password and when I click a login button to run code run as the user I've entered as input.</p>
| [
{
"answer_id": 48571,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": true,
"text": "<p>You can use the WindowsIdentity.Impersonate method to \nachieve this. This method allows code to impersonate a different Windo... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360/"
] | I wrote a simple Windows Forms program in C#. I want to be able to input a windows user name and password and when I click a login button to run code run as the user I've entered as input. | You can use the WindowsIdentity.Impersonate method to
achieve this. This method allows code to impersonate a different Windows
user. Here is a link for more information on this method with a good sample:
<http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.impersonate.aspx>
Complete example:
```
// This sample demonstrates the use of the WindowsIdentity class to impersonate a user.
// IMPORTANT NOTES:
// This sample can be run only on Windows XP. The default Windows 2000 security policy
// prevents this sample from executing properly, and changing the policy to allow
// proper execution presents a security risk.
// This sample requests the user to enter a password on the console screen.
// Because the console window does not support methods allowing the password to be masked,
// it will be visible to anyone viewing the screen.
// The sample is intended to be executed in a .NET Framework 1.1 environment. To execute
// this code in a 1.0 environment you will need to use a duplicate token in the call to the
// WindowsIdentity constructor. See KB article Q319615 for more information.
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using System.Windows.Forms;
[assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode=true)]
[assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
public class ImpersonationDemo
{
[DllImport("advapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)]
private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource,
int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr *Arguments);
[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
// Test harness.
// If you incorporate this code into a DLL, be sure to demand FullTrust.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public static void Main(string[] args)
{
IntPtr tokenHandle = new IntPtr(0);
IntPtr dupeTokenHandle = new IntPtr(0);
try
{
string userName, domainName;
// Get the user token for the specified user, domain, and password using the
// unmanaged LogonUser method.
// The local machine name can be used for the domain name to impersonate a user on this machine.
Console.Write("Enter the name of the domain on which to log on: ");
domainName = Console.ReadLine();
Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
userName = Console.ReadLine();
Console.Write("Enter the password for {0}: ", userName);
const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
tokenHandle = IntPtr.Zero;
// Call LogonUser to obtain a handle to an access token.
bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
ref tokenHandle);
Console.WriteLine("LogonUser called.");
if (false == returnValue)
{
int ret = Marshal.GetLastWin32Error();
Console.WriteLine("LogonUser failed with error code : {0}", ret);
throw new System.ComponentModel.Win32Exception(ret);
}
Console.WriteLine("Did LogonUser Succeed? " + (returnValue? "Yes" : "No"));
Console.WriteLine("Value of Windows NT token: " + tokenHandle);
// Check the identity.
Console.WriteLine("Before impersonation: "
+ WindowsIdentity.GetCurrent().Name);
// Use the token handle returned by LogonUser.
WindowsIdentity newId = new WindowsIdentity(tokenHandle);
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
// Check the identity.
Console.WriteLine("After impersonation: "
+ WindowsIdentity.GetCurrent().Name);
// Stop impersonating the user.
impersonatedUser.Undo();
// Check the identity.
Console.WriteLine("After Undo: " + WindowsIdentity.GetCurrent().Name);
// Free the tokens.
if (tokenHandle != IntPtr.Zero)
CloseHandle(tokenHandle);
}
catch(Exception ex)
{
Console.WriteLine("Exception occurred. " + ex.Message);
}
}
}
``` |
48,570 | <p>I would like to implement something similar to a c# delegate method in PHP. A quick word to explain what I'm trying to do overall: I am trying to implement some asynchronous functionality. Basically, some resource-intensive calls that get queued, cached and dispatched when the underlying system gets around to it. When the asynchronous call finally receives a response I would like a callback event to be raised.</p>
<p>I am having some problems coming up with a mechanism to do callbacks in PHP. I have come up with a method that works for now but I am unhappy with it. Basically, it involves passing a reference to the object and the name of the method on it that will serve as the callback (taking the response as an argument) and then use eval to call the method when need be. This is sub-optimal for a variety of reasons, is there a better way of doing this that anyone knows of? </p>
| [
{
"answer_id": 48585,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": 2,
"selected": false,
"text": "<p>How do you feel about using the <a href=\"http://en.wikipedia.org/wiki/Observer_Pattern\" rel=\"nofollow noreferre... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | I would like to implement something similar to a c# delegate method in PHP. A quick word to explain what I'm trying to do overall: I am trying to implement some asynchronous functionality. Basically, some resource-intensive calls that get queued, cached and dispatched when the underlying system gets around to it. When the asynchronous call finally receives a response I would like a callback event to be raised.
I am having some problems coming up with a mechanism to do callbacks in PHP. I have come up with a method that works for now but I am unhappy with it. Basically, it involves passing a reference to the object and the name of the method on it that will serve as the callback (taking the response as an argument) and then use eval to call the method when need be. This is sub-optimal for a variety of reasons, is there a better way of doing this that anyone knows of? | (Apart from the observer pattern) you can also use [`call_user_func()`](http://php.net/manual/function.call-user-func.php) or [`call_user_func_array()`](http://php.net/manual/function.call-user-func-array.php).
If you pass an `array(obj, methodname)` as first parameter it will invoked as `$obj->methodname()`.
```
<?php
class Foo {
public function bar($x) {
echo $x;
}
}
function xyz($cb) {
$value = rand(1,100);
call_user_func($cb, $value);
}
$foo = new Foo;
xyz( array($foo, 'bar') );
?>
``` |
48,578 | <p>Not entirely sure what's going on here; any help would be appreciated.</p>
<p>I'm trying to create a new .NET MVC web app. I was pretty sure I had it set up correctly, but I'm getting the following error:</p>
<pre><code>The type 'System.Web.Mvc.ViewPage' is ambiguous: it could come from assembly
'C:\MyProject\bin\System.Web.Mvc.DLL' or from assembly
'C:\MyProject\bin\MyProject.DLL'. Please specify the assembly explicitly in the type name.
</code></pre>
<p>The source error it reports is as follows:</p>
<pre><code>Line 1: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
Line 2:
Line 3: <asp:Content ID="indexContent" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
</code></pre>
<p>Anything stand out that I'm doing completely wrong?</p>
| [
{
"answer_id": 48581,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 1,
"selected": false,
"text": "<p>This error usually indicates a class naming conflict. You are referencing two namespaces or you created a class with t... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1540/"
] | Not entirely sure what's going on here; any help would be appreciated.
I'm trying to create a new .NET MVC web app. I was pretty sure I had it set up correctly, but I'm getting the following error:
```
The type 'System.Web.Mvc.ViewPage' is ambiguous: it could come from assembly
'C:\MyProject\bin\System.Web.Mvc.DLL' or from assembly
'C:\MyProject\bin\MyProject.DLL'. Please specify the assembly explicitly in the type name.
```
The source error it reports is as follows:
```
Line 1: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
Line 2:
Line 3: <asp:Content ID="indexContent" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
```
Anything stand out that I'm doing completely wrong? | Are you using a CodeBehind file, I don't see CodeBehind="" attribute where you are specifying the Inherits from? Then you have to point inherits to the class name of the codebehind.
Example:
```
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication4.Views.Home.Index" %>
```
Make sure the Inherits is fully qualified. It should be the namespace followed by the class name. |
48,616 | <p>How do I set a property of a user control in <code>ListView</code>'s <code>LayoutTemplate</code> from the code-behind?</p>
<pre><code><asp:ListView ...>
<LayoutTemplate>
<myprefix:MyControl id="myControl" ... />
</LayoutTemplate>
...
</asp:ListView>
</code></pre>
<p>I want to do this:</p>
<pre><code>myControl.SomeProperty = somevalue;
</code></pre>
<p>Please notice that my control is not in <code>ItemTemplate</code>, it is in <code>LayoutTemplate</code>, so it does not exist for all items, it exists only once. So I should be able to access it once, not for every data bound item.</p>
| [
{
"answer_id": 48636,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 1,
"selected": false,
"text": "<p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.control.findcontrol.aspx\" rel=\"nofollow noreferr... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] | How do I set a property of a user control in `ListView`'s `LayoutTemplate` from the code-behind?
```
<asp:ListView ...>
<LayoutTemplate>
<myprefix:MyControl id="myControl" ... />
</LayoutTemplate>
...
</asp:ListView>
```
I want to do this:
```
myControl.SomeProperty = somevalue;
```
Please notice that my control is not in `ItemTemplate`, it is in `LayoutTemplate`, so it does not exist for all items, it exists only once. So I should be able to access it once, not for every data bound item. | To set a property of a control that is inside the LayoutTemplate, simply use the FindControl method on the ListView control.
```
var control = (MyControl)myListView.FindControl("myControlId");
``` |
48,642 | <p>I want to write a command that specifies "the word under the cursor" in VIM. For instance, let's say I have the cursor on a word and I make it appear twice. For instance, if the word is "abc" and I want "abcabc" then I could type: </p>
<pre><code>:s/\(abc\)/\1\1/
</code></pre>
<p>But then I'd like to be able to move the cursor to "def" and use the same command to change it to "defdef": </p>
<pre><code>:s/\(def\)/\1\1/
</code></pre>
<p>How can I write the command in the commandline so that it does this?</p>
<pre><code>:s/\(*whatever is under the commandline*\)/\1\1
</code></pre>
| [
{
"answer_id": 48657,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 7,
"selected": true,
"text": "<p><code><cword></code> is the word under the cursor (:help <code><cword></code>).</p>\n\n<p>Sorry, I should have b... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
] | I want to write a command that specifies "the word under the cursor" in VIM. For instance, let's say I have the cursor on a word and I make it appear twice. For instance, if the word is "abc" and I want "abcabc" then I could type:
```
:s/\(abc\)/\1\1/
```
But then I'd like to be able to move the cursor to "def" and use the same command to change it to "defdef":
```
:s/\(def\)/\1\1/
```
How can I write the command in the commandline so that it does this?
```
:s/\(*whatever is under the commandline*\)/\1\1
``` | `<cword>` is the word under the cursor (:help `<cword>`).
Sorry, I should have been more complete in this answer.
You can nmap a command to it, or this series of keystrokes for the lazy will work:
```
b #go to beginning of current word
yw #yank to register
```
Then, when you are typing in your pattern you can hit `<control-r>0<enter>` which will paste in your command the contents of the 0-th register.
You can also make a command for this like:
```
:nmap <leader>w :s/\(<c-r>=expand("<cword>")<cr>\)/
```
Which will map hitting '\' and 'w' at the same time to replace your command line with
```
:s/\(<currentword>\)/
``` |
48,668 | <p>I've seen lots of descriptions how anonymous types work, but I'm not sure how they're really useful. What are some scenarios that anonymous types can be used to address in a well-designed program?</p>
| [
{
"answer_id": 48672,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "<p>When you create types for 'Use and throw' purposes. \nThis seems to have come due to LINQ. Seems to be a way to create struc... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | I've seen lots of descriptions how anonymous types work, but I'm not sure how they're really useful. What are some scenarios that anonymous types can be used to address in a well-designed program? | Anonymous types have nothing to do with the design of systems or even at the class level. They're a tool for developers to use when coding.
I don't even treat anonymous types as types per-se. I use them mainly as method-level anonymous tuples. If I query the database and then manipulate the results, I would rather create an anonymous type and use that rather than declare a whole new type that will never be used or known outside of the scope of my method.
For instance:
```
var query = from item in database.Items
// ...
select new { Id = item.Id, Name = item.Name };
return query.ToDictionary(item => item.Id, item => item.Name);
```
Nobody cares about `a, the anonymous type. It's there so you don't have to declare another class. |
48,669 | <p>I receive HTML pages from our creative team, and then use those to build aspx pages. One challenge I frequently face is getting the HTML I spit out to match theirs exactly. I almost always end up screwing up the nesting of <code><div></code>s between my page and the master pages.</p>
<p>Does anyone know of a tool that will help in this situation -- something that will compare 2 pages and output the structural differences? I can't use a standard diff tool, because IDs change from what I receive from creative, text replaces <i>lorem ipsum</i>, etc.. </p>
| [
{
"answer_id": 48674,
"author": "DrFloyd5",
"author_id": 1736623,
"author_profile": "https://Stackoverflow.com/users/1736623",
"pm_score": 2,
"selected": false,
"text": "<p>If out output XML compliant HTML. Or at least translate your HTML product into XML compliancy, you at least could t... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757/"
] | I receive HTML pages from our creative team, and then use those to build aspx pages. One challenge I frequently face is getting the HTML I spit out to match theirs exactly. I almost always end up screwing up the nesting of `<div>`s between my page and the master pages.
Does anyone know of a tool that will help in this situation -- something that will compare 2 pages and output the structural differences? I can't use a standard diff tool, because IDs change from what I receive from creative, text replaces *lorem ipsum*, etc.. | You can use [HTMLTidy](http://tidy.sourceforge.net/) to convert the HTML to well-formed XML so you can use [XML Diff](http://msdn.microsoft.com/en-us/library/aa302294.aspx), as Gulzar suggested.
```
tidy -asxml index.html
``` |
48,680 | <p>Say I have a <code>Textbox</code> nested within a <code>TabControl</code>. </p>
<p>When the form loads, I would like to focus on that <code>Textbox</code> (by default the focus is set to the <code>TabControl</code>).</p>
<p>Simply calling <code>textbox1.focus()</code> in the <code>Load</code> event of the form does not appear to work. </p>
<p>I have been able to focus it by doing the following:</p>
<pre><code> private void frmMainLoad(object sender, EventArgs e)
{
foreach (TabPage tab in this.tabControl1.TabPages)
{
this.tabControl1.SelectedTab = tab;
}
}
</code></pre>
<p><strong>My question is:</strong></p>
<p>Is there a more elegant way to do this?</p>
| [
{
"answer_id": 48719,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 7,
"selected": true,
"text": "<p>The following is the solution:</p>\n\n<pre><code>private void frmMainLoad(object sender, EventArgs e)\n{\n ActiveContr... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736/"
] | Say I have a `Textbox` nested within a `TabControl`.
When the form loads, I would like to focus on that `Textbox` (by default the focus is set to the `TabControl`).
Simply calling `textbox1.focus()` in the `Load` event of the form does not appear to work.
I have been able to focus it by doing the following:
```
private void frmMainLoad(object sender, EventArgs e)
{
foreach (TabPage tab in this.tabControl1.TabPages)
{
this.tabControl1.SelectedTab = tab;
}
}
```
**My question is:**
Is there a more elegant way to do this? | The following is the solution:
```
private void frmMainLoad(object sender, EventArgs e)
{
ActiveControl = textBox1;
}
```
The better question would however be why... I'm not entirely sure what the answer to that one is.
Edit: I suspect it is something to do with the fact that both the form, and the TabControl are containers, but I'm not sure. |
48,744 | <h2>How do you find the phone numbers in 50,000 HTML pages?<br><br></h2>
<blockquote>
<h3>Jeff Attwood posted 5 Questions for programmers applying for jobs:</h3>
<p>In an effort to make life simpler for phone screeners, I've put together
this list of Five Essential Questions
that you need to ask during an SDE
screen. They won't guarantee that your
candidate will be great, but they will
help eliminate a huge number of
candidates who are slipping through
our process today.</p>
<p><strong>1) Coding</strong> The candidate has to write
some simple code, with correct syntax,
in C, C++, or Java.</p>
<p><strong>2) OO design</strong> The candidate has to
define basic OO concepts, and come up
with classes to model a simple
problem.</p>
<p><strong>3) Scripting and regexes</strong> The
candidate has to describe how to find
the phone numbers in 50,000 HTML
pages.</p>
<p><strong>4) Data structures</strong> The candidate has
to demonstrate basic knowledge of the
most common data structures.</p>
<p><strong>5) Bits and bytes</strong> The candidate has
to answer simple questions about bits,
bytes, and binary numbers.</p>
<p>Please understand: what I'm looking
for here is a total vacuum in one of
these areas. It's OK if they struggle
a little and then figure it out. It's
OK if they need some minor hints or
prompting. I don't mind if they're
rusty or slow. What you're looking for
is candidates who are utterly
clueless, or horribly confused, about
the area in question.</p>
<p><strong><a href="http://www.codinghorror.com/blog/archives/001042.html" rel="noreferrer">>>> The Entirety of Jeff´s Original Post <<<</a></strong></p>
</blockquote>
<p><br>
<strong>Note:</strong> Steve Yegge originally posed the Question.</p>
| [
{
"answer_id": 48767,
"author": "Ande Turner",
"author_id": 4857,
"author_profile": "https://Stackoverflow.com/users/4857",
"pm_score": 1,
"selected": false,
"text": "<h2>Perl Solution</h2>\n<p>By: "MH" via codinghorror,com on September 5, 2008 07:29 AM</p>\n<pre><code>#!/usr/b... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
] | How do you find the phone numbers in 50,000 HTML pages?
-------------------------------------------------------
>
> ### Jeff Attwood posted 5 Questions for programmers applying for jobs:
>
>
> In an effort to make life simpler for phone screeners, I've put together
> this list of Five Essential Questions
> that you need to ask during an SDE
> screen. They won't guarantee that your
> candidate will be great, but they will
> help eliminate a huge number of
> candidates who are slipping through
> our process today.
>
>
> **1) Coding** The candidate has to write
> some simple code, with correct syntax,
> in C, C++, or Java.
>
>
> **2) OO design** The candidate has to
> define basic OO concepts, and come up
> with classes to model a simple
> problem.
>
>
> **3) Scripting and regexes** The
> candidate has to describe how to find
> the phone numbers in 50,000 HTML
> pages.
>
>
> **4) Data structures** The candidate has
> to demonstrate basic knowledge of the
> most common data structures.
>
>
> **5) Bits and bytes** The candidate has
> to answer simple questions about bits,
> bytes, and binary numbers.
>
>
> Please understand: what I'm looking
> for here is a total vacuum in one of
> these areas. It's OK if they struggle
> a little and then figure it out. It's
> OK if they need some minor hints or
> prompting. I don't mind if they're
> rusty or slow. What you're looking for
> is candidates who are utterly
> clueless, or horribly confused, about
> the area in question.
>
>
> **[>>> The Entirety of Jeff´s Original Post <<<](http://www.codinghorror.com/blog/archives/001042.html)**
>
>
>
**Note:** Steve Yegge originally posed the Question. | ```
egrep "(([0-9]{1,2}.)?[0-9]{3}.[0-9]{3}.[0-9]{4})" . -R --include='*.html'
``` |
48,772 | <p>I have never "hand-coded" object creation code for SQL Server and foreign key decleration is seemingly different between SQL Server and Postgres. Here is my sql so far:</p>
<pre><code>drop table exams;
drop table question_bank;
drop table anwser_bank;
create table exams
(
exam_id uniqueidentifier primary key,
exam_name varchar(50),
);
create table question_bank
(
question_id uniqueidentifier primary key,
question_exam_id uniqueidentifier not null,
question_text varchar(1024) not null,
question_point_value decimal,
constraint question_exam_id foreign key references exams(exam_id)
);
create table anwser_bank
(
anwser_id uniqueidentifier primary key,
anwser_question_id uniqueidentifier,
anwser_text varchar(1024),
anwser_is_correct bit
);
</code></pre>
<p>When I run the query I get this error:</p>
<blockquote>
<p>Msg 8139, Level 16, State 0, Line 9
Number of referencing columns in
foreign key differs from number of
referenced columns, table
'question_bank'.</p>
</blockquote>
<p>Can you spot the error?</p>
| [
{
"answer_id": 48778,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 9,
"selected": true,
"text": "<pre><code>create table question_bank\n(\n question_id uniqueidentifier primary key,\n question_exam_id uniqueidentif... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | I have never "hand-coded" object creation code for SQL Server and foreign key decleration is seemingly different between SQL Server and Postgres. Here is my sql so far:
```
drop table exams;
drop table question_bank;
drop table anwser_bank;
create table exams
(
exam_id uniqueidentifier primary key,
exam_name varchar(50),
);
create table question_bank
(
question_id uniqueidentifier primary key,
question_exam_id uniqueidentifier not null,
question_text varchar(1024) not null,
question_point_value decimal,
constraint question_exam_id foreign key references exams(exam_id)
);
create table anwser_bank
(
anwser_id uniqueidentifier primary key,
anwser_question_id uniqueidentifier,
anwser_text varchar(1024),
anwser_is_correct bit
);
```
When I run the query I get this error:
>
> Msg 8139, Level 16, State 0, Line 9
> Number of referencing columns in
> foreign key differs from number of
> referenced columns, table
> 'question\_bank'.
>
>
>
Can you spot the error? | ```
create table question_bank
(
question_id uniqueidentifier primary key,
question_exam_id uniqueidentifier not null,
question_text varchar(1024) not null,
question_point_value decimal,
constraint fk_questionbank_exams foreign key (question_exam_id) references exams (exam_id)
);
``` |
48,774 | <p>What's the "right" way to do the following as a boolean expression?</p>
<pre><code>for i in `ls $1/resources`; do
if [ $i != "database.db" ]
then
if [ $i != "tiles" ]
then
if [ $i != "map.pdf" ]
then
if [ $i != "map.png" ]
then
svn export -q $1/resources/$i ../MyProject/Resources/$i
...
</code></pre>
| [
{
"answer_id": 48787,
"author": "frizz",
"author_id": 1003,
"author_profile": "https://Stackoverflow.com/users/1003",
"pm_score": 1,
"selected": false,
"text": "<pre><code>for i in `ls $1/resources`; do\n if [ $i != \"database.db\" ] && [ $i != \"tiles\" ] && [ $i != \... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/79/"
] | What's the "right" way to do the following as a boolean expression?
```
for i in `ls $1/resources`; do
if [ $i != "database.db" ]
then
if [ $i != "tiles" ]
then
if [ $i != "map.pdf" ]
then
if [ $i != "map.png" ]
then
svn export -q $1/resources/$i ../MyProject/Resources/$i
...
``` | The other solutions have a couple of common mistakes:
<http://www.pixelbeat.org/programming/shell_script_mistakes.html>
1. `for i in $(ls ...)` is redundant/problematic
just do: `for i in $1/resources*; do ...`
2. `[ $i != file1 -a $1 != file2 ]` This actually has 2 problems.
a. The `$i` is not quoted, hence names with spaces will cause issues
b. `-a` is inefficient if `stat`ing files as it doesn't short circuit (I know the above is not `stat`ing files).
So instead try:
```bsh
for i in $1/resources/*; do
if [ "$i" != "database.db" ] &&
[ "$i" != "tiles" ] &&
[ "$i" != "map.pdf" ] &&
[ "$i" != "map.png" ]; then
svn export -q "$i" "../MyProject/Resources/$(basename $i)"
fi
done
``` |
48,794 | <p>Here is a scenario: Let's say I have site with two controllers responsible for displaying different type of content - Pages and Articles. I need to embed Partial View into my masterpage that will list pages and articles filtered with some criteria, and be displayed on each page. I cannot set Model on my masterpage (am I right?). How do I solve this task using Html.RenderPartial?</p>
<p>[EDIT]
Yes, I'd probably create separate partial views for listing articles and pages, but still, there is a barrier that I cannot and shouldn't set model on masterpage. I need somehow to say "here are the pages" as an argument to my renderpartial, and also for articles. Entire concept of renderpartial with data from database in masterpages is a bit blurry to me.</p>
| [
{
"answer_id": 48821,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 0,
"selected": false,
"text": "<p>The ViewData Model property should only be used for the content that you're viewing/editing on the main section of t... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/481/"
] | Here is a scenario: Let's say I have site with two controllers responsible for displaying different type of content - Pages and Articles. I need to embed Partial View into my masterpage that will list pages and articles filtered with some criteria, and be displayed on each page. I cannot set Model on my masterpage (am I right?). How do I solve this task using Html.RenderPartial?
[EDIT]
Yes, I'd probably create separate partial views for listing articles and pages, but still, there is a barrier that I cannot and shouldn't set model on masterpage. I need somehow to say "here are the pages" as an argument to my renderpartial, and also for articles. Entire concept of renderpartial with data from database in masterpages is a bit blurry to me. | How about creating an HtmlHelper extension method that allows you to call a partial view result on the an action on the controller.
Something like
```
public static void RenderPartialAction<TController>(this HtmlHelper helper, Func<TController, PartialViewResult> actionToRender)
where TController : Controller, new()
{
var arg = new TController {ControllerContext = helper.ViewContext.Controller.ControllerContext};
actionToRender(arg).ExecuteResult(arg.ControllerContext);
}
```
you could then use this in your master page like
```
<% Html.RenderPartialAction((HomeController x) => x.RenderPartial()) %>
```
and in your controller the appropriate method
```
public PartialViewResult RenderPartial()
{
return PartialView("~/Path/or/View",_homeService.GetModel())
}
```
Well that is my 2 cents anyway |
48,872 | <p>In <a href="https://web.archive.org/web/20141127115939/https://blogs.msmvps.com/kathleen/2008/09/05/in-praise-of-nested-classes/" rel="noreferrer">Kathleen Dollard's 2008 blog post</a>, she presents an interesting reason to use nested classes in .net. However, she also mentions that FxCop doesn't like nested classes. I'm assuming that the people writing FxCop rules aren't stupid, so there must be reasoning behind that position, but I haven't been able to find it.</p>
| [
{
"answer_id": 48879,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 8,
"selected": true,
"text": "<p>Use a nested class when the class you are nesting is only useful to the enclosing class. For instance, nested classes allow ... | 2008/09/07 | [
"https://Stackoverflow.com/questions/48872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/100/"
] | In [Kathleen Dollard's 2008 blog post](https://web.archive.org/web/20141127115939/https://blogs.msmvps.com/kathleen/2008/09/05/in-praise-of-nested-classes/), she presents an interesting reason to use nested classes in .net. However, she also mentions that FxCop doesn't like nested classes. I'm assuming that the people writing FxCop rules aren't stupid, so there must be reasoning behind that position, but I haven't been able to find it. | Use a nested class when the class you are nesting is only useful to the enclosing class. For instance, nested classes allow you to write something like (simplified):
```
public class SortedMap {
private class TreeNode {
TreeNode left;
TreeNode right;
}
}
```
You can make a complete definition of your class in one place, you don't have to jump through any PIMPL hoops to define how your class works, and the outside world doesn't need to see anything of your implementation.
If the TreeNode class was external, you would either have to make all the fields `public` or make a bunch of `get/set` methods to use it. The outside world would have another class polluting their intellisense. |
48,908 | <p>I am a bit confused about socket programming in C.</p>
<p>You create a socket, bind it to an interface and an IP address and get it to listen. I found a couple of web resources on that, and understood it fine. In particular, I found an article <s><a href="http://users.actcom.co.il/~choo/lupg/tutorials/internetworking/internet-theory.html" rel="nofollow noreferrer">Network programming under Unix systems</a></s> to be very informative.</p>
<p>What confuses me is the timing of data arriving on the socket.</p>
<p>How can you tell when packets arrive, and how big the packet is, do you have to do all the heavy lifting yourself? </p>
<p>My basic assumption here is that packets can be of variable length, so once binary data starts appearing down the socket, how do you begin to construct packets from that?</p>
| [
{
"answer_id": 48910,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 2,
"selected": false,
"text": "<p>When you do a read on the socket, you tell it how many maximum bytes to read, but if it doesn't have that many, it gi... | 2008/09/08 | [
"https://Stackoverflow.com/questions/48908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] | I am a bit confused about socket programming in C.
You create a socket, bind it to an interface and an IP address and get it to listen. I found a couple of web resources on that, and understood it fine. In particular, I found an article ~~[Network programming under Unix systems](http://users.actcom.co.il/~choo/lupg/tutorials/internetworking/internet-theory.html)~~ to be very informative.
What confuses me is the timing of data arriving on the socket.
How can you tell when packets arrive, and how big the packet is, do you have to do all the heavy lifting yourself?
My basic assumption here is that packets can be of variable length, so once binary data starts appearing down the socket, how do you begin to construct packets from that? | Short answer is that you have to do all the heavy lifting yourself. You can be notified that there is data available to be read, but you won't know how many bytes are available. In most IP protocols that use variable length packets, there will be a header with a known fixed length prepended to the packet. This header will contain the length of the packet. You read the header, get the length of the packet, then read the packet. You repeat this pattern (read header, then read packet) until communication is complete.
When reading data from a socket, you request a certain number of bytes. The read call may block until the requested number of bytes are read, but it can return fewer bytes than what was requested. When this happens, you simply retry the read, requesting the remaining bytes.
Here's a typical C function for reading a set number of bytes from a socket:
```
/* buffer points to memory block that is bigger than the number of bytes to be read */
/* socket is open socket that is connected to a sender */
/* bytesToRead is the number of bytes expected from the sender */
/* bytesRead is a pointer to a integer variable that will hold the number of bytes */
/* actually received from the sender. */
/* The function returns either the number of bytes read, */
/* 0 if the socket was closed by the sender, and */
/* -1 if an error occurred while reading from the socket */
int readBytes(int socket, char *buffer, int bytesToRead, int *bytesRead)
{
*bytesRead = 0;
while(*bytesRead < bytesToRead)
{
int ret = read(socket, buffer + *bytesRead, bytesToRead - *bytesRead);
if(ret <= 0)
{
/* either connection was closed or an error occurred */
return ret;
}
else
{
*bytesRead += ret;
}
}
return *bytesRead;
}
``` |
48,916 | <p>I want a splash screen to show while the application is loading. I have a form with a system tray control tied to it. I want the splash screen to display while this form loads, which takes a bit of time since it's accessing a web service API to populate some drop-downs. I also want to do some basic testing for dependencies before loading (that is, the web service is available, the configuration file is readable). As each phase of the startup goes, I want to update the splash screen with progress.</p>
<p>I have been reading a lot on threading, but I am getting lost on where this should be controlled from (the <code>main()</code> method?). I am also missing how <code>Application.Run()</code> works, is this where the threads for this should be created from? Now, if the form with the system tray control is the "living" form, should the splash come from there? Wouldn't it not load until the form is completed anyway?</p>
<p>I'm not looking for a code handout, more of an algorithm/approach so I can figure this out once and for all :) </p>
| [
{
"answer_id": 48944,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 3,
"selected": false,
"text": "<p>One simple way is the use something like this as main():</p>\n\n<pre><code><STAThread()> Public Shared Sub Main()... | 2008/09/08 | [
"https://Stackoverflow.com/questions/48916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4246/"
] | I want a splash screen to show while the application is loading. I have a form with a system tray control tied to it. I want the splash screen to display while this form loads, which takes a bit of time since it's accessing a web service API to populate some drop-downs. I also want to do some basic testing for dependencies before loading (that is, the web service is available, the configuration file is readable). As each phase of the startup goes, I want to update the splash screen with progress.
I have been reading a lot on threading, but I am getting lost on where this should be controlled from (the `main()` method?). I am also missing how `Application.Run()` works, is this where the threads for this should be created from? Now, if the form with the system tray control is the "living" form, should the splash come from there? Wouldn't it not load until the form is completed anyway?
I'm not looking for a code handout, more of an algorithm/approach so I can figure this out once and for all :) | Well, for a ClickOnce app that I deployed in the past, we used the `Microsoft.VisualBasic` namespace to handle the splash screen threading. You can reference and use the `Microsoft.VisualBasic` assembly from C# in .NET 2.0 and it provides a lot of nice services.
1. Have the main form inherit from `Microsoft.VisualBasic.WindowsFormsApplicationBase`
2. Override the "OnCreateSplashScreen" method like so:
```
protected override void OnCreateSplashScreen()
{
this.SplashScreen = new SplashForm();
this.SplashScreen.TopMost = true;
}
```
Very straightforward, it shows your SplashForm (which you need to create) while loading is going on, then closes it automatically once the main form has completed loading.
This really makes things simple, and the `VisualBasic.WindowsFormsApplicationBase` is of course well tested by Microsoft and has a lot of functionality that can make your life a lot easier in Winforms, even in an application that is 100% C#.
At the end of the day, it's all IL and `bytecode` anyway, so why not use it? |
48,919 | <p>What is the JavaScript to scroll to the top when a button/link/etc. is clicked?</p>
| [
{
"answer_id": 48925,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 4,
"selected": true,
"text": "<pre><code><a href=\"javascript:scroll(0, 0)\">Top</a>\n</code></pre>\n"
},
{
"answer_id": 48939,
"... | 2008/09/08 | [
"https://Stackoverflow.com/questions/48919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
] | What is the JavaScript to scroll to the top when a button/link/etc. is clicked? | ```
<a href="javascript:scroll(0, 0)">Top</a>
``` |
48,931 | <p>I used jQuery to set hover callbacks for elements on my page. I'm now writing a module which needs to temporarily set new hover behaviour for some elements. The new module has no access to the original code for the hover functions.</p>
<p>I want to store the old hover functions before I set new ones so I can restore them when finished with the temporary hover behaviour.</p>
<p>I think these can be stored using the <code>jQuery.data()</code> function:</p>
<pre><code>//save old hover behavior (somehow)
$('#foo').data('oldhoverin',???)
$('#foo').data('oldhoverout',???);
//set new hover behavior
$('#foo').hover(newhoverin,newhoverout);
</code></pre>
<p>Do stuff with new hover behaviour...</p>
<pre><code>//restore old hover behaviour
$('#foo').hover($('#foo').data('oldhoverin'),$('#foo').data('oldhoverout'));
</code></pre>
<p>But how do I get the currently registered hover functions from jQuery?</p>
<p>Shadow2531, I am trying to do this without modifying the code which originally registered the callbacks. Your suggestion would work fine otherwise. Thanks for the suggestion, and for helping clarify what I'm searching for. Maybe I have to go into the source of jquery and figure out how these callbacks are stored internally. Maybe I should change the question to "Is it possible to do this without modifying jquery?"</p>
| [
{
"answer_id": 49042,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure if this is what you mean, but you can bind custom events and then trigger them.</p>\n\n<p><a href=\"http://docs... | 2008/09/08 | [
"https://Stackoverflow.com/questions/48931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5114/"
] | I used jQuery to set hover callbacks for elements on my page. I'm now writing a module which needs to temporarily set new hover behaviour for some elements. The new module has no access to the original code for the hover functions.
I want to store the old hover functions before I set new ones so I can restore them when finished with the temporary hover behaviour.
I think these can be stored using the `jQuery.data()` function:
```
//save old hover behavior (somehow)
$('#foo').data('oldhoverin',???)
$('#foo').data('oldhoverout',???);
//set new hover behavior
$('#foo').hover(newhoverin,newhoverout);
```
Do stuff with new hover behaviour...
```
//restore old hover behaviour
$('#foo').hover($('#foo').data('oldhoverin'),$('#foo').data('oldhoverout'));
```
But how do I get the currently registered hover functions from jQuery?
Shadow2531, I am trying to do this without modifying the code which originally registered the callbacks. Your suggestion would work fine otherwise. Thanks for the suggestion, and for helping clarify what I'm searching for. Maybe I have to go into the source of jquery and figure out how these callbacks are stored internally. Maybe I should change the question to "Is it possible to do this without modifying jquery?" | Calling an event `bind` method (such as `hover`) does not delete old event handlers, only adds your new events, so your idea of 'restoring' the old event functions wouldn't work, as it wouldn't delete your events.
You can add your own events, and then remove them without affecting any other events then use Event namespacing: <http://docs.jquery.com/Events_(Guide)#Namespacing_events> |
48,933 | <p>Does anybody know of a way to list up the "loaded plugins" in <strong>Vim</strong>?
I know I should be keeping track of this kind of stuff myself but
it would always be nice to be able to check the current status.</p>
| [
{
"answer_id": 48952,
"author": "Rob Rolnick",
"author_id": 4798,
"author_profile": "https://Stackoverflow.com/users/4798",
"pm_score": 10,
"selected": true,
"text": "<p>Not a VIM user myself, so forgive me if this is totally offbase. But according to what I gather from the following <a ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/48933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4037/"
] | Does anybody know of a way to list up the "loaded plugins" in **Vim**?
I know I should be keeping track of this kind of stuff myself but
it would always be nice to be able to check the current status. | Not a VIM user myself, so forgive me if this is totally offbase. But according to what I gather from the following [VIM Tips](http://rayninfo.co.uk/vimtips.html) site:
```
" where was an option set
:scriptnames : list all plugins, _vimrcs loaded (super)
:verbose set history? : reveals value of history and where set
:function : list functions
:func SearchCompl : List particular function
``` |
48,934 | <p>I copied some Delphi code from one project to another, and found that it doesn't compile in the new project, though it did in the old one. The code looks something like this:</p>
<pre><code>procedure TForm1.CalculateGP(..)
const
Price : money = 0;
begin
...
Price := 1.0;
...
end;
</code></pre>
<p>So in the new project, Delphi complains that "left side cannot be assigned to" - understandable! But this code compiles in the old project. So my question is, <strong>why</strong>? Is there a compiler switch to allow consts to be reassigned? How does that even work? I thought consts were replaced by their values at compile time?</p>
| [
{
"answer_id": 48938,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 6,
"selected": true,
"text": "<p>You need to turn assignable typed constants on.\n\nProject -> Options -> Compiler -> Assignable typed Constants</p>\n\n<p>Also yo... | 2008/09/08 | [
"https://Stackoverflow.com/questions/48934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
] | I copied some Delphi code from one project to another, and found that it doesn't compile in the new project, though it did in the old one. The code looks something like this:
```
procedure TForm1.CalculateGP(..)
const
Price : money = 0;
begin
...
Price := 1.0;
...
end;
```
So in the new project, Delphi complains that "left side cannot be assigned to" - understandable! But this code compiles in the old project. So my question is, **why**? Is there a compiler switch to allow consts to be reassigned? How does that even work? I thought consts were replaced by their values at compile time? | You need to turn assignable typed constants on.
Project -> Options -> Compiler -> Assignable typed Constants
Also you can add `{$J+}` or `{$WRITEABLECONST ON}` to the pas file, which is probably better, since it'll work even if you move the file to another project. |
48,935 | <p>I'm building an application in C# using WPF. How can I bind to some keys?</p>
<p>Also, how can I bind to the <a href="http://en.wikipedia.org/wiki/Windows_key" rel="noreferrer">Windows key</a>?</p>
| [
{
"answer_id": 48942,
"author": "John Virgolino",
"author_id": 4246,
"author_profile": "https://Stackoverflow.com/users/4246",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure about WPF, but this may help. I used the solution described in <em><a href=\"http://www.pinvoke.net/de... | 2008/09/08 | [
"https://Stackoverflow.com/questions/48935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146637/"
] | I'm building an application in C# using WPF. How can I bind to some keys?
Also, how can I bind to the [Windows key](http://en.wikipedia.org/wiki/Windows_key)? | I'm not sure of what you mean by "global" here, but here it goes (I'm assuming you mean a command at the application level, for example, *Save All* that can be triggered from anywhere by `Ctrl` + `Shift` + `S`.)
You find the global `UIElement` of your choice, for example, the top level window which is the parent of all the controls where you need this binding. Due to "bubbling" of WPF events, events at child elements will bubble all the way up to the root of the control tree.
Now, first you need
1. to bind the Key-Combo with a Command using an `InputBinding` like this
2. you can then hookup the command to your handler (e.g. code that gets called by `SaveAll`) via a `CommandBinding`.
For the `Windows` Key, you use the right [Key](http://msdn.microsoft.com/en-us/library/system.windows.input.key.aspx) enumerated member, **`Key.LWin`** or **`Key.RWin`**
```
public WindowMain()
{
InitializeComponent();
// Bind Key
var ib = new InputBinding(
MyAppCommands.SaveAll,
new KeyGesture(Key.S, ModifierKeys.Shift | ModifierKeys.Control));
this.InputBindings.Add(ib);
// Bind handler
var cb = new CommandBinding( MyAppCommands.SaveAll);
cb.Executed += new ExecutedRoutedEventHandler( HandlerThatSavesEverthing );
this.CommandBindings.Add (cb );
}
private void HandlerThatSavesEverthing (object obSender, ExecutedRoutedEventArgs e)
{
// Do the Save All thing here.
}
``` |
48,947 | <p>How are callbacks written in PHP?</p>
| [
{
"answer_id": 48948,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": 5,
"selected": false,
"text": "<p>Implementation of a callback is done like so</p>\n\n<pre><code>// This function uses a callback function. \nfuncti... | 2008/09/08 | [
"https://Stackoverflow.com/questions/48947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960/"
] | How are callbacks written in PHP? | The manual uses the terms "callback" and "callable" interchangeably, however, "callback" traditionally refers to a string or array value that acts like a [function pointer](http://en.wikipedia.org/wiki/Function_pointer), referencing a function or class method for future invocation. This has allowed some elements of functional programming since PHP 4. The flavors are:
```
$cb1 = 'someGlobalFunction';
$cb2 = ['ClassName', 'someStaticMethod'];
$cb3 = [$object, 'somePublicMethod'];
// this syntax is callable since PHP 5.2.3 but a string containing it
// cannot be called directly
$cb2 = 'ClassName::someStaticMethod';
$cb2(); // fatal error
// legacy syntax for PHP 4
$cb3 = array(&$object, 'somePublicMethod');
```
This is a safe way to use callable values in general:
```
if (is_callable($cb2)) {
// Autoloading will be invoked to load the class "ClassName" if it's not
// yet defined, and PHP will check that the class has a method
// "someStaticMethod". Note that is_callable() will NOT verify that the
// method can safely be executed in static context.
$returnValue = call_user_func($cb2, $arg1, $arg2);
}
```
Modern PHP versions allow the first three formats above to be invoked directly as `$cb()`. `call_user_func` and `call_user_func_array` support all the above.
See: <http://php.net/manual/en/language.types.callable.php>
Notes/Caveats:
1. If the function/class is namespaced, the string must contain the fully-qualified name. E.g. `['Vendor\Package\Foo', 'method']`
2. `call_user_func` does not support passing non-objects by reference, so you can either use `call_user_func_array` or, in later PHP versions, save the callback to a var and use the direct syntax: `$cb()`;
3. Objects with an [`__invoke()`](http://us2.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.invoke) method (including anonymous functions) fall under the category "callable" and can be used the same way, but I personally don't associate these with the legacy "callback" term.
4. The legacy `create_function()` creates a global function and returns its name. It's a wrapper for `eval()` and anonymous functions should be used instead. |
48,984 | <p>We're using WatiN for testing our UI, but one page (which is unfortunately not under our teams control) takes forever to finish loading. Is there a way to get WatiN to click a link on the page before the page finishes rendering completely?</p>
| [
{
"answer_id": 49136,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 5,
"selected": true,
"text": "<p>Here's the code we found to work:</p>\n\n<pre><code>IE browser = new IE(....);\nbrowser.Button(\"SlowPageLoadingButton... | 2008/09/08 | [
"https://Stackoverflow.com/questions/48984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
] | We're using WatiN for testing our UI, but one page (which is unfortunately not under our teams control) takes forever to finish loading. Is there a way to get WatiN to click a link on the page before the page finishes rendering completely? | Here's the code we found to work:
```
IE browser = new IE(....);
browser.Button("SlowPageLoadingButton").ClickNoWait();
Link continueLink = browser.Link(Find.ByText("linktext"));
continueLink.WaitUntilExists();
continueLink.Click();
``` |
48,993 | <p>I am wondering if anyone has any experience using a JQuery plugin that converts a html </p>
<pre><code><select>
<option> Blah </option>
</select>
</code></pre>
<p>combo box into something (probably a div) where selecting an item acts the same as clicking a link.</p>
<p>I guess you could probably use javascript to handle a selection event (my javascript knowledge is a little in disrepair at the moment) and 'switch' on the value of the combo box but this seems like more of a hack.</p>
<p>Your advice, experience and recommendations are appreciated.</p>
| [
{
"answer_id": 49027,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 0,
"selected": false,
"text": "<p>This bit of javascript in the 'select':</p>\n\n<pre><code>onchange=\"if(this.options[this.selectedIndex].value!=''){th... | 2008/09/08 | [
"https://Stackoverflow.com/questions/48993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | I am wondering if anyone has any experience using a JQuery plugin that converts a html
```
<select>
<option> Blah </option>
</select>
```
combo box into something (probably a div) where selecting an item acts the same as clicking a link.
I guess you could probably use javascript to handle a selection event (my javascript knowledge is a little in disrepair at the moment) and 'switch' on the value of the combo box but this seems like more of a hack.
Your advice, experience and recommendations are appreciated. | The simple solution is to use
```
$("#mySelect").change(function() {
document.location = this.value;
});
```
This creates an onchange event on the select box that redirects you to the url stored in the value field of the selected option. |
49,035 | <p>Given a declaration like this:</p>
<pre><code>class A {
public:
void Foo() const;
};
</code></pre>
<p>What does it mean?</p>
<p>Google turns up this:</p>
<blockquote>
<p>Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const, in can not be applied to a const object, and the compiler will give an error message.</p>
</blockquote>
<p>But I find that somewhat confusing; can anyone out there put it in better terms?</p>
<p>Thanks. </p>
| [
{
"answer_id": 49036,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 1,
"selected": false,
"text": "<p>that will cause the method to not be able to alter any member variables of the object</p>\n"
},
{
"answer_id": ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | Given a declaration like this:
```
class A {
public:
void Foo() const;
};
```
What does it mean?
Google turns up this:
>
> Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const, in can not be applied to a const object, and the compiler will give an error message.
>
>
>
But I find that somewhat confusing; can anyone out there put it in better terms?
Thanks. | Consider a variation of your class `A`.
```
class A {
public:
void Foo() const;
void Moo();
private:
int m_nState; // Could add mutable keyword if desired
int GetState() const { return m_nState; }
void SetState(int val) { m_nState = val; }
};
const A *A1 = new A();
A *A2 = new A();
A1->Foo(); // OK
A2->Foo(); // OK
A1->Moo(); // Error - Not allowed to call non-const function on const object instance
A2->Moo(); // OK
```
The `const` keyword on a function declaration indicates to the compiler that the function is contractually obligated not to modify the state of `A`. Thus you are unable to call non-`const` functions within `A::Foo` nor change the value of member variables.
To illustrate, *Foo()* may not invoke `A::SetState` as it is declared non-`const`, `A::GetState` however is ok because it is explicitly declared `const`. The member `m_nState` may not be changed either unless declared with the keyword `mutable`.
One example of this usage of `const` is for 'getter' functions to obtain the value of member variables.
>
> @1800 Information: I forgot about mutable!
>
>
>
The `mutable` keyword instructs the compiler to accept modifications to the member variable which would otherwise cause a compiler error. It is used when the function needs to modify state but the object is considered logically consistent (constant) regardless of the modification. |
49,046 | <p>Why does <code>n</code> not equal to <code>8</code> in the following function?</p>
<pre><code>void foo(char cvalue[8])
{
int n = sizeof (cvalue);
}
</code></pre>
<p>But <code>n</code> <em>does</em> equal to <code>8</code> in this version of the function:</p>
<pre><code>void bar()
{
char cvalue[8];
int n = sizeof (cvalue);
}
</code></pre>
| [
{
"answer_id": 49055,
"author": "Nick Retallack",
"author_id": 2653,
"author_profile": "https://Stackoverflow.com/users/2653",
"pm_score": 7,
"selected": true,
"text": "<p>Because you can't pass entire arrays as function parameters in C. You're actually passing a pointer to it; the brac... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5065/"
] | Why does `n` not equal to `8` in the following function?
```
void foo(char cvalue[8])
{
int n = sizeof (cvalue);
}
```
But `n` *does* equal to `8` in this version of the function:
```
void bar()
{
char cvalue[8];
int n = sizeof (cvalue);
}
``` | Because you can't pass entire arrays as function parameters in C. You're actually passing a pointer to it; the brackets are syntactic sugar. There are no guarantees the array you're pointing to has size 8, since you could pass this function any character pointer you want.
```
// These all do the same thing
void foo(char cvalue[8])
void foo(char cvalue[])
void foo(char *cvalue)
``` |
49,098 | <p>So I have a function that looks something like this:</p>
<pre><code>float function(){
float x = SomeValue;
return x / SomeOtherValue;
}
</code></pre>
<p>At some point, this function overflows and returns a really large negative value. To try and track down exactly where this was happening, I added a cout statement so that the function looked like this:</p>
<pre><code>float function(){
float x = SomeValue;
cout << x;
return x / SomeOtherValue;
}
</code></pre>
<p>and it worked! Of course, I solved the problem altogether by using a double. But I'm curious as to why the function worked properly when I couted it. Is this typical, or could there be a bug somewhere else that I'm missing?</p>
<p>(If it's any help, the value stored in the float is just an integer value, and not a particularly big one. I just put it in a float to avoid casting.)</p>
| [
{
"answer_id": 49120,
"author": "David Dibben",
"author_id": 5022,
"author_profile": "https://Stackoverflow.com/users/5022",
"pm_score": 2,
"selected": false,
"text": "<p>Printing a value to cout should not change the value of the paramter in any way at all.</p>\n\n<p>However, I have see... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] | So I have a function that looks something like this:
```
float function(){
float x = SomeValue;
return x / SomeOtherValue;
}
```
At some point, this function overflows and returns a really large negative value. To try and track down exactly where this was happening, I added a cout statement so that the function looked like this:
```
float function(){
float x = SomeValue;
cout << x;
return x / SomeOtherValue;
}
```
and it worked! Of course, I solved the problem altogether by using a double. But I'm curious as to why the function worked properly when I couted it. Is this typical, or could there be a bug somewhere else that I'm missing?
(If it's any help, the value stored in the float is just an integer value, and not a particularly big one. I just put it in a float to avoid casting.) | Welcome to the wonderful world of floating point. The answer you get will likely depend on the floating point model you compiled the code with.
This happens because of the difference between the IEEE spec and the hardware the code is running on. Your CPU likely has 80 bit floating point registers that get use to hold the 32-bit float value. This means that there is far more precision while the value stays in a register than when it is forced to a memory address (also known as 'homing' the register).
When you passed the value to cout the compiler had to write the floating point to memory, and this results in a lost of precision and interesting behaviour WRT overflow cases.
See the MSDN documentation on VC++ [floating point switches](http://msdn.microsoft.com/en-us/library/e7s85ffb(VS.80).aspx). You could try compiling with /fp:strict and seeing what happens. |
49,107 | <p>Actionscript 3.0 (and I assume Javascript and ECMAScript in general) lacks pass-by-reference for native types like ints. As a result I'm finding getting values back from a function really clunky. What's the normal pattern to work around this? </p>
<p>For example, is there a clean way to implement <em>swap( intA, intB )</em> in Actionscript?</p>
| [
{
"answer_id": 49109,
"author": "Nick Retallack",
"author_id": 2653,
"author_profile": "https://Stackoverflow.com/users/2653",
"pm_score": -1,
"selected": false,
"text": "<p>If ActionScript works like Javascript,</p>\n\n<pre><code>[a,b] = [b,a]\n</code></pre>\n"
},
{
"answer_id":... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4969/"
] | Actionscript 3.0 (and I assume Javascript and ECMAScript in general) lacks pass-by-reference for native types like ints. As a result I'm finding getting values back from a function really clunky. What's the normal pattern to work around this?
For example, is there a clean way to implement *swap( intA, intB )* in Actionscript? | I Believe the best you can do is pass a container object as an argument to a function and change the values of some properties in that object:
```
function swapAB(aValuesContainer:Object):void
{
if (!(aValuesContainer.hasOwnProperty("a") && aValuesContainer.hasOwnProperty("b")))
throw new ArgumentError("aValuesContainer must have properties a and b");
var tempValue:int = aValuesContainer["a"];
aValuesContainer["a"] = aValuesContainer["b"];
aValuesContainer["b"] = tempValue;
}
var ints:Object = {a:13, b:25};
swapAB(ints);
``` |
49,110 | <p>I'm looking for the basic loop like:</p>
<pre><code>for(int i = 0; i < MAX; i++) {
doSomething(i);
}
</code></pre>
<p>but for Bash.</p>
| [
{
"answer_id": 49111,
"author": "Rob Rolnick",
"author_id": 4798,
"author_profile": "https://Stackoverflow.com/users/4798",
"pm_score": 8,
"selected": true,
"text": "<p>From <a href=\"http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html\" rel=\"noreferrer\">this site</a>:</p>\n\n<pre><code... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535/"
] | I'm looking for the basic loop like:
```
for(int i = 0; i < MAX; i++) {
doSomething(i);
}
```
but for Bash. | From [this site](http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html):
```
for i in $(seq 1 10);
do
echo $i
done
``` |
49,147 | <p>I have just installed C# for the first time, and at first glance it appears to be very similar to VB6. I decided to start off by trying to make a 'Hello, World!' UI Edition.</p>
<p>I started in the Form Designer and made a button named "Click Me!" proceeded to double-click it and typed in</p>
<pre><code>MessageBox("Hello, World!");
</code></pre>
<p>I received the following error:</p>
<p>MessageBox is a 'type' but used as a 'variable'</p>
<p>Fair enough, it seems in C# MessageBox is an Object. I tried the following</p>
<pre><code>MessageBox a = new MessageBox("Hello, World!");
</code></pre>
<p>I received the following error:
MessageBox does not contain a constructor that takes '1' arguments</p>
<p>Now I am stumped. Please help.</p>
| [
{
"answer_id": 49151,
"author": "moobaa",
"author_id": 3569,
"author_profile": "https://Stackoverflow.com/users/3569",
"pm_score": 5,
"selected": false,
"text": "<p>Code summary:</p>\n\n<pre><code>using System.Windows.Forms;\n\n...\n\nMessageBox.Show( \"hello world\" );\n</code></pre>\n\... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4960/"
] | I have just installed C# for the first time, and at first glance it appears to be very similar to VB6. I decided to start off by trying to make a 'Hello, World!' UI Edition.
I started in the Form Designer and made a button named "Click Me!" proceeded to double-click it and typed in
```
MessageBox("Hello, World!");
```
I received the following error:
MessageBox is a 'type' but used as a 'variable'
Fair enough, it seems in C# MessageBox is an Object. I tried the following
```
MessageBox a = new MessageBox("Hello, World!");
```
I received the following error:
MessageBox does not contain a constructor that takes '1' arguments
Now I am stumped. Please help. | MessageBox.Show also returns a DialogResult, which if you put some buttons on there, means you can have it returned what the user clicked. Most of the time I write something like
```
if (MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) {
//some interesting behaviour here
}
```
which I guess is a bit unwieldy but it gets the job done.
See <https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.dialogresult> for additional enum options you can use here. |
49,158 | <p>I've got quite a few GreaseMonkey scripts that I wrote at my work which automatically log me into the internal sites we have here. I've managed to write a script for nearly each one of these sites except for our time sheet application, which uses HTTP authentication. </p>
<p>Is there a way I can use GreaseMonkey to log me into this site automatically?</p>
<p>Edit: I am aware of the store password functionality in browsers, but my scripts go a step further by checking if I'm logged into the site when it loads (by traversing HTML) and then submitting a post to the login page. This removes the step of having to load up the site, entering the login page, entering my credentials, then hitting submit</p>
| [
{
"answer_id": 49188,
"author": "Garo Yeriazarian",
"author_id": 2655,
"author_profile": "https://Stackoverflow.com/users/2655",
"pm_score": 1,
"selected": false,
"text": "<p>Why don't you use Firefox (I assume you're using Firefox) to remember your credentials using the Password Manager... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3847/"
] | I've got quite a few GreaseMonkey scripts that I wrote at my work which automatically log me into the internal sites we have here. I've managed to write a script for nearly each one of these sites except for our time sheet application, which uses HTTP authentication.
Is there a way I can use GreaseMonkey to log me into this site automatically?
Edit: I am aware of the store password functionality in browsers, but my scripts go a step further by checking if I'm logged into the site when it loads (by traversing HTML) and then submitting a post to the login page. This removes the step of having to load up the site, entering the login page, entering my credentials, then hitting submit | It is possible to log in using HTTP authentication by setting the "Authorization" HTTP header, with the value of this header set to the string "basic username:password", but with the "username:password" portion of the string Base 64 encoded.
<http://frontier.userland.com/stories/storyReader$2159>
A bit of researching found that GreaseMonkey has a a function built into it where you can send GET / POST requests to the server called GM\_xmlhttpRequest
<http://diveintogreasemonkey.org/api/gm_xmlhttprequest.html>
So putting it all together (and also getting this JavaScript code to convert strings into base64 I get the following
<http://www.webtoolkit.info/javascript-base64.html>
```
var loggedInText = document.getElementById('metanav').firstChild.firstChild.innerHTML;
if (loggedInText != "logged in as jklp") {
var username = 'jklp';
var password = 'jklpPass';
var base64string = Base64.encode(username + ":" + password);
GM_xmlhttpRequest({
method: 'GET',
url: 'http://foo.com/trac/login',
headers: {
'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey/0.3',
'Accept': 'application/atom+xml,application/xml,text/xml',
'Authorization':'Basic ' + base64string,
}
});
}
```
So when I now visit the site, it traverses the DOM and if I'm not logged in, it automagically logs me in. |
49,166 | <p>I've inherited a hoary old piece of code (by hoary, I mean warty with lots of undocumented bug fixes than WTF-y) and there's one part that's giving me a bit of trouble. Here's how it connects to the remote registry to get the add/remove programs key:</p>
<pre><code>try
{
remoteKey = RegistryKey.OpenRemoteBaseKey(
RegistryHive.LocalMachine, addr.Value).OpenSubKey(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
return 1;
}
catch (IOException e)
{
IOException myexception = e;
//Console.WriteLine("{0}: {1}: {2}",
// e.GetType().Name, e.Message, addr.Value);
return 2;
}
catch (UnauthorizedAccessException e)
{
UnauthorizedAccessException myexception = e;
//Console.WriteLine("{0}: {1}: {2}",
// e.GetType().Name, e.Message, addr.Value);
return 3;
}
catch (System.Security.SecurityException e)
{
System.Security.SecurityException myexception = e;
//Console.WriteLine("{0}: {1}: {2}",
// e.GetType().Name, e.Message, addr.Value);
return 4;
}
</code></pre>
<p>Now, I have two problems:</p>
<ul>
<li><p>I know why the IOException - if it's a non-Windows machine it'll throw that. The difference between UnauthorizedAccessException and SecurityException I'm not so clear on. Anyone got any ideas?</p></li>
<li><p>This entire bit of code was designed before anyone had thought you might not use your local logon for everything. I can't work out how you do authentication for remotely connecting to the registry, anyway, and this code looks like it's only used in one case, when it can't get this information from WMI.</p></li>
</ul>
<p>Any help with either would be great.</p>
| [
{
"answer_id": 49176,
"author": "Garo Yeriazarian",
"author_id": 2655,
"author_profile": "https://Stackoverflow.com/users/2655",
"pm_score": 1,
"selected": false,
"text": "<p>You probably have to use impersonation to change the credentials of the thread that calls the remote registry met... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5133/"
] | I've inherited a hoary old piece of code (by hoary, I mean warty with lots of undocumented bug fixes than WTF-y) and there's one part that's giving me a bit of trouble. Here's how it connects to the remote registry to get the add/remove programs key:
```
try
{
remoteKey = RegistryKey.OpenRemoteBaseKey(
RegistryHive.LocalMachine, addr.Value).OpenSubKey(
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall");
return 1;
}
catch (IOException e)
{
IOException myexception = e;
//Console.WriteLine("{0}: {1}: {2}",
// e.GetType().Name, e.Message, addr.Value);
return 2;
}
catch (UnauthorizedAccessException e)
{
UnauthorizedAccessException myexception = e;
//Console.WriteLine("{0}: {1}: {2}",
// e.GetType().Name, e.Message, addr.Value);
return 3;
}
catch (System.Security.SecurityException e)
{
System.Security.SecurityException myexception = e;
//Console.WriteLine("{0}: {1}: {2}",
// e.GetType().Name, e.Message, addr.Value);
return 4;
}
```
Now, I have two problems:
* I know why the IOException - if it's a non-Windows machine it'll throw that. The difference between UnauthorizedAccessException and SecurityException I'm not so clear on. Anyone got any ideas?
* This entire bit of code was designed before anyone had thought you might not use your local logon for everything. I can't work out how you do authentication for remotely connecting to the registry, anyway, and this code looks like it's only used in one case, when it can't get this information from WMI.
Any help with either would be great. | John's pointer to MSDN answered what UnauthorizedAccessException is for - it only appears when you try to access a key remotely, using OpenRemoteBaseKey.
We're a little wary about changing the security context on the computer - I've found a reference [here](http://vbcity.com/forums/topic.asp?tid=43510) about using WMI (which we're already using for the vast majority of the heavy lifting) to access the registry, so I might try that instead. |
49,194 | <p>I have an action like this:</p>
<pre><code>public class News : System.Web.Mvc.Controller
{
public ActionResult Archive(int year)
{
/ *** /
}
}
</code></pre>
<p>With a route like this:</p>
<pre><code>routes.MapRoute(
"News-Archive",
"News.mvc/Archive/{year}",
new { controller = "News", action = "Archive" }
);
</code></pre>
<p>The URL that I am on is:</p>
<pre><code>News.mvc/Archive/2008
</code></pre>
<p>I have a form on this page like this:</p>
<pre><code><form>
<select name="year">
<option value="2007">2007</option>
</select>
</form>
</code></pre>
<p>Submitting the form should go to News.mvc/Archive/2007 if '2007' is selected in the form.</p>
<p>This requires the form 'action' attribute to be "News.mvc/Archive".</p>
<p>However, if I declare a form like this:</p>
<pre><code><form method="get" action="<%=Url.RouteUrl("News-Archive")%>">
</code></pre>
<p>it renders as:</p>
<pre><code><form method="get" action="/News.mvc/Archive/2008">
</code></pre>
<p>Can someone please let me know what I'm missing?</p>
| [
{
"answer_id": 49197,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 3,
"selected": true,
"text": "<p>You have a couple problems, I think.</p>\n\n<p>First, your route doesn't have a default value for \"year\", so the URL ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | I have an action like this:
```
public class News : System.Web.Mvc.Controller
{
public ActionResult Archive(int year)
{
/ *** /
}
}
```
With a route like this:
```
routes.MapRoute(
"News-Archive",
"News.mvc/Archive/{year}",
new { controller = "News", action = "Archive" }
);
```
The URL that I am on is:
```
News.mvc/Archive/2008
```
I have a form on this page like this:
```
<form>
<select name="year">
<option value="2007">2007</option>
</select>
</form>
```
Submitting the form should go to News.mvc/Archive/2007 if '2007' is selected in the form.
This requires the form 'action' attribute to be "News.mvc/Archive".
However, if I declare a form like this:
```
<form method="get" action="<%=Url.RouteUrl("News-Archive")%>">
```
it renders as:
```
<form method="get" action="/News.mvc/Archive/2008">
```
Can someone please let me know what I'm missing? | You have a couple problems, I think.
First, your route doesn't have a default value for "year", so the URL "/News.mvc/Archive" is actually not valid for routing purposes.
Second, you're expect form values to show up as route parameters, but that's not how HTML works. If you use a plain form with a select and a submit, your URLs will end up having "?year=2007" on the end of them. This is just how GET-method forms are designed to work in HTML.
So you need to come to some conclusion about what's important.
* If you want the user to be able to select something from the dropdown and that changes the submission URL, then you're going to have to use Javascript to achieve this (by intercepting the form submit and formulating the correct URL).
* If you're okay with /News.mvc/Archive?year=2007 as your URL, then you should remove the {year} designator from the route entirely. You can still leave the "int year" parameter on your action, since form values will also populate action method parameters. |
49,211 | <p>I have an existing application that is written in C++ for Windows. This application uses the Win32 CryptoAPI to generate a TripleDES session key for encrypting/decrypting data. We're using the <a href="http://www.phdcc.com/cryptorc4.htm" rel="nofollow noreferrer">exponent of one trick</a> to export the session key out as a blob, which allows the blob to be stored somewhere in a decrypted format.</p>
<p>The question is how can we use this in our .NET application (C#). The framework encapsulates/wraps much of what the CryptoAPI is doing. Part of the problem is the CryptAPI states that the TripleDES algorithm for the <a href="http://msdn.microsoft.com/en-us/library/aa386986(VS.85).aspx" rel="nofollow noreferrer">Microsoft Enhanced Cryptographic Provider</a> is 168 bits (3 keys of 56 bits). However, the .NET framework states their keys are 192 bits (3 keys of 64 bits). Apparently, the 3 extra bytes in the .NET framework is for parity?</p>
<p>Anyway, we need to read the key portion out of the blob and somehow be able to use that in our .NET application. Currently we are not getting the expected results when attempting to use the key in .NET. The decryption is failing miserably. Any help would be greatly appreciated. </p>
<h2>Update:</h2>
<p>I've been working on ways to resolve this and have come up with a solution that I will post in time. However, still would appreciate any feedback from others.</p>
| [
{
"answer_id": 49232,
"author": "Nic Strong",
"author_id": 2281,
"author_profile": "https://Stackoverflow.com/users/2281",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, forget the last answer I can't read :) You are working with 3Des keys not RSA keys.</p>\n\n<p>I worked on a bunch o... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4916/"
] | I have an existing application that is written in C++ for Windows. This application uses the Win32 CryptoAPI to generate a TripleDES session key for encrypting/decrypting data. We're using the [exponent of one trick](http://www.phdcc.com/cryptorc4.htm) to export the session key out as a blob, which allows the blob to be stored somewhere in a decrypted format.
The question is how can we use this in our .NET application (C#). The framework encapsulates/wraps much of what the CryptoAPI is doing. Part of the problem is the CryptAPI states that the TripleDES algorithm for the [Microsoft Enhanced Cryptographic Provider](http://msdn.microsoft.com/en-us/library/aa386986(VS.85).aspx) is 168 bits (3 keys of 56 bits). However, the .NET framework states their keys are 192 bits (3 keys of 64 bits). Apparently, the 3 extra bytes in the .NET framework is for parity?
Anyway, we need to read the key portion out of the blob and somehow be able to use that in our .NET application. Currently we are not getting the expected results when attempting to use the key in .NET. The decryption is failing miserably. Any help would be greatly appreciated.
Update:
-------
I've been working on ways to resolve this and have come up with a solution that I will post in time. However, still would appreciate any feedback from others. | Intro
-----
I'm Finally getting around to posting the solution. I hope it provides some help to others out there that might be doing similar type things. There really isn't much reference to doing this elsewhere.
Prerequisites
-------------
In order for a lot of this to make sense it's necessary to read the [*exponent of one trick*](http://www.phdcc.com/cryptorc4.htm), which allows you to export a session key out to a blob (a well known byte structure). One can then do what they wish with this byte stream, but it holds the all important key.
MSDN Documentation is Confusing
-------------------------------
In this particular example, I'm using the [Microsoft Enhanced Cryptographic Provider](http://msdn.microsoft.com/en-us/library/aa386986(VS.85).aspx), with the Triple DES ([CALG\_3DES](http://msdn.microsoft.com/en-us/library/aa382020(VS.85).aspx)) algorithm. The first thing that threw me for a loop was the fact that the key length is listed at 168 bits, with a block length of 64 bits. How can the key length be 168? Three keys of 56 bits? What happens to the other byte?
So with that information I started to read elsewhere how the last byte is really parity and for whatever reason CryptoAPI strips that off. Is that really the case? Seems kind of crazy that they would do that, but OK.
Consumption of Key in .NET
--------------------------
Using the [TripleDESCryptoServiceProvider](http://msdn.microsoft.com/en-us/library/system.security.cryptography.tripledescryptoserviceprovider(VS.80).aspx), I noticed the remarks in the docs indicated that:
>
> This algorithm supports key lengths from 128 bits to 192 bits in increments of 64 bits.
>
>
>
So if CryptoAPI has key lengths of 168, how will I get that into .NET which supports only supports multiples of 64? Therefore, the .NET side of the API takes parity into account, where the CryptoAPI does not. As one could imagine... *confused was I*.
So with all of this, I'm trying to figure out how to reconstruct the key on the .NET side with the proper parity information. Doable, but not very fun... let's just leave it at that. Once I got all of this in place, everything ended up failing with a CAPITAL **F**.
Still with me? Good, because I just fell off my horse again.
Light Bulbs and Fireworks
-------------------------
Low and behold, as I'm scraping MSDN for every last bit of information I find a conflicting piece in the Win32 [CryptExportKey](http://msdn.microsoft.com/en-us/library/aa379931(VS.85).aspx) function. Low and behold I find this piece of invaluble information:
>
> For any of the DES key permutations that use a PLAINTEXTKEYBLOB, only the full key size, including parity bit, may be exported. The following key sizes are supported.
>
>
> Algorithm Supported key size
>
>
> CALG\_DES 64 bits
>
>
> CALG\_3DES\_112 128 bits
>
>
> CALG\_3DES 192 bits
>
>
>
So it does export a key that is a multiple of 64 bits! Woohoo! Now to fix the code on the .NET side.
.NET Import Code Tweak
----------------------
The byte order is important to keep in mind when importing a byte stream that contains a key that was exported as a blob from the CryptoAPI. The two API's do not use the same byte order, therefore, as [@nic-strong](https://stackoverflow.com/questions/49211/how-can-i-use-a-key-blob-generated-from-win32-cryptoapi-in-my-net-application#49232) indicates, reversing the byte array is essential before actually trying to use the key. Other than that, things work as expected. Simply solved:
```
Array.Reverse( keyByteArray );
```
Conclusion
----------
I hope this helps somebody out there. I spent way too much time trying to track this down. Leave any comments if you have further questions and I can attempt to help fill in any details.
Happy Crypto! |
49,214 | <p>I need a list of integers from 1 to x where x is set by the user. I could build it with a for loop eg assuming x is an integer set previously:</p>
<pre><code>List<int> iList = new List<int>();
for (int i = 1; i <= x; i++)
{
iList.Add(i);
}
</code></pre>
<p>This seems dumb, surely there's a more elegant way to do this, something like the <a href="http://au2.php.net/manual/en/function.range.php" rel="noreferrer">PHP range method</a></p>
| [
{
"answer_id": 49216,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 6,
"selected": false,
"text": "<p>LINQ to the rescue:</p>\n\n<pre><code>// Adding value to existing list\nvar list = new List<int>();\nlist.AddRange(Enume... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
] | I need a list of integers from 1 to x where x is set by the user. I could build it with a for loop eg assuming x is an integer set previously:
```
List<int> iList = new List<int>();
for (int i = 1; i <= x; i++)
{
iList.Add(i);
}
```
This seems dumb, surely there's a more elegant way to do this, something like the [PHP range method](http://au2.php.net/manual/en/function.range.php) | If you're using .Net 3.5, [Enumerable.Range](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx) is what you need.
>
> Generates a sequence of integral
> numbers within a specified range.
>
>
> |
49,252 | <p>For a project I am working on in ruby I am overriding the method_missing method so that I can set variables using a method call like this, similar to setting variables in an ActiveRecord object:</p>
<p><code>Object.variable_name= 'new value'</code> </p>
<p>However, after implementing this I found out that many of the variable names have periods (.) in them. I have found this workaround:</p>
<p><code>Object.send('variable.name=', 'new value')</code></p>
<p>However, I am wondering is there a way to escape the period so that I can use</p>
<p><code>Object.variable.name= 'new value'</code></p>
| [
{
"answer_id": 49255,
"author": "Nick Retallack",
"author_id": 2653,
"author_profile": "https://Stackoverflow.com/users/2653",
"pm_score": 4,
"selected": true,
"text": "<p>Don't do it!</p>\n\n<p>Trying to create identifiers that are not valid in your language is not a good idea. If you r... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] | For a project I am working on in ruby I am overriding the method\_missing method so that I can set variables using a method call like this, similar to setting variables in an ActiveRecord object:
`Object.variable_name= 'new value'`
However, after implementing this I found out that many of the variable names have periods (.) in them. I have found this workaround:
`Object.send('variable.name=', 'new value')`
However, I am wondering is there a way to escape the period so that I can use
`Object.variable.name= 'new value'` | Don't do it!
Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros:
```
attr_writer :bar
attr_reader :baz
attr_accessor :foo
```
Okay, now that you have been warned, here's how to do it. Just return another instance of the same class every time you get a regular accessor, and collect the needed information as you go.
```
class SillySetter
def initialize path=nil
@path = path
end
def method_missing name,value=nil
new_path = @path ? "#{@path}.#{name}" : name
if name.to_s[-1] == ?=
puts "setting #{new_path} #{value}"
else
return self.class.new(path=new_path)
end
end
end
s = SillySetter.new
s.foo = 5 # -> setting foo= 5
s.foo.bar.baz = 4 # -> setting foo.bar.baz= 4
```
I didn't want to encourage ruby sillyness, but I just couldn't help myself! |
49,258 | <p>I am writing my first serious wxWidgets program. I'd like to use the wxConfig facility to make the program's user options persistent. However I <em>don't</em> want wxConfigBase to automatically use the Windows registry. Even though I'm initially targeting Windows, I'd prefer to use a configuration (eg .ini) file. Does anyone know a clean and simple way of doing this ? Thanks.</p>
| [
{
"answer_id": 49255,
"author": "Nick Retallack",
"author_id": 2653,
"author_profile": "https://Stackoverflow.com/users/2653",
"pm_score": 4,
"selected": true,
"text": "<p>Don't do it!</p>\n\n<p>Trying to create identifiers that are not valid in your language is not a good idea. If you r... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3955/"
] | I am writing my first serious wxWidgets program. I'd like to use the wxConfig facility to make the program's user options persistent. However I *don't* want wxConfigBase to automatically use the Windows registry. Even though I'm initially targeting Windows, I'd prefer to use a configuration (eg .ini) file. Does anyone know a clean and simple way of doing this ? Thanks. | Don't do it!
Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros:
```
attr_writer :bar
attr_reader :baz
attr_accessor :foo
```
Okay, now that you have been warned, here's how to do it. Just return another instance of the same class every time you get a regular accessor, and collect the needed information as you go.
```
class SillySetter
def initialize path=nil
@path = path
end
def method_missing name,value=nil
new_path = @path ? "#{@path}.#{name}" : name
if name.to_s[-1] == ?=
puts "setting #{new_path} #{value}"
else
return self.class.new(path=new_path)
end
end
end
s = SillySetter.new
s.foo = 5 # -> setting foo= 5
s.foo.bar.baz = 4 # -> setting foo.bar.baz= 4
```
I didn't want to encourage ruby sillyness, but I just couldn't help myself! |