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 |
|---|---|---|---|---|---|---|
20,952 | <p>I'm trying to unit test a custom ConfigurationSection I've written, and I'd like to load some arbitrary configuration XML into a <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx" rel="noreferrer">System.Configuration.Configuration</a> for each test (rather than put the test configuration xml in the Tests.dll.config file. That is, I'd like to do something like this:</p>
<pre><code>Configuration testConfig = new Configuration("<?xml version=\"1.0\"?><configuration>...</configuration>");
MyCustomConfigSection section = testConfig.GetSection("mycustomconfigsection");
Assert.That(section != null);
</code></pre>
<p>However, it looks like <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx" rel="noreferrer">ConfigurationManager</a> will only give you Configuration instances that are associated with an EXE file or a machine config. Is there a way to load arbitrary XML into a Configuration instance?</p>
| [
{
"answer_id": 21005,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 0,
"selected": false,
"text": "<p>Looking at the members of the class, I'd say the answer is probably no*. I'm not sure why you'd want to do this any... | 2008/08/21 | [
"https://Stackoverflow.com/questions/20952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2338/"
] | I'm trying to unit test a custom ConfigurationSection I've written, and I'd like to load some arbitrary configuration XML into a [System.Configuration.Configuration](http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx) for each test (rather than put the test configuration xml in the Tests.dll.config file. That is, I'd like to do something like this:
```
Configuration testConfig = new Configuration("<?xml version=\"1.0\"?><configuration>...</configuration>");
MyCustomConfigSection section = testConfig.GetSection("mycustomconfigsection");
Assert.That(section != null);
```
However, it looks like [ConfigurationManager](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx) will only give you Configuration instances that are associated with an EXE file or a machine config. Is there a way to load arbitrary XML into a Configuration instance? | There is actually a way I've discovered....
You need to define a new class inheriting from your original configuration section as follows:
```
public class MyXmlCustomConfigSection : MyCustomConfigSection
{
public MyXmlCustomConfigSection (string configXml)
{
XmlTextReader reader = new XmlTextReader(new StringReader(configXml));
DeserializeSection(reader);
}
}
```
You can then instantiate your ConfigurationSection object as follows:
```
string configXml = "<?xml version=\"1.0\"?><configuration>...</configuration>";
MyCustomConfigSection config = new MyXmlCustomConfigSection(configXml);
```
Hope it helps someone :-) |
20,959 | <p>How can I determine all of the assemblies that my .NET desktop application has loaded? I'd like to put them in the about box so I can query customers over the phone to determine what version of XYZ they have on their PC.</p>
<p>It would be nice to see both managed and unmanaged assemblies. I realize the list will get long but I plan to slap an incremental search on it.</p>
| [
{
"answer_id": 20970,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 0,
"selected": false,
"text": "<p>Looks like <code>AppDomain.CurrentDomain.GetAssemblies();</code> will do the trick :)</p>\n"
},
{
"answer_id": 20974,... | 2008/08/21 | [
"https://Stackoverflow.com/questions/20959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1490/"
] | How can I determine all of the assemblies that my .NET desktop application has loaded? I'd like to put them in the about box so I can query customers over the phone to determine what version of XYZ they have on their PC.
It would be nice to see both managed and unmanaged assemblies. I realize the list will get long but I plan to slap an incremental search on it. | ```
using System;
using System.Reflection;
using System.Windows.Forms;
public class MyAppDomain
{
public static void Main(string[] args)
{
AppDomain ad = AppDomain.CurrentDomain;
Assembly[] loadedAssemblies = ad.GetAssemblies();
Console.WriteLine("Here are the assemblies loaded in this appdomain\n");
foreach(Assembly a in loadedAssemblies)
{
Console.WriteLine(a.FullName);
}
}
}
``` |
20,998 | <p>When I try to create a SQL Server Login by saying</p>
<pre><code>CREATE LOGIN [ourdomain\SQLAccessGroup] FROM WINDOWS;
</code></pre>
<p>I get this error</p>
<blockquote>
<p>The server principal 'ourdomain\SQLAccessGroup' already exists.</p>
</blockquote>
<p>However, when I try this code</p>
<pre><code>DROP LOGIN [ourdomain\SQLAccessGroup]
</code></pre>
<p>I get this error</p>
<blockquote>
<p>Cannot drop the login 'ourdomain\SQLAccessGroup', because it does not exist or you do not have permission.</p>
</blockquote>
<p>The user that I am executing this code as is a sysadmin. Additionally, the user <code>ourdomain\SQLAccessGroup</code> does not show up in this query</p>
<pre><code>select * from sys.server_principals
</code></pre>
<p>Does anyone have any ideas?</p>
| [
{
"answer_id": 21074,
"author": "Pete",
"author_id": 76,
"author_profile": "https://Stackoverflow.com/users/76",
"pm_score": 4,
"selected": true,
"text": "<p>We are still struggling to understand the <em>HOW</em> of this issue, but it seems that [ourdomain\\SQLAccessGroup] was aliased by... | 2008/08/21 | [
"https://Stackoverflow.com/questions/20998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/76/"
] | When I try to create a SQL Server Login by saying
```
CREATE LOGIN [ourdomain\SQLAccessGroup] FROM WINDOWS;
```
I get this error
>
> The server principal 'ourdomain\SQLAccessGroup' already exists.
>
>
>
However, when I try this code
```
DROP LOGIN [ourdomain\SQLAccessGroup]
```
I get this error
>
> Cannot drop the login 'ourdomain\SQLAccessGroup', because it does not exist or you do not have permission.
>
>
>
The user that I am executing this code as is a sysadmin. Additionally, the user `ourdomain\SQLAccessGroup` does not show up in this query
```
select * from sys.server_principals
```
Does anyone have any ideas? | We are still struggling to understand the *HOW* of this issue, but it seems that [ourdomain\SQLAccessGroup] was aliased by a consultant to a different user name (this is part of an MS CRM installation). We finally were able to use some logic and some good old SID comparisons to determine who was playing the imposter game.
Our hint came when I tried to add the login as a user to the database (since it supposedly already existed) and got this error:
```
The login already has an account under a different user name.
```
So, I started to examine each DB user and was able to figure out the culprit. I eventually tracked it down and was able to rename the user and login so that the CRM install would work. I wonder if I can bill them $165.00 an hour for my time... :-) |
21,052 | <p>When I'm working with DataBound controls in ASP.NET 2.0 such as a Repeater, I know the fastest way to retrieve a property of a bound object (instead of using Reflection with the Eval() function) is to cast the DataItem object to the type it is and then use that object natively, like the following:</p>
<pre><code><%#((MyType)Container.DataItem).PropertyOfMyType%>
</code></pre>
<p>The problem is, if this type is in a namespace (which is the case 99.99% of the time) then this single statement because a lot longer due to the fact that the ASP page has no concept of class scope so all of my types need to be fully qualified.</p>
<pre><code><%#((RootNamespace.SubNamespace1.SubNamspace2.SubNamespace3.MyType)Container.DataItem).PropertyOfMyType%>
</code></pre>
<p>Is there any kind of <code>using</code> directive or some equivalent I could place somewhere in an ASP.NET page so I don't need to use the full namespace every time?</p>
| [
{
"answer_id": 21056,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 7,
"selected": true,
"text": "<p>I believe you can add something like:</p>\n\n<pre><code><%@ Import Namespace=\"RootNamespace.SubNamespace1\" %> \n</code></... | 2008/08/21 | [
"https://Stackoverflow.com/questions/21052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] | When I'm working with DataBound controls in ASP.NET 2.0 such as a Repeater, I know the fastest way to retrieve a property of a bound object (instead of using Reflection with the Eval() function) is to cast the DataItem object to the type it is and then use that object natively, like the following:
```
<%#((MyType)Container.DataItem).PropertyOfMyType%>
```
The problem is, if this type is in a namespace (which is the case 99.99% of the time) then this single statement because a lot longer due to the fact that the ASP page has no concept of class scope so all of my types need to be fully qualified.
```
<%#((RootNamespace.SubNamespace1.SubNamspace2.SubNamespace3.MyType)Container.DataItem).PropertyOfMyType%>
```
Is there any kind of `using` directive or some equivalent I could place somewhere in an ASP.NET page so I don't need to use the full namespace every time? | I believe you can add something like:
```
<%@ Import Namespace="RootNamespace.SubNamespace1" %>
```
At the top of the page. |
21,060 | <p>I'm tired of being in the middle of typing something, having a pop-up with a question appear, and hitting enter before reading it... (it also happens with some windows that are not pop-ups)</p>
<p>Do you know if there's some setting I could touch for this not to happen?</p>
| [
{
"answer_id": 21056,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 7,
"selected": true,
"text": "<p>I believe you can add something like:</p>\n\n<pre><code><%@ Import Namespace=\"RootNamespace.SubNamespace1\" %> \n</code></... | 2008/08/21 | [
"https://Stackoverflow.com/questions/21060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | I'm tired of being in the middle of typing something, having a pop-up with a question appear, and hitting enter before reading it... (it also happens with some windows that are not pop-ups)
Do you know if there's some setting I could touch for this not to happen? | I believe you can add something like:
```
<%@ Import Namespace="RootNamespace.SubNamespace1" %>
```
At the top of the page. |
21,078 | <p>What's the most efficient way to concatenate strings?</p>
| [
{
"answer_id": 21084,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 2,
"selected": false,
"text": "<p>The most efficient is to use StringBuilder, like so:</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nsb.... | 2008/08/21 | [
"https://Stackoverflow.com/questions/21078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2358/"
] | What's the most efficient way to concatenate strings? | The `StringBuilder.Append()` method is much better than using the `+` operator. But I've found that, when executing 1000 concatenations or less, `String.Join()` is even more efficient than `StringBuilder`.
```
StringBuilder sb = new StringBuilder();
sb.Append(someString);
```
The only problem with `String.Join` is that you have to concatenate the strings with a common delimiter.
**Edit:** as *@ryanversaw* pointed out, you can make the delimiter `string.Empty`.
```
string key = String.Join("_", new String[]
{ "Customers_Contacts", customerID, database, SessionID });
``` |
21,133 | <p>What's the easiest way to profile a PHP script?</p>
<p>I'd love tacking something on that shows me a dump of all function calls and how long they took but I'm also OK with putting something around specific functions.</p>
<p>I tried experimenting with the <a href="http://php.net/microtime" rel="noreferrer">microtime</a> function:</p>
<pre><code>$then = microtime();
myFunc();
$now = microtime();
echo sprintf("Elapsed: %f", $now-$then);
</code></pre>
<p>but that sometimes gives me negative results. Plus it's a lot of trouble to sprinkle that all over my code.</p>
| [
{
"answer_id": 21139,
"author": "Eric Lamb",
"author_id": 538,
"author_profile": "https://Stackoverflow.com/users/538",
"pm_score": 3,
"selected": false,
"text": "<p>I like to use phpDebug for profiling.\n<a href=\"http://phpdebug.sourceforge.net/www/index.html\" rel=\"noreferrer\">http:... | 2008/08/21 | [
"https://Stackoverflow.com/questions/21133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | What's the easiest way to profile a PHP script?
I'd love tacking something on that shows me a dump of all function calls and how long they took but I'm also OK with putting something around specific functions.
I tried experimenting with the [microtime](http://php.net/microtime) function:
```
$then = microtime();
myFunc();
$now = microtime();
echo sprintf("Elapsed: %f", $now-$then);
```
but that sometimes gives me negative results. Plus it's a lot of trouble to sprinkle that all over my code. | The [PECL APD](http://www.php.net/apd) extension is used as follows:
```
<?php
apd_set_pprof_trace();
//rest of the script
?>
```
After, parse the generated file using `pprofp`.
Example output:
```
Trace for /home/dan/testapd.php
Total Elapsed Time = 0.00
Total System Time = 0.00
Total User Time = 0.00
Real User System secs/ cumm
%Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name
--------------------------------------------------------------------------------------
100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main
56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace
28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 preg_replace
14.3 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 str_replace
```
**Warning: the latest release of APD is dated 2004, the extension [is no longer maintained](https://pecl.php.net/package/apd) and has various compability issues (see comments).** |
21,184 | <p>I've got a System.Generic.Collections.List(Of MyCustomClass) type object.</p>
<p>Given integer varaibles pagesize and pagenumber, how can I query only any single page of MyCustomClass objects?</p>
| [
{
"answer_id": 21389,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 6,
"selected": true,
"text": "<p>If you have your linq-query that contains all the rows you want to display, this code can be used:</p>\n\n<pre><code>var pageN... | 2008/08/21 | [
"https://Stackoverflow.com/questions/21184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | I've got a System.Generic.Collections.List(Of MyCustomClass) type object.
Given integer varaibles pagesize and pagenumber, how can I query only any single page of MyCustomClass objects? | If you have your linq-query that contains all the rows you want to display, this code can be used:
```
var pageNum = 3;
var pageSize = 20;
query = query.Skip((pageNum - 1) * pageSize).Take(pageSize);
```
You can also make an extension method on the object to be able to write
```
query.Page(2,50)
```
to get the first 50 records of page 2. If that is want you want, the information is on the [solid code blog.](http://solidcoding.blogspot.com/2007/11/paging-with-linq.html) |
21,207 | <p>I'm currently trying out db4o (the java version) and I pretty much like what I see. But I cannot help wondering how it does perform in a real live (web-)environment. Does anyone have any experiences (good or bad) to share about running db4o? </p>
| [
{
"answer_id": 24499,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 7,
"selected": true,
"text": "<p>We run DB40 .NET version in a large client/server project.</p>\n\n<p>Our experiences is that you can potentiall... | 2008/08/21 | [
"https://Stackoverflow.com/questions/21207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1562/"
] | I'm currently trying out db4o (the java version) and I pretty much like what I see. But I cannot help wondering how it does perform in a real live (web-)environment. Does anyone have any experiences (good or bad) to share about running db4o? | We run DB40 .NET version in a large client/server project.
Our experiences is that you can potentially get much better performance than typical relational databases.
However, you really have to tweak your objects to get this kind of performance. For example, if you've got a list containing a lot of objects, DB4O activation of these lists is slow. There are a number of ways to get around this problem, for example, by inverting the relationship.
Another pain is activation. When you retrieve or delete an object from DB4O, by default it will activate the whole object tree. For example, loading a Foo will load Foo.Bar.Baz.Bat, etc until there's nothing left to load. While this is nice from a programming standpoint, performance will slow down the more nesting in your objects. To improve performance, you can tell DB4O how many levels deep to activate. This is time-consuming to do if you've got a lot of objects.
Another area of pain was text searching. DB4O's text searching is far, far slower than SQL full text indexing. (They'll tell you this outright on their site.) The good news is, it's easy to setup a text searching engine on top of DB4O. On our project, we've hooked up Lucene.NET to index the text fields we want.
Some APIs don't seem to work, such as the GetField APIs useful in applying database upgrades. (For example, you've renamed a property and you want to upgrade your existing objects in the database, you need to use these "reflection" APIs to find objects in the database. Other APIs, such as the [Index] attribute don't work in the stable 6.4 version, and you must instead specify indexes using the Configure().Index("someField"), which is not strongly typed.
We've witnessed performance degrade the larger your database. We have a 1GB database right now and things are still fast, but not nearly as fast as when we started with a tiny database.
We've found another issue where Db4O.GetByID will close the database if the ID doesn't exist anymore in the database.
We've found the Native Query syntax (the most natural, language-integrated syntax for queries) is far, far slower than the less-friendly SODA queries. So instead of typing:
```
// C# syntax for "Find all MyFoos with Bar == 23".
// (Note the Java syntax is more verbose using the Predicate class.)
IList<MyFoo> results = db4o.Query<MyFoo>(input => input.Bar == 23);
```
Instead of that nice query code, you have to an ugly SODA query which is string-based and not strongly-typed.
For .NET folks, they've recently introduced a LINQ-to-DB4O provider, which provides for the best syntax yet. However, it's yet to be seen whether performance will be up-to-par with the ugly SODA queries.
DB4O support has been decent: we've talked to them on the phone a number of times and have received helpful info. Their user forums are next to worthless, however, almost all questions go unanswered. Their JIRA bug tracker receives a lot of attention, so if you've got a nagging bug, file it on JIRA on it often will get fixed. (We've had 2 bugs that have been fixed, and another one that got patched in a half-assed way.)
If all this hasn't scared you off, let me say that we're very happy with DB4O, despite the problems we've encountered. The performance we've got has blown away some O/RM frameworks we tried. I recommend it.
**update July 2015** Keep in mind, this answer was written back in 2008. While I appreciate the upvotes, the world has changed since then, and this information may not be as reliable as it was when it was written. |
21,232 | <p>I've got a System.Generic.Collections.List(Of MyCustomClass) type object.</p>
<p>Given integer varaibles pagesize and pagenumber, how can I collect only any single page of <code>MyCustomClass</code> objects?</p>
<p>This is what I've got. How can I improve it?</p>
<pre><code>'my given collection and paging parameters
Dim AllOfMyCustomClassObjects As System.Collections.Generic.List(Of MyCustomClass) = GIVEN
Dim pagesize As Integer = GIVEN
Dim pagenumber As Integer = GIVEN
'collect current page objects
Dim PageObjects As New System.Collections.Generic.List(Of MyCustomClass)
Dim objcount As Integer = 1
For Each obj As MyCustomClass In AllOfMyCustomClassObjects
If objcount > pagesize * (pagenumber - 1) And count <= pagesize * pagenumber Then
PageObjects.Add(obj)
End If
objcount = objcount + 1
Next
'find total page count
Dim totalpages As Integer = CInt(Math.Floor(objcount / pagesize))
If objcount Mod pagesize > 0 Then
totalpages = totalpages + 1
End If
</code></pre>
| [
{
"answer_id": 21267,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "<p>You use GetRange on your IEnuramble implementing collection:</p>\n\n<pre><code>List<int> lolInts = new List<int&g... | 2008/08/21 | [
"https://Stackoverflow.com/questions/21232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | I've got a System.Generic.Collections.List(Of MyCustomClass) type object.
Given integer varaibles pagesize and pagenumber, how can I collect only any single page of `MyCustomClass` objects?
This is what I've got. How can I improve it?
```
'my given collection and paging parameters
Dim AllOfMyCustomClassObjects As System.Collections.Generic.List(Of MyCustomClass) = GIVEN
Dim pagesize As Integer = GIVEN
Dim pagenumber As Integer = GIVEN
'collect current page objects
Dim PageObjects As New System.Collections.Generic.List(Of MyCustomClass)
Dim objcount As Integer = 1
For Each obj As MyCustomClass In AllOfMyCustomClassObjects
If objcount > pagesize * (pagenumber - 1) And count <= pagesize * pagenumber Then
PageObjects.Add(obj)
End If
objcount = objcount + 1
Next
'find total page count
Dim totalpages As Integer = CInt(Math.Floor(objcount / pagesize))
If objcount Mod pagesize > 0 Then
totalpages = totalpages + 1
End If
``` | Generic.List should provide the Skip() and Take() methods, so you could do this:
```
Dim PageObjects As New System.Collections.Generic.List(Of MyCustomClass)
PageObjects = AllOfMyCustomClassObjects.Skip(pagenumber * pagesize).Take(pagesize)
```
---
If by "without Linq" you meant on the 2.0 Framework, I don't believe List(Of T) supports those methods. In that case, use GetRange like Jonathan suggested. |
21,265 | <p>What is the best method for comparing IEEE floats and doubles for equality? I have heard of several methods, but I wanted to see what the community thought.</p>
| [
{
"answer_id": 21277,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 4,
"selected": true,
"text": "<p>The best approach I think is to compare <a href=\"http://en.wikipedia.org/wiki/Unit_in_the_last_place\" rel=\"noreferrer\">... | 2008/08/21 | [
"https://Stackoverflow.com/questions/21265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2328/"
] | What is the best method for comparing IEEE floats and doubles for equality? I have heard of several methods, but I wanted to see what the community thought. | The best approach I think is to compare [ULPs](http://en.wikipedia.org/wiki/Unit_in_the_last_place).
```
bool is_nan(float f)
{
return (*reinterpret_cast<unsigned __int32*>(&f) & 0x7f800000) == 0x7f800000 && (*reinterpret_cast<unsigned __int32*>(&f) & 0x007fffff) != 0;
}
bool is_finite(float f)
{
return (*reinterpret_cast<unsigned __int32*>(&f) & 0x7f800000) != 0x7f800000;
}
// if this symbol is defined, NaNs are never equal to anything (as is normal in IEEE floating point)
// if this symbol is not defined, NaNs are hugely different from regular numbers, but might be equal to each other
#define UNEQUAL_NANS 1
// if this symbol is defined, infinites are never equal to finite numbers (as they're unimaginably greater)
// if this symbol is not defined, infinities are 1 ULP away from +/- FLT_MAX
#define INFINITE_INFINITIES 1
// test whether two IEEE floats are within a specified number of representable values of each other
// This depends on the fact that IEEE floats are properly ordered when treated as signed magnitude integers
bool equal_float(float lhs, float rhs, unsigned __int32 max_ulp_difference)
{
#ifdef UNEQUAL_NANS
if(is_nan(lhs) || is_nan(rhs))
{
return false;
}
#endif
#ifdef INFINITE_INFINITIES
if((is_finite(lhs) && !is_finite(rhs)) || (!is_finite(lhs) && is_finite(rhs)))
{
return false;
}
#endif
signed __int32 left(*reinterpret_cast<signed __int32*>(&lhs));
// transform signed magnitude ints into 2s complement signed ints
if(left < 0)
{
left = 0x80000000 - left;
}
signed __int32 right(*reinterpret_cast<signed __int32*>(&rhs));
// transform signed magnitude ints into 2s complement signed ints
if(right < 0)
{
right = 0x80000000 - right;
}
if(static_cast<unsigned __int32>(std::abs(left - right)) <= max_ulp_difference)
{
return true;
}
return false;
}
```
A similar technique can be used for doubles. The trick is to convert the floats so that they're ordered (as if integers) and then just see how different they are.
I have no idea why this damn thing is screwing up my underscores. Edit: Oh, perhaps that is just an artefact of the preview. That's OK then. |
21,280 | <p>I seem to be missing something about LINQ. To me, it looks like it's taking some of the elements of SQL that I like the least and moving them into the C# language and using them for other things.</p>
<p>I mean, I could see the benefit of using SQL-like statements on things other than databases. But if I wanted to write SQL, well, why not just write SQL and keep it out of C#? What am I missing here?</p>
| [
{
"answer_id": 21287,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 2,
"selected": false,
"text": "<p>The point is that LINQ integrates your queries into your primary programming language, allowing your IDE to provide... | 2008/08/21 | [
"https://Stackoverflow.com/questions/21280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] | I seem to be missing something about LINQ. To me, it looks like it's taking some of the elements of SQL that I like the least and moving them into the C# language and using them for other things.
I mean, I could see the benefit of using SQL-like statements on things other than databases. But if I wanted to write SQL, well, why not just write SQL and keep it out of C#? What am I missing here? | LINQ is not about SQL. LINQ is about being apply functional programming paradigmns on objects.
LINQ to SQL is an ORM built ontop of the LINQ foundation, but LINQ is much more. I don't use LINQ to SQL, yet I use LINQ all the time.
Take the task of finding the intersection of two lists:
Before LINQ, this tasks requires writing a nested foreach that iterates the small list once for every item in the big list O(N\*M), and takes about 10 lines of code.
```
foreach (int number in list1)
{
foreach (int number2 in list2)
{
if (number2 == number)
{
returnList.add(number2);
}
}
}
```
Using LINQ, it does the same thing in one line of code:
```
var results = list1.Intersect(list2);
```
You'll notice that doesn't look like LINQ, yet it is. You don't need to use the expression syntax if you don't want to. |
21,294 | <p>How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand.</p>
<p>The client that uses the component isn't required to load all the library script files (and manually insert <code><script></code> tags into their web page) that implement this component - just the 'main' component script file.</p>
<p><strong>How do mainstream JavaScript libraries accomplish this (Prototype, jQuery, etc)?</strong> Do these tools merge multiple JavaScript files into a single redistributable 'build' version of a script file? Or do they do any dynamic loading of ancillary 'library' scripts?</p>
<p>An addition to this question: <strong>is there a way to handle the event after a dynamically included JavaScript file is loaded?</strong> Prototype has <code>document.observe</code> for document-wide events. Example:</p>
<pre><code>document.observe("dom:loaded", function() {
// initially hide all containers for tab content
$$('div.tabcontent').invoke('hide');
});
</code></pre>
<p><strong>What are the available events for a script element?</strong></p>
| [
{
"answer_id": 21297,
"author": "Adam",
"author_id": 1341,
"author_profile": "https://Stackoverflow.com/users/1341",
"pm_score": 3,
"selected": false,
"text": "<p>Here is some example code I've found... does anyone have a better way?</p>\n\n<pre><code> function include(url)\n {\n va... | 2008/08/21 | [
"https://Stackoverflow.com/questions/21294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341/"
] | How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand.
The client that uses the component isn't required to load all the library script files (and manually insert `<script>` tags into their web page) that implement this component - just the 'main' component script file.
**How do mainstream JavaScript libraries accomplish this (Prototype, jQuery, etc)?** Do these tools merge multiple JavaScript files into a single redistributable 'build' version of a script file? Or do they do any dynamic loading of ancillary 'library' scripts?
An addition to this question: **is there a way to handle the event after a dynamically included JavaScript file is loaded?** Prototype has `document.observe` for document-wide events. Example:
```
document.observe("dom:loaded", function() {
// initially hide all containers for tab content
$$('div.tabcontent').invoke('hide');
});
```
**What are the available events for a script element?** | You may create a script element dynamically, using [Prototypes](http://www.prototypejs.org/):
```
new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"});
```
The problem here is that we do not know *when* the external script file is fully loaded.
We often want our dependant code on the very next line and like to write something like:
```
if (iNeedSomeMore) {
Script.load("myBigCodeLibrary.js"); // includes code for myFancyMethod();
myFancyMethod(); // cool, no need for callbacks!
}
```
There is a smart way to inject script dependencies without the need of callbacks. You simply have to pull the script via a *synchronous AJAX request* and eval the script on global level.
If you use Prototype the Script.load method looks like this:
```
var Script = {
_loadedScripts: [],
include: function(script) {
// include script only once
if (this._loadedScripts.include(script)) {
return false;
}
// request file synchronous
var code = new Ajax.Request(script, {
asynchronous: false,
method: "GET",
evalJS: false,
evalJSON: false
}).transport.responseText;
// eval code on global level
if (Prototype.Browser.IE) {
window.execScript(code);
} else if (Prototype.Browser.WebKit) {
$$("head").first().insert(Object.extend(
new Element("script", {
type: "text/javascript"
}), {
text: code
}
));
} else {
window.eval(code);
}
// remember included script
this._loadedScripts.push(script);
}
};
``` |
21,303 | <p>VC++ makes functions which are implemented within the class declaration inline functions.</p>
<p>If I declare a class <code>Foo</code> as follows, then are the CONSTRUCTOR and DESTRUCTOR inline functions?</p>
<pre><code>class Foo
{
int* p;
public:
Foo() { p = new char[0x00100000]; }
~Foo() { delete [] p; }
};
{
Foo f;
(f);
}
</code></pre>
| [
{
"answer_id": 21322,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": true,
"text": "<p>Defining the body of the constructor INSIDE the class has the same effect as placing the function OUTSIDE the class with the ... | 2008/08/21 | [
"https://Stackoverflow.com/questions/21303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1556/"
] | VC++ makes functions which are implemented within the class declaration inline functions.
If I declare a class `Foo` as follows, then are the CONSTRUCTOR and DESTRUCTOR inline functions?
```
class Foo
{
int* p;
public:
Foo() { p = new char[0x00100000]; }
~Foo() { delete [] p; }
};
{
Foo f;
(f);
}
``` | Defining the body of the constructor INSIDE the class has the same effect as placing the function OUTSIDE the class with the "inline" keyword.
In both cases it's a hint to the compiler. An "inline" function doesn't necessarily mean the function will be inlined. That depends on the complexity of the function and other rules. |
21,448 | <p>I have an SSIS package that exports data to a couple of Excel files for transfer to a third party. To get this to run as a scheduled job on a 64-bit server I understand that I need to set the step as a CmdExec type and call the 32-bit version of DTExec. But I don't seem to be able to get the command right to pass in the connection string for the Excel files.</p>
<p>So far I have this: </p>
<pre><code>DTExec.exe /SQL \PackageName /SERVER OUR2005SQLSERVER /CONNECTION
LETTER_Excel_File;\""Provider=Microsoft.Jet.OLEDB.4.0";"Data
Source=""C:\Temp\BaseFiles\LETTER.xls";"Extended Properties=
""Excel 8.0;HDR=Yes"" /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING E
</code></pre>
<p>This gives me the error: <strong><code>Option "Properties=Excel 8.0;HDR=Yes" is not valid.</code></strong></p>
<p>I've tried a few variations with the Quotation marks but have not been able to get it right yet.</p>
<p>Does anyone know how to fix this?</p>
<p><strong><code>UPDATE:</code></strong></p>
<p>Thanks for your help but I've decided to go with CSV files for now, as they seem to just work on the 64-bit version.</p>
| [
{
"answer_id": 22093,
"author": "Marek Grzenkowicz",
"author_id": 95,
"author_profile": "https://Stackoverflow.com/users/95",
"pm_score": 2,
"selected": false,
"text": "<p>Unless it's a business requirement, I suggest you move the connection string from the command line to the package an... | 2008/08/21 | [
"https://Stackoverflow.com/questions/21448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2375/"
] | I have an SSIS package that exports data to a couple of Excel files for transfer to a third party. To get this to run as a scheduled job on a 64-bit server I understand that I need to set the step as a CmdExec type and call the 32-bit version of DTExec. But I don't seem to be able to get the command right to pass in the connection string for the Excel files.
So far I have this:
```
DTExec.exe /SQL \PackageName /SERVER OUR2005SQLSERVER /CONNECTION
LETTER_Excel_File;\""Provider=Microsoft.Jet.OLEDB.4.0";"Data
Source=""C:\Temp\BaseFiles\LETTER.xls";"Extended Properties=
""Excel 8.0;HDR=Yes"" /MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING E
```
This gives me the error: **`Option "Properties=Excel 8.0;HDR=Yes" is not valid.`**
I've tried a few variations with the Quotation marks but have not been able to get it right yet.
Does anyone know how to fix this?
**`UPDATE:`**
Thanks for your help but I've decided to go with CSV files for now, as they seem to just work on the 64-bit version. | This step-by-step example is for others who might stumble upon this question. This example uses *SSIS 2005* and uses *SQL Server 2005 64-bit edition server* to run the job.
The answer here concentrates only on fixing the error message mentioned in the question. The example will demonstrate the steps to recreate the issue and also the cause of the issue followed by how to fix it.
**`NOTE:`** I would recommend using the option of storing the package configuration values in database or using indirect XML configuration with the help of Environment Variables. Also, the steps to create Excel file would be done using a template which would then archived by moving to a different folder. These steps are not discussed in this post. As mentioned earlier, the purpose of this post is to address the error.
Let’s proceed with the example. I have also blogged about this answer, which can be found in [this link](http://learnbycoding.com/2011/07/accessing-excel-data-source-from-an-ssis-package-that-is-deployed-on-a-64-bit-server/). It is the same answer.
Create an SSIS package ([Steps to create an SSIS package](http://learnbycoding.com/2011/07/creating-a-simple-ssis-package-using-bids/)). This example uses BIDS 2005. I have named the package in the format YYYYMMDD\_hhmm in the beginning followed by SO stands for Stack Overflow, followed by the SO question id, and finally a description. I am not saying that you should name your package like this. This is for me to easily refer this back later. Note that I also have a Data Sources named Adventure Works. I will be using Adventure Works data source, which points to AdventureWorks database downloaded from [this link](http://msftdbprodsamples.codeplex.com/). The example uses SQL Server 2008 R2 database. Refer screenshot **#1**.
In the AdventureWorks database, create a stored procedure named *dbo.GetCurrency* using the below given script.
```
CREATE PROCEDURE [dbo].[GetCurrency]
AS
BEGIN
SET NOCOUNT ON;
SELECT
TOP 10 CurrencyCode
, Name
, ModifiedDate
FROM Sales.Currency
ORDER BY CurrencyCode
END
GO
```
On the package’s Connection Manager section, right-click and select *New Connection From Data Source*. On the *Select Data Source* dialog, select *Adventure Works* and click OK. You should now see the Adventure Works data source under the *Connection Managers* section.
On the package’s Connection Managers section, right-click again but this time select *New Connection…*. This is to create the Excel connection. On the Add SSIS Connection Manager, select *EXCEL*. On the Excel Connection Manager, enter the path *C:\Temp\Template.xls*. When we deploy it to the server, we will change this path. I have selected Excel version *Microsoft Excel 97-2005* and chose to leave the checkbox *First row has column names* checked so that the create the Excel file is created column headers. Click *OK*. Rename the Excel connection to *Excel*, just to keep it simple. Refer screenshots **#2** - **#7**.
On the package, create the following variable. Refer screenshot **#8**.
* *SQLGetData*: This variable is of type String. This will contain the Stored Procedure execution statement. This example uses the value *EXEC dbo.GetCurrency*
Screenshot **#9** shows the output of the stored procedure execution statement *EXEC dbo.GetCurrency*
On the package’s Control Flow tab, place a `Data Flow task` and name it as Export to Excel. Refer screenshot **#10**.
Double-click on the Data Flow Task to switch to the Data Flow tab.
On the Data Flow tab, place an `OLE DB Source` to connect to the SQL Server data to fetch the data from the stored procedure and name it as SQL. Double-click on the OLE DB Source to bring up the OLE DB Source Editor. On the Connection Manager section, select *Adventure Works* from the OLE DB connection manager, select SQL command from variable from Data access mode and select the variable *User::SQLGetData* from the Variable name drop down. On the Columns section, make sure the column names are mapped correctly. Click OK to close the OLE DB Source Editor. Refer screenshots **#11** and **#12**.
On the Data Flow tab, place an `Excel Destination` to insert the data into the Excel file and name it as Excel. Double-click on the Excel Destination to open the Excel Destination Editor. On the Connection Manager section, select Excel from the OLE DB connection manager and select Table or view from Data access mode. At this point, we don’t have an Excel because while creating the Excel connection manager, we simply specified the path but never created the file. Hence, there won’t be any values in the drop down Name of the Excel sheet. So, click the *New…* button (the second New one) to create a new Excel sheet. On the Create Table window, BIDS automatically provide a create sheet based on the incoming data source. You can change the values according to your preferences. I will simply click OK by retaining the default value. The name of the sheet will be populated in the drop down Name of the Excel sheet. The name of the sheet is taken from the task name, here in this case the Excel Destination, which we have named it as Excel. On the Mappings section, make sure the column names are mapped correctly. Click OK to close the Excel Destination Editor. Refer screenshots **#13** - **#16**.
Once the data flow task is configured, it should look like as shown in screenshot **#17**.
Execute the package by pressing F5. Screenshots **#18** - **#21** show the successful execution of the package in both Control Flow and Data Flow Task. Also, the file is generated in the path *C:\Temp\Template.xls* provided in the Excel connection and the data shown in the stored procedure execution output matches with the data written to the file.
The package developed on my local machine in the folder path *C:\Learn\Learn.VS2005\Learn.SSIS*. Now, we need to deploy the files on to the Server that hosts the 64-bit version of the SQL Server to schedule a job. So, the folder on the server would be *D:\SSIS\Practice*. Copy the package file (**.dtsx**) from the local machine and paste it in the server folder. Also, in order for the package to run correctly, we need to have the Excel spreadsheet present on the server. Otherwise, the validation will fail. Usually, I create a Template folder that will contain the empty Excel spreadsheet file that matches the output. Later, during run time I will change the Excel output path to a different location using package configuration. For this example, I am going to keep it simple. So, let’s copy the Excel file generated in the local machine in the path *C:\Temp\Template.xls* to the server location *D:\SSIS\Practice*. I want the SQL job to generate the file in the name Currencies.xls. So, rename the file Template.xls to *Currencies.xls*. Refer screenshot **#22**.
To show that I am indeed going to run the job on the server in a 64-bit edition of SQL Server, I executed the command SELECT @@version on the SQL Server and screenshot **#23** shows the results.
We will use *Execute Package Utility* (dtexec.exe) to generate the command line parameters. Log into the server which will run the SSIS package in an SQL job. Double-click on the package file, this will bring the Execute Package Utility. On the General section, select File system from Package source. Click on the Ellipsis and browse to the package path. On the Connection Managers section, select Excel and change the path inside the Excel file from C:\Temp\Template.xls to D:\SSIS\Practice\Currencies.xls. The changes made in the Utility will generate a command line accordingly on the Command Line section. On the Command Line section, copy the Command line that contains all the necessary parameters. We are not going to execute the package from here. Click *Close*. Refer screenshots **#24** - **#26**.
Next, we need to set up a job to run the SSIS package. We cannot choose SQL Server Integration Services Package type because that will run under 64-bit and won’t find the Excel connection provider. So, we have to run it as `Operating System (CmdExec)` job type. Go to SQL Server Management Studio and connect to the Database Engine. Expand SQL Server Agent and right-click on Jobs node. Select New Job…. On the General section of the Job Properties window, provide the job name as 01\_SSIS\_Export\_To\_Excel, Owner will be the user creating the job. I have a Category named SSIS, so I will select that but the default category is *[Uncategorized (Local)]* and provide a brief description. On the Steps section, click *New…* button. This will bring Job Step properties. On the General section of the Job Step properties, provide Step name as Export to Excel, Select type `Operating system (CmdExec)`, leave the default Run as account as SQL Server Agent Service Account and provide the following Command. Click OK. On the New Job window, Click OK. Refer screenshots **#27** - **#31**.
```
C:\Program Files (x86)\Microsoft SQL Server\90\DTS\Binn\DTExec.exe /FILE
"D:\SSIS\Practice\20110723_1015_SO_21448_Excel_64_bit_Error.dtsx"
/CONNECTION Excel;"\"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=D:\SSIS\Practice\Currencies.xls;Extended Properties=""EXCEL 8.0;HDR=YES"";\""
/MAXCONCURRENT " -1 " /CHECKPOINTING OFF /REPORTING EWCDI
```
The new job should appear under SQL Server Agent –> Jobs node. Right-click on the newly created job 01\_SSIS\_Export\_To\_Excel and select *Start Job at Step…*, this will commence the job execution. The job will fail as expected because that is the context of this issue. Click Close to close the Start Jobs dialog. Refer screenshots **#32** and **#33**.
Let’s take a look at what happened. Go to SQL Server Agent and Jobs node. Right-click on the job 01\_SSIS\_Export\_To\_Excel and select View History. This will bring the Log File Viewer window. You can notice that the job failed. Expand the node near the red cross and click on the line that Step ID value of 1. At the bottom section, you can see the error message **`Option “8.0;HDR=YES’;” is not valid.`** Click Close to close the Log File Viewer window. Refer screenshots **#34** and **#35**.
Now, right-click on the job and select Properties to open the Job Properties. You can also double-click on the job to bring the Job Properties window. Click on the Steps on the left section. and click Edit. Replace the command with the following command and click OK. Click OK on the Job Properties to close the window. Right-click on the job 01\_SSIS\_Export\_To\_Excel and select Start Job at Step…, this will commence the job execution. The job will fail execute successfully. Click Close to close the Start Jobs dialog. Let’s take a look at the history. Right-click on the job 01\_SSIS\_Export\_To\_Excel and select View History. This will bring the Log File Viewer window. You can notice that the job succeeded during the second run. Expand the node near the green tick cross and click on the line that Step ID value of 1. At the bottom section, you can see the message Option The step succeeded. Click Close to close the Log File Viewer window. The file D:\SSIS\Practice\Currencies.xls will be successfully populated with the data. If you execute the job successfully multiple times, the data will get appended to the file and you will find more data. As I mentioned earlier, this is not the right-way to generate the files. This example was created to demonstrate a fix for this issue. Refer screenshots **#36** - **#38**.
Screenshot **#39** shows the differences between the working and the non-working command line arguments. The one on the right is the working command line and the left one is incorrect. It required another double quotes with backslash escape sequence to fix the error. There could be other ways to fix this well but this option seems to work.
Thus, the example demonstrated a way to fix the command line argument issue while accessing Excel data source from an SSIS package that is deployed on a 64-bit server.
Hope that helps someone.
**Screenshots:**
**#1:** Solution\_Explorer

**#2:** New\_Connection\_Data\_Source

**#3:** Select\_Data\_Source

**#4:** New\_Connection

**#5:** Add\_SSIS\_Connection\_Manager

**#6:** Excel\_Connection\_Manager

**#7:** Connection\_Managers

**#8:** Variables

**#9:** Stored\_Procedure\_Output

**#10:** Control\_Flow

**#11:** OLE\_DB\_Source\_Connections\_Manager

**#12:** OLE\_DB\_Source\_Columns

**#13:** Excel\_Destination\_Editor\_New

**#14:** Excel\_Destination\_Create\_Table

**#15:** Excel\_Destination\_Edito

**#16:** Excel\_Destination\_Mappings

**#17:** Data\_Flow

**#18:** Successful\_Package\_Execution\_Control

**#19:** Successful\_Package\_Execution\_Data\_Flow

**#20:** C\_Temp\_File\_Created

**#21:** Data\_Populated

**#22:** File\_On\_Server

**#23:** SQL\_Server\_Version

**#24:** Execute\_Package\_Utility\_General

**#25:** Execute\_Package\_Utility\_Connection\_Managers

**#26:** Execute\_Package\_Utility\_Command\_Line

**#27:** Job\_New\_Job

**#28:** New\_Job\_General

**#29:** New\_Job\_Step

**#30:** New\_Job\_Step\_General

**#31:** New\_Job\_Steps\_Added

**#32:** Job\_Start\_Job\_at\_Step

**#33:** SQL\_Job\_Execution\_Failure

**#34:** View\_History

**#35:** SQL\_Job\_Error\_Message

**#36:** SQL\_Job\_Execution\_Success

**#37:** SQL\_Job\_Success\_Message

**#38:** Excel\_File\_Generated

**#39:** Command\_Comparison
 |
21,449 | <p>What is the difference between the following types of endianness?</p>
<ul>
<li>byte (8b) invariant big and little endianness</li>
<li>half-word (16b) invariant big and little endianness</li>
<li>word (32b) invariant big and little endianness</li>
<li>double-word (64b) invariant big and little endianness</li>
</ul>
<p>Are there other types/variations?</p>
| [
{
"answer_id": 21455,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": -1,
"selected": false,
"text": "<p>the basic concept is the ordering of bits:</p>\n\n<pre><code>1010 0011\n</code></pre>\n\n<p>in little-endian is th... | 2008/08/21 | [
"https://Stackoverflow.com/questions/21449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2045/"
] | What is the difference between the following types of endianness?
* byte (8b) invariant big and little endianness
* half-word (16b) invariant big and little endianness
* word (32b) invariant big and little endianness
* double-word (64b) invariant big and little endianness
Are there other types/variations? | There are two approaches to endian mapping: *address invariance* and *data invariance*.
Address Invariance
------------------
In this type of mapping, the address of bytes is always preserved between big and little. This has the side effect of reversing the order of significance (most significant to least significant) of a particular datum (e.g. 2 or 4 byte word) and therefore the interpretation of data. Specifically, in little-endian, the interpretation of data is least-significant to most-significant bytes whilst in big-endian, the interpretation is most-significant to least-significant. In both cases, the set of bytes accessed remains the same.
**Example**
Address invariance (also known as *byte invariance*): the byte address is constant but byte significance is reversed.
```
Addr Memory
7 0
| | (LE) (BE)
|----|
+0 | aa | lsb msb
|----|
+1 | bb | : :
|----|
+2 | cc | : :
|----|
+3 | dd | msb lsb
|----|
| |
At Addr=0: Little-endian Big-endian
Read 1 byte: 0xaa 0xaa (preserved)
Read 2 bytes: 0xbbaa 0xaabb
Read 4 bytes: 0xddccbbaa 0xaabbccdd
```
Data Invariance
---------------
In this type of mapping, the relative byte significance is preserved for datum of a particular size. There are therefore different types of data invariant endian mappings for different datum sizes. For example, a 32-bit word invariant endian mapping would be used for a datum size of 32. The effect of preserving the value of particular sized datum, is that the byte addresses of bytes within the datum are reversed between big and little endian mappings.
**Example**
32-bit data invariance (also known as *word invariance*): The datum is a 32-bit word which always has the value `0xddccbbaa`, independent of endianness. However, for accesses smaller than a word, the address of the bytes are reversed between big and little endian mappings.
```
Addr Memory
| +3 +2 +1 +0 | <- LE
|-------------------|
+0 msb | dd | cc | bb | aa | lsb
|-------------------|
+4 msb | 99 | 88 | 77 | 66 | lsb
|-------------------|
BE -> | +0 +1 +2 +3 |
At Addr=0: Little-endian Big-endian
Read 1 byte: 0xaa 0xdd
Read 2 bytes: 0xbbaa 0xddcc
Read 4 bytes: 0xddccbbaa 0xddccbbaa (preserved)
Read 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved)
```
**Example**
16-bit data invariance (also known as *half-word invariance*): The datum is a 16-bit
which always has the value `0xbbaa`, independent of endianness. However, for accesses smaller than a half-word, the address of the bytes are reversed between big and little endian mappings.
```
Addr Memory
| +1 +0 | <- LE
|---------|
+0 msb | bb | aa | lsb
|---------|
+2 msb | dd | cc | lsb
|---------|
+4 msb | 77 | 66 | lsb
|---------|
+6 msb | 99 | 88 | lsb
|---------|
BE -> | +0 +1 |
At Addr=0: Little-endian Big-endian
Read 1 byte: 0xaa 0xbb
Read 2 bytes: 0xbbaa 0xbbaa (preserved)
Read 4 bytes: 0xddccbbaa 0xddccbbaa (preserved)
Read 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved)
```
**Example**
64-bit data invariance (also known as *double-word invariance*): The datum is a 64-bit
word which always has the value `0x99887766ddccbbaa`, independent of endianness. However, for accesses smaller than a double-word, the address of the bytes are reversed between big and little endian mappings.
```
Addr Memory
| +7 +6 +5 +4 +3 +2 +1 +0 | <- LE
|---------------------------------------|
+0 msb | 99 | 88 | 77 | 66 | dd | cc | bb | aa | lsb
|---------------------------------------|
BE -> | +0 +1 +2 +3 +4 +5 +6 +7 |
At Addr=0: Little-endian Big-endian
Read 1 byte: 0xaa 0x99
Read 2 bytes: 0xbbaa 0x9988
Read 4 bytes: 0xddccbbaa 0x99887766
Read 8 bytes: 0x99887766ddccbbaa 0x99887766ddccbbaa (preserved)
``` |
21,454 | <p>How do I go about specifying and using an ENUM in a Django model?</p>
| [
{
"answer_id": 21468,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": 7,
"selected": false,
"text": "<p>From the <a href=\"https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.choices\" rel=\"... | 2008/08/21 | [
"https://Stackoverflow.com/questions/21454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019/"
] | How do I go about specifying and using an ENUM in a Django model? | From the [Django documentation](https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.Field.choices):
```
MAYBECHOICE = (
('y', 'Yes'),
('n', 'No'),
('u', 'Unknown'),
)
```
And you define a charfield in your model :
```
married = models.CharField(max_length=1, choices=MAYBECHOICE)
```
You can do the same with integer fields if you don't like to have letters
in your db.
In that case, rewrite your choices:
```
MAYBECHOICE = (
(0, 'Yes'),
(1, 'No'),
(2, 'Unknown'),
)
``` |
21,461 | <pre><code>#if SYMBOL
//code
#endif
</code></pre>
<p>what values does C# predefine for use?</p>
| [
{
"answer_id": 21467,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 2,
"selected": false,
"text": "<p>Depends on what /define compiler options you use. <code>Visual Studio</code> puts the <code>DEBUG</code> symbol in there for... | 2008/08/21 | [
"https://Stackoverflow.com/questions/21461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] | ```
#if SYMBOL
//code
#endif
```
what values does C# predefine for use? | To add to what Nick said, the MSDN documentation does not list any pre-defined names. It would seem that all need to come from `#define` and `/define`.
[#if on MSDN](http://msdn.microsoft.com/en-us/library/4y6tbswk.aspx) |
21,489 | <p>SQL Experts,</p>
<p>Is there an efficient way to group runs of data together using SQL?<br>
Or is it going to be more efficient to process the data in code. </p>
<p>For example if I have the following data:</p>
<pre><code>ID|Name
01|Harry Johns
02|Adam Taylor
03|John Smith
04|John Smith
05|Bill Manning
06|John Smith
</code></pre>
<p>I need to display this:</p>
<pre><code>Harry Johns
Adam Taylor
John Smith (2)
Bill Manning
John Smith
</code></pre>
<p>@Matt: Sorry I had trouble formatting the data using an embedded html table it worked in the preview but not in the final display.</p>
| [
{
"answer_id": 21492,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<p>For this particular case, all you need to do is group by the name and ask for the count, like this:</p>\n\n<pre><code>... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2281/"
] | SQL Experts,
Is there an efficient way to group runs of data together using SQL?
Or is it going to be more efficient to process the data in code.
For example if I have the following data:
```
ID|Name
01|Harry Johns
02|Adam Taylor
03|John Smith
04|John Smith
05|Bill Manning
06|John Smith
```
I need to display this:
```
Harry Johns
Adam Taylor
John Smith (2)
Bill Manning
John Smith
```
@Matt: Sorry I had trouble formatting the data using an embedded html table it worked in the preview but not in the final display. | Try this:
```
select n.name,
(select count(*)
from myTable n1
where n1.name = n.name and n1.id >= n.id and (n1.id <=
(
select isnull(min(nn.id), (select max(id) + 1 from myTable))
from myTable nn
where nn.id > n.id and nn.name <> n.name
)
))
from myTable n
where not exists (
select 1
from myTable n3
where n3.name = n.name and n3.id < n.id and n3.id > (
select isnull(max(n4.id), (select min(id) - 1 from myTable))
from myTable n4
where n4.id < n.id and n4.name <> n.name
)
)
```
I think that'll do what you want. Bit of a kludge though.
Phew! After a few edits I think I have all the edge cases sorted out. |
21,547 | <p>I've spent a good amount of time coming up with solution to this problem, so in the spirit of <a href="https://stackoverflow.com/questions/21245/questions-vs-conveying-information">this post</a>, I'm posting it here, since I think it might be useful to others. </p>
<p>If anyone has a better script, or anything to add, please post it.</p>
<p>Edit: Yes guys, I know how to do it in Management Studio - but I needed to be able to do it from within another application.</p>
| [
{
"answer_id": 21551,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 5,
"selected": false,
"text": "<p>Here's the script that I came up with. It handles Identity columns, default values, and primary keys. It does not handle ... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
] | I've spent a good amount of time coming up with solution to this problem, so in the spirit of [this post](https://stackoverflow.com/questions/21245/questions-vs-conveying-information), I'm posting it here, since I think it might be useful to others.
If anyone has a better script, or anything to add, please post it.
Edit: Yes guys, I know how to do it in Management Studio - but I needed to be able to do it from within another application. | I've modified the version above to run for all tables and support new SQL 2005 data types. It also retains the primary key names. Works only on SQL 2005 (using cross apply).
```
select 'create table [' + so.name + '] (' + o.list + ')' + CASE WHEN tc.Constraint_Name IS NULL THEN '' ELSE 'ALTER TABLE ' + so.Name + ' ADD CONSTRAINT ' + tc.Constraint_Name + ' PRIMARY KEY ' + ' (' + LEFT(j.List, Len(j.List)-1) + ')' END
from sysobjects so
cross apply
(SELECT
' ['+column_name+'] ' +
data_type + case data_type
when 'sql_variant' then ''
when 'text' then ''
when 'ntext' then ''
when 'xml' then ''
when 'decimal' then '(' + cast(numeric_precision as varchar) + ', ' + cast(numeric_scale as varchar) + ')'
else coalesce('('+case when character_maximum_length = -1 then 'MAX' else cast(character_maximum_length as varchar) end +')','') end + ' ' +
case when exists (
select id from syscolumns
where object_name(id)=so.name
and name=column_name
and columnproperty(id,name,'IsIdentity') = 1
) then
'IDENTITY(' +
cast(ident_seed(so.name) as varchar) + ',' +
cast(ident_incr(so.name) as varchar) + ')'
else ''
end + ' ' +
(case when UPPER(IS_NULLABLE) = 'NO' then 'NOT ' else '' end ) + 'NULL ' +
case when information_schema.columns.COLUMN_DEFAULT IS NOT NULL THEN 'DEFAULT '+ information_schema.columns.COLUMN_DEFAULT ELSE '' END + ', '
from information_schema.columns where table_name = so.name
order by ordinal_position
FOR XML PATH('')) o (list)
left join
information_schema.table_constraints tc
on tc.Table_name = so.Name
AND tc.Constraint_Type = 'PRIMARY KEY'
cross apply
(select '[' + Column_Name + '], '
FROM information_schema.key_column_usage kcu
WHERE kcu.Constraint_Name = tc.Constraint_Name
ORDER BY
ORDINAL_POSITION
FOR XML PATH('')) j (list)
where xtype = 'U'
AND name NOT IN ('dtproperties')
```
**Update:** Added handling of the XML data type
**Update 2:** Fixed cases when 1) there is multiple tables with the same name but with different schemas, 2) there is multiple tables having PK constraint with the same name |
21,558 | <p>I want to know what a "<em>virtual base class</em>" is and what it means.</p>
<p>Let me show an example:</p>
<pre><code>class Foo
{
public:
void DoSomething() { /* ... */ }
};
class Bar : public virtual Foo
{
public:
void DoSpecific() { /* ... */ }
};
</code></pre>
| [
{
"answer_id": 21598,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 1,
"selected": false,
"text": "<p>It means a call to a virtual function will be forwarded to the \"right\" class.</p>\n\n<p>C++ <a href=\"https://isocpp.o... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1556/"
] | I want to know what a "*virtual base class*" is and what it means.
Let me show an example:
```
class Foo
{
public:
void DoSomething() { /* ... */ }
};
class Bar : public virtual Foo
{
public:
void DoSpecific() { /* ... */ }
};
``` | Virtual base classes, used in virtual inheritance, is a way of preventing multiple "instances" of a given class appearing in an inheritance hierarchy when using multiple inheritance.
Consider the following scenario:
```
class A { public: void Foo() {} };
class B : public A {};
class C : public A {};
class D : public B, public C {};
```
The above class hierarchy results in the "dreaded diamond" which looks like this:
```
A
/ \
B C
\ /
D
```
An instance of D will be made up of B, which includes A, and C which also includes A. So you have two "instances" (for want of a better expression) of A.
When you have this scenario, you have the possibility of ambiguity. What happens when you do this:
```
D d;
d.Foo(); // is this B's Foo() or C's Foo() ??
```
Virtual inheritance is there to solve this problem. When you specify virtual when inheriting your classes, you're telling the compiler that you only want a single instance.
```
class A { public: void Foo() {} };
class B : public virtual A {};
class C : public virtual A {};
class D : public B, public C {};
```
This means that there is only one "instance" of A included in the hierarchy. Hence
```
D d;
d.Foo(); // no longer ambiguous
```
This is a mini summary. For more information, have a read of [this](http://en.wikipedia.org/wiki/Virtual_inheritance) and [this](https://isocpp.org/wiki/faq/multiple-inheritance). A good example is also available [here](http://www.learncpp.com/cpp-tutorial/118-virtual-base-classes/). |
21,564 | <p>I ended up writing a quick little script for this in Python, but I was wondering if there was a utility you could feed text into which would prepend each line with some text -- in my specific case, a timestamp. Ideally, the use would be something like:</p>
<pre><code>cat somefile.txt | prepend-timestamp
</code></pre>
<p>(Before you answer sed, I tried this:</p>
<pre><code>cat somefile.txt | sed "s/^/`date`/"
</code></pre>
<p>But that only evaluates the date command once when sed is executed, so the same timestamp is incorrectly prepended to each line.)</p>
| [
{
"answer_id": 21602,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 5,
"selected": false,
"text": "<p>How about this?</p>\n\n<pre><code>cat somefile.txt | perl -pne 'print scalar(localtime()), \" \";'\n</code></pre>\n\n<p>Judging... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/156/"
] | I ended up writing a quick little script for this in Python, but I was wondering if there was a utility you could feed text into which would prepend each line with some text -- in my specific case, a timestamp. Ideally, the use would be something like:
```
cat somefile.txt | prepend-timestamp
```
(Before you answer sed, I tried this:
```
cat somefile.txt | sed "s/^/`date`/"
```
But that only evaluates the date command once when sed is executed, so the same timestamp is incorrectly prepended to each line.) | Could try using `awk`:
```
<command> | awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0; fflush(); }'
```
You may need to make sure that `<command>` produces line buffered output, i.e. it flushes its output stream after each line; the timestamp `awk` adds will be the time that the end of the line appeared on its input pipe.
If awk shows errors, then try `gawk` instead. |
21,574 | <p>I'm not clear on the differences between the "current" version of Ruby (1.8) and the "new" version (1.9). Is there an "easy" or a "simple" explanation of the differences and why it is so different?</p>
| [
{
"answer_id": 21621,
"author": "Tim Sullivan",
"author_id": 722,
"author_profile": "https://Stackoverflow.com/users/722",
"pm_score": 8,
"selected": true,
"text": "<p>Sam Ruby has a <a href=\"http://slideshow.rubyforge.org/ruby19.html\" rel=\"noreferrer\">cool slideshow that outline the... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/757/"
] | I'm not clear on the differences between the "current" version of Ruby (1.8) and the "new" version (1.9). Is there an "easy" or a "simple" explanation of the differences and why it is so different? | Sam Ruby has a [cool slideshow that outline the differences](http://slideshow.rubyforge.org/ruby19.html).
In the interest of bringing this information inline for easier reference, and in case the link goes dead in the abstract future, here's an overview of Sam's slides. The slideshow is less overwhelming to review, but having it all laid out in a list like this is also helpful.
Ruby 1.9 - Major Features
=========================
* Performance
* Threads/Fibers
* Encoding/Unicode
* gems is (mostly) built-in now
* if statements do not introduce scope in Ruby.
What's changed?
===============
Single character strings.
-------------------------
Ruby 1.9
```
irb(main):001:0> ?c
=> "c"
```
Ruby 1.8.6
```
irb(main):001:0> ?c
=> 99
```
---
String index.
-------------
Ruby 1.9
```
irb(main):001:0> "cat"[1]
=> "a"
```
Ruby 1.8.6
```
irb(main):001:0> "cat"[1]
=> 97
```
---
{"a","b"} No Longer Supported
-----------------------------
Ruby 1.9
```
irb(main):002:0> {1,2}
SyntaxError: (irb):2: syntax error, unexpected ',', expecting tASSOC
```
Ruby 1.8.6
```
irb(main):001:0> {1,2}
=> {1=>2}
```
**Action:** Convert to {1 => 2}
---
`Array.to_s` Now Contains Punctuation
-------------------------------------
Ruby 1.9
```
irb(main):001:0> [1,2,3].to_s
=> "[1, 2, 3]"
```
Ruby 1.8.6
```
irb(main):001:0> [1,2,3].to_s
=> "123"
```
**Action:** Use .join instead
---
Colon No Longer Valid In When Statements
----------------------------------------
Ruby 1.9
```
irb(main):001:0> case 'a'; when /\w/: puts 'word'; end
SyntaxError: (irb):1: syntax error, unexpected ':',
expecting keyword_then or ',' or ';' or '\n'
```
Ruby 1.8.6
```
irb(main):001:0> case 'a'; when /\w/: puts 'word'; end
word
```
**Action:** Use semicolon, then, or newline
---
Block Variables Now Shadow Local Variables
------------------------------------------
Ruby 1.9
```
irb(main):001:0> i=0; [1,2,3].each {|i|}; i
=> 0
irb(main):002:0> i=0; for i in [1,2,3]; end; i
=> 3
```
Ruby 1.8.6
```
irb(main):001:0> i=0; [1,2,3].each {|i|}; i
=> 3
```
---
`Hash.index` Deprecated
-----------------------
Ruby 1.9
```
irb(main):001:0> {1=>2}.index(2)
(irb):18: warning: Hash#index is deprecated; use Hash#key
=> 1
irb(main):002:0> {1=>2}.key(2)
=> 1
```
Ruby 1.8.6
```
irb(main):001:0> {1=>2}.index(2)
=> 1
```
**Action:** Use Hash.key
---
`Fixnum.to_sym` Now Gone
------------------------
Ruby 1.9
```
irb(main):001:0> 5.to_sym
NoMethodError: undefined method 'to_sym' for 5:Fixnum
```
Ruby 1.8.6
```
irb(main):001:0> 5.to_sym
=> nil
```
(Cont'd) Ruby 1.9
```
# Find an argument value by name or index.
def [](index)
lookup(index.to_sym)
end
```
svn.ruby-lang.org/repos/ruby/trunk/lib/rake.rb
---
Hash Keys Now Unordered
-----------------------
Ruby 1.9
```
irb(main):001:0> {:a=>"a", :c=>"c", :b=>"b"}
=> {:a=>"a", :c=>"c", :b=>"b"}
```
Ruby 1.8.6
```
irb(main):001:0> {:a=>"a", :c=>"c", :b=>"b"}
=> {:a=>"a", :b=>"b", :c=>"c"}
```
Order is insertion order
---
Stricter Unicode Regular Expressions
------------------------------------
Ruby 1.9
```
irb(main):001:0> /\x80/u
SyntaxError: (irb):2: invalid multibyte escape: /\x80/
```
Ruby 1.8.6
```
irb(main):001:0> /\x80/u
=> /\x80/u
```
---
`tr` and `Regexp` Now Understand Unicode
----------------------------------------
Ruby 1.9
```
unicode(string).tr(CP1252_DIFFERENCES, UNICODE_EQUIVALENT).
gsub(INVALID_XML_CHAR, REPLACEMENT_CHAR).
gsub(XML_PREDEFINED) {|c| PREDEFINED[c.ord]}
```
---
`pack` and `unpack`
-------------------
Ruby 1.8.6
```
def xchr(escape=true)
n = XChar::CP1252[self] || self
case n when *XChar::VALID
XChar::PREDEFINED[n] or
(n>128 ? n.chr : (escape ? "&##{n};" : [n].pack('U*')))
else
Builder::XChar::REPLACEMENT_CHAR
end
end
unpack('U*').map {|n| n.xchr(escape)}.join
```
---
`BasicObject` More Brutal Than `BlankSlate`
-------------------------------------------
Ruby 1.9
```
irb(main):001:0> class C < BasicObject; def f; Math::PI; end; end; C.new.f
NameError: uninitialized constant C::Math
```
Ruby 1.8.6
```
irb(main):001:0> require 'blankslate'
=> true
irb(main):002:0> class C < BlankSlate; def f; Math::PI; end; end; C.new.f
=> 3.14159265358979
```
**Action:** Use ::Math::PI
---
Delegation Changes
------------------
Ruby 1.9
```
irb(main):002:0> class C < SimpleDelegator; end
=> nil
irb(main):003:0> C.new('').class
=> String
```
Ruby 1.8.6
```
irb(main):002:0> class C < SimpleDelegator; end
=> nil
irb(main):003:0> C.new('').class
=> C
irb(main):004:0>
```
[Defect 17700](http://rubyforge.org/tracker/index.php?func=detail&aid=17700&group_id=426&atid=1698)
---
Use of $KCODE Produces Warnings
-------------------------------
Ruby 1.9
```
irb(main):004:1> $KCODE = 'UTF8'
(irb):4: warning: variable $KCODE is no longer effective; ignored
=> "UTF8"
```
Ruby 1.8.6
```
irb(main):001:0> $KCODE = 'UTF8'
=> "UTF8"
```
---
`instance_methods` Now an Array of Symbols
------------------------------------------
Ruby 1.9
```
irb(main):001:0> {}.methods.sort.last
=> :zip
```
Ruby 1.8.6
```
irb(main):001:0> {}.methods.sort.last
=> "zip"
```
**Action:** Replace instance\_methods.include? with method\_defined?
---
Source File Encoding
--------------------
### Basic
```
# coding: utf-8
```
### Emacs
```
# -*- encoding: utf-8 -*-
```
### Shebang
```
#!/usr/local/rubybook/bin/ruby
# encoding: utf-8
```
---
Real Threading
--------------
* Race Conditions
* Implicit Ordering Assumptions
* Test Code
---
What's New?
===========
Alternate Syntax for Symbol as Hash Keys
----------------------------------------
Ruby 1.9
```
{a: b}
redirect_to action: show
```
Ruby 1.8.6
```
{:a => b}
redirect_to :action => show
```
---
Block Local Variables
---------------------
Ruby 1.9
```
[1,2].each {|value; t| t=value*value}
```
---
Inject Methods
--------------
Ruby 1.9
```
[1,2].inject(:+)
```
Ruby 1.8.6
```
[1,2].inject {|a,b| a+b}
```
---
`to_enum`
---------
Ruby 1.9
```
short_enum = [1, 2, 3].to_enum
long_enum = ('a'..'z').to_enum
loop do
puts "#{short_enum.next} #{long_enum.next}"
end
```
---
No block? Enum!
---------------
Ruby 1.9
```
e = [1,2,3].each
```
---
Lambda Shorthand
----------------
Ruby 1.9
```
p = -> a,b,c {a+b+c}
puts p.(1,2,3)
puts p[1,2,3]
```
Ruby 1.8.6
```
p = lambda {|a,b,c| a+b+c}
puts p.call(1,2,3)
```
---
Complex Numbers
---------------
Ruby 1.9
```
Complex(3,4) == 3 + 4.im
```
---
Decimal Is Still Not The Default
--------------------------------
Ruby 1.9
```
irb(main):001:0> 1.2-1.1
=> 0.0999999999999999
```
---
Regex “Properties”
------------------
Ruby 1.9
```
/\p{Space}/
```
Ruby 1.8.6
```
/[:space:]/
```
---
Splat in Middle
---------------
Ruby 1.9
```
def foo(first, *middle, last)
(->a, *b, c {p a-c}).(*5.downto(1))
```
---
Fibers
------
Ruby 1.9
```
f = Fiber.new do
a,b = 0,1
Fiber.yield a
Fiber.yield b
loop do
a,b = b,a+b
Fiber.yield b
end
end
10.times {puts f.resume}
```
---
Break Values
------------
Ruby 1.9
```
match =
while line = gets
next if line =~ /^#/
break line if line.find('ruby')
end
```
---
“Nested” Methods
----------------
Ruby 1.9
```
def toggle
def toggle
"subsequent times"
end
"first time"
end
```
---
HTH! |
21,589 | <p>I did some tests a while ago and never figured out how to make this work. </p>
<p><strong>The ingredients:</strong></p>
<ul>
<li>COM+ transactional object (developed in VB6) </li>
<li>.Net web application (with transaction) in IIS that...<br>
makes a call to the COM+ component<br>
updates a row in a SQL database</li>
</ul>
<p><strong>Testing:</strong> </p>
<p>Run the .Net application and force an exception. </p>
<p><strong>Result:</strong> </p>
<p>The update made from the .Net application rolls back.<br>
The update made by the COM+ object does not roll back.</p>
<p>If I call the COM+ object from an old ASP page the rollback works.</p>
<p>I know some people may be thinking "what?! COM+ and .Net you must be out of your mind!", but there are some places in this world where there still are a lot of COM+ components. I was just curious if someone ever faced this and if you figured out how to make this work.</p>
| [
{
"answer_id": 21599,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 1,
"selected": false,
"text": "<p>How are you implementing this? If you are using EnterpriseServices to manage the .NET transaction, then both transac... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1328/"
] | I did some tests a while ago and never figured out how to make this work.
**The ingredients:**
* COM+ transactional object (developed in VB6)
* .Net web application (with transaction) in IIS that...
makes a call to the COM+ component
updates a row in a SQL database
**Testing:**
Run the .Net application and force an exception.
**Result:**
The update made from the .Net application rolls back.
The update made by the COM+ object does not roll back.
If I call the COM+ object from an old ASP page the rollback works.
I know some people may be thinking "what?! COM+ and .Net you must be out of your mind!", but there are some places in this world where there still are a lot of COM+ components. I was just curious if someone ever faced this and if you figured out how to make this work. | Because VB and .NET will use different SQL connections (and there is no way to make ADO and ADO.NET share the same connection), your only possibility is to enlist the DTC (Distributed Transaction Coordinator). The DTC will coordinates the two independent transactions so they commit or are rolled-back together.
**From .NET**, EnterpriseServices manages COM+ functionality, such as the DTC. In .NET 2.0 and forward, you can use the System.Transactions namespace, which makes things a little nicer. I think something like this should work (untested code):
```
void SomeMethod()
{
EnterpriseServicesInteropOption e = EnterpriseServicesInteropOption.Full;
using (TransactionScope s = new TransactionScope(e))
{
MyComPlusClass o = new MyComPlusClass();
o.SomeTransactionalMethod();
}
}
```
I am not familiar enough with this to give you more advice at this point.
**On the COM+ side**, your object needs to be configured to use (most likely "require") a distributed transaction. You can do that from COM+ Explorer, by going to your object's *Properties*, selecting the *Transaction* tab, and clicking on "*Required*". I don't remember if you can do this from code as well; VB6 was created before COM+ was released, so it doesn't fully support everything COM+ does (its transactional support was meant for COM+'s predecessor, called MS Transaction Server).
If everything works correctly, your COM+ object should be enlisting in the existing Context created by your .NET code.
You can use the "Distributed Transaction Coordinator\Transaction List" node in "Component Services" to check and see the distributed transaction being created during the call.
Be aware that you cannot see the changes from the COM+ component reflected on data queries from the .NET side until the Transaction is committed! In fact, it is possible to deadlock! Remember that DTC will make sure that the two transactions are paired, but they are still separate database transactions. |
21,640 | <p>Is there a simple way in .NET to quickly get the current protocol, host, and port? For example, if I'm on the following URL:</p>
<p><code>http://www.mywebsite.com:80/pages/page1.aspx</code></p>
<p>I need to return:</p>
<p><code>http://www.mywebsite.com:80</code></p>
<p>I know I can use <code>Request.Url.AbsoluteUri</code> to get the complete URL, and I know I can use <code>Request.Url.Authority</code> to get the host and port, but I'm not sure of the best way to get the protocol without parsing out the URL string.</p>
<p>Any suggestions?</p>
| [
{
"answer_id": 21653,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 5,
"selected": false,
"text": "<p>Request.Url will return you the <a href=\"http://msdn.microsoft.com/en-us/library/system.uri.aspx\" rel=\"noreferrer\">... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2076253/"
] | Is there a simple way in .NET to quickly get the current protocol, host, and port? For example, if I'm on the following URL:
`http://www.mywebsite.com:80/pages/page1.aspx`
I need to return:
`http://www.mywebsite.com:80`
I know I can use `Request.Url.AbsoluteUri` to get the complete URL, and I know I can use `Request.Url.Authority` to get the host and port, but I'm not sure of the best way to get the protocol without parsing out the URL string.
Any suggestions? | The following (C#) code should do the trick
```
Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
``` |
21,647 | <p>The following <strong>C++</strong> code uses a <strong>ifstream</strong> object to read integers from a text file (which has one number per line) until it hits <strong>EOF</strong>. Why does it read the integer on the last line twice? How to fix this?</p>
<p><strong>Code:</strong></p>
<pre><code>#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream iFile("input.txt"); // input.txt has integers, one per line
while (!iFile.eof())
{
int x;
iFile >> x;
cerr << x << endl;
}
return 0;
}
</code></pre>
<p><strong>input.txt</strong>:</p>
<pre><code>10
20
30
</code></pre>
<p><strong>Output</strong>:</p>
<pre><code>10
20
30
30
</code></pre>
<p><strong>Note</strong>: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc).</p>
| [
{
"answer_id": 21656,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 8,
"selected": true,
"text": "<p>Just follow closely the chain of events.</p>\n\n<ul>\n<li>Grab 10</li>\n<li>Grab 20</li>\n<li>Grab 30</li>\n<li>Grab EOF<... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | The following **C++** code uses a **ifstream** object to read integers from a text file (which has one number per line) until it hits **EOF**. Why does it read the integer on the last line twice? How to fix this?
**Code:**
```
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream iFile("input.txt"); // input.txt has integers, one per line
while (!iFile.eof())
{
int x;
iFile >> x;
cerr << x << endl;
}
return 0;
}
```
**input.txt**:
```
10
20
30
```
**Output**:
```
10
20
30
30
```
**Note**: I've skipped all error checking code to keep the code snippet small. The above behaviour is seen on Windows (Visual C++), cygwin (gcc) and Linux (gcc). | Just follow closely the chain of events.
* Grab 10
* Grab 20
* Grab 30
* Grab EOF
Look at the second-to-last iteration. You grabbed 30, then carried on to check for EOF. You haven't reached EOF because the EOF mark hasn't been read yet ("binarically" speaking, its conceptual location is just after the 30 line). Therefore you carry on to the next iteration. x is still 30 from previous iteration. Now you read from the stream and you get EOF. x remains 30 and the ios::eofbit is raised. You output to stderr x (which is 30, just like in the previous iteration). Next you check for EOF in the loop condition, and this time you're out of the loop.
Try this:
```
while (true) {
int x;
iFile >> x;
if( iFile.eof() ) break;
cerr << x << endl;
}
```
By the way, there is another bug in your code. Did you ever try to run it on an empty file? The behaviour you get is for the exact same reason. |
21,651 | <p>I have a script that retrieves objects from a remote server through an Ajax call. The server returns objects in JSON notation.</p>
<p>However, in Adobe AIR, there is a restriction on using <a href="http://labs.adobe.com/wiki/index.php/AIR:HTML_Security_FAQ#Why_restrict_eval.28.29_for_all_Application_content_if_there_are_legitimate_use_cases_for_using_it.3F" rel="nofollow noreferrer">eval()</a> for security reasons. So I'm able to get replies from the remote server, but can't turn them back into JavaScript objects. Is there any workaround for this issue? I would like to use JSON for my JavaScript objects, since it can be used almost immediately.</p>
<p>Side-note : I do understand the security implications for forcing the issue, but I will be doing some rapid application development for a competition, so the program would only be a quick prototype, and not used for production purposes. Nevertheless, it would be great if there's a better alternative to what I'm trying to do now</p>
<hr>
<p><strong>Update:</strong></p>
<p>Thanks to <a href="https://stackoverflow.com/a/24919/7750640">Theo</a> and <a href="https://stackoverflow.com/a/21716/7750640">jsight</a> for their answers; </p>
<p>One important thing I learnt today is that I can actually make use of ActionScript libraries by using the <pre><script src="lib/myClasses.swf" type="application/x-shockwave-flash"></script></pre> tag extended by Adobe AIR. Check out <a href="https://stackoverflow.com/a/24919/7750640">Theo's</a> link for more details!</p>
| [
{
"answer_id": 21716,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 2,
"selected": false,
"text": "<p>Have you looked at <a href=\"http://code.google.com/p/as3corelib/\" rel=\"nofollow noreferrer\">as3corelib</a>? It appears... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2504504/"
] | I have a script that retrieves objects from a remote server through an Ajax call. The server returns objects in JSON notation.
However, in Adobe AIR, there is a restriction on using [eval()](http://labs.adobe.com/wiki/index.php/AIR:HTML_Security_FAQ#Why_restrict_eval.28.29_for_all_Application_content_if_there_are_legitimate_use_cases_for_using_it.3F) for security reasons. So I'm able to get replies from the remote server, but can't turn them back into JavaScript objects. Is there any workaround for this issue? I would like to use JSON for my JavaScript objects, since it can be used almost immediately.
Side-note : I do understand the security implications for forcing the issue, but I will be doing some rapid application development for a competition, so the program would only be a quick prototype, and not used for production purposes. Nevertheless, it would be great if there's a better alternative to what I'm trying to do now
---
**Update:**
Thanks to [Theo](https://stackoverflow.com/a/24919/7750640) and [jsight](https://stackoverflow.com/a/21716/7750640) for their answers;
One important thing I learnt today is that I can actually make use of ActionScript libraries by using the
```
<script src="lib/myClasses.swf" type="application/x-shockwave-flash"></script>
```
tag extended by Adobe AIR. Check out [Theo's](https://stackoverflow.com/a/24919/7750640) link for more details! | You can find a [JSON parser written in JavaScript here](http://www.JSON.org/js.html) ([source code here](https://github.com/douglascrockford/JSON-js/blob/master/json2.js)). You can also use the as3corelib JSON parser from JavaScript, there's [a description of how to access ActionScript libraries from JavaScript here](http://help.adobe.com/en_US/AIR/1.1/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7ed9.html). |
21,652 | <p>I have some code that gives a user id to a utility that then send email to that user.</p>
<pre><code>emailUtil.sendEmail(userId, "foo");
public void sendEmail(String userId, String message) throws MailException {
/* ... logic that could throw a MailException */
}
</code></pre>
<p><code>MailException</code> could be thrown for a number of reasons, problems with the email address, problems with the mail template etc.</p>
<p>My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened.</p>
<p><strong>Edit:</strong> As a clarification, the exceptions aren't for logs and what-not, this relates to how code reacts to them. To keep going with the mail example, let's say that when we send mail it could fail because you don't have an email address, or it could because you don't have a <strong>valid</strong> email address, or it could fail.. etc.</p>
<p>My code would want to react differently to each of these issues (mostly by changing the message returned to the client, but actual logic as well).</p>
<p>Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it (an enum say) that let the code distinguish what kind of issue it was.</p>
| [
{
"answer_id": 21667,
"author": "stimms",
"author_id": 361,
"author_profile": "https://Stackoverflow.com/users/361",
"pm_score": 1,
"selected": false,
"text": "<p>It depends on what your application is doing. You might want to throw individual exceptions in cases like </p>\n\n<ul>\n<li>... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] | I have some code that gives a user id to a utility that then send email to that user.
```
emailUtil.sendEmail(userId, "foo");
public void sendEmail(String userId, String message) throws MailException {
/* ... logic that could throw a MailException */
}
```
`MailException` could be thrown for a number of reasons, problems with the email address, problems with the mail template etc.
My question is this: do you create a new Exception type for every one of these exceptions and then deal with them individually or do you create one MailException and then store something in the exception (something computer-readable, not the description text) that allows us to do different things based on what actually happened.
**Edit:** As a clarification, the exceptions aren't for logs and what-not, this relates to how code reacts to them. To keep going with the mail example, let's say that when we send mail it could fail because you don't have an email address, or it could because you don't have a **valid** email address, or it could fail.. etc.
My code would want to react differently to each of these issues (mostly by changing the message returned to the client, but actual logic as well).
Would it be best to have an exception implementation for each one of these issues or one umbrella exception that had something internal to it (an enum say) that let the code distinguish what kind of issue it was. | I usually start with a general exception and subclass it as needed. I always can catch the general exception (and with it all subclassed exceptions) if needed, but also the specific.
An example from the Java-API is IOException, that has subclasses like FileNotFoundException or EOFException (and much more).
This way you get the advantages of both, you don't have throw-clauses like:
```
throws SpecificException1, SpecificException2, SpecificException3 ...
```
a general
```
throws GeneralException
```
is enough. But if you want to have a special reaction to special circumstances you can always catch the specific exception. |
21,697 | <p>I'm currently writing an ASP.Net app from the UI down. I'm implementing an MVP architecture because I'm sick of Winforms and wanted something that had a better separation of concerns.</p>
<p>So with MVP, the Presenter handles events raised by the View. Here's some code that I have in place to deal with the creation of users:</p>
<pre><code>public class CreateMemberPresenter
{
private ICreateMemberView view;
private IMemberTasks tasks;
public CreateMemberPresenter(ICreateMemberView view)
: this(view, new StubMemberTasks())
{
}
public CreateMemberPresenter(ICreateMemberView view, IMemberTasks tasks)
{
this.view = view;
this.tasks = tasks;
HookupEventHandlersTo(view);
}
private void HookupEventHandlersTo(ICreateMemberView view)
{
view.CreateMember += delegate { CreateMember(); };
}
private void CreateMember()
{
if (!view.IsValid)
return;
try
{
int newUserId;
tasks.CreateMember(view.NewMember, out newUserId);
view.NewUserCode = newUserId;
view.Notify(new NotificationDTO() { Type = NotificationType.Success });
}
catch(Exception e)
{
this.LogA().Message(string.Format("Error Creating User: {0}", e.Message));
view.Notify(new NotificationDTO() { Type = NotificationType.Failure, Message = "There was an error creating a new member" });
}
}
}
</code></pre>
<p>I have my main form validation done using the built in .Net Validation Controls, but now I need to verify that the data sufficiently satisfies the criteria for the Service Layer.</p>
<p>Let's say the following Service Layer messages can show up:</p>
<ul>
<li>E-mail account already exists (failure)</li>
<li>Refering user entered does not exist (failure)</li>
<li>Password length exceeds datastore allowed length (failure)</li>
<li>Member created successfully (success)</li>
</ul>
<p>Let's also say that more rules will be in the service layer that the UI cannot anticipate.</p>
<p>Currently I'm having the service layer throw an exception if things didn't go as planned. Is that a sufficent strategy? Does this code smell to you guys? If I wrote a service layer like this would you be annoyed at having to write Presenters that use it in this way? Return codes seem too old school and a bool is just not informative enough.</p>
<hr>
<blockquote>
<p><strong>Edit not by OP: merging in follow-up comments that were posted as answers by the OP</strong></p>
</blockquote>
<hr>
<p>Cheekysoft, I like the concept of a ServiceLayerException. I already have a global exception module for the exceptions that I don't anticipate. Do you find making all these custom exceptions tedious? I was thinking that catching base Exception class was a bit smelly but wasn't exactly sure how progress from there.</p>
<p>tgmdbm, I like the clever use of the lambda expression there!</p>
<hr>
<p>Thanks Cheekysoft for the follow-up. So I'm guessing that would be the strategy if you don't mind the user being displayed a separate page (I'm primarily a web developer) if the Exception is not handled.</p>
<p>However, if I want to return the error message in the same view where the user submitted the data that caused the error, I would then have to catch the Exception in the Presenter?</p>
<p>Here's what the CreateUserView looks like when the Presenter has handled the ServiceLayerException:</p>
<p><img src="https://i.stack.imgur.com/HOJU7.png" alt="Create a user"></p>
<p>For this kind of error, it's nice to report it to the same view. </p>
<p>Anyways, I think we're going beyond the scope of my original question now. I'll play around with what you've posted and if I need further details I'll post a new question.</p>
| [
{
"answer_id": 22043,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 5,
"selected": true,
"text": "<p>That sounds just right to me. Exceptions are preferable as they can be thrown up to the top of the service layer from an... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1894/"
] | I'm currently writing an ASP.Net app from the UI down. I'm implementing an MVP architecture because I'm sick of Winforms and wanted something that had a better separation of concerns.
So with MVP, the Presenter handles events raised by the View. Here's some code that I have in place to deal with the creation of users:
```
public class CreateMemberPresenter
{
private ICreateMemberView view;
private IMemberTasks tasks;
public CreateMemberPresenter(ICreateMemberView view)
: this(view, new StubMemberTasks())
{
}
public CreateMemberPresenter(ICreateMemberView view, IMemberTasks tasks)
{
this.view = view;
this.tasks = tasks;
HookupEventHandlersTo(view);
}
private void HookupEventHandlersTo(ICreateMemberView view)
{
view.CreateMember += delegate { CreateMember(); };
}
private void CreateMember()
{
if (!view.IsValid)
return;
try
{
int newUserId;
tasks.CreateMember(view.NewMember, out newUserId);
view.NewUserCode = newUserId;
view.Notify(new NotificationDTO() { Type = NotificationType.Success });
}
catch(Exception e)
{
this.LogA().Message(string.Format("Error Creating User: {0}", e.Message));
view.Notify(new NotificationDTO() { Type = NotificationType.Failure, Message = "There was an error creating a new member" });
}
}
}
```
I have my main form validation done using the built in .Net Validation Controls, but now I need to verify that the data sufficiently satisfies the criteria for the Service Layer.
Let's say the following Service Layer messages can show up:
* E-mail account already exists (failure)
* Refering user entered does not exist (failure)
* Password length exceeds datastore allowed length (failure)
* Member created successfully (success)
Let's also say that more rules will be in the service layer that the UI cannot anticipate.
Currently I'm having the service layer throw an exception if things didn't go as planned. Is that a sufficent strategy? Does this code smell to you guys? If I wrote a service layer like this would you be annoyed at having to write Presenters that use it in this way? Return codes seem too old school and a bool is just not informative enough.
---
>
> **Edit not by OP: merging in follow-up comments that were posted as answers by the OP**
>
>
>
---
Cheekysoft, I like the concept of a ServiceLayerException. I already have a global exception module for the exceptions that I don't anticipate. Do you find making all these custom exceptions tedious? I was thinking that catching base Exception class was a bit smelly but wasn't exactly sure how progress from there.
tgmdbm, I like the clever use of the lambda expression there!
---
Thanks Cheekysoft for the follow-up. So I'm guessing that would be the strategy if you don't mind the user being displayed a separate page (I'm primarily a web developer) if the Exception is not handled.
However, if I want to return the error message in the same view where the user submitted the data that caused the error, I would then have to catch the Exception in the Presenter?
Here's what the CreateUserView looks like when the Presenter has handled the ServiceLayerException:

For this kind of error, it's nice to report it to the same view.
Anyways, I think we're going beyond the scope of my original question now. I'll play around with what you've posted and if I need further details I'll post a new question. | That sounds just right to me. Exceptions are preferable as they can be thrown up to the top of the service layer from anywhere inside the service layer, no matter how deeply nested inside the service method implementation it is. This keeps the service code clean as you know the calling presenter will always get notification of the problem.
**Don't catch Exception**
However, [don't catch Exception](https://stackoverflow.com/questions/21938/is-it-really-that-bad-to-catch-a-general-exception) in the presenter, I know its tempting because it keeps the code shorter, but you need to catch specific exceptions to avoid catching the system-level exceptions.
**Plan a Simple Exception Hierarchy**
If you are going to use exceptions in this way, you should design an exception hierarchy for your own exception classes.
At a minumum create a ServiceLayerException class and throw one of these in your service methods when a problem occurs. Then if you need to throw an exception that should/could be handled differently by the presenter, you can throw a specific subclass of ServiceLayerException: say, AccountAlreadyExistsException.
Your presenter then has the option of doing
```
try {
// call service etc.
// handle success to view
}
catch (AccountAlreadyExistsException) {
// set the message and some other unique data in the view
}
catch (ServiceLayerException) {
// set the message in the view
}
// system exceptions, and unrecoverable exceptions are allowed to bubble
// up the call stack so a general error can be shown to the user, rather
// than showing the form again.
```
Using inheritance in your own exception classes means you are not required to catch multipile exceptions in your presenter -- you can if there's a need to -- and you don't end up accidentally catching exceptions you can't handle. If your presenter is already at the top of the call stack, add a catch( Exception ) block to handle the system errors with a different view.
I always try and think of my service layer as a seperate distributable library, and throw as specific an exception as makes sense. It is then up to the presenter/controller/remote-service implementation to decide if it needs to worry about the specific details or just to treat problems as a generic error. |
21,715 | <p>Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable</p>
<p>IE:</p>
<pre><code>public class CollectionBase : IEnumerable
</code></pre>
<p>and then would derive their Business Object collections from that.</p>
<pre><code>public class BusinessObjectCollection : CollectionBase
</code></pre>
<p>Now with the generic list class, does anyone just use that instead? I've found that I use a compromise of the two techniques:</p>
<pre><code>public class BusinessObjectCollection : List<BusinessObject>
</code></pre>
<p>I do this because I like to have strongly typed names instead of just passing Lists around.</p>
<p>What is <strong>your</strong> approach?</p>
| [
{
"answer_id": 21720,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "<p>I generally only derive my own collection classes if I need to \"add value\". Like, if the collection itself needed to... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable
IE:
```
public class CollectionBase : IEnumerable
```
and then would derive their Business Object collections from that.
```
public class BusinessObjectCollection : CollectionBase
```
Now with the generic list class, does anyone just use that instead? I've found that I use a compromise of the two techniques:
```
public class BusinessObjectCollection : List<BusinessObject>
```
I do this because I like to have strongly typed names instead of just passing Lists around.
What is **your** approach? | I am generally in the camp of just using a List directly, unless for some reason I need to encapsulate the data structure and provide a limited subset of its functionality. This is mainly because if I don't have a specific need for encapsulation then doing it is just a waste of time.
However, with the aggregate initializes feature in C# 3.0, there are some new situations where I would advocate using customized collection classes.
Basically, C# 3.0 allows any class that implements `IEnumerable` and has an Add method to use the new aggregate initializer syntax. For example, because Dictionary defines a method Add(K key, V value) it is possible to initialize a dictionary using this syntax:
```
var d = new Dictionary<string, int>
{
{"hello", 0},
{"the answer to life the universe and everything is:", 42}
};
```
The great thing about the feature is that it works for add methods with any number of arguments. For example, given this collection:
```
class c1 : IEnumerable
{
void Add(int x1, int x2, int x3)
{
//...
}
//...
}
```
it would be possible to initialize it like so:
```
var x = new c1
{
{1,2,3},
{4,5,6}
}
```
This can be really useful if you need to create static tables of complex objects. For example, if you were just using `List<Customer>` and you wanted to create a static list of customer objects you would have to create it like so:
```
var x = new List<Customer>
{
new Customer("Scott Wisniewski", "555-555-5555", "Seattle", "WA"),
new Customer("John Doe", "555-555-1234", "Los Angeles", "CA"),
new Customer("Michael Scott", "555-555-8769", "Scranton PA"),
new Customer("Ali G", "", "Staines", "UK")
}
```
However, if you use a customized collection, like this one:
```
class CustomerList : List<Customer>
{
public void Add(string name, string phoneNumber, string city, string stateOrCountry)
{
Add(new Customer(name, phoneNumber, city, stateOrCounter));
}
}
```
You could then initialize the collection using this syntax:
```
var customers = new CustomerList
{
{"Scott Wisniewski", "555-555-5555", "Seattle", "WA"},
{"John Doe", "555-555-1234", "Los Angeles", "CA"},
{"Michael Scott", "555-555-8769", "Scranton PA"},
{"Ali G", "", "Staines", "UK"}
}
```
This has the advantage of being both easier to type and easier to read because their is no need to retype the element type name for each element. The advantage can be particularly strong if the element type is long or complex.
That being said, this is only useful if you need static collections of data defined in your app. Some types of apps, like compilers, use them all the time. Others, like typical database apps don't because they load all their data from a database.
My advice would be that if you either need to define a static collection of objects, or need to encapsulate away the collection interface, then create a custom collection class. Otherwise I would just use `List<T>` directly. |
21,749 | <p>I have a Delphi 7 application that has two views of a document (e.g. a WYSIWYG HTML edit might have a WYSIWYG view and a source view - not my real application). They can be opened in separate windows, or docked into tabs in the main window.</p>
<p>If I open a modal dialog from one of the separate forms, the main form is brought to the front, and is shown as the selected window in the windows taskbar. Say the main form is the WYSIWYG view, and the source view is poped out. You go to a particular point in the source view and insert an image tag. A dialog appears to allow you to select and enter the properties you want for the image. If the WYSIWYG view and the source view overlap, the WYSIWYG view will be brought to the front and the source view is hidden. Once the dialog is dismissed, the source view comes back into sight.</p>
<p>I've tried setting the owner and the ParentWindow properties to the form it is related to:</p>
<blockquote><code>dialog := TDialogForm.Create( parentForm );<br>
dialog.ParentWindow := parentForm.Handle;
</code></blockquote>
<p>How can I fix this problem? What else should I be trying?</p>
<p>Given that people seem to be stumbling on my example, perhaps I can try with a better example: a text editor that allows you to have more than one file open at the same time. The files you have open are either in tabs (like in the Delphi IDE) or in its own window. Suppose the user brings up the spell check dialog or the find dialog. What happens, is that if the file is being editing in its own window, that window is sent to below the main form in the z-order when the modal dialog is shown; once the dialog is closed, it is returned to its original z-order.</p>
<p><b>Note</b>: If you are using Delphi 7 and looking for a solution to this problem, see my answer lower down on the page to see what I ended up doing.</p>
| [
{
"answer_id": 21809,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 0,
"selected": false,
"text": "<p>First of all, I am not completely sure I follow, you might need to provide some additional details to help us understa... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2219/"
] | I have a Delphi 7 application that has two views of a document (e.g. a WYSIWYG HTML edit might have a WYSIWYG view and a source view - not my real application). They can be opened in separate windows, or docked into tabs in the main window.
If I open a modal dialog from one of the separate forms, the main form is brought to the front, and is shown as the selected window in the windows taskbar. Say the main form is the WYSIWYG view, and the source view is poped out. You go to a particular point in the source view and insert an image tag. A dialog appears to allow you to select and enter the properties you want for the image. If the WYSIWYG view and the source view overlap, the WYSIWYG view will be brought to the front and the source view is hidden. Once the dialog is dismissed, the source view comes back into sight.
I've tried setting the owner and the ParentWindow properties to the form it is related to:
> `dialog := TDialogForm.Create( parentForm );
>
> dialog.ParentWindow := parentForm.Handle;`
How can I fix this problem? What else should I be trying?
Given that people seem to be stumbling on my example, perhaps I can try with a better example: a text editor that allows you to have more than one file open at the same time. The files you have open are either in tabs (like in the Delphi IDE) or in its own window. Suppose the user brings up the spell check dialog or the find dialog. What happens, is that if the file is being editing in its own window, that window is sent to below the main form in the z-order when the modal dialog is shown; once the dialog is closed, it is returned to its original z-order.
**Note**: If you are using Delphi 7 and looking for a solution to this problem, see my answer lower down on the page to see what I ended up doing. | I'd use this code... (Basically what Lars said)
```
dialog := TDialogForm.Create( parentForm );
dialog.PopupParent := parentForm;
dialog.PopupMode := pmExplicit;
dialog.ShowModal();
``` |
21,817 | <p>The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface?</p>
<pre><code>public interface ITest {
public static String test();
}
</code></pre>
<p>The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only public & abstract are permitted".</p>
| [
{
"answer_id": 21819,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 3,
"selected": false,
"text": "<p>Static methods are not instance methods. There's no instance context, therefore to implement it from the interface mak... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2238/"
] | The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface?
```
public interface ITest {
public static String test();
}
```
The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only public & abstract are permitted". | There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between
```
public interface Foo {
public static int bar();
}
```
and
```
public interface Foo {
public static int bar() {
...
}
}
```
The first is impossible for the reasons that [Espo](https://stackoverflow.com/questions/21817/why-cant-i-declare-static-methods-in-an-interface#21826) mentions: you don't know which implementing class is the correct definition.
Java *could* allow the latter; and in fact, starting in Java 8, it does! |
21,848 | <p>There may be more than one way to ask this question, so here's a desciption of the problem. I was working on master and committed some stuff and then decided I wanted to put that work on hold. I backed up a few commits and then branched from before I started my crap work. Practically this works fine, I just now have a different branch as my main development branch. I'm wondering how I could change things around so I'm working on master again but it doesn't have my junk work and said work is on a different branch.</p>
<p>Some ways this could be asked/solved:
How do I rename my master branch to something else and then rename something else to master?
How do I back up master and then cause all commits I've backed up past to be on a different branch?</p>
<p>Thanks for all the (quick) answers! They're all good.</p>
| [
{
"answer_id": 21897,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 3,
"selected": false,
"text": "<p>This is relatively easy:</p>\n\n<pre><code>git checkout -b fake_master master # fake_master now points to the same commit as ... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2427/"
] | There may be more than one way to ask this question, so here's a desciption of the problem. I was working on master and committed some stuff and then decided I wanted to put that work on hold. I backed up a few commits and then branched from before I started my crap work. Practically this works fine, I just now have a different branch as my main development branch. I'm wondering how I could change things around so I'm working on master again but it doesn't have my junk work and said work is on a different branch.
Some ways this could be asked/solved:
How do I rename my master branch to something else and then rename something else to master?
How do I back up master and then cause all commits I've backed up past to be on a different branch?
Thanks for all the (quick) answers! They're all good. | In addition to the other comments, you may find the -m (move) switch to git-branch helpful. You could rename your old master to something else, then rename your new branch to master:
```
git branch -m master crap_work
git branch -m previous_master master
``` |
21,877 | <p>What I want to achieve is this. I want to give the user the ability to upload an image file, store the image in BLOB in SQL Server, and then use this image as a logo in other pages of the site. </p>
<p>I have done this by using </p>
<pre><code> Response.Clear();
Response.ContentType = "image/pjpeg";
Response.BinaryWrite(imageConents);
Response.End();
</code></pre>
<p>but to do this, I use a User control in the place where I want to show the image. I want to do it if possible using an asp:Image control, or even a pure old html image control. Is this possible?</p>
| [
{
"answer_id": 21883,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 0,
"selected": false,
"text": "<p>We actually just released some classes that help with exactly this kind of thing:</p>\n\n<p><a href=\"http://www.codep... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/932/"
] | What I want to achieve is this. I want to give the user the ability to upload an image file, store the image in BLOB in SQL Server, and then use this image as a logo in other pages of the site.
I have done this by using
```
Response.Clear();
Response.ContentType = "image/pjpeg";
Response.BinaryWrite(imageConents);
Response.End();
```
but to do this, I use a User control in the place where I want to show the image. I want to do it if possible using an asp:Image control, or even a pure old html image control. Is this possible? | Add a 'Generic Handler' to your web project, name it something like Image.ashx. Implement it like this:
```
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
using(Image image = GetImage(context.Request.QueryString["ID"]))
{
context.Response.ContentType = "image/jpeg";
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
public bool IsReusable
{
get
{
return true;
}
}
}
```
Now just implement the GetImage method to load the image with the given ID, and you can use
```
<asp:Image runat="server" ImageUrl="~/Image.ashx?ID=myImageId" />
```
to display it. You might want to think about implementing some form of caching in the handler too. And remember if you want to change the image format to PNG, you need to use an intermediate MemoryStream (because PNGs require a seekable stream to be saved). |
21,879 | <p>I'm trying to reteach myself some long forgotten math skills. This is part of a much larger project to effectively "teach myself software development" from the ground up (the details are <a href="http://www.appscanadian.ca/archives/cs-101-introduction-to-computer-science/" rel="noreferrer">here</a> if you're interested in helping out). </p>
<p>My biggest stumbling block so far has been math - how can I learn about algorithms and asymptotic notation without it??</p>
<p>What I'm looking for is some sort of "dependency tree" showing what I need to know. Is calculus required before discrete? What do I need to know before calculus (read: components to the general "pre-calculus" topic)? What can I cut out to fast track the project ("what can I go back for later")?</p>
<p>Thank!</p>
| [
{
"answer_id": 21962,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 4,
"selected": true,
"text": "<p>Here's how my school did it:</p>\n\n<pre><code>base:\n algebra\n trigonometry\n analytic geometry\n\ntrack 1 ... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1588/"
] | I'm trying to reteach myself some long forgotten math skills. This is part of a much larger project to effectively "teach myself software development" from the ground up (the details are [here](http://www.appscanadian.ca/archives/cs-101-introduction-to-computer-science/) if you're interested in helping out).
My biggest stumbling block so far has been math - how can I learn about algorithms and asymptotic notation without it??
What I'm looking for is some sort of "dependency tree" showing what I need to know. Is calculus required before discrete? What do I need to know before calculus (read: components to the general "pre-calculus" topic)? What can I cut out to fast track the project ("what can I go back for later")?
Thank! | Here's how my school did it:
```
base:
algebra
trigonometry
analytic geometry
track 1 track 2 track 3
calc 1 linear algebra statistics
calc 2 discrete math 1
calc 3 (multivariable) discrete math 2
differential equations
```
The base courses were a prerequisite for everything, the tracks were independent and taken in order.
So to answer your specific question, only algebra is needed for discrete. If you want to fast track, do one of these:
```
algebra, discrete
algebra, linear algebra, discrete (if you want to cover matrices first)
```
HTH... It about killed me when I returned to school and took these, but I'm a much better programmer for it. Good Luck! |
21,938 | <p>Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please.</p>
| [
{
"answer_id": 21942,
"author": "Philippe",
"author_id": 920,
"author_profile": "https://Stackoverflow.com/users/920",
"pm_score": 3,
"selected": false,
"text": "<p>Well, I don't see any difference between catching a general exception or a specific one, except that when having multiple c... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1731/"
] | Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please. | Obviously this is one of those questions where the only real answer is "it depends."
The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch.
The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here.
The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java:
```
try {
something();
} catch (Exception ex) {}
```
or this in Python:
```
try:
something()
except:
pass
```
Because these can be some of the hardest issues to track down.
A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can. |
21,961 | <pre><code>>>> import time
>>> time.strptime("01-31-2009", "%m-%d-%Y")
(2009, 1, 31, 0, 0, 0, 5, 31, -1)
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233378000.0
>>> 60*60*24 # seconds in a day
86400
>>> 1233378000.0 / 86400
14275.208333333334
</code></pre>
<p><code>time.mktime</code> should return the number of seconds since the epoch. Since I'm giving it a time at midnight and the epoch is at midnight, shouldn't the result be evenly divisible by the number of seconds in a day?</p>
| [
{
"answer_id": 21973,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 2,
"selected": false,
"text": "<pre><code>mktime(...)\n mktime(tuple) -> floating point number\n\n Convert a time tuple in local time to se... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2427/"
] | ```
>>> import time
>>> time.strptime("01-31-2009", "%m-%d-%Y")
(2009, 1, 31, 0, 0, 0, 5, 31, -1)
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233378000.0
>>> 60*60*24 # seconds in a day
86400
>>> 1233378000.0 / 86400
14275.208333333334
```
`time.mktime` should return the number of seconds since the epoch. Since I'm giving it a time at midnight and the epoch is at midnight, shouldn't the result be evenly divisible by the number of seconds in a day? | Short answer: Because of timezones.
The Epoch is in UTC.
For example, I'm on IST (Irish Standard Time) or UTC+1. [`time.mktime()`](https://docs.python.org/3/library/time.html#time.gmtime) is relative to my timezone, so on my system this refers to
```
>>> time.mktime((2009, 1, 31, 0, 0, 0, 5, 31, -1))
1233360000.0
```
Because you got the result 1233378000, that would suggest that you're 5 hours behind me
```
>>> (1233378000 - 1233360000) / (60*60)
5
```
Have a look at the [`time.gmtime()`](https://docs.python.org/3/library/time.html#time.gmtime) function which works off UTC. |
21,987 | <p>I am developing an application that controls an Machine.<br/>
When I receive an error from the Machine the users should be able to directly notice it, one way that is done is Flashing the tray on the taskbar. When the machine clears the error the tray should stop flashing.</p>
<p>There's one little annoyance using the <code>FlashWindowEx</code> function, when I clear the flashing of the window, it stays (in my case WinXP) orange (not flashing).</p>
<p><a href="https://i.stack.imgur.com/GOS2r.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GOS2r.gif" alt="" /></a></p>
<pre><code>[Flags]
public enum FlashMode {
/// <summary>
/// Stop flashing. The system restores the window to its original state.
/// </summary>
FLASHW_STOP = 0,
/// <summary>
/// Flash the window caption.
/// </summary>
FLASHW_CAPTION = 1,
/// <summary>
/// Flash the taskbar button.
/// </summary>
FLASHW_TRAY = 2,
/// <summary>
/// Flash both the window caption and taskbar button.
/// This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags.
/// </summary>
FLASHW_ALL = 3,
/// <summary>
/// Flash continuously, until the FLASHW_STOP flag is set.
/// </summary>
FLASHW_TIMER = 4,
/// <summary>
/// Flash continuously until the window comes to the foreground.
/// </summary>
FLASHW_TIMERNOFG = 12
}
public static bool FlashWindowEx(IntPtr hWnd, FlashMode fm) {
FLASHWINFO fInfo = new FLASHWINFO();
fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));
fInfo.hwnd = hWnd;
fInfo.dwFlags = (UInt32)fm;
fInfo.uCount = UInt32.MaxValue;
fInfo.dwTimeout = 0;
return FlashWindowEx(ref fInfo);
}
[StructLayout(LayoutKind.Sequential)]
public struct FLASHWINFO {
public UInt32 cbSize;
public IntPtr hwnd;
public UInt32 dwFlags;
public UInt32 uCount;
public UInt32 dwTimeout;
}
</code></pre>
<p>In my case I use <code>FLASHW_TRAY</code> to start flashing and <code>FLASHW_STOP</code> to stop the flashing.</p>
<p>Am I doing something wrong or is this a known bug of WinXP and is there a fix for it?</p>
| [
{
"answer_id": 23285,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 4,
"selected": true,
"text": "<p>Behaviour is the same when a window finishes flashing for as long as it's supposed to: the taskbar button stays colo... | 2008/08/22 | [
"https://Stackoverflow.com/questions/21987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2090/"
] | I am developing an application that controls an Machine.
When I receive an error from the Machine the users should be able to directly notice it, one way that is done is Flashing the tray on the taskbar. When the machine clears the error the tray should stop flashing.
There's one little annoyance using the `FlashWindowEx` function, when I clear the flashing of the window, it stays (in my case WinXP) orange (not flashing).
[](https://i.stack.imgur.com/GOS2r.gif)
```
[Flags]
public enum FlashMode {
/// <summary>
/// Stop flashing. The system restores the window to its original state.
/// </summary>
FLASHW_STOP = 0,
/// <summary>
/// Flash the window caption.
/// </summary>
FLASHW_CAPTION = 1,
/// <summary>
/// Flash the taskbar button.
/// </summary>
FLASHW_TRAY = 2,
/// <summary>
/// Flash both the window caption and taskbar button.
/// This is equivalent to setting the FLASHW_CAPTION | FLASHW_TRAY flags.
/// </summary>
FLASHW_ALL = 3,
/// <summary>
/// Flash continuously, until the FLASHW_STOP flag is set.
/// </summary>
FLASHW_TIMER = 4,
/// <summary>
/// Flash continuously until the window comes to the foreground.
/// </summary>
FLASHW_TIMERNOFG = 12
}
public static bool FlashWindowEx(IntPtr hWnd, FlashMode fm) {
FLASHWINFO fInfo = new FLASHWINFO();
fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo));
fInfo.hwnd = hWnd;
fInfo.dwFlags = (UInt32)fm;
fInfo.uCount = UInt32.MaxValue;
fInfo.dwTimeout = 0;
return FlashWindowEx(ref fInfo);
}
[StructLayout(LayoutKind.Sequential)]
public struct FLASHWINFO {
public UInt32 cbSize;
public IntPtr hwnd;
public UInt32 dwFlags;
public UInt32 uCount;
public UInt32 dwTimeout;
}
```
In my case I use `FLASHW_TRAY` to start flashing and `FLASHW_STOP` to stop the flashing.
Am I doing something wrong or is this a known bug of WinXP and is there a fix for it? | Behaviour is the same when a window finishes flashing for as long as it's supposed to: the taskbar button stays coloured. I don't think this is a bug. If you think about it, when you use `FLASHW_STOP`, the flashing does in fact stop, but the point of the flashing is to get the user's attention. The button stays coloured because the user still may not have looked down and discovered *which* window was trying to get her attention. Keeping the button coloured keeps that information available. |
22,001 | <p>I'm learning objective-C and Cocoa. In the Apple tutorial I'm working through there's a side note that says: </p>
<blockquote>
<p><code>IBOutlet</code> is a null-defined macro, which the C preprocessor removes at compile time.</p>
</blockquote>
<p>I'm curious - what's a null-defined macro?</p>
| [
{
"answer_id": 22003,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<pre><code>#define IBOutlet\n</code></pre>\n\n<p>Whenever IBOutlet is used in program text, it will be replaced with nothi... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm learning objective-C and Cocoa. In the Apple tutorial I'm working through there's a side note that says:
>
> `IBOutlet` is a null-defined macro, which the C preprocessor removes at compile time.
>
>
>
I'm curious - what's a null-defined macro? | ```
#define IBOutlet
```
Whenever IBOutlet is used in program text, it will be replaced with nothing at all. |
22,012 | <p>My application dynamically loads assemblies at runtime from specific subfolders. These assemblies are compiled with dependencies to other assemblies. The runtime trys to load these from the application directory. But I want to put them into the modules directory.</p>
<p>Is there a way to tell the runtime that the dlls are in a seperate subfolder?</p>
| [
{
"answer_id": 22022,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <code><probing></code> element in a manifest file to tell the Runtime to look in different directo... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2374/"
] | My application dynamically loads assemblies at runtime from specific subfolders. These assemblies are compiled with dependencies to other assemblies. The runtime trys to load these from the application directory. But I want to put them into the modules directory.
Is there a way to tell the runtime that the dlls are in a seperate subfolder? | One nice approach I've used lately is to add an event handler for the AppDomain's AssemblyResolve event.
```
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
```
Then in the event handler method you can load the assembly that was attempted to be resolved using one of the Assembly.Load, Assembly.LoadFrom overrides and return it from the method.
EDIT:
Based on your additional information I think using the technique above, specifically resolving the references to an assembly yourself is the only real approach that is going to work without restructuring your app. What it gives you is that the location of each and every assembly that the CLR fails to resolve can be determined and loaded by your code at runtime... I've used this in similar situations for both pluggable architectures and for an assembly reference integrity scanning tool. |
22,135 | <p>I am trying to implement NTLM authentication on one of our internal sites and everything is working. The one piece of the puzzle I do not have is how to take the information from NTLM and authenticate with Active Directory.</p>
<p>There is a <a href="http://www.innovation.ch/personal/ronald/ntlm.html" rel="nofollow noreferrer">good description of NTLM</a> and the <a href="http://us1.samba.org/samba/docs/man/Samba-Developers-Guide/pwencrypt.html" rel="nofollow noreferrer">encryption used for the passwords</a>, which I used to implement this, but I am not sure of how to verify if the user's password is valid.</p>
<p>I am using ColdFusion but a solution to this problem can be in any language (Java, Python, PHP, etc).</p>
<p>Edit:</p>
<p>I am using ColdFusion on Redhat Enterprise Linux. Unfortunately we cannot use IIS to manage this and instead have to write or use a 3rd party tool for this.</p>
<hr>
<p><strong>Update</strong> - <em>I got this working and here is what I did</em></p>
<p>I went with the <a href="http://jcifs.samba.org/" rel="nofollow noreferrer">JCIFS library from samba.org.</a></p>
<blockquote>
<p>Note that the method below will only work with NTLMv1 and <strong>DOES NOT</strong> work with NTLMv2. If you are unable to use NTLMv1 you can try <a href="http://www.ioplex.com/jespa.html" rel="nofollow noreferrer">Jespa</a>, which supports NTLMv2 but is not open source, or you can use <a href="http://spnego.sourceforge.net" rel="nofollow noreferrer">Kerberos/SPNEGO.</a></p>
</blockquote>
<p>Here is my web.xml:</p>
<pre><code><web-app>
<display-name>Ntlm</display-name>
<filter>
<filter-name>NtlmHttpFilter</filter-name>
<filter-class>jcifs.http.NtlmHttpFilter</filter-class>
<init-param>
<param-name>jcifs.http.domainController</param-name>
<param-value>dc01.corp.example.com</param-value>
</init-param>
<init-param>
<param-name>jcifs.smb.client.domain</param-name>
<param-value>CORP.EXAMPLE.COM</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>NtlmHttpFilter</filter-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
</web-app>
</code></pre>
<p>Now all URLs matching <code>/admin/*</code> will require NTLM authentication.</p>
| [
{
"answer_id": 22185,
"author": "Portman",
"author_id": 1690,
"author_profile": "https://Stackoverflow.com/users/1690",
"pm_score": 0,
"selected": false,
"text": "<p>Hm, I'm not sure what you're trying to accomplish.</p>\n\n<p>Usually implementing NTLM on an internal site is as simple as... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/309844/"
] | I am trying to implement NTLM authentication on one of our internal sites and everything is working. The one piece of the puzzle I do not have is how to take the information from NTLM and authenticate with Active Directory.
There is a [good description of NTLM](http://www.innovation.ch/personal/ronald/ntlm.html) and the [encryption used for the passwords](http://us1.samba.org/samba/docs/man/Samba-Developers-Guide/pwencrypt.html), which I used to implement this, but I am not sure of how to verify if the user's password is valid.
I am using ColdFusion but a solution to this problem can be in any language (Java, Python, PHP, etc).
Edit:
I am using ColdFusion on Redhat Enterprise Linux. Unfortunately we cannot use IIS to manage this and instead have to write or use a 3rd party tool for this.
---
**Update** - *I got this working and here is what I did*
I went with the [JCIFS library from samba.org.](http://jcifs.samba.org/)
>
> Note that the method below will only work with NTLMv1 and **DOES NOT** work with NTLMv2. If you are unable to use NTLMv1 you can try [Jespa](http://www.ioplex.com/jespa.html), which supports NTLMv2 but is not open source, or you can use [Kerberos/SPNEGO.](http://spnego.sourceforge.net)
>
>
>
Here is my web.xml:
```
<web-app>
<display-name>Ntlm</display-name>
<filter>
<filter-name>NtlmHttpFilter</filter-name>
<filter-class>jcifs.http.NtlmHttpFilter</filter-class>
<init-param>
<param-name>jcifs.http.domainController</param-name>
<param-value>dc01.corp.example.com</param-value>
</init-param>
<init-param>
<param-name>jcifs.smb.client.domain</param-name>
<param-value>CORP.EXAMPLE.COM</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>NtlmHttpFilter</filter-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
</web-app>
```
Now all URLs matching `/admin/*` will require NTLM authentication. | What you're really asking is: Is there any way to validate the "WWW-Authenticate: NTLM" tokens submitted by IE and other HTTP clients when doing Single Sign-On (SSO). SSO is when the user enters their password a "single" time when they do Ctrl-Alt-Del and the workstation remembers and uses it as necessary to transparently access other resources without prompting the user for a password again.
Note that Kerberos, like NTLM, can also be used to implement SSO authentication. When presented with a "WWW-Authenticate: Negotiate" header, IE and other browsers will send SPNEGO wrapped Kerberos and / or NTLM tokens. More on this later but first I will answer the question as asked.
The only way to validate an NTLMSSP password "response" (like the ones encoded in "WWW-Authenticate: NTLM" headers submitted by IE and other browsers) is with a NetrLogonSamLogon(Ex) DCERPC call with the NETLOGON service of an Active Directory domain controller that is an authority for, or has a "trust" with an authority for, the target account. Additionally, to properly secure the NETLOGON communication, Secure Channel encryption should be used and is required as of Windows Server 2008.
Needless to say, there are very few packages that implement the necessary NETLOGON service calls. The only ones I'm aware of are:
1. Windows (of course)
2. Samba - Samba is a set of software programs for UNIX that implements a number of Windows protocols including the necessary NETLOGON service calls. In fact, Samba 3 has a special daemon for this called "winbind" that other programs like PAM and Apache modules can (and do) interface with. On a Red Hat system you can do a `yum install samba-winbind` and `yum install mod_auth_ntlm_winbind`. But that's the easy part - setting these things up is another story.
3. Jespa - Jespa (<http://www.ioplex.com/jespa.html>) is a 100% Java library that implements all of the necessary NETLOGON service calls. It also provides implementations of standard Java interfaces for authenticating clients in various ways such as with an HTTP Servlet Filter, SASL server, JAAS LoginModule, etc.
Beware that there are a number of NTLM authentication acceptors that do not implement the necessary NETLOGON service calls but instead do something else that ultimately leads to failure in one scenario or another. For example, for years, the way to do this in Java was with the NTLM HTTP authentication Servlet Filter from a project called JCIFS. But that Filter uses a man-in-the-middle technique that has been responsible for a long-standing "hiccup bug" and, more important, it does not support NTLMv2. For these reasons and others it is scheduled to be removed from JCIFS. There are several projects that have been unintentionally inspired by that package that are now also equally doomed. There are also a lot of code fragments posted in Java forums that decode the header token and pluck out the domain and username but do absolutely nothing to actually validate the password responses. Suffice it to say, if you use one of those code fragments, you might as well walk around with your pants down.
As I eluded to earlier, NTLM is only one of several Windows Security Support Providers (SSP). There's also a Digest SSP, Kerberos SSP, etc. But the Negotiate SSP, which is also known as SPNEGO, is usually the provider that MS uses in their own protocol clients. The Negotiate SSP actually just negotiates either the NTLM SSP or Kerberos SSP. Note that Kerberos can only be used if both the server and client have accounts in the target domain and the client can communicate with the domain controller sufficiently to acquire a Kerberos ticket. If these conditions are not satisfied, the NTLM SSP is used directly. So NTLM is by no means obsolete.
Finally, some people have mentioned using an LDAP "simple bind" as a make-shift password validation service. LDAP is not really designed as an authentication service and for this reason it is not efficient. It is also not possible to implement SSO using LDAP. SSO requires NTLM or SPNEGO. If you can find a NETLOGON or SPNEGO acceptor, you should use that instead.
Mike |
22,181 | <p>I have a very simple mapping function called "BuildEntity" that does the usual boring "left/right" coding required to dump my reader data into my domain object. (shown below) My question is this - If I don't bring back every column in this mapping as is, I get the "System.IndexOutOfRangeException" exception and wanted to know if ado.net had anything to correct this so I don't need to bring back every column with each call into SQL ... </p>
<p>What I'm really looking for is something like "IsValidColumn" so I can keep this 1 mapping function throughout my DataAccess class with all the left/right mappings defined - and have it work even when a sproc doesn't return every column listed ...</p>
<pre><code>Using reader As SqlDataReader = cmd.ExecuteReader()
Dim product As Product
While reader.Read()
product = New Product()
product.ID = Convert.ToInt32(reader("ProductID"))
product.SupplierID = Convert.ToInt32(reader("SupplierID"))
product.CategoryID = Convert.ToInt32(reader("CategoryID"))
product.ProductName = Convert.ToString(reader("ProductName"))
product.QuantityPerUnit = Convert.ToString(reader("QuantityPerUnit"))
product.UnitPrice = Convert.ToDouble(reader("UnitPrice"))
product.UnitsInStock = Convert.ToInt32(reader("UnitsInStock"))
product.UnitsOnOrder = Convert.ToInt32(reader("UnitsOnOrder"))
product.ReorderLevel = Convert.ToInt32(reader("ReorderLevel"))
productList.Add(product)
End While
</code></pre>
| [
{
"answer_id": 22186,
"author": "Slavo",
"author_id": 1801,
"author_profile": "https://Stackoverflow.com/users/1801",
"pm_score": 0,
"selected": false,
"text": "<p>Why don't you use LinqToSql - everything you need is done automatically. For the sake of being general you can use any other... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a very simple mapping function called "BuildEntity" that does the usual boring "left/right" coding required to dump my reader data into my domain object. (shown below) My question is this - If I don't bring back every column in this mapping as is, I get the "System.IndexOutOfRangeException" exception and wanted to know if ado.net had anything to correct this so I don't need to bring back every column with each call into SQL ...
What I'm really looking for is something like "IsValidColumn" so I can keep this 1 mapping function throughout my DataAccess class with all the left/right mappings defined - and have it work even when a sproc doesn't return every column listed ...
```
Using reader As SqlDataReader = cmd.ExecuteReader()
Dim product As Product
While reader.Read()
product = New Product()
product.ID = Convert.ToInt32(reader("ProductID"))
product.SupplierID = Convert.ToInt32(reader("SupplierID"))
product.CategoryID = Convert.ToInt32(reader("CategoryID"))
product.ProductName = Convert.ToString(reader("ProductName"))
product.QuantityPerUnit = Convert.ToString(reader("QuantityPerUnit"))
product.UnitPrice = Convert.ToDouble(reader("UnitPrice"))
product.UnitsInStock = Convert.ToInt32(reader("UnitsInStock"))
product.UnitsOnOrder = Convert.ToInt32(reader("UnitsOnOrder"))
product.ReorderLevel = Convert.ToInt32(reader("ReorderLevel"))
productList.Add(product)
End While
``` | Although connection.GetSchema("Tables") does return meta data about the tables in your database, it won't return everything in your sproc if you define any custom columns.
For example, if you throw in some random ad-hoc column like \*SELECT ProductName,'Testing' As ProductTestName FROM dbo.Products" you won't see 'ProductTestName' as a column because it's not in the Schema of the Products table. To solve this, and ask for every column available in the returned data, leverage a method on the SqlDataReader object "GetSchemaTable()"
If I add this to the existing code sample you listed in your original question, you will notice just after the reader is declared I add a data table to capture the meta data from the reader itself. Next I loop through this meta data and add each column to another table that I use in the left-right code to check if each column exists.
**Updated Source Code**
```
Using reader As SqlDataReader = cmd.ExecuteReader()
Dim table As DataTable = reader.GetSchemaTable()
Dim colNames As New DataTable()
For Each row As DataRow In table.Rows
colNames.Columns.Add(row.ItemArray(0))
Next
Dim product As Product While reader.Read()
product = New Product()
If Not colNames.Columns("ProductID") Is Nothing Then
product.ID = Convert.ToInt32(reader("ProductID"))
End If
product.SupplierID = Convert.ToInt32(reader("SupplierID"))
product.CategoryID = Convert.ToInt32(reader("CategoryID"))
product.ProductName = Convert.ToString(reader("ProductName"))
product.QuantityPerUnit = Convert.ToString(reader("QuantityPerUnit"))
product.UnitPrice = Convert.ToDouble(reader("UnitPrice"))
product.UnitsInStock = Convert.ToInt32(reader("UnitsInStock"))
product.UnitsOnOrder = Convert.ToInt32(reader("UnitsOnOrder"))
product.ReorderLevel = Convert.ToInt32(reader("ReorderLevel"))
productList.Add(product)
End While
```
This is a hack to be honest, as you *should* return every column to hydrate your object correctly. But I thought to include this reader method as it would actually grab all the columns, even if they are not defined in your table schema.
This approach to mapping your relational data into your domain model might cause some issues when you get into a lazy loading scenario. |
22,187 | <p>What libraries exist for other programming languages to provide an Erlang-style concurrency model (processes, mailboxes, pattern-matching receive, etc.)?</p>
<p>Note: I am specifically interested in things that are intended to be similar to Erlang, not just any threading or queueing library.</p>
| [
{
"answer_id": 22197,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 3,
"selected": false,
"text": "<p>Microsoft <a href=\"http://msdn.microsoft.com/en-us/library/bb648752.aspx\" rel=\"noreferrer\">Concurrency and Coordin... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
] | What libraries exist for other programming languages to provide an Erlang-style concurrency model (processes, mailboxes, pattern-matching receive, etc.)?
Note: I am specifically interested in things that are intended to be similar to Erlang, not just any threading or queueing library. | Message Passing Interface (MPI) (<http://www-unix.mcs.anl.gov/mpi/>) is a highly scalable and robust library for parallel programming, geared original towards C but now available in several flavors <http://en.wikipedia.org/wiki/Message_Passing_Interface#Implementations>. While the library doesn't introduce new syntax, it provides a communication protocol to orchestrate the sharing of data between routines which are parallelizable.
Traditionally, it is used in large cluster computing rather than on a single system for concurrency, although multi-core systems can certainly take advantage of this library.
Another interesting solution to the problem of parallel programming is OpenMP, which is an attempt to provide a portable extension on various platforms to provide hints to the compiler about what sections of code are easily parallelizable.
For example (<http://en.wikipedia.org/wiki/OpenMP#Work-sharing_constructs>):
```
#define N 100000
int main(int argc, char *argv[])
{
int i, a[N];
#pragma omp parallel for
for (i=0;i<N;i++)
a[i]= 2*i;
return 0;
}
```
There are advantages and disadvantages to both, of course, but the former has proven to be extremely successful in academia and other heavy scientific computing applications. YMMV. |
22,239 | <p>(I'm using Visual C++ 2008) I've always heard that main() is <em>required</em> to return an integer, but here I didn't put in <code>return 0;</code> and and it compiled with 0 errors and 0 warnings! In the debug window it says the program has exited with code 0. If this function is named anything other than main(), the compiler complains saying 'blah' must return a value. Sticking a <code>return;</code> also causes the error to appear. But leaving it out completely, it compiles just fine.</p>
<pre><code>#include <iostream>
using namespace std;
int main()
{
cout << "Hey look I'm supposed to return an int but I'm not gonna!\n";
}
</code></pre>
<p>Could this be a bug in VC++?</p>
| [
{
"answer_id": 22251,
"author": "bradtgmurray",
"author_id": 1546,
"author_profile": "https://Stackoverflow.com/users/1546",
"pm_score": 2,
"selected": false,
"text": "<p>I'm pretty sure VC++ just inserts a return 0 if you don't include one in main functions. The same thing can happen wi... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2222/"
] | (I'm using Visual C++ 2008) I've always heard that main() is *required* to return an integer, but here I didn't put in `return 0;` and and it compiled with 0 errors and 0 warnings! In the debug window it says the program has exited with code 0. If this function is named anything other than main(), the compiler complains saying 'blah' must return a value. Sticking a `return;` also causes the error to appear. But leaving it out completely, it compiles just fine.
```
#include <iostream>
using namespace std;
int main()
{
cout << "Hey look I'm supposed to return an int but I'm not gonna!\n";
}
```
Could this be a bug in VC++? | >
> 3.6.1 Main function
> ===================
>
>
> ....
>
>
> 2 An implementation shall not predefine the `main` function. This function shall not be overloaded. It shall have a return type of type `int`, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:
>
>
>
> ```
> int main() { /* ... */ }
>
> ```
>
> and
>
>
>
> ```
> int main(int argc, char* argv[]) {
> /* ... */
> }
>
> ```
>
> .... and it continues to add ...
>
>
> 5 A `return` statement in `main` has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling `exit` with the return value as the argument. **If control reaches the end of `main` without encountering a return statement, the effect is that of executing return 0**;
>
>
>
attempting to find an online copy of the C++ standard so I could quote this passage [I found a blog post that quotes all the right bits better than I could.](http://zamanbakshifirst.blogspot.com/2006/11/c-c-main-should-return-void.html) |
22,259 | <p>I want to allow users to upload avatar-type images in a variety of formats (<strong>GIF, JPEG, and PNG at least</strong>), but to save them all as <strong>PNG database BLOBs</strong>. If the images are oversized, pixelwise, I want to resize them before DB-insertion.</p>
<p><strong>What is the best way to use GD to do the resizing and PNG conversion?</strong></p>
<p>Edit: Sadly, only <a href="http://php.net/manual/en/book.image.php" rel="nofollow noreferrer">GD</a> is available on the server I need to use, no <a href="http://www.imagemagick.org/script/index.php" rel="nofollow noreferrer">ImageMagick</a>.</p>
| [
{
"answer_id": 22267,
"author": "tslocum",
"author_id": 1662,
"author_profile": "https://Stackoverflow.com/users/1662",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.phpit.net/article/image-manipulation-php-gd-part2/\" rel=\"nofollow noreferrer\">This article</a> see... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820/"
] | I want to allow users to upload avatar-type images in a variety of formats (**GIF, JPEG, and PNG at least**), but to save them all as **PNG database BLOBs**. If the images are oversized, pixelwise, I want to resize them before DB-insertion.
**What is the best way to use GD to do the resizing and PNG conversion?**
Edit: Sadly, only [GD](http://php.net/manual/en/book.image.php) is available on the server I need to use, no [ImageMagick](http://www.imagemagick.org/script/index.php). | ```
<?php
/*
Resizes an image and converts it to PNG returning the PNG data as a string
*/
function imageToPng($srcFile, $maxSize = 100) {
list($width_orig, $height_orig, $type) = getimagesize($srcFile);
// Get the aspect ratio
$ratio_orig = $width_orig / $height_orig;
$width = $maxSize;
$height = $maxSize;
// resize to height (orig is portrait)
if ($ratio_orig < 1) {
$width = $height * $ratio_orig;
}
// resize to width (orig is landscape)
else {
$height = $width / $ratio_orig;
}
// Temporarily increase the memory limit to allow for larger images
ini_set('memory_limit', '32M');
switch ($type)
{
case IMAGETYPE_GIF:
$image = imagecreatefromgif($srcFile);
break;
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($srcFile);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($srcFile);
break;
default:
throw new Exception('Unrecognized image type ' . $type);
}
// create a new blank image
$newImage = imagecreatetruecolor($width, $height);
// Copy the old image to the new image
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output to a temp file
$destFile = tempnam();
imagepng($newImage, $destFile);
// Free memory
imagedestroy($newImage);
if ( is_file($destFile) ) {
$f = fopen($destFile, 'rb');
$data = fread($f);
fclose($f);
// Remove the tempfile
unlink($destFile);
return $data;
}
throw new Exception('Image conversion failed.');
}
``` |
22,269 | <p>I'm trying to build a C# console application to automate grabbing certain files from our website, mostly to save myself clicks and - frankly - just to have done it. But I've hit a snag that for which I've been unable to find a working solution.</p>
<p>The website I'm trying to which I'm trying to connect uses ASP.Net forms authorization, and I cannot figure out how to authenticate myself with it. This application is a complete hack so I can hard code my username and password or any other needed auth info, and the solution itself doesn't need to be something that is viable enough to release to general users. In other words, if the only possible solution is a hack, I'm fine with that.</p>
<p>Basically, I'm trying to use HttpWebRequest to pull the site that has the list of files, iterating through that list and then downloading what I need. So the actual work on the site is fairly trivial once I can get the website to consider me authorized.</p>
| [
{
"answer_id": 22267,
"author": "tslocum",
"author_id": 1662,
"author_profile": "https://Stackoverflow.com/users/1662",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.phpit.net/article/image-manipulation-php-gd-part2/\" rel=\"nofollow noreferrer\">This article</a> see... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/111/"
] | I'm trying to build a C# console application to automate grabbing certain files from our website, mostly to save myself clicks and - frankly - just to have done it. But I've hit a snag that for which I've been unable to find a working solution.
The website I'm trying to which I'm trying to connect uses ASP.Net forms authorization, and I cannot figure out how to authenticate myself with it. This application is a complete hack so I can hard code my username and password or any other needed auth info, and the solution itself doesn't need to be something that is viable enough to release to general users. In other words, if the only possible solution is a hack, I'm fine with that.
Basically, I'm trying to use HttpWebRequest to pull the site that has the list of files, iterating through that list and then downloading what I need. So the actual work on the site is fairly trivial once I can get the website to consider me authorized. | ```
<?php
/*
Resizes an image and converts it to PNG returning the PNG data as a string
*/
function imageToPng($srcFile, $maxSize = 100) {
list($width_orig, $height_orig, $type) = getimagesize($srcFile);
// Get the aspect ratio
$ratio_orig = $width_orig / $height_orig;
$width = $maxSize;
$height = $maxSize;
// resize to height (orig is portrait)
if ($ratio_orig < 1) {
$width = $height * $ratio_orig;
}
// resize to width (orig is landscape)
else {
$height = $width / $ratio_orig;
}
// Temporarily increase the memory limit to allow for larger images
ini_set('memory_limit', '32M');
switch ($type)
{
case IMAGETYPE_GIF:
$image = imagecreatefromgif($srcFile);
break;
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($srcFile);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($srcFile);
break;
default:
throw new Exception('Unrecognized image type ' . $type);
}
// create a new blank image
$newImage = imagecreatetruecolor($width, $height);
// Copy the old image to the new image
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
// Output to a temp file
$destFile = tempnam();
imagepng($newImage, $destFile);
// Free memory
imagedestroy($newImage);
if ( is_file($destFile) ) {
$f = fopen($destFile, 'rb');
$data = fread($f);
fclose($f);
// Remove the tempfile
unlink($destFile);
return $data;
}
throw new Exception('Image conversion failed.');
}
``` |
22,322 | <p>I've got a problem similar to,but subtly different from, that described <a href="https://stackoverflow.com/questions/22012/loading-assemblies-and-its-dependencies">here</a> (Loading assemblies and their dependencies).</p>
<p>I have a C++ DLL for 3D rendering that is what we sell to customers. For .NET users we will have a CLR wrapper around it. The C++ DLL can be built in both 32 and 64bit versions, but I think this means we need to have two CLR wrappers since the CLR binds to a specific DLL? </p>
<p>Say now our customer has a .NET app that can be either 32 or 64bit, and that it being a pure .NET app it leaves the CLR to work it out from a single set of assemblies. The question is how can the app code dynamically choose between our 32 and 64bit CLR/DLL combinations at run-time?</p>
<p>Even more specifically, is the suggested answer to the aforementioned question applicable here too (i.e. create a ResolveEvent handler)?</p>
| [
{
"answer_id": 22347,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 1,
"selected": false,
"text": "<p>I encountered a similar scenario a while back. A toolkit I was using did not behave well in a 64-bit environment and I wasn... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2102/"
] | I've got a problem similar to,but subtly different from, that described [here](https://stackoverflow.com/questions/22012/loading-assemblies-and-its-dependencies) (Loading assemblies and their dependencies).
I have a C++ DLL for 3D rendering that is what we sell to customers. For .NET users we will have a CLR wrapper around it. The C++ DLL can be built in both 32 and 64bit versions, but I think this means we need to have two CLR wrappers since the CLR binds to a specific DLL?
Say now our customer has a .NET app that can be either 32 or 64bit, and that it being a pure .NET app it leaves the CLR to work it out from a single set of assemblies. The question is how can the app code dynamically choose between our 32 and 64bit CLR/DLL combinations at run-time?
Even more specifically, is the suggested answer to the aforementioned question applicable here too (i.e. create a ResolveEvent handler)? | I finally have an answer for this that appears to work.
Compile both 32 & 64 bit versions - both managed & unmanaged - into separate folders. Then have the .NET app choose at run time which directory to load the assemblies from.
The problem with using the ResolveEvent is that it only gets called if assemblies aren't found, so it is all to easy to accidentally end up with 32 bit versions. Instead use a second AppDomain object where we can change the ApplicationBase property to point at the right folder. So you end up with code like:
```
static void Main(String[] argv)
{
// Create a new AppDomain, but with the base directory set to either the 32-bit or 64-bit
// sub-directories.
AppDomainSetup objADS = new AppDomainSetup();
System.String assemblyDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
switch (System.IntPtr.Size)
{
case (4): assemblyDir += "\\win32\\";
break;
case (8): assemblyDir += "\\x64\\";
break;
}
objADS.ApplicationBase = assemblyDir;
// We set the PrivateBinPath to the application directory, so that we can still
// load the platform neutral assemblies from the app directory.
objADS.PrivateBinPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
AppDomain objAD = AppDomain.CreateDomain("", null, objADS);
if (argv.Length > 0)
objAD.ExecuteAssembly(argv[0]);
else
objAD.ExecuteAssembly("MyApplication.exe");
AppDomain.Unload(objAD);
}
```
You end up with 2 exes - your normal app and a second switching app that chooses which bits to load.
Note - I can't take credit for the details of this myself. One of my colleagues sussed that out given my initial pointer. If and when he signs up to StackOverflow I'll assign the answer to him |
22,326 | <p>I am trying to <strong>replace the current selection in Word (2003/2007)</strong> by some <strong>RTF string</strong> stored in a variable.</p>
<p>Here is the current code:</p>
<pre><code>Clipboard.SetText(strRTFString, TextDataFormat.Rtf)
oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0)
</code></pre>
<p>Is there any way to do the same thing without going through the clipboard. Or is there any way to push the clipboard data to a safe place and restore it after?</p>
| [
{
"answer_id": 22335,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": -1,
"selected": false,
"text": "<p>You can use a RichTextbox to convert RTF to text or vice versa.</p>\n\n<pre><code>RichTextBox r = new RichTextBox();\nr... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1508/"
] | I am trying to **replace the current selection in Word (2003/2007)** by some **RTF string** stored in a variable.
Here is the current code:
```
Clipboard.SetText(strRTFString, TextDataFormat.Rtf)
oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0)
```
Is there any way to do the same thing without going through the clipboard. Or is there any way to push the clipboard data to a safe place and restore it after? | Put the RTF in a file instead of the clipboard, then insert from the file, e.g.
>
> `Selection.InsertFile FileName:="myfile.rtf", Range :="", _
> ConfirmConversions:=False, Link:=False, Attachment:=False`
>
>
> |
22,354 | <p>I am working on a SharePoint application that supports importing multiple documents in a single operation. I also have an ItemAdded event handler that performs some basic maintenance of the item metadata. This event fires for both imported documents and manually created ones. The final piece of the puzzle is a batch operation feature that I implemented to kick off a workflow and update another metadata field.</p>
<p>I am able to cause a COMException 0x81020037 by extracting the file data of a SPListItem. This file is just an InfoPath form/XML document. I am able to modify the XML and sucessfully push it back into the SPListItem. When I fire off the custom feature immediately afterwards and modify metadata, it occassionally causes the COM error.</p>
<p>The error message basically indicates that the file was modified by another thread. It would seem that the ItemAdded event is still writing the file back to the database while the custom feature is changing metadata. I have tried putting in delays and error catching loops to try to detect that the SPListItem is safe to modify with little success.</p>
<p>Is there a way to tell if another thread has a lock on a document?</p>
| [
{
"answer_id": 22703,
"author": "vitule",
"author_id": 1287,
"author_profile": "https://Stackoverflow.com/users/1287",
"pm_score": 1,
"selected": false,
"text": "<p>Sometimes I see the <code>ItemAdded</code> or <code>ItemUpdated</code> firing twice for a single operation. \nYou can try t... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
] | I am working on a SharePoint application that supports importing multiple documents in a single operation. I also have an ItemAdded event handler that performs some basic maintenance of the item metadata. This event fires for both imported documents and manually created ones. The final piece of the puzzle is a batch operation feature that I implemented to kick off a workflow and update another metadata field.
I am able to cause a COMException 0x81020037 by extracting the file data of a SPListItem. This file is just an InfoPath form/XML document. I am able to modify the XML and sucessfully push it back into the SPListItem. When I fire off the custom feature immediately afterwards and modify metadata, it occassionally causes the COM error.
The error message basically indicates that the file was modified by another thread. It would seem that the ItemAdded event is still writing the file back to the database while the custom feature is changing metadata. I have tried putting in delays and error catching loops to try to detect that the SPListItem is safe to modify with little success.
Is there a way to tell if another thread has a lock on a document? | Sometimes I see the `ItemAdded` or `ItemUpdated` firing twice for a single operation.
You can try to put a breakpoint in the `ItemAdded()` method to confirm that.
The solution in my case was to single thread the `ItemAdded()` method:
```
private static object myLock = new object();
public override void ItemAdded(SPItemEventProperties properties) {
if (System.Threading.Monitor.TryEnter(myLock, TimeSpan.FromSeconds(30))
{
//do your stuff here.
System.Threading.Monitor.Exit(myLock);
}
}
``` |
22,356 | <p>I find that the .NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is.</p>
<p>Based on the community suggestions, I've used this:</p>
<pre><code>// earlier in the code
mCoolObject.CoolEvent+=
new CoolObjectEventHandler(mCoolObject_CoolEvent);
// then
private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
if (InvokeRequired)
{
CoolObjectEventHandler cb =
new CoolObjectEventHandler(
mCoolObject_CoolEvent);
Invoke(cb, new object[] { sender, args });
return;
}
// do the dirty work of my method here
}
</code></pre>
| [
{
"answer_id": 22387,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "<p>I shun redundant delegate declarations.</p>\n\n<pre><code>private void mCoolObject_CoolEvent(object sender, CoolObj... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1490/"
] | I find that the .NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is.
Based on the community suggestions, I've used this:
```
// earlier in the code
mCoolObject.CoolEvent+=
new CoolObjectEventHandler(mCoolObject_CoolEvent);
// then
private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
if (InvokeRequired)
{
CoolObjectEventHandler cb =
new CoolObjectEventHandler(
mCoolObject_CoolEvent);
Invoke(cb, new object[] { sender, args });
return;
}
// do the dirty work of my method here
}
``` | A couple of observations:
* Don't create simple delegates explicitly in code like that unless you're pre-2.0 so you could use:
```cs
BeginInvoke(new EventHandler<CoolObjectEventArgs>(mCoolObject_CoolEvent),
sender,
args);
```
* Also you don't need to create and populate the object array because the args parameter is a "params" type so you can just pass in the list.
* I would probably favor `Invoke` over `BeginInvoke` as the latter will result in the code being called asynchronously which may or may not be what you're after but would make handling subsequent exceptions difficult to propagate without a call to `EndInvoke`. What would happen is that your app will end up getting a `TargetInvocationException` instead. |
22,379 | <p>I'm wondering how you can implement a program similar to <code>tail -f</code> in C/C++, a program that watches for and processes new lines added to a log file?</p>
| [
{
"answer_id": 22384,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/18632/how-to-monitor-a-text-file-in-realtime#18635\">See here</a></p>\n\n<p... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486/"
] | I'm wondering how you can implement a program similar to `tail -f` in C/C++, a program that watches for and processes new lines added to a log file? | You can use fseek() to clear the eof condition on the stream. Essentially, read to the end of the file, sleep for a while, fseek() (without changing your position) to clear eof, the read to end of file again. wash, rinse, repeat. man fseek(3) for details.
Here's what it looks like in perl. perl's seek() is essentially a wrapper for fseek(3), so the logic is the same:
```
wembley 0 /home/jj33/swap >#> cat p
my $f = shift;
open(I, "<$f") || die "Couldn't open $f: $!\n";
while (1) {
seek(I, 0, 1);
while (defined(my $l = <I>)) {
print "Got: $l";
}
print "Hit EOF, sleeping\n";
sleep(10);
}
wembley 0 /home/jj33/swap >#> cat tfile
This is
some
text
in
a file
wembley 0 /home/jj33/swap >#> perl p tfile
Got: This is
Got: some
Got: text
Got: in
Got: a file
Hit EOF, sleeping
```
Then, in another session:
```
wembley 0 /home/jj33/swap > echo "another line of text" >> tfile
```
And back to the original program output:
```
Hit EOF, sleeping
Got: another line of text
Hit EOF, sleeping
``` |
22,409 | <p>I have a need to convert images from CMYK to RGB - not necessarily back again, but hey, if it can be done...</p>
<p>With the release of ColdFusion 8, we got the <a href="http://cfquickdocs.com/cf8/?getDoc=cfimage" rel="nofollow noreferrer">CFImage</a> tag, but it doesn't support this conversion; and nor does <a href="http://x.com" rel="nofollow noreferrer">Image.cfc</a>, or <a href="http://x.com" rel="nofollow noreferrer">Alagad's Image Component</a>.</p>
<p>However, it should be possible in Java; which we can leverage through CF. For example, here's how you might create a Java thread to sleep a process:</p>
<pre><code><cfset jthread = createObject("java", "java.lang.Thread")/>
<cfset jthread.sleep(5000)/>
</code></pre>
<p>I would guess a similar method could be used to leverage java to do this image conversion, but not being a Java developer, I don't have a clue where to start. Can anyone lend a hand here?</p>
| [
{
"answer_id": 23577,
"author": "Michał Piaskowski",
"author_id": 1534,
"author_profile": "https://Stackoverflow.com/users/1534",
"pm_score": 4,
"selected": false,
"text": "<p>A very simple formula for converting from CMYK to RGB ignoring all color profiles is:</p>\n\n<pre>\n R = ( (2... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751/"
] | I have a need to convert images from CMYK to RGB - not necessarily back again, but hey, if it can be done...
With the release of ColdFusion 8, we got the [CFImage](http://cfquickdocs.com/cf8/?getDoc=cfimage) tag, but it doesn't support this conversion; and nor does [Image.cfc](http://x.com), or [Alagad's Image Component](http://x.com).
However, it should be possible in Java; which we can leverage through CF. For example, here's how you might create a Java thread to sleep a process:
```
<cfset jthread = createObject("java", "java.lang.Thread")/>
<cfset jthread.sleep(5000)/>
```
I would guess a similar method could be used to leverage java to do this image conversion, but not being a Java developer, I don't have a clue where to start. Can anyone lend a hand here? | I use the Java ImageIO libraries (<https://jai-imageio.dev.java.net>). They aren't perfect, but can be simple and get the job done. As far as converting from CMYK to RGB, here is the best I have been able to come up with.
Download and install the ImageIO JARs and native libraries for your platform. The native libraries are essential. Without them the ImageIO JAR files will not be able to detect the CMYK images. Originally, I was under the impression that the native libraries would improve performance but was not required for any functionality. I was wrong.
The only other thing that I noticed is that the converted RGB images are sometimes much lighter than the CMYK images. If anyone knows how to solve that problem, I would be appreciative.
Below is some code to convert a CMYK image into an RGB image of any supported format.
Thank you,
Randy Stegbauer
```
package cmyk;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.commons.lang.StringUtils;
public class Main
{
/**
* Creates new RGB images from all the CMYK images passed
* in on the command line.
* The new filename generated is, for example "GIF_original_filename.gif".
*
*/
public static void main(String[] args)
{
for (int ii = 0; ii < args.length; ii++)
{
String filename = args[ii];
boolean cmyk = isCMYK(filename);
System.out.println(cmyk + ": " + filename);
if (cmyk)
{
try
{
String rgbFile = cmyk2rgb(filename);
System.out.println(isCMYK(rgbFile) + ": " + rgbFile);
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}
}
/**
* If 'filename' is a CMYK file, then convert the image into RGB,
* store it into a JPEG file, and return the new filename.
*
* @param filename
*/
private static String cmyk2rgb(String filename) throws IOException
{
// Change this format into any ImageIO supported format.
String format = "gif";
File imageFile = new File(filename);
String rgbFilename = filename;
BufferedImage image = ImageIO.read(imageFile);
if (image != null)
{
int colorSpaceType = image.getColorModel().getColorSpace().getType();
if (colorSpaceType == ColorSpace.TYPE_CMYK)
{
BufferedImage rgbImage =
new BufferedImage(
image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
ColorConvertOp op = new ColorConvertOp(null);
op.filter(image, rgbImage);
rgbFilename = changeExtension(imageFile.getName(), format);
rgbFilename = new File(imageFile.getParent(), format + "_" + rgbFilename).getPath();
ImageIO.write(rgbImage, format, new File(rgbFilename));
}
}
return rgbFilename;
}
/**
* Change the extension of 'filename' to 'newExtension'.
*
* @param filename
* @param newExtension
* @return filename with new extension
*/
private static String changeExtension(String filename, String newExtension)
{
String result = filename;
if (filename != null && newExtension != null && newExtension.length() != 0);
{
int dot = filename.lastIndexOf('.');
if (dot != -1)
{
result = filename.substring(0, dot) + '.' + newExtension;
}
}
return result;
}
private static boolean isCMYK(String filename)
{
boolean result = false;
BufferedImage img = null;
try
{
img = ImageIO.read(new File(filename));
}
catch (IOException e)
{
System.out.println(e.getMessage() + ": " + filename);
}
if (img != null)
{
int colorSpaceType = img.getColorModel().getColorSpace().getType();
result = colorSpaceType == ColorSpace.TYPE_CMYK;
}
return result;
}
}
``` |
22,417 | <p>Say I have a Student table, it's got an int ID. I have a fixed set of 10 multiple choice questions with 5 possible answers. I have a normalized answer table that has the question id, the Student.answer (1-5) and the Student.ID</p>
<p>I'm trying to write a single query that will return all scores over a certain pecentage. To this end I wrote a simple UDF that accepts the Student.answers and the correct answer, so it has 20 parameters.</p>
<p>I'm starting to wonder if it's better to denormalize the answer table, bring it into my applcation and let my application do the scoring.</p>
<p>Anyone ever tackle something like this and have insight? </p>
| [
{
"answer_id": 22421,
"author": "Bryan Roth",
"author_id": 299,
"author_profile": "https://Stackoverflow.com/users/299",
"pm_score": 1,
"selected": false,
"text": "<p>I would probably leave it up to your application to perform the scoring. Check out <a href=\"http://www.codinghorror.com... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1975/"
] | Say I have a Student table, it's got an int ID. I have a fixed set of 10 multiple choice questions with 5 possible answers. I have a normalized answer table that has the question id, the Student.answer (1-5) and the Student.ID
I'm trying to write a single query that will return all scores over a certain pecentage. To this end I wrote a simple UDF that accepts the Student.answers and the correct answer, so it has 20 parameters.
I'm starting to wonder if it's better to denormalize the answer table, bring it into my applcation and let my application do the scoring.
Anyone ever tackle something like this and have insight? | If I understand your schema and question correctly, how about something like this:
```
select student_name, score
from students
join (select student_answers.student_id, count(*) as score
from student_answers, answer_key
group by student_id
where student_answers.question_id = answer_key.question_id
and student_answers.answer = answer_key.answer)
as student_scores on students.student_id = student_scores.student_id
where score >= 7
order by score, student_name
```
That should select the students with a score of 7 or more, for example. Just adjust the where clause for your purposes. |
22,429 | <p>Is it possible to embed an inline search box into a web page which provides similar functionality to the <a href="http://www.ie7pro.com/inline-search.html" rel="noreferrer">IE7Pro Inline Search</a> or similar plugins for Firefox/Safari?</p>
| [
{
"answer_id": 22421,
"author": "Bryan Roth",
"author_id": 299,
"author_profile": "https://Stackoverflow.com/users/299",
"pm_score": 1,
"selected": false,
"text": "<p>I would probably leave it up to your application to perform the scoring. Check out <a href=\"http://www.codinghorror.com... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2418/"
] | Is it possible to embed an inline search box into a web page which provides similar functionality to the [IE7Pro Inline Search](http://www.ie7pro.com/inline-search.html) or similar plugins for Firefox/Safari? | If I understand your schema and question correctly, how about something like this:
```
select student_name, score
from students
join (select student_answers.student_id, count(*) as score
from student_answers, answer_key
group by student_id
where student_answers.question_id = answer_key.question_id
and student_answers.answer = answer_key.answer)
as student_scores on students.student_id = student_scores.student_id
where score >= 7
order by score, student_name
```
That should select the students with a score of 7 or more, for example. Just adjust the where clause for your purposes. |
22,444 | <p>I have this gigantic ugly string:</p>
<pre class="lang-none prettyprint-override"><code>J0000000: Transaction A0001401 started on 8/22/2008 9:49:29 AM
J0000010: Project name: E:\foo.pf
J0000011: Job name: MBiek Direct Mail Test
J0000020: Document 1 - Completed successfully
</code></pre>
<p>I'm trying to extract pieces from it using regex. In this case, I want to grab everything after <code>Project Name</code> up to the part where it says <code>J0000011:</code> (the 11 is going to be a different number every time).</p>
<p>Here's the regex I've been playing with:</p>
<pre class="lang-none prettyprint-override"><code>Project name:\s+(.*)\s+J[0-9]{7}:
</code></pre>
<p>The problem is that it doesn't stop until it hits the <strong>J0000020:</strong> at the end.</p>
<p>How do I make the regex stop at the first occurrence of <code>J[0-9]{7}</code>?</p>
| [
{
"answer_id": 22449,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 8,
"selected": true,
"text": "<p>Make <code>.*</code> non-greedy by adding '<code>?</code>' after it:</p>\n\n<pre><code>Project name:\\s+(.*?)\\s+J[0-9]{7}:\n</c... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | I have this gigantic ugly string:
```none
J0000000: Transaction A0001401 started on 8/22/2008 9:49:29 AM
J0000010: Project name: E:\foo.pf
J0000011: Job name: MBiek Direct Mail Test
J0000020: Document 1 - Completed successfully
```
I'm trying to extract pieces from it using regex. In this case, I want to grab everything after `Project Name` up to the part where it says `J0000011:` (the 11 is going to be a different number every time).
Here's the regex I've been playing with:
```none
Project name:\s+(.*)\s+J[0-9]{7}:
```
The problem is that it doesn't stop until it hits the **J0000020:** at the end.
How do I make the regex stop at the first occurrence of `J[0-9]{7}`? | Make `.*` non-greedy by adding '`?`' after it:
```
Project name:\s+(.*?)\s+J[0-9]{7}:
``` |
22,459 | <p>I'm getting some strange, intermittent, data aborts (< 5% of the time) in some of my code, when calling <code>memset()</code>. The problem is that is usually doesn't happen unless the code is running for a couple days, so it's hard to catch it in the act.</p>
<p>I'm using the following code:</p>
<pre><code>char *msg = (char*)malloc(sizeof(char)*2048);
char *temp = (char*)malloc(sizeof(char)*1024);
memset(msg, 0, 2048);
memset(temp, 0, 1024);
char *tempstr = (char*)malloc(sizeof(char)*128);
sprintf(temp, "%s %s/%s %s%s", EZMPPOST, EZMPTAG, EZMPVER, TYPETXT, EOL);
strcat(msg, temp);
//Add Data
memset(tempstr, '\0', 128);
wcstombs(tempstr, gdevID, wcslen(gdevID));
sprintf(temp, "%s: %s%s", "DeviceID", tempstr, EOL);
strcat(msg, temp);
</code></pre>
<p>As you can see, I'm not trying to use memset with a size larger that what's originally allocated with <code>malloc()</code></p>
<p>Anyone see what might be wrong with this?</p>
| [
{
"answer_id": 22464,
"author": "Doug",
"author_id": 1618,
"author_profile": "https://Stackoverflow.com/users/1618",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried using Valgrind? That is usually the fastest and easiest way to debug these sorts of errors. If you are reading... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] | I'm getting some strange, intermittent, data aborts (< 5% of the time) in some of my code, when calling `memset()`. The problem is that is usually doesn't happen unless the code is running for a couple days, so it's hard to catch it in the act.
I'm using the following code:
```
char *msg = (char*)malloc(sizeof(char)*2048);
char *temp = (char*)malloc(sizeof(char)*1024);
memset(msg, 0, 2048);
memset(temp, 0, 1024);
char *tempstr = (char*)malloc(sizeof(char)*128);
sprintf(temp, "%s %s/%s %s%s", EZMPPOST, EZMPTAG, EZMPVER, TYPETXT, EOL);
strcat(msg, temp);
//Add Data
memset(tempstr, '\0', 128);
wcstombs(tempstr, gdevID, wcslen(gdevID));
sprintf(temp, "%s: %s%s", "DeviceID", tempstr, EOL);
strcat(msg, temp);
```
As you can see, I'm not trying to use memset with a size larger that what's originally allocated with `malloc()`
Anyone see what might be wrong with this? | `malloc` can return `NULL` if no memory is available. You're not checking for that. |
22,474 | <p>How do I select all records that contain "LCS" within the title column in sql.</p>
| [
{
"answer_id": 22476,
"author": "Owen",
"author_id": 2109,
"author_profile": "https://Stackoverflow.com/users/2109",
"pm_score": 3,
"selected": true,
"text": "<pre><code>SELECT * FROM TABLE WHERE TABLE.TITLE LIKE '%LCS%';\n</code></pre>\n\n<p>% is the wild card matcher.</p>\n"
},
{
... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453046/"
] | How do I select all records that contain "LCS" within the title column in sql. | ```
SELECT * FROM TABLE WHERE TABLE.TITLE LIKE '%LCS%';
```
% is the wild card matcher. |
22,503 | <p>I have a form view, in the edit template I have two drop downs.
Drop down 1 is explicitly set with a list of allowed values. It is also set to autopostback.
Drop down 2 is databound to an objectdatasource, this objectdatasource uses the first dropdown as one of it's parameters. (The idea is that drop down 1 limits what is shown in drop down 2)</p>
<p>On the first view of the edit template for an item it works fine. But if drop down 1 has a different item selected it post back and generates an error </p>
<blockquote>
<p>Databinding methods such as Eval(),
XPath(), and Bind() can only be used
in the context of a databound control.</p>
</blockquote>
<p>Here is the drop down list #2:</p>
<pre><code><asp:DropDownList ID="ProjectList" runat="server" SelectedValue='<%# Bind("ConnectToProject_ID","{0:D}") %>' DataSourceID="MasterProjectsDataSource2" DataTextField="Name" DataValueField="ID" AppendDataBoundItems="true">
<asp:ListItem Value="0" Text="{No Master Project}" Selected="True" />
</asp:DropDownList>
</code></pre>
<p>And here is the MasterProjectDataSource2:</p>
<pre><code><asp:ObjectDataSource ID="MasterProjectsDataSource2" runat="server"
SelectMethod="GetMasterProjectList" TypeName="WebWorxData.Project" >
<SelectParameters>
<asp:ControlParameter ControlID="RPMTypeList" Name="RPMType_ID"
PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
</code></pre>
<p>Any help on how to get this to work would be greatly appriciated.</p>
| [
{
"answer_id": 22797,
"author": "Joel Meador",
"author_id": 1976,
"author_profile": "https://Stackoverflow.com/users/1976",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like the controls aren't being databound properly after the postback.</p>\n\n<p>Are you databinding the first d... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2496/"
] | I have a form view, in the edit template I have two drop downs.
Drop down 1 is explicitly set with a list of allowed values. It is also set to autopostback.
Drop down 2 is databound to an objectdatasource, this objectdatasource uses the first dropdown as one of it's parameters. (The idea is that drop down 1 limits what is shown in drop down 2)
On the first view of the edit template for an item it works fine. But if drop down 1 has a different item selected it post back and generates an error
>
> Databinding methods such as Eval(),
> XPath(), and Bind() can only be used
> in the context of a databound control.
>
>
>
Here is the drop down list #2:
```
<asp:DropDownList ID="ProjectList" runat="server" SelectedValue='<%# Bind("ConnectToProject_ID","{0:D}") %>' DataSourceID="MasterProjectsDataSource2" DataTextField="Name" DataValueField="ID" AppendDataBoundItems="true">
<asp:ListItem Value="0" Text="{No Master Project}" Selected="True" />
</asp:DropDownList>
```
And here is the MasterProjectDataSource2:
```
<asp:ObjectDataSource ID="MasterProjectsDataSource2" runat="server"
SelectMethod="GetMasterProjectList" TypeName="WebWorxData.Project" >
<SelectParameters>
<asp:ControlParameter ControlID="RPMTypeList" Name="RPMType_ID"
PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
```
Any help on how to get this to work would be greatly appriciated. | I had a similar problem with bound dropdownlists in a FormView. I worked around it by setting the selected value manually in the formview's "OnDataBound".
(don't know where you get ConnectToProject\_ID from)
```
FormView fv = (FormView)sender;
DropDownList ddl = (DropDownList)fv.FindControl("ProjectList");
ddl.SelectedValue = String.Format("{0:D}", ConnectToProject_ID);
```
When you ready to save, use the "OnItemInserting" event:
```
FormView fv = (FormView)sender;
DropDownList ddl = (DropDownList)fv.FindControl("ProjectList");
e.Values["ConnectToProject_ID"] = ddl.SelectedValue;
```
or "OnItemUpdating"
When you ready to save, use the "OnItemInserting" event:
```
FormView fv = (FormView)sender;
DropDownList ddl = (DropDownList)fv.FindControl("ProjectList");
e.NewValues["ConnectToProject_ID"] = ddl.SelectedValue;
``` |
22,509 | <p>I have an ASP.NET webforms application (3.5 SP1) that I'm working on, and attempting to enable gzip fpr HTML and CSS that comes down the pipe. I'm using <a href="http://www.stardeveloper.com/articles/display.html?article=2007110401&page=1" rel="nofollow noreferrer">this implementation</a> (and tried a few others that hook into Application_BeginRequest), and it seems to be corrupting the external CSS file that the pages use, but intermittently...suddenly all styles will disappear on a page refresh, stay that way for awhile, and then suddenly start working again.</p>
<p>Both IE7 and FF3 exhibit this behavior. When viewing the CSS using the web developer toolbar, it returns jibberish. The cache-control header is coming through as "private," but I don't know enough to figure out if that's a contributing factor or not.</p>
<p>Also, this is running on the ASP.NET Development Server. Maybe it'd be fine with IIS, but I'm developing on XP and it'd be IIS5.</p>
| [
{
"answer_id": 22563,
"author": "Sean Carpenter",
"author_id": 729,
"author_profile": "https://Stackoverflow.com/users/729",
"pm_score": 0,
"selected": false,
"text": "<p>If you will be deploying on IIS 6 or IIS 7, just use the built-in IIS compression. We're using it on production site... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212/"
] | I have an ASP.NET webforms application (3.5 SP1) that I'm working on, and attempting to enable gzip fpr HTML and CSS that comes down the pipe. I'm using [this implementation](http://www.stardeveloper.com/articles/display.html?article=2007110401&page=1) (and tried a few others that hook into Application\_BeginRequest), and it seems to be corrupting the external CSS file that the pages use, but intermittently...suddenly all styles will disappear on a page refresh, stay that way for awhile, and then suddenly start working again.
Both IE7 and FF3 exhibit this behavior. When viewing the CSS using the web developer toolbar, it returns jibberish. The cache-control header is coming through as "private," but I don't know enough to figure out if that's a contributing factor or not.
Also, this is running on the ASP.NET Development Server. Maybe it'd be fine with IIS, but I'm developing on XP and it'd be IIS5. | Is it only CSS files that get corrupted? Do JS files (or any other static text files) come through ok?
Also can you duplicate the behavior if you browse directly to the CSS file?
I've only enabled compression on Windows 2003 server's IIS using this approach:
1. IIS → Web Sites → Properties → Service tab, check both boxes
2. IIS → Web Service Extensions → Right click, Add New
```
Name
Http Compression
Required Files
%systemroot%\system32\inetsrv\gzip.dll
```
3. IIS → Right click top node, Internet Information Services, check *Enable Direct Metabase Edit*
4. Backup and Edit `%systemroot%\system32\inetsrv\MetaBase.xml`
1. Find `Location ="/LM/W3SVC/Filters/Compression/gzip"`
* Add `png`, `css`, `js` and any other static file extensions to `HcFileExtensions`
* Add `aspx` and any other executable extensions to `HcScriptFileExtensions`
* Save
5. Restart IIS (run `iisreset`)
If you have a Windows 2003/2008 server to play with you could try that approach. |
22,552 | <p>I have a regex that is going to end up being a bit long and it'd make it much easier to read to have it across multiple lines.</p>
<p>I tried this but it just barfs.</p>
<pre><code>preg_match(
'^J[0-9]{7}:\s+
(.*?) #Extract the Transaction Start Date msg
\s+J[0-9]{7}:\s+Project\sname:\s+
(.*?) #Extract the Project Name
\s+J[0-9]{7}:\s+Job\sname:\s+
(.*?) #Extract the Job Name
\s+J[0-9]{7}:\s+',
$this->getResultVar('FullMessage'),
$atmp
);
</code></pre>
<p>Is there are way to pass a regex in the above form to preg_match?</p>
| [
{
"answer_id": 22572,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": true,
"text": "<p>You can use the extended syntax:</p>\n\n<pre><code>preg_match(\"/\n test\n/x\", $foo, $bar);\n</code></pre>\n"
... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | I have a regex that is going to end up being a bit long and it'd make it much easier to read to have it across multiple lines.
I tried this but it just barfs.
```
preg_match(
'^J[0-9]{7}:\s+
(.*?) #Extract the Transaction Start Date msg
\s+J[0-9]{7}:\s+Project\sname:\s+
(.*?) #Extract the Project Name
\s+J[0-9]{7}:\s+Job\sname:\s+
(.*?) #Extract the Job Name
\s+J[0-9]{7}:\s+',
$this->getResultVar('FullMessage'),
$atmp
);
```
Is there are way to pass a regex in the above form to preg\_match? | You can use the extended syntax:
```
preg_match("/
test
/x", $foo, $bar);
``` |
22,566 | <p>How do I get Perl to read the contents of a given directory into an array?</p>
<p><a href="https://en.wikipedia.org/wiki/Grave_accent#Use_in_programming" rel="noreferrer">Backticks</a> can do it, but is there some method using 'scandir' or a similar term?</p>
| [
{
"answer_id": 22573,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 7,
"selected": true,
"text": "<pre><code>opendir(D, \"/path/to/directory\") || die \"Can't open directory: $!\\n\";\nwhile (my $f = readdir(D)) {\n print \"\\... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] | How do I get Perl to read the contents of a given directory into an array?
[Backticks](https://en.wikipedia.org/wiki/Grave_accent#Use_in_programming) can do it, but is there some method using 'scandir' or a similar term? | ```
opendir(D, "/path/to/directory") || die "Can't open directory: $!\n";
while (my $f = readdir(D)) {
print "\$f = $f\n";
}
closedir(D);
```
EDIT: Oh, sorry, missed the "into an array" part:
```
my $d = shift;
opendir(D, "$d") || die "Can't open directory $d: $!\n";
my @list = readdir(D);
closedir(D);
foreach my $f (@list) {
print "\$f = $f\n";
}
```
EDIT2: Most of the other answers are valid, but I wanted to comment on [this answer](https://stackoverflow.com/questions/22566/how-do-i-read-in-the-contents-of-a-directory-in-perl#24436) specifically, in which this solution is offered:
```
opendir(DIR, $somedir) || die "Can't open directory $somedir: $!";
@dots = grep { (!/^\./) && -f "$somedir/$_" } readdir(DIR);
closedir DIR;
```
First, to document what it's doing since the poster didn't: it's passing the returned list from [readdir()](http://perldoc.perl.org/functions/readdir.html) through a [grep()](http://perldoc.perl.org/functions/grep.html) that only returns those values that are files (as opposed to directories, devices, named pipes, etc.) and that do not begin with a dot (which makes the list name `@dots` misleading, but that's due to the change he made when copying it over from the readdir() documentation). Since it limits the contents of the directory it returns, I don't think it's technically a correct answer to this question, but it illustrates a common idiom used to filter filenames in [Perl](http://en.wikipedia.org/wiki/Perl), and I thought it would be valuable to document. Another example seen a lot is:
```
@list = grep !/^\.\.?$/, readdir(D);
```
This snippet reads all contents from the directory handle D **except** '.' and '..', since those are very rarely desired to be used in the listing. |
22,570 | <p>Here is the issue I am having: I have a large query that needs to compare datetimes in the where clause to see if two dates are on the same day. My current solution, which sucks, is to send the datetimes into a UDF to convert them to midnight of the same day, and then check those dates for equality. When it comes to the query plan, this is a disaster, as are almost all UDFs in joins or where clauses. This is one of the only places in my application that I haven't been able to root out the functions and give the query optimizer something it can actually use to locate the best index.</p>
<p>In this case, merging the function code back into the query seems impractical.</p>
<p>I think I am missing something simple here.</p>
<p>Here's the function for reference.</p>
<pre><code>if not exists (select * from dbo.sysobjects
where id = object_id(N'dbo.f_MakeDate') and
type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
exec('create function dbo.f_MakeDate() returns int as
begin declare @retval int return @retval end')
go
alter function dbo.f_MakeDate
(
@Day datetime,
@Hour int,
@Minute int
)
returns datetime
as
/*
Creates a datetime using the year-month-day portion of @Day, and the
@Hour and @Minute provided
*/
begin
declare @retval datetime
set @retval = cast(
cast(datepart(m, @Day) as varchar(2)) +
'/' +
cast(datepart(d, @Day) as varchar(2)) +
'/' +
cast(datepart(yyyy, @Day) as varchar(4)) +
' ' +
cast(@Hour as varchar(2)) +
':' +
cast(@Minute as varchar(2)) as datetime)
return @retval
end
go
</code></pre>
<p>To complicate matters, I am joining on time zone tables to check the date against the local time, which could be different for every row:</p>
<pre><code>where
dbo.f_MakeDate(dateadd(hh, tz.Offset +
case when ds.LocalTimeZone is not null
then 1 else 0 end, t.TheDateINeedToCheck), 0, 0) = @activityDateMidnight
</code></pre>
<p>[Edit]</p>
<p>I'm incorporating @Todd's suggestion:</p>
<pre><code>where datediff(day, dateadd(hh, tz.Offset +
case when ds.LocalTimeZone is not null
then 1 else 0 end, t.TheDateINeedToCheck), @ActivityDate) = 0
</code></pre>
<p>My misconception about how datediff works (the same day of year in consecutive years yields 366, not 0 as I expected) caused me to waste a lot of effort.</p>
<p>But the query plan didn't change. I think I need to go back to the drawing board with the whole thing.</p>
| [
{
"answer_id": 22579,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 3,
"selected": false,
"text": "<pre><code>where\nyear(date1) = year(date2)\nand month(date1) = month(date2)\nand day(date1) = day(date2)\n</code></pre>\... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
] | Here is the issue I am having: I have a large query that needs to compare datetimes in the where clause to see if two dates are on the same day. My current solution, which sucks, is to send the datetimes into a UDF to convert them to midnight of the same day, and then check those dates for equality. When it comes to the query plan, this is a disaster, as are almost all UDFs in joins or where clauses. This is one of the only places in my application that I haven't been able to root out the functions and give the query optimizer something it can actually use to locate the best index.
In this case, merging the function code back into the query seems impractical.
I think I am missing something simple here.
Here's the function for reference.
```
if not exists (select * from dbo.sysobjects
where id = object_id(N'dbo.f_MakeDate') and
type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
exec('create function dbo.f_MakeDate() returns int as
begin declare @retval int return @retval end')
go
alter function dbo.f_MakeDate
(
@Day datetime,
@Hour int,
@Minute int
)
returns datetime
as
/*
Creates a datetime using the year-month-day portion of @Day, and the
@Hour and @Minute provided
*/
begin
declare @retval datetime
set @retval = cast(
cast(datepart(m, @Day) as varchar(2)) +
'/' +
cast(datepart(d, @Day) as varchar(2)) +
'/' +
cast(datepart(yyyy, @Day) as varchar(4)) +
' ' +
cast(@Hour as varchar(2)) +
':' +
cast(@Minute as varchar(2)) as datetime)
return @retval
end
go
```
To complicate matters, I am joining on time zone tables to check the date against the local time, which could be different for every row:
```
where
dbo.f_MakeDate(dateadd(hh, tz.Offset +
case when ds.LocalTimeZone is not null
then 1 else 0 end, t.TheDateINeedToCheck), 0, 0) = @activityDateMidnight
```
[Edit]
I'm incorporating @Todd's suggestion:
```
where datediff(day, dateadd(hh, tz.Offset +
case when ds.LocalTimeZone is not null
then 1 else 0 end, t.TheDateINeedToCheck), @ActivityDate) = 0
```
My misconception about how datediff works (the same day of year in consecutive years yields 366, not 0 as I expected) caused me to waste a lot of effort.
But the query plan didn't change. I think I need to go back to the drawing board with the whole thing. | This is much more concise:
```
where
datediff(day, date1, date2) = 0
``` |
22,617 | <p>I need to find out how to format numbers as strings. My code is here:</p>
<pre><code>return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
</code></pre>
<p>Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".</p>
<p>Bottom line, what library / function do I need to do this for me?</p>
| [
{
"answer_id": 22624,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 8,
"selected": true,
"text": "<p>Starting with Python 3.6, formatting in Python can be done using <a href=\"https://docs.python.org/3/whatsnew/3.6.ht... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2504/"
] | I need to find out how to format numbers as strings. My code is here:
```
return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm
```
Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".
Bottom line, what library / function do I need to do this for me? | Starting with Python 3.6, formatting in Python can be done using [formatted string literals](https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498) or *f-strings*:
```
hours, minutes, seconds = 6, 56, 33
f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
```
or the [`str.format`](https://docs.python.org/library/stdtypes.html#str.format) function starting with 2.7:
```
"{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am")
```
or the [string formatting `%` operator](https://docs.python.org/library/stdtypes.html#printf-style-string-formatting) for even older versions of Python, but see the note in the docs:
```
"%02d:%02d:%02d" % (hours, minutes, seconds)
```
And for your specific case of formatting time, there’s [`time.strftime`](https://docs.python.org/library/time.html#time.strftime):
```
import time
t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)
time.strftime('%I:%M:%S %p', t)
``` |
22,623 | <p>What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the <code>Exception</code> object's <code>InnerException</code> and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this?</p>
<pre><code>try
{
//some code
}
catch (Exception ex)
{
throw ex;
}
</code></pre>
<p>Vs:</p>
<pre><code>try
{
//some code
}
catch
{
throw;
}
</code></pre>
| [
{
"answer_id": 22628,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 9,
"selected": true,
"text": "<p>The way to preserve the stack trace is through the use of the <code>throw;</code> This is valid as well</p>\n\n<pre><code>t... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] | What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the `Exception` object's `InnerException` and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this?
```
try
{
//some code
}
catch (Exception ex)
{
throw ex;
}
```
Vs:
```
try
{
//some code
}
catch
{
throw;
}
``` | The way to preserve the stack trace is through the use of the `throw;` This is valid as well
```
try {
// something that bombs here
} catch (Exception ex)
{
throw;
}
```
`throw ex;` is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the `throw ex;` statement.
[Mike](https://stackoverflow.com/questions/22623/net-throwing-exceptions-best-practices#22649) is also correct, assuming the exception allows you to pass an exception (which is recommended).
[Karl Seguin](http://openmymind.net) has a [great write up on exception handling](http://codebetter.com/blogs/karlseguin/archive/2008/05/29/foundations-of-programming-pt-8-back-to-basics-exceptions.aspx) in his [foundations of programming e-book](http://openmymind.net/FoundationsOfProgramming.pdf) as well, which is a great read.
Edit: Working link to [Foundations of Programming](http://openmymind.net/FoundationsOfProgramming.pdf) pdf. Just search the text for "exception". |
22,676 | <p>I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes.</p>
<p>The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows <code>.bat</code> file to download the actual MP3 file. I would prefer to have the entire utility written in Python.</p>
<p>I struggled to find a way to actually download the file in Python, thus why I resorted to using <code>wget</code>.</p>
<p>So, how do I download the file using Python?</p>
| [
{
"answer_id": 22682,
"author": "Corey",
"author_id": 1595,
"author_profile": "https://Stackoverflow.com/users/1595",
"pm_score": 10,
"selected": true,
"text": "<p>Use <a href=\"https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen\" rel=\"noreferrer\"><code>urllib... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2109/"
] | I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes.
The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows `.bat` file to download the actual MP3 file. I would prefer to have the entire utility written in Python.
I struggled to find a way to actually download the file in Python, thus why I resorted to using `wget`.
So, how do I download the file using Python? | Use [`urllib.request.urlopen()`](https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen):
```
import urllib.request
with urllib.request.urlopen('http://www.example.com/') as f:
html = f.read().decode('utf-8')
```
This is the most basic way to use the library, minus any error handling. You can also do more complex stuff such as changing headers.
On Python 2, the method is in [`urllib2`](http://docs.python.org/2/library/urllib2.html):
```
import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read()
``` |
22,697 | <p>What's the best framework for creating mock objects in Java? Why? What are the pros and cons of each framework?</p>
| [
{
"answer_id": 23048,
"author": "Brian Laframboise",
"author_id": 1557,
"author_profile": "https://Stackoverflow.com/users/1557",
"pm_score": 9,
"selected": true,
"text": "<p>I've had good success using <a href=\"https://github.com/mockito/mockito\" rel=\"noreferrer\">Mockito</a>.</p>\n\... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2030/"
] | What's the best framework for creating mock objects in Java? Why? What are the pros and cons of each framework? | I've had good success using [Mockito](https://github.com/mockito/mockito).
When I tried learning about JMock and EasyMock, I found the learning curve to be a bit steep (though maybe that's just me).
I like Mockito because of its simple and clean syntax that I was able to grasp pretty quickly. The minimal syntax is designed to support the common cases very well, although the few times I needed to do something more complicated I found what I wanted was supported and easy to grasp.
Here's an (abridged) example from the Mockito homepage:
```
import static org.mockito.Mockito.*;
List mockedList = mock(List.class);
mockedList.clear();
verify(mockedList).clear();
```
It doesn't get much simpler than that.
The only major downside I can think of is that it won't mock static methods. |
22,708 | <p>How would you determine the column name (e.g. "AQ" or "BH") of the nth column in Excel?</p>
<p>Edit: A language-agnostic algorithm to determine this is the main goal here.</p>
| [
{
"answer_id": 22715,
"author": "Joseph Sturtevant",
"author_id": 317,
"author_profile": "https://Stackoverflow.com/users/317",
"pm_score": 6,
"selected": true,
"text": "<p>I once wrote this function to perform that exact task:</p>\n\n<pre><code>public static string Column(int column)\n{... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940/"
] | How would you determine the column name (e.g. "AQ" or "BH") of the nth column in Excel?
Edit: A language-agnostic algorithm to determine this is the main goal here. | I once wrote this function to perform that exact task:
```
public static string Column(int column)
{
column--;
if (column >= 0 && column < 26)
return ((char)('A' + column)).ToString();
else if (column > 25)
return Column(column / 26) + Column(column % 26 + 1);
else
throw new Exception("Invalid Column #" + (column + 1).ToString());
}
``` |
22,720 | <p>I have a listening port on my server that I'm connecting to using a Java class and the <code>Socket</code> interface, i.e.</p>
<pre><code>Socket mySocket = new Socket(host,port);
</code></pre>
<p>I then grab an <code>OutputStream</code>, decorate with a <code>PrintWriter</code> in autoflush mode and I'm laughing - except if the listening port closes. Then I get </p>
<pre><code>tcp4 0 0 *.9999 *.* LISTEN
tcp 0 0 127.0.0.1.45737 127.0.0.1.9999 CLOSE_WAIT
</code></pre>
<p>and I can't seem to detect the problem in the program - I've tried using the <code>isConnected()</code> method on the socket but it doesn't seem to know that the connection is closed.</p>
<p>I want to be aware of the problem the next time I try and write to the Socket so that I can try and reconnect and report the issue.</p>
<p>Any advice please?</p>
<p>Thanks all</p>
| [
{
"answer_id": 22803,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": true,
"text": "<p>Set a short timeout?</p>\n\n<p>Does <code>isOutputShutdown()</code> not get you what you want?</p>\n\n<p>You could a... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2362/"
] | I have a listening port on my server that I'm connecting to using a Java class and the `Socket` interface, i.e.
```
Socket mySocket = new Socket(host,port);
```
I then grab an `OutputStream`, decorate with a `PrintWriter` in autoflush mode and I'm laughing - except if the listening port closes. Then I get
```
tcp4 0 0 *.9999 *.* LISTEN
tcp 0 0 127.0.0.1.45737 127.0.0.1.9999 CLOSE_WAIT
```
and I can't seem to detect the problem in the program - I've tried using the `isConnected()` method on the socket but it doesn't seem to know that the connection is closed.
I want to be aware of the problem the next time I try and write to the Socket so that I can try and reconnect and report the issue.
Any advice please?
Thanks all | Set a short timeout?
Does `isOutputShutdown()` not get you what you want?
You could always build a `SocketWatcher` class that spins up in its own `Thread` and repeatedly tries to write empty strings to the `Socket` until that raises a `SocketClosedException`. |
22,732 | <p>I am trying to do some string concatenation/formatting, but it's putting all the parameters into the first placeholder.</p>
<p><strong>Code</strong></p>
<pre><code>function CreateAppPoolScript([string]$AppPoolName, [string]$AppPoolUser, [string]$AppPoolPass)
{
# Command to create an IIS application pool
$AppPoolScript = "cscript adsutil.vbs CREATE ""w3svc/AppPools/$AppPoolName"" IIsApplicationPool`n"
$AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserName"" ""$AppPoolUser""`n"
$AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserPass"" ""$AppPoolPass""`n"
$AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/AppPoolIdentityType"" 3"
return $AppPoolScript
}
$s = CreateAppPoolScript("name", "user", "pass")
write-host $s
</code></pre>
<p><strong>Output</strong></p>
<pre class="lang-none prettyprint-override"><code>cscript adsutil.vbs CREATE "w3svc/AppPools/name user pass" IIsApplicationPool
cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserName" ""
cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserPass" ""
cscript adsutil.vbs SET "w3svc/AppPools/name user pass/AppPoolIdentityType" 3
</code></pre>
| [
{
"answer_id": 22770,
"author": "Paul Roub",
"author_id": 1324,
"author_profile": "https://Stackoverflow.com/users/1324",
"pm_score": 7,
"selected": true,
"text": "<p>Lose the parentheses and commas. </p>\n\n<p>Calling your function as:</p>\n\n<pre><code>$s = CreateAppPoolScript \"name\... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
] | I am trying to do some string concatenation/formatting, but it's putting all the parameters into the first placeholder.
**Code**
```
function CreateAppPoolScript([string]$AppPoolName, [string]$AppPoolUser, [string]$AppPoolPass)
{
# Command to create an IIS application pool
$AppPoolScript = "cscript adsutil.vbs CREATE ""w3svc/AppPools/$AppPoolName"" IIsApplicationPool`n"
$AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserName"" ""$AppPoolUser""`n"
$AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserPass"" ""$AppPoolPass""`n"
$AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/AppPoolIdentityType"" 3"
return $AppPoolScript
}
$s = CreateAppPoolScript("name", "user", "pass")
write-host $s
```
**Output**
```none
cscript adsutil.vbs CREATE "w3svc/AppPools/name user pass" IIsApplicationPool
cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserName" ""
cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserPass" ""
cscript adsutil.vbs SET "w3svc/AppPools/name user pass/AppPoolIdentityType" 3
``` | Lose the parentheses and commas.
Calling your function as:
```
$s = CreateAppPoolScript "name" "user" "pass"
```
gives:
```none
cscript adsutil.vbs CREATE "w3svc/AppPools/name" IIsApplicationPool
cscript adsutil.vbs SET "w3svc/AppPools/name/WamUserName" "user"
cscript adsutil.vbs SET "w3svc/AppPools/name/WamUserPass" "pass"
cscript adsutil.vbs SET "w3svc/AppPools/name/AppPoolIdentityType" 3
``` |
22,764 | <p>In Ruby 1.8 and earlier,</p>
<pre><code>Foo
</code></pre>
<p>is a constant (a Class, a Module, or another constant). Whereas</p>
<pre><code>foo
</code></pre>
<p>is a variable. The key difference is as follows:</p>
<pre><code>module Foo
bar = 7
BAZ = 8
end
Foo::BAZ
# => 8
Foo::bar
# NoMethodError: undefined method 'bar' for Foo:Module
</code></pre>
<p>That's all well and good, but Ruby 1.9 <a href="http://pragdave.blogs.pragprog.com/pragdave/2008/04/fun-with-ruby-1.html" rel="nofollow noreferrer">allows UTF-8 source code</a>. So is <code>℃</code> "uppercase" or "lowecase" as far as this is concerned? What about <code>⊂</code> (strict subset) or <code>Ɖfoo</code>?</p>
<p>Is there a general rule?</p>
<p><em>Later:</em></p>
<p>Ruby-core is already considering some of the mathematical operators. For example</p>
<pre><code>module Kernel
def √(num)
...
end
def ∑(*args)
...
end
end
</code></pre>
<p>would allow</p>
<pre><code>x = √2
y = ∑(1, 45, ...)
</code></pre>
<p>I would love to see</p>
<pre><code>my_proc = λ { |...| ... }
x ∈ my_enumerable # same as my_enumerable.include?(x)
my_infinite_range = (1..∞)
return 'foo' if x ≠ y
2.21 ≈ 2.2
</code></pre>
| [
{
"answer_id": 23945,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know what ruby would do if you used extended UTF8 characters as identifiers in your source code, but I know wh... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] | In Ruby 1.8 and earlier,
```
Foo
```
is a constant (a Class, a Module, or another constant). Whereas
```
foo
```
is a variable. The key difference is as follows:
```
module Foo
bar = 7
BAZ = 8
end
Foo::BAZ
# => 8
Foo::bar
# NoMethodError: undefined method 'bar' for Foo:Module
```
That's all well and good, but Ruby 1.9 [allows UTF-8 source code](http://pragdave.blogs.pragprog.com/pragdave/2008/04/fun-with-ruby-1.html). So is `℃` "uppercase" or "lowecase" as far as this is concerned? What about `⊂` (strict subset) or `Ɖfoo`?
Is there a general rule?
*Later:*
Ruby-core is already considering some of the mathematical operators. For example
```
module Kernel
def √(num)
...
end
def ∑(*args)
...
end
end
```
would allow
```
x = √2
y = ∑(1, 45, ...)
```
I would love to see
```
my_proc = λ { |...| ... }
x ∈ my_enumerable # same as my_enumerable.include?(x)
my_infinite_range = (1..∞)
return 'foo' if x ≠ y
2.21 ≈ 2.2
``` | I can't get IRB to accept UTF-8 characters, so I used a test script (`/tmp/utf_test.rb`).
"λ" works fine as a variable name:
```
# encoding: UTF-8
λ = 'foo'
puts λ
# from the command line:
> ruby -KU /tmp/utf_test.rb
foo
```
"λ" also works fine as a method name:
```
# encoding: UTF-8
Kernel.class_eval do
alias_method :λ, :lambda
end
(λ { puts 'hi' }).call
# from the command line:
> ruby -KU /tmp/utf_test.rb:
hi
```
It doesn't work as a constant, though:
```
# encoding: UTF-8
Object.const_set :λ, 'bar'
# from the command line:
> ruby -KU /tmp/utf_test.rb:
utf_test.rb:2:in `const_set': wrong constant name λ (NameError)
```
Nor does the capitalized version:
```
# encoding: UTF-8
Object.const_set :Λ, 'bar'
# from the command line:
> ruby -KU /tmp/utf_test.rb:
utf_test.rb:2:in `const_set': wrong constant name Λ (NameError)
```
My suspicion is that constant names must start with a capital ASCII letter (must match `/^[A-Z]/`). |
22,801 | <p>It's about PHP but I've no doubt many of the same comments will apply to other languages.</p>
<p>Simply put, what are the differences in the different types of loop for PHP? Is one faster/better than the others or should I simply put in the most readable loop?</p>
<pre><code>for ($i = 0; $i < 10; $i++)
{
# code...
}
foreach ($array as $index => $value)
{
# code...
}
do
{
# code...
}
while ($flag == false);
</code></pre>
| [
{
"answer_id": 22806,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 0,
"selected": false,
"text": "<p>I use the first loop when iterating over a conventional (indexed?) array and the foreach loop when dealing with an asso... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] | It's about PHP but I've no doubt many of the same comments will apply to other languages.
Simply put, what are the differences in the different types of loop for PHP? Is one faster/better than the others or should I simply put in the most readable loop?
```
for ($i = 0; $i < 10; $i++)
{
# code...
}
foreach ($array as $index => $value)
{
# code...
}
do
{
# code...
}
while ($flag == false);
``` | For loop and While loops are entry condition loops. They evaluate condition first, so the statement block associated with the loop won't run even once if the condition fails to meet
The statements inside this for loop block will run 10 times, the value of $i will be 0 to 9;
```
for ($i = 0; $i < 10; $i++)
{
# code...
}
```
Same thing done with while loop:
```
$i = 0;
while ($i < 10)
{
# code...
$i++
}
```
Do-while loop is exit-condition loop. It's guaranteed to execute once, then it will evaluate condition before repeating the block
```
do
{
# code...
}
while ($flag == false);
```
foreach is used to access array elements from start to end. At the beginning of foreach loop, the internal pointer of the array is set to the first element of the array, in next step it is set to the 2nd element of the array and so on till the array ends. In the loop block The value of current array item is available as $value and the key of current item is available as $index.
```
foreach ($array as $index => $value)
{
# code...
}
```
You could do the same thing with while loop, like this
```
while (current($array))
{
$index = key($array); // to get key of the current element
$value = $array[$index]; // to get value of current element
# code ...
next($array); // advance the internal array pointer of $array
}
```
And lastly: [The PHP Manual](http://www.php.net/download-docs.php) is your friend :) |
22,807 | <p>Wondering if there is a better why in the WHERE clause of choosing records when you need to look at effective start and end dates?</p>
<p>Currently this how I've done it in the past on MS SQL Server. Just worried about the date and not the time. I'm using SQL Server 2005.</p>
<pre><code>AND Convert(datetime, Convert(char(10), ep.EffectiveStartDate, 101))
<= Convert(datetime, Convert(char(10), GetDate(), 101))
AND Convert(datetime, Convert(char(10), ep.EffectiveEndDate, 101))
>= Convert(datetime, Convert(char(10), GetDate(), 101))
</code></pre>
| [
{
"answer_id": 22809,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": -1,
"selected": false,
"text": "<p>try</p>\n\n<pre><code>ep.EffectiveStartDate BETWEEN @date1 AND @date2\n</code></pre>\n\n<p>where you would do something l... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2526/"
] | Wondering if there is a better why in the WHERE clause of choosing records when you need to look at effective start and end dates?
Currently this how I've done it in the past on MS SQL Server. Just worried about the date and not the time. I'm using SQL Server 2005.
```
AND Convert(datetime, Convert(char(10), ep.EffectiveStartDate, 101))
<= Convert(datetime, Convert(char(10), GetDate(), 101))
AND Convert(datetime, Convert(char(10), ep.EffectiveEndDate, 101))
>= Convert(datetime, Convert(char(10), GetDate(), 101))
``` | That is terrible, take a look at [Only In A Database Can You Get 1000% + Improvement By Changing A Few Lines Of Code](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/only-in-a-database-can-you-get-1000-impr) to see how you can optimize this since that is not sargable
Also check out [Get Datetime Without Time](http://wiki.lessthandot.com/index.php/Get_Datetime_Without_Time) and [Query Optimizations With Dates](http://wiki.lessthandot.com/index.php/Query_Optimizations_With_Dates) |
22,816 | <p>I know the following libraries for drawing charts in an SWT/Eclipse RCP application:</p>
<ul>
<li><a href="http://www.eclipse.org/articles/article.php?file=Article-BIRTChartEngine/index.html" rel="noreferrer">Eclipse BIRT Chart Engine</a> (Links to an article on how to use it)</li>
<li><a href="http://www.jfree.org/jfreechart/" rel="noreferrer">JFreeChart</a></li>
</ul>
<p>Which other libraries are there for drawing pretty charts with SWT? Or charts in Java generally? After all, you can always display an image...</p>
| [
{
"answer_id": 22830,
"author": "FreeMemory",
"author_id": 2132,
"author_profile": "https://Stackoverflow.com/users/2132",
"pm_score": 0,
"selected": false,
"text": "<p>There's also JGraph, but I'm not sure if that's only for graphs (i.e. nodes and edges), or if it does charts also.</p>\... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1793/"
] | I know the following libraries for drawing charts in an SWT/Eclipse RCP application:
* [Eclipse BIRT Chart Engine](http://www.eclipse.org/articles/article.php?file=Article-BIRTChartEngine/index.html) (Links to an article on how to use it)
* [JFreeChart](http://www.jfree.org/jfreechart/)
Which other libraries are there for drawing pretty charts with SWT? Or charts in Java generally? After all, you can always display an image... | I have not used BIRT or JGraph, however I use JFreeChart in my SWT application. I have found the best way to use JFreeChart in SWT is by making a composite an AWT frame and using the AWT functionality for JFreeChart. The way to do this is by creating a composite
```
Composite comp = new Composite(parent, SWT.NONE | SWT.EMBEDDED);
Frame frame = SWT_AWT.new_Frame(comp);
JFreeChart chart = createChart();
ChartPanel chartPanel = new ChartPanel(chart);
frame.add(chartPanel);
```
There are several problems in regards to implementations across different platforms as well as the SWT code in it is very poor (in its defense Mr. Gilbert does not know SWT well and it is made for AWT). My two biggest problems are as AWT events bubble up through SWT there are some erroneous events fired and due to wrapping the AWT frame JFreeChart becomes substantially slower.
@zvikico
The idea of putting the chart into a web page is probably not a great way to go. There are a few problems first being how Eclipse handles integrating the web browser on different platforms is inconsistent. Also from my understanding of a few graphing packages for the web they are server side requiring that setup, also many companies including mine use proxy servers and sometimes this creates issues with the Eclipse web browsing. |
22,836 | <p>In Perl, what is a good way to perform a replacement on a string using a regular expression and store the value in a different variable, without changing the original?</p>
<p>I usually just copy the string to a new variable then bind it to the <code>s///</code> regex that does the replacement on the new string, but I was wondering if there is a better way to do this?</p>
<pre><code>$newstring = $oldstring;
$newstring =~ s/foo/bar/g;
</code></pre>
| [
{
"answer_id": 22896,
"author": "John Siracusa",
"author_id": 164,
"author_profile": "https://Stackoverflow.com/users/164",
"pm_score": 9,
"selected": true,
"text": "<p>This is the idiom I've always used to get a modified copy of a string without changing the original:</p>\n<pre><code>(m... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] | In Perl, what is a good way to perform a replacement on a string using a regular expression and store the value in a different variable, without changing the original?
I usually just copy the string to a new variable then bind it to the `s///` regex that does the replacement on the new string, but I was wondering if there is a better way to do this?
```
$newstring = $oldstring;
$newstring =~ s/foo/bar/g;
``` | This is the idiom I've always used to get a modified copy of a string without changing the original:
```
(my $newstring = $oldstring) =~ s/foo/bar/g;
```
In perl 5.14.0 or later, you can use the new `/r` [non-destructive substitution modifier](https://metacpan.org/pod/release/FLORA/perl-5.14.2/pod/perl5140delta.pod#Non-destructive-substitution):
```
my $newstring = $oldstring =~ s/foo/bar/gr;
```
---
**NOTE:**
The above solutions work without `g` too. They also work with any other modifiers.
**SEE ALSO:**
[`perldoc perlrequick`: Perl regular expressions quick start](https://perldoc.perl.org/perlrequick) |
22,879 | <p>I'm able to connect to and read an excel file no problem. But when importing data such as zipcodes that have leading zeros, how do you prevent excel from guessing the datatype and in the process stripping out leading zeros?</p>
| [
{
"answer_id": 22891,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 1,
"selected": false,
"text": "<p>Prefix with '</p>\n"
},
{
"answer_id": 22897,
"author": "Owen",
"author_id": 2109,
"author_profile": "https:... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1874/"
] | I'm able to connect to and read an excel file no problem. But when importing data such as zipcodes that have leading zeros, how do you prevent excel from guessing the datatype and in the process stripping out leading zeros? | I believe you have to set the option in your connect string to force textual import rather than auto-detecting it.
```
Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=c:\path\to\myfile.xlsx;
Extended Properties=\"Excel 12.0 Xml;IMEX=1\";
```
Your milage may vary depending on the version you have installed. The IMEX=1 extended property tells Excel to treat intermixed data as text. |
22,935 | <p>Does anyone have a technique for generating SQL table create (and data insert) commands pragmatically from a CSV (or sheet in a .xls) file? </p>
<p>I've got a third party database system which I'd like to populate with data from a csv file (or sheet in a xls file) but the importer supplied can't create the table structure automatically as it does the import. My csv file has lots of tables with lots of columns so I'd like to automate the table creation process as well as the data importing if possible but I'm unsure about how to go about generating the create statement...</p>
| [
{
"answer_id": 22948,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": true,
"text": "<p>In SQL server it is as easy as</p>\n\n<pre><code>SELECT * INTO NewTablenNmeHere\nFROM OPENROWSET( 'Microsoft.Jet.OLEDB.4.0'... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39040/"
] | Does anyone have a technique for generating SQL table create (and data insert) commands pragmatically from a CSV (or sheet in a .xls) file?
I've got a third party database system which I'd like to populate with data from a csv file (or sheet in a xls file) but the importer supplied can't create the table structure automatically as it does the import. My csv file has lots of tables with lots of columns so I'd like to automate the table creation process as well as the data importing if possible but I'm unsure about how to go about generating the create statement... | In SQL server it is as easy as
```
SELECT * INTO NewTablenNmeHere
FROM OPENROWSET( 'Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\testing.xls','SELECT * FROM [Sheet1$]')
``` |
22,976 | <p>I've got a JavaScript "object", built this way:</p>
<pre><code>function foo()
{
this.length = 0;
}
foo.prototype.getLength = function()
{
return this.length;
}
...
</code></pre>
<p>I know how to emulate namespaces with singleton JavaScript objects, but what is the best way to "namepace" an object such as that above that will intanced? </p>
<p>I know that several JavaScript libraries have namepacing capabilities, but I'm using jQuery and would rather not add another library to the mix. I'd like to be able to provide my own, perhaps by exploiting jQuery, intrinsic namespacing scheme for the JS objects of mine that need to be instanced. </p>
<p>Thanks
rp</p>
| [
{
"answer_id": 22998,
"author": "Nickolay",
"author_id": 1026,
"author_profile": "https://Stackoverflow.com/users/1026",
"pm_score": 2,
"selected": false,
"text": "<p>Shouldn't be much different:</p>\n\n<pre><code>namespace.foo = function foo() {...}\nnamespace.foo.prototype.getLength = ... | 2008/08/22 | [
"https://Stackoverflow.com/questions/22976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2536/"
] | I've got a JavaScript "object", built this way:
```
function foo()
{
this.length = 0;
}
foo.prototype.getLength = function()
{
return this.length;
}
...
```
I know how to emulate namespaces with singleton JavaScript objects, but what is the best way to "namepace" an object such as that above that will intanced?
I know that several JavaScript libraries have namepacing capabilities, but I'm using jQuery and would rather not add another library to the mix. I'd like to be able to provide my own, perhaps by exploiting jQuery, intrinsic namespacing scheme for the JS objects of mine that need to be instanced.
Thanks
rp | Simple:
```
if(!MyNamespace) MyNamespace = {};
MyNamespace.foo = function() {
this.length = 0;
};
MyNamespace.foo.prototype.getLength = function() {
return this.length;
};
``` |
23,027 | <p>While setting up CruiseControl, I added a buildpublisher block to the publisher tasks:</p>
<pre><code><buildpublisher>
<sourceDir>C:\MyBuild\</sourceDir>
<publishDir>C:\MyBuildPublished\</publishDir>
<alwaysPublish>false</alwaysPublish>
</buildpublisher>
</code></pre>
<p>This works, but it copies the entire file contents of the build, I only want to copy the DLL's and .aspx pages, I don't need the source code to get published.</p>
<p>Does anyone know of a way to filter this, or do I need to setup a task to run a RoboCopy script instead?</p>
| [
{
"answer_id": 23060,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 3,
"selected": true,
"text": "<p>I set up a task to do this. I'm not aware of any way to make CruiseControl be that specific. I usually just chain a ... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | While setting up CruiseControl, I added a buildpublisher block to the publisher tasks:
```
<buildpublisher>
<sourceDir>C:\MyBuild\</sourceDir>
<publishDir>C:\MyBuildPublished\</publishDir>
<alwaysPublish>false</alwaysPublish>
</buildpublisher>
```
This works, but it copies the entire file contents of the build, I only want to copy the DLL's and .aspx pages, I don't need the source code to get published.
Does anyone know of a way to filter this, or do I need to setup a task to run a RoboCopy script instead? | I set up a task to do this. I'm not aware of any way to make CruiseControl be that specific. I usually just chain a batch file to do the copy to the CC.net task. |
23,064 | <p>I'm creating an application that will store a hierarchical collection of items in an XML file and I'm wondering about the industry standard for storing collections in XML. Which of the following two formats is preferred? (If there is another option I'm not seeing, please advise.)</p>
<p><strong>Option A</strong></p>
<pre><code><School>
<Student Name="Jack" />
<Student Name="Jill" />
<Class Name="English 101" />
<Class Name="Math 101" />
</School>
</code></pre>
<p><strong>Option B</strong></p>
<pre><code><School>
<Students>
<Student Name="Jack" />
<Student Name="Jill" />
</Students>
<Classes>
<Class Name="English 101" />
<Class Name="Math 101" />
</Classes>
</School>
</code></pre>
| [
{
"answer_id": 23067,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 3,
"selected": true,
"text": "<p>I'm no XML expert, but I find Option B to be more human readable, and I think it's just as machine readable as Option A.... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317/"
] | I'm creating an application that will store a hierarchical collection of items in an XML file and I'm wondering about the industry standard for storing collections in XML. Which of the following two formats is preferred? (If there is another option I'm not seeing, please advise.)
**Option A**
```
<School>
<Student Name="Jack" />
<Student Name="Jill" />
<Class Name="English 101" />
<Class Name="Math 101" />
</School>
```
**Option B**
```
<School>
<Students>
<Student Name="Jack" />
<Student Name="Jill" />
</Students>
<Classes>
<Class Name="English 101" />
<Class Name="Math 101" />
</Classes>
</School>
``` | I'm no XML expert, but I find Option B to be more human readable, and I think it's just as machine readable as Option A. I believe that XML is designed to be both human and machine readable, so I would go for Option B myself.
---
I just realized something else after Ryan Farley's post. If the Students or Classes section becomes too big and must be moved to another XML file, it seems like it would be easier to copy the node and create a new XML file out of that node with Option B. |
23,083 | <p>In the Windows applications I work on, we have a custom framework that sits directly above Win32 (don't ask). When we create a window, our normal practice is to put <code>this</code> in the window's user data area via <code>SetWindowLong(hwnd, GWL_USERDATA, this)</code>, which allows us to have an MFC-like callback or a tightly integrated <code>WndProc</code>, depending. The problem is that this will not work on 64-bit Windows, since LONG is only 32-bits wide. What's a better solution to this problem that works on both 32- and 64-bit systems?</p>
| [
{
"answer_id": 23101,
"author": "Chris",
"author_id": 2134,
"author_profile": "https://Stackoverflow.com/users/2134",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms644898%28VS.85%29.aspx\" rel=\"noreferrer\">SetWindowLongPtr</a> was crea... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2354/"
] | In the Windows applications I work on, we have a custom framework that sits directly above Win32 (don't ask). When we create a window, our normal practice is to put `this` in the window's user data area via `SetWindowLong(hwnd, GWL_USERDATA, this)`, which allows us to have an MFC-like callback or a tightly integrated `WndProc`, depending. The problem is that this will not work on 64-bit Windows, since LONG is only 32-bits wide. What's a better solution to this problem that works on both 32- and 64-bit systems? | [SetWindowLongPtr](http://msdn.microsoft.com/en-us/library/ms644898%28VS.85%29.aspx) was created to replace [SetWindowLong](http://msdn.microsoft.com/en-us/library/ms633591%28VS.85%29.aspx) in these instances. It's LONG\_PTR parameter allows you to store a pointer for 32-bit or 64-bit compilations.
```
LONG_PTR SetWindowLongPtr(
HWND hWnd,
int nIndex,
LONG_PTR dwNewLong
);
```
Remember that the constants have changed too, so usage now looks like:
```
SetWindowLongPtr(hWnd, GWLP_USERDATA, this);
```
Also don't forget that now to retrieve the pointer, you must use [GetWindowLongPtr](http://msdn.microsoft.com/en-us/library/ms633585%28VS.85%29.aspx):
```
LONG_PTR GetWindowLongPtr(
HWND hWnd,
int nIndex
);
```
And usage would look like (again, with changed constants):
```
LONG_PTR lpUserData = GetWindowLongPtr(hWnd, GWLP_USERDATA);
MyObject* pMyObject = (MyObject*)lpUserData;
``` |
23,094 | <p>What's the best way to handle a user going back to a page that had cached items in an asp.net app? Is there a good way to capture the back button (event?) and handle the cache that way?</p>
| [
{
"answer_id": 23104,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 0,
"selected": false,
"text": "<p>The best way to deal with it is to probably put a no-cache directive in your ASP.NET pages (or a master page if you... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1874/"
] | What's the best way to handle a user going back to a page that had cached items in an asp.net app? Is there a good way to capture the back button (event?) and handle the cache that way? | You can try using the [HttpResponse.Cache property](http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cache.aspx) if that would help:
```
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(false);
Response.Cache.VaryByParams["Category"] = true;
if (Response.Cache.VaryByParams["Category"])
{
//...
}
```
Or could could block caching of the page altogether with [HttpResponse.CacheControl](http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cachecontrol.aspx), but its been deprecated in favor of the Cache property above:
```
Response.CacheControl = "No-Cache";
```
Edit: OR you could really [go nuts](http://forums.asp.net/t/1013531.aspx) and do it all by hand:
```
Response.ClearHeaders();
Response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1
Response.AppendHeader("Cache-Control", "private"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1
Response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.1
Response.AppendHeader("Keep-Alive", "timeout=3, max=993"); // HTTP 1.1
Response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.1
``` |
23,124 | <p>As the title mentions, I have a timeout callback handler on an ajax call, and I want to be able to test that condition but nothing is coming to mind immediately on ways I can force my application to hit that state, any suggestions?</p>
| [
{
"answer_id": 23131,
"author": "Andy",
"author_id": 1993,
"author_profile": "https://Stackoverflow.com/users/1993",
"pm_score": 2,
"selected": false,
"text": "<p>You could always run a server-side script that keeps running for a period of time. \nFor example:</p>\n\n<pre><code><?php\... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2272/"
] | As the title mentions, I have a timeout callback handler on an ajax call, and I want to be able to test that condition but nothing is coming to mind immediately on ways I can force my application to hit that state, any suggestions? | First off, I think you need to be clearer in your question - what technology are you using and where is this process that is timing out - server-side or client-side?
If you want to have the server-side code take a long time and you are using .NET, place this line in the method you call server-side:
```
System.Threading.Thread.Sleep(timeoutMilliseconds);
```
As long as you use a number sufficient so that your client-side code assumes the server has timed out, you should be good. |
23,169 | <p>When using Groovy <code>MarkupBuilder</code>, I have places where I need to output text into the document, or call a function which outputs text into the document. Currently, I'm using the undefined tag <em>"text"</em> to do the output. Is there a better way to write this code?</p>
<pre><code>li {
text("${type.getAlias()} blah blah ")
function1(type.getXYZ())
if (type instanceof Class1) {
text(" implements ")
ft.getList().each {
if (it == '') return
text(it)
if (!function2(type, it)) text(", ")
}
}
}
</code></pre>
| [
{
"answer_id": 23734,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Include a method:</p>\n\n<pre><code>void text(n){\n builder.yield n\n}\n</code></pre>\n\n<p>Most likely you (I) copied th... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | When using Groovy `MarkupBuilder`, I have places where I need to output text into the document, or call a function which outputs text into the document. Currently, I'm using the undefined tag *"text"* to do the output. Is there a better way to write this code?
```
li {
text("${type.getAlias()} blah blah ")
function1(type.getXYZ())
if (type instanceof Class1) {
text(" implements ")
ft.getList().each {
if (it == '') return
text(it)
if (!function2(type, it)) text(", ")
}
}
}
``` | Actually, the recommended way now is to use `mkp.yield`, e.g.,
```
src.p {
mkp.yield 'Some element that has a '
strong 'child element'
mkp.yield ' which seems pretty basic.'
}
```
to produce
```
<p>Some element that has a <strong>child element</strong> which seems pretty basic.</p>
``` |
23,175 | <p>This is mostly geared toward desktop application developers. <br />How do I design a caching block which plays nicely with the GC? <br />How do I tell the GC that I have just done a cache sweep and it is time to do a GC? <br />How do I get an accurate measure of when it is time to do a cache sweep?</p>
<p>Are there any prebuilt caching schemes which I could borrow some ideas from?</p>
| [
{
"answer_id": 23734,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Include a method:</p>\n\n<pre><code>void text(n){\n builder.yield n\n}\n</code></pre>\n\n<p>Most likely you (I) copied th... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1490/"
] | This is mostly geared toward desktop application developers.
How do I design a caching block which plays nicely with the GC?
How do I tell the GC that I have just done a cache sweep and it is time to do a GC?
How do I get an accurate measure of when it is time to do a cache sweep?
Are there any prebuilt caching schemes which I could borrow some ideas from? | Actually, the recommended way now is to use `mkp.yield`, e.g.,
```
src.p {
mkp.yield 'Some element that has a '
strong 'child element'
mkp.yield ' which seems pretty basic.'
}
```
to produce
```
<p>Some element that has a <strong>child element</strong> which seems pretty basic.</p>
``` |
23,178 | <p>Is there a .NET variable that returns the "All Users" directory?</p>
| [
{
"answer_id": 23194,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 4,
"selected": true,
"text": "<p>You'll want to use the <code>system.environment</code> variables.<br>\nMost of the predefined ones are <a href=\"http://msdn... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] | Is there a .NET variable that returns the "All Users" directory? | You'll want to use the `system.environment` variables.
Most of the predefined ones are [shown here](http://msdn.microsoft.com/en-us/library/system.environment.getenvironmentvariable.aspx).
For the "**All Users**" you would use:
```
System.Environment.GetEnvironmentVariable("ALLUSERSPROFILE")
```
I know I got a lot of upmods and a correct answer for my other stuff, but this actually works. where as the other [environment variables](http://msdn.microsoft.com/en-us/library/ms933062.aspx)
I linked to previously don't seem to work with that function call. |
23,190 | <p>I am working on a function to establish the entropy of a distribution. It uses a copula, if any are familiar with that. I need to sum up the values in the array based on which dimensions are "cared about."</p>
<p>Example: Consider the following example...</p>
<pre>
Dimension 0 (across)
_ _ _ _ _ _ _ _ _ _ _ _ _
|_ 0 _|_ 0 _|_ 0 _|_ 2 _| Dimension 1
|_ 1 _|_ 0 _|_ 2 _|_ 0 _| (down)
|_ 0 _|_ 3 _|_ 0 _|_ 6 _|
|_ 0 _|_ 0 _|_ 0 _|_ 0 _|
I "care about" dimension 0 only, and "don't care" about the rest (dim 1).
Summing this array with the above specifications will
"collapse" the "stacks" of dimension 1 down to a single 4 x 1 array:
_ _ _ _ _ _ _ _ _ _ _ _ _
|_ 1 _|_ 3 _|_ 2 _|_ 8 _|
This can then be summed, or have any operation performed.
</pre>
<p>I need to do this with an array of 'n' dimensions, which could feasibly be 20. Also, I need to be able to do this, caring about certain dimensions, and collapsing the rest. I am having an especially hard time with this because I cant visualize 20 dimensions :p . If anyone could help me set up some c/c++ code to collapse/sum, I would be very very grateful.</p>
<h3>Update:</h3>
<p>Just got home. Here is some info to answer your questions:</p>
<ol>
<li>Sorry for rolling back the edits, I was hoping when I clicked roll-back it would show me the changes so I could see what I messed up, a bit like wikipedia. This wasn't the case, as I found out.</li>
<li>@jeff - What doesnt make sense? I am using this great service for (what I think is) a legit reason. I want to get better at my hobby, which is all it is, as I am in high school. Many of my posts regard implementing a genetic algorithm (This post, sparsearray, rank an array, pointer manipulation).</li>
<li>I am using a sparse array representation, as it is possible to exceed the number of molecules in the universe using a traditional (dense) array. For now, the implementation of the sparsearray itself doesnt matter a whole lot, as I am working to make it work with a standard array before going to a sparse representation. For those who havent seen my previous questions, I am using a binary search tree as the structure to contain the sparse array points, and a "driver" function to traverse the tree as necessary, returning whatever the function is designed to do. This is flexible, so I can accomodate a lot of different methods of accessing the array.</li>
<li>The structure is a hypercube, and the number of dimensions is specified at run time, as well as the length of each dimension (which are all the same, as it is a hypercube).</li>
</ol>
<p>Thanks everyone for your imput.</p>
| [
{
"answer_id": 23196,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, by colllapsing the colums you already summed them, so the dimension doesn't matter at all for your exampl... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/522/"
] | I am working on a function to establish the entropy of a distribution. It uses a copula, if any are familiar with that. I need to sum up the values in the array based on which dimensions are "cared about."
Example: Consider the following example...
```
Dimension 0 (across)
_ _ _ _ _ _ _ _ _ _ _ _ _
|_ 0 _|_ 0 _|_ 0 _|_ 2 _| Dimension 1
|_ 1 _|_ 0 _|_ 2 _|_ 0 _| (down)
|_ 0 _|_ 3 _|_ 0 _|_ 6 _|
|_ 0 _|_ 0 _|_ 0 _|_ 0 _|
I "care about" dimension 0 only, and "don't care" about the rest (dim 1).
Summing this array with the above specifications will
"collapse" the "stacks" of dimension 1 down to a single 4 x 1 array:
_ _ _ _ _ _ _ _ _ _ _ _ _
|_ 1 _|_ 3 _|_ 2 _|_ 8 _|
This can then be summed, or have any operation performed.
```
I need to do this with an array of 'n' dimensions, which could feasibly be 20. Also, I need to be able to do this, caring about certain dimensions, and collapsing the rest. I am having an especially hard time with this because I cant visualize 20 dimensions :p . If anyone could help me set up some c/c++ code to collapse/sum, I would be very very grateful.
### Update:
Just got home. Here is some info to answer your questions:
1. Sorry for rolling back the edits, I was hoping when I clicked roll-back it would show me the changes so I could see what I messed up, a bit like wikipedia. This wasn't the case, as I found out.
2. @jeff - What doesnt make sense? I am using this great service for (what I think is) a legit reason. I want to get better at my hobby, which is all it is, as I am in high school. Many of my posts regard implementing a genetic algorithm (This post, sparsearray, rank an array, pointer manipulation).
3. I am using a sparse array representation, as it is possible to exceed the number of molecules in the universe using a traditional (dense) array. For now, the implementation of the sparsearray itself doesnt matter a whole lot, as I am working to make it work with a standard array before going to a sparse representation. For those who havent seen my previous questions, I am using a binary search tree as the structure to contain the sparse array points, and a "driver" function to traverse the tree as necessary, returning whatever the function is designed to do. This is flexible, so I can accomodate a lot of different methods of accessing the array.
4. The structure is a hypercube, and the number of dimensions is specified at run time, as well as the length of each dimension (which are all the same, as it is a hypercube).
Thanks everyone for your imput. | This could have applications. Lets say you implemented a 2D Conway's Game of Life (which defines a 2D plane, 1 for 'alive', 0 for 'dead') and you stored the Games history for every iteration (which then defines a 3D cube). If you wanted to know how many bacteria there was alive over history, you would use the above algorithm. You could use the same algorithm for a 3D, (and 4D, 5D etc.) version of Game of Life grid.
I'd say this was a question for recursion, I'm not yet a C programmer but I know it is possible in C. In python,
```
def iter_arr(array):
sum = 0
for i in array:
if type(i) == type(list()):
sum = sum + iter_arr(i)
else:
sum = sum + i
return sum
```
1. Iterate over each element in array
2. If element is another array, call the function again
3. If element is not array, add it to the sum
4. Return sum
You would then apply this to each element in the 'cared about' dimension.
This is easier in python due to duck-typing though ... |
23,197 | <p>I have a library that reads/writes to a USB-device using CreateFile() API. The device happens to implement the HID-device profile, such that it's compatible with Microsoft's HID class driver.</p>
<p>Some other application installed on the system is opening the device in read/write mode with no share mode. Which prevents my library (and anything that consumes it) from working with the device. I suppose that's the rub with being an HID-compatible device -- other driver software (mice, controllers, PHIDGETS, etc) can be uncooperative. </p>
<p>Anyway, the device file path is of the form: </p>
<pre>
1: "\\?\hid#hpqremhiddevice&col01#5&21ff20e7&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}".
2: "\\?\hid#vid_045e&pid_0023#7&34aa9ece&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}".
3: "\?\hid#vid_056a&pid_00b0&col01#6&5b05f29&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}".
</pre>
<p>And I'm trying to open it using code, like:</p>
<pre><code>// First, open it with minimum permissions, this device may not be ours.
// we'll re-open it later in read/write
hid_device_ref = CreateFile(
device_path, GENERIC_READ,
0, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
</code></pre>
<p>I've considered a tool like FileMon or Process Monitor from SysInternals. But I can't seem to get it to report usage on device file handles like the one listed above.</p>
| [
{
"answer_id": 23219,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 1,
"selected": false,
"text": "<p>This is what I use to read from a Magtek card reader:</p>\n\n<pre><code>//Open file on the device\ndeviceHandle = \n ... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2146/"
] | I have a library that reads/writes to a USB-device using CreateFile() API. The device happens to implement the HID-device profile, such that it's compatible with Microsoft's HID class driver.
Some other application installed on the system is opening the device in read/write mode with no share mode. Which prevents my library (and anything that consumes it) from working with the device. I suppose that's the rub with being an HID-compatible device -- other driver software (mice, controllers, PHIDGETS, etc) can be uncooperative.
Anyway, the device file path is of the form:
```
1: "\\?\hid#hpqremhiddevice&col01#5&21ff20e7&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}".
2: "\\?\hid#vid_045e&pid_0023#7&34aa9ece&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}".
3: "\?\hid#vid_056a&pid_00b0&col01#6&5b05f29&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}".
```
And I'm trying to open it using code, like:
```
// First, open it with minimum permissions, this device may not be ours.
// we'll re-open it later in read/write
hid_device_ref = CreateFile(
device_path, GENERIC_READ,
0, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
```
I've considered a tool like FileMon or Process Monitor from SysInternals. But I can't seem to get it to report usage on device file handles like the one listed above. | Have you tried the tool called [handle](http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx) from sysinternals?
Anyway, neither windows does this (display the name of the application that locked the device): when you try to eject an USB device, Windows just says that the device is currently in use and cannot be remove right now. |
23,209 | <p>I'm building an application against some legacy, third party libraries, and having problems with the linking stage. I'm trying to compile with Visual Studio 9. My compile command is:</p>
<pre><code>cl -DNT40 -DPOMDLL -DCRTAPI1=_cdecl
-DCRTAPI2=cdecl -D_WIN32 -DWIN32 -DWIN32_LEAN_AND_MEAN -DWNT -DBYPASS_FLEX -D_INTEL=1 -DIPLIB=none -I. -I"D:\src\include" -I"C:\Program Files\Microsoft Visual Studio
9.0\VC\include" -c -nologo -EHsc -W1 -Ox -Oy- -MD mymain.c
</code></pre>
<p>The code compiles cleanly. The link command is:</p>
<pre><code>link -debug -nologo -machine:IX86
-verbose:lib -subsystem:console mymain.obj wsock32.lib advapi32.lib
msvcrt.lib oldnames.lib kernel32.lib
winmm.lib [snip large list of
dependencies] D:\src\lib\app_main.obj
-out:mymain.exe
</code></pre>
<p>The errors that I'm getting are:</p>
<pre><code>app_main.obj : error LNK2019:
unresolved external symbol
"_\_declspec(dllimport) public: void
__thiscall std::locale::facet::_Register(void)"
(__imp_?_Register@facet@locale@std@@QAEXXZ)
referenced in function "class
std::ctype<char> const & __cdecl
std::use_facet<class std::ctype<char>
(class std::locale const &)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z)
app_main.obj : error LNK2019:
unresolved external symbol
"__declspec(dllimport) public: static
unsigned int __cdecl
std::ctype<char>::_Getcat(class
std::locale::facet const * *)"
(__imp_?_Getcat@?$ctype@D@std@@SAIPAPBVfacet@locale@2@@Z)
referenced in function "class
std::ctype<char> const & __cdecl
std::use_facet<class std::ctype<char>
(class std::locale const &)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z)
app_main.obj : error LNK2019:
unresolved external symbol
"__declspec(dllimport) public: static
unsigned int __cdecl
std::ctype<unsigned
short>::_Getcat(class
std::locale::facet const * *)"
(__imp_?_Getcat@?$ctype@G@std@@SAIPAPBVfacet@locale@2@@Z)
referenced in function "class
std::ctype<unsigned short> const &
__cdecl std::use_facet<class std::ctype<unsigned short> >(class
std::locale const &)"
(??$use_facet@V?$ctype@G@std@@@std@@YAABV?$ctype@G@0@ABVlocale@0@@Z)
mymain.exe : fatal error LNK1120: 3
unresolved externals
</code></pre>
<p>Notice that these errors are coming from the legacy code, not my code - app_main.obj is part of the legacy code, while mymain.c is my source. I've done some searching around, and what that I've read says that this type of error is caused by a mismatch with the -MD switch between my code and the library that I'm linking to. Since I'm dealing with legacy code, a solution has to come from my environment. It's been a long time since I've done C++ work, and even longer since I've used Visual Studio, so I'm hoping that this is just some ignorance on my part. Any ideas on how to get these resolved?</p>
| [
{
"answer_id": 23212,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>These are standard library references. Make sure that all libraries (including the standard library) are using the ... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1322/"
] | I'm building an application against some legacy, third party libraries, and having problems with the linking stage. I'm trying to compile with Visual Studio 9. My compile command is:
```
cl -DNT40 -DPOMDLL -DCRTAPI1=_cdecl
-DCRTAPI2=cdecl -D_WIN32 -DWIN32 -DWIN32_LEAN_AND_MEAN -DWNT -DBYPASS_FLEX -D_INTEL=1 -DIPLIB=none -I. -I"D:\src\include" -I"C:\Program Files\Microsoft Visual Studio
9.0\VC\include" -c -nologo -EHsc -W1 -Ox -Oy- -MD mymain.c
```
The code compiles cleanly. The link command is:
```
link -debug -nologo -machine:IX86
-verbose:lib -subsystem:console mymain.obj wsock32.lib advapi32.lib
msvcrt.lib oldnames.lib kernel32.lib
winmm.lib [snip large list of
dependencies] D:\src\lib\app_main.obj
-out:mymain.exe
```
The errors that I'm getting are:
```
app_main.obj : error LNK2019:
unresolved external symbol
"_\_declspec(dllimport) public: void
__thiscall std::locale::facet::_Register(void)"
(__imp_?_Register@facet@locale@std@@QAEXXZ)
referenced in function "class
std::ctype<char> const & __cdecl
std::use_facet<class std::ctype<char>
(class std::locale const &)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z)
app_main.obj : error LNK2019:
unresolved external symbol
"__declspec(dllimport) public: static
unsigned int __cdecl
std::ctype<char>::_Getcat(class
std::locale::facet const * *)"
(__imp_?_Getcat@?$ctype@D@std@@SAIPAPBVfacet@locale@2@@Z)
referenced in function "class
std::ctype<char> const & __cdecl
std::use_facet<class std::ctype<char>
(class std::locale const &)" (??$use_facet@V?$ctype@D@std@@@std@@YAABV?$ctype@D@0@ABVlocale@0@@Z)
app_main.obj : error LNK2019:
unresolved external symbol
"__declspec(dllimport) public: static
unsigned int __cdecl
std::ctype<unsigned
short>::_Getcat(class
std::locale::facet const * *)"
(__imp_?_Getcat@?$ctype@G@std@@SAIPAPBVfacet@locale@2@@Z)
referenced in function "class
std::ctype<unsigned short> const &
__cdecl std::use_facet<class std::ctype<unsigned short> >(class
std::locale const &)"
(??$use_facet@V?$ctype@G@std@@@std@@YAABV?$ctype@G@0@ABVlocale@0@@Z)
mymain.exe : fatal error LNK1120: 3
unresolved externals
```
Notice that these errors are coming from the legacy code, not my code - app\_main.obj is part of the legacy code, while mymain.c is my source. I've done some searching around, and what that I've read says that this type of error is caused by a mismatch with the -MD switch between my code and the library that I'm linking to. Since I'm dealing with legacy code, a solution has to come from my environment. It's been a long time since I've done C++ work, and even longer since I've used Visual Studio, so I'm hoping that this is just some ignorance on my part. Any ideas on how to get these resolved? | After trying to get this stuff to compile under VS 2008, I tried earlier versions of VS - 2005 worked with warnings, and 2003 just worked. I double checked the linkages and couldn't find any problems, so either I just couldn't find it, or that wasn't the problem.
So to reiterate, downgrading to VS 2003 fixed it. |
23,217 | <p>I've been making a concerted effort to improve my javascript skills lately by reading as much javascript code as I can. In doing this I've sometimes seen the <code>javascript:</code> prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciable difference between:</p>
<pre><code>onchange="javascript: myFunction(this)"
</code></pre>
<p>and</p>
<pre><code>onchange="myFunction(this)"
</code></pre>
<p>?</p>
| [
{
"answer_id": 23222,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 5,
"selected": true,
"text": "<p>Probably nothing in your example. My understanding is that <code>javascript:</code> is for anchor tags (in place of ... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1680/"
] | I've been making a concerted effort to improve my javascript skills lately by reading as much javascript code as I can. In doing this I've sometimes seen the `javascript:` prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciable difference between:
```
onchange="javascript: myFunction(this)"
```
and
```
onchange="myFunction(this)"
```
? | Probably nothing in your example. My understanding is that `javascript:` is for anchor tags (in place of an actual `href`). You'd use it so that your script can execute when the user clicks the link, but without initiating a navigation back to the page (which a blank `href` coupled with an `onclick` will do).
For example:
```
<a href="javascript:someFunction();">Blah</a>
```
Rather than:
```
<a href="" onclick="someFunction();">Blah</a>
``` |
23,228 | <p>Compare</p>
<pre><code>String.Format("Hello {0}", "World");
</code></pre>
<p>with</p>
<pre><code>"Hello {0}".Format("World");
</code></pre>
<p>Why did the .Net designers choose a static method over an instance method? What do you think?</p>
| [
{
"answer_id": 23234,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 3,
"selected": false,
"text": "<p>I think it's because it's a creator method (not sure if there's a better name). All it does is take what you give it an... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
] | Compare
```
String.Format("Hello {0}", "World");
```
with
```
"Hello {0}".Format("World");
```
Why did the .Net designers choose a static method over an instance method? What do you think? | I don't actually know the answer but I suspect that it has something to do with the aspect of invoking methods on string literals directly.
If I recall correctly (I didn't actually verify this because I don't have an old IDE handy), early versions of the C# IDE had trouble detecting method calls against string literals in IntelliSense, and that has a big impact on the discoverability of the API. If that was the case, typing the following wouldn't give you any help:
```
"{0}".Format(12);
```
If you were forced to type
```
new String("{0}").Format(12);
```
It would be clear that there was no advantage to making the Format method an instance method rather than a static method.
The .NET libraries were designed by a lot of the same people that gave us MFC, and the String class in particular bears a strong resemblance to the CString class in MFC. MFC does have an instance Format method (that uses printf style formatting codes rather than the curly-brace style of .NET) which is painful because there's no such thing as a CString literal. So in a MFC codebase that I worked on I see a lot of this:
```
CString csTemp = "";
csTemp.Format("Some string: %s", szFoo);
```
which is painful. (I'm not saying that the code above is a great way to do things even in MFC, but that does seem to be the way that most of the developers on the project learned how to use CString::Format). Coming from that heritage, I can imagine that the API designers were trying to avoid that sort of situation again. |
23,250 | <p>I was curious about how other people use the <strong>this</strong> keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:</p>
<p>In a constructor:</p>
<pre><code>public Light(Vector v)
{
this.dir = new Vector(v);
}
</code></pre>
<p>Elsewhere</p>
<pre><code>public void SomeMethod()
{
Vector vec = new Vector();
double d = (vec * vec) - (this.radius * this.radius);
}
</code></pre>
| [
{
"answer_id": 23257,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 5,
"selected": false,
"text": "<p>I use it every time I refer to an instance variable, even if I don't need to. I think it makes the code more clear.</p>... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016/"
] | I was curious about how other people use the **this** keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:
In a constructor:
```
public Light(Vector v)
{
this.dir = new Vector(v);
}
```
Elsewhere
```
public void SomeMethod()
{
Vector vec = new Vector();
double d = (vec * vec) - (this.radius * this.radius);
}
``` | There are several usages of [this](http://msdn.microsoft.com/en-us/library/dk1507sz.aspx) keyword in C#.
1. [To qualify members hidden by similar name](http://msdn.microsoft.com/en-us/library/vstudio/dk1507sz%28v=vs.100%29.aspx)
2. [To have an object pass itself as a parameter to other methods](http://msdn.microsoft.com/en-us/library/vstudio/dk1507sz%28v=vs.100%29.aspx)
3. To have an object return itself from a method
4. [To declare indexers](http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx)
5. [To declare extension methods](http://msdn.microsoft.com/en-us/library/bb383977.aspx)
6. [To pass parameters between constructors](http://www.codeproject.com/Articles/7011/An-Intro-to-Constructors-in-C%29)
7. [To internally reassign value type (struct) value](https://stackoverflow.com/questions/194484/whats-the-strangest-corner-case-youve-seen-in-c-or-net/1800162#1800162).
8. To invoke an extension method on the current instance
9. To cast itself to another type
10. [To chain constructors defined in the same class](https://stackoverflow.com/questions/1814953/c-sharp-constructor-chaining-how-to-do-it)
You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using [auto-implemented properties](https://msdn.microsoft.com/en-us/library/bb384054.aspx). |
23,372 | <p>What would be the best method for getting a custom element (that is using J2ME native Graphics) painted on LWUIT elements?</p>
<p>The custom element is an implementation from mapping library, that paints it's content (for example Google map) to Graphics object. How would it be possible to paint the result directly on LWUIT elements (at the moment I am trying to paint it on a Component). </p>
<p>Is the only way to write a wrapper in LWUIT package, that would expose the internal implementation of it?</p>
<p><strong>Edit:</strong></p>
<p><strong><em>John:</em></strong> your solution looks like a lot of engineering :P What I ended up using is following wrapper:</p>
<pre><code>package com.sun.lwuit;
public class ImageWrapper {
private final Image image;
public ImageWrapper(final Image lwuitBuffer) {
this.image = lwuitBuffer;
}
public javax.microedition.lcdui.Graphics getGraphics() {
return image.getGraphics().getGraphics();
}
}
</code></pre>
<p>Now I can get the 'native' Graphics element from LWUIT. Paint on it - effectively painting on LWUIT image. And I can use the image to paint on a component.</p>
<p>And it still looks like a hack :)</p>
<p>But the real problem is 50kB of code overhead, even after obfuscation. But this is a issue for another post :)</p>
<p>/JaanusSiim</p>
| [
{
"answer_id": 48945,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 0,
"selected": false,
"text": "<p>Based on the javadoc for LWUIT and J2ME and guessing that the custom J2ME class is a <a href=\"http://java.sun.com/ja... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/706/"
] | What would be the best method for getting a custom element (that is using J2ME native Graphics) painted on LWUIT elements?
The custom element is an implementation from mapping library, that paints it's content (for example Google map) to Graphics object. How would it be possible to paint the result directly on LWUIT elements (at the moment I am trying to paint it on a Component).
Is the only way to write a wrapper in LWUIT package, that would expose the internal implementation of it?
**Edit:**
***John:*** your solution looks like a lot of engineering :P What I ended up using is following wrapper:
```
package com.sun.lwuit;
public class ImageWrapper {
private final Image image;
public ImageWrapper(final Image lwuitBuffer) {
this.image = lwuitBuffer;
}
public javax.microedition.lcdui.Graphics getGraphics() {
return image.getGraphics().getGraphics();
}
}
```
Now I can get the 'native' Graphics element from LWUIT. Paint on it - effectively painting on LWUIT image. And I can use the image to paint on a component.
And it still looks like a hack :)
But the real problem is 50kB of code overhead, even after obfuscation. But this is a issue for another post :)
/JaanusSiim | I do not think any hacking is necessary. You can subclass the LWTUI Component class and then you can pain whatever you want on to the graphic context of the component. You do not get the native lcdui.Graphics object but an object with a same interface that is easy to use.
If you really need to pass a lcdui.Graphics to some underlying library to display its output then I would suggest this:
Somewhere in your component code (do only when the component contents really need to be changed):
```
private Image buffer = null; // keep this
int[] bufferArray = new int[desiredWidth * desiredHeight];
javax.microedition.lcdui.Image bufferImage =
Image.createEmptyImage(desiredWidth, desiredHeight);
thirPartyComponent.paint(bufferImage.getGraphics());
bufferImage.getRGB(bufferArray,0,1,0,0,desiredWidth, desiredHeight);
bufferImage = null; //no longer needed
buffer = Image.createImage(bufferArray, desiredWidth, desiredHeight);
```
In the component paint(g) method:
```
g.drawImage(0,0, buffer);
```
By doing the hack you did you are losing portablity and also sice you are exposing implementation private object you might also break other things.
Hope this helps. |
23,399 | <p>I've got an interesting design question. I'm designing the security side of our project, to allow us to have different versions of the program for different costs and also to allow Manager-type users to grant or deny access to parts of the program to other users. Its going to web-based and hosted on our servers.</p>
<p>I'm using a simple Allow or Deny option for each 'Resource' or screen.</p>
<p>We're going to have a large number of resources, and the user will be able to set up many different groups to put users in to control access. Each user can only belong to a single group.</p>
<p>I've got two approaches to this in mind, and was curious which would be better for the SQL server in terms of performance.</p>
<p><strong>Option A</strong>
The presence of an entry in the access table means access is allowed. This will not need a column in the database to store information. If no results are returned, then access is denied.</p>
<p>I think this will mean a smaller table, but would queries search the whole table to determine there is no match?</p>
<p><strong>Option B</strong>
A bit column is included in the database that controls the Allow/Deny. This will mean there is always a result to be found, and makes for a larger table.</p>
<p>Thoughts?</p>
| [
{
"answer_id": 23413,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 1,
"selected": false,
"text": "<p>I would vote for Option B. If you go with Option A and the assumption that if a user exists, they can get in, then you'll ... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1470/"
] | I've got an interesting design question. I'm designing the security side of our project, to allow us to have different versions of the program for different costs and also to allow Manager-type users to grant or deny access to parts of the program to other users. Its going to web-based and hosted on our servers.
I'm using a simple Allow or Deny option for each 'Resource' or screen.
We're going to have a large number of resources, and the user will be able to set up many different groups to put users in to control access. Each user can only belong to a single group.
I've got two approaches to this in mind, and was curious which would be better for the SQL server in terms of performance.
**Option A**
The presence of an entry in the access table means access is allowed. This will not need a column in the database to store information. If no results are returned, then access is denied.
I think this will mean a smaller table, but would queries search the whole table to determine there is no match?
**Option B**
A bit column is included in the database that controls the Allow/Deny. This will mean there is always a result to be found, and makes for a larger table.
Thoughts? | If it's only going to be Allow/Deny, then a simple linking table between Users and Resources would work fine. If there is an entry keyed to the User-Resource in the linking table, allow access.
```
UserResources
-------------
UserId FK->Users
ResourceId FK->Resources
```
and the sql would be something like
```
if exists (select 1 from UserResources
where UserId = @uid and ResourceId=@rid)
set @allow=1;
```
With a clustered index on (UserId and ResourceId), the query would be blindingly fast even with millions of records. |
23,603 | <p>I'm developing a library alongside several projects that use it, and I've found myself frequently modifying the library at the same time as a project (e.g., adding a function to the library and immediately using it in the project).<br>
As a result, the project would no longer compile with previous versions of the library.</p>
<p>So if I need to rollback a change or test a previous version of the project, I'd like to know what version of the library was used at check-in.<br>
I suppose I could do this manually (by just writing the version number in the log file), but it would be great if this could happen automatically.</p>
| [
{
"answer_id": 23624,
"author": "thelsdj",
"author_id": 163,
"author_profile": "https://Stackoverflow.com/users/163",
"pm_score": 0,
"selected": false,
"text": "<p>One option is to use a single subversion repository and check-in changes that effect both library and project at the same ti... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/112/"
] | I'm developing a library alongside several projects that use it, and I've found myself frequently modifying the library at the same time as a project (e.g., adding a function to the library and immediately using it in the project).
As a result, the project would no longer compile with previous versions of the library.
So if I need to rollback a change or test a previous version of the project, I'd like to know what version of the library was used at check-in.
I suppose I could do this manually (by just writing the version number in the log file), but it would be great if this could happen automatically. | I think if I were going to do this, I would use tags. It would be pretty easy to write a script that would tag both repositories with the same ID each time you upgraded the library and used it in the project. Then, if you need to roll back to a previous version, you just see what its most recent tag was, and roll the library back to that version.
UPDATE: Sorry, I've been in Mercurial land for a while, and forgot that subversion doesn't directly support tagging. Assuming you use the usual subversion directory structure
```
/
/trunk
/tags
/branches
```
you just need to run
```
svn copy trunk/ tags/TagName
```
on both repos, with the same tag name. Subversion is pretty good about smart copies, so you don't need to worry about disk space. |
23,610 | <p>I'm looking for a way to find a the windows login associated with a specific group. I'm trying to add permissions to a tool that only allows names formatted like:</p>
<pre><code>DOMAIN\USER
DOMAIN\GROUP
</code></pre>
<p>I have a list of users in active directory format that I need to add:</p>
<pre><code>ou=group1;ou=group2;ou=group3
</code></pre>
<p>I have tried adding DOMAIN\Group1, but I get a 'user not found' error.</p>
<p>P.S. should also be noted that I'm not a Lan admin </p>
| [
{
"answer_id": 23611,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 0,
"selected": false,
"text": "<p>OU is an Organizational Unit (sort of like a Subfolder in Explorer), not a Group, Hence group1, 2 and 3 are not actually ... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1580/"
] | I'm looking for a way to find a the windows login associated with a specific group. I'm trying to add permissions to a tool that only allows names formatted like:
```
DOMAIN\USER
DOMAIN\GROUP
```
I have a list of users in active directory format that I need to add:
```
ou=group1;ou=group2;ou=group3
```
I have tried adding DOMAIN\Group1, but I get a 'user not found' error.
P.S. should also be noted that I'm not a Lan admin | Programatically or Manually?
Manually, i prefer [AdExplorer](http://technet.microsoft.com/en-us/sysinternals/bb963907.aspx), which is a nice Active directory Browser. You just connect to your domain controller and then you can look for the user and see all the details. Of course, you need permissions on the Domain Controller, not sure which though.
Programatically, it depends on your language of couse. On .net, the [System.DirectoryServices](http://msdn.microsoft.com/en-us/library/system.directoryservices.aspx) Namespace is your friend. (I don't have any code examples here unfortunately)
For Active Directory, I'm not really an expert apart from how to query it, but here are two links I found useful:
<http://www.computerperformance.co.uk/Logon/LDAP_attributes_active_directory.htm>
<http://en.wikipedia.org/wiki/Active_Directory> (General stuff about the Structure of AD) |
23,620 | <p>I'm using TinyMCE in an ASP.Net project, and I need a spell check. The only TinyMCE plugins I've found use PHP on the server side, and I guess I could just break down and install PHP on my server and do that, but quite frankly, what a pain. I don't want to do that.</p>
<p>As it turns out, Firefox's built-in spell check will work fine for me, but it doesn't seem to work on TinyMCE editor boxes. I've enabled the gecko_spellcheck option, which is supposed to fix it, but it doesn't.</p>
<p>Does anybody know of a nice rich-text editor that doesn't break the browser's spell check?</p>
| [
{
"answer_id": 23655,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>I know at least <a href=\"http://developer.yahoo.com/yui/editor/\" rel=\"nofollow noreferrer\">yahoo!'s Rich Text Editor</a> ... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527/"
] | I'm using TinyMCE in an ASP.Net project, and I need a spell check. The only TinyMCE plugins I've found use PHP on the server side, and I guess I could just break down and install PHP on my server and do that, but quite frankly, what a pain. I don't want to do that.
As it turns out, Firefox's built-in spell check will work fine for me, but it doesn't seem to work on TinyMCE editor boxes. I've enabled the gecko\_spellcheck option, which is supposed to fix it, but it doesn't.
Does anybody know of a nice rich-text editor that doesn't break the browser's spell check? | TinyMCE only goes out of its way to disable spell-checking when you don't specify the `gecko_spellcheck` option (i verified this with their example code). Might want to double-check your `tinyMCE.init()` call - it should look something like this:
```
tinyMCE.init({
mode : "textareas",
theme : "simple",
gecko_spellcheck : true
});
``` |
23,715 | <p>Has anyone had any success running two different web servers -- such as Apache and CherryPy -- alongside each other on the same machine? I am experimenting with other web servers right now, and I'd like to see if I can do my experiments while keeping my other sites up and running. You could say that this isn't so much a specific-software question as it is a general networking question.</p>
<ul>
<li>I know it's possible to run two web servers on different ports; but is there any way to configure them so that they can run on the <em>same port</em> (ie, they both run on port 80)?</li>
<li>The web servers would <em>not</em> be serving files from the same domains. For example, Apache might serve up documents from foo.domain.com, and the other web server would serve from bar.domain.com.</li>
</ul>
<p>I do know that this is not an ideal configuration. I'd just like to see if it can be done before I go sprinting down the rabbit hole. :) </p>
| [
{
"answer_id": 23718,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 0,
"selected": false,
"text": "<p>Your best bet would be putting Apache httpd in front of port 80 and relay requests meant for other servers through Apache b... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2321/"
] | Has anyone had any success running two different web servers -- such as Apache and CherryPy -- alongside each other on the same machine? I am experimenting with other web servers right now, and I'd like to see if I can do my experiments while keeping my other sites up and running. You could say that this isn't so much a specific-software question as it is a general networking question.
* I know it's possible to run two web servers on different ports; but is there any way to configure them so that they can run on the *same port* (ie, they both run on port 80)?
* The web servers would *not* be serving files from the same domains. For example, Apache might serve up documents from foo.domain.com, and the other web server would serve from bar.domain.com.
I do know that this is not an ideal configuration. I'd just like to see if it can be done before I go sprinting down the rabbit hole. :) | You can't have two processes bound to the same port on the same IP address. You can add another IP address to the box and have each server listen on one.
Another option is to proxy pass one server to the other. With Apache, you could do something like:
```
NameVirtualHost *
<virtualhost *>
ServerName other.site.com
# assumes CherryPy listens on port 8080
ProxyPass / http://127.0.0.1:8080/
ProxyPassReverse / http://127.0.0.1:8080/
</Virtualhost>
```
That's a pretty quick example, but you can always check the [ProxyPass documentation](http://httpd.apache.org/docs/2.2/mod/mod_proxy.html). Remember though, the application being proxyed to will get 127.0.0.1 in it's logs instead of the requester's IP address. Some web servers (apache does with [mod\_rpaf](http://stderr.net/apache/rpaf/)) can substitute the X-Forwarded-For header in place of the wrong IP address. Possibly CherryPy has this? |
23,755 | <p>When implementing a needle search of a haystack in an object-oriented way, you essentially have three alternatives:</p>
<pre><code>1. needle.find(haystack)
2. haystack.find(needle)
3. searcher.find(needle, haystack)</code></pre>
<p>Which do you prefer, and why?</p>
<p>I know some people prefer the second alternative because it avoids introducing a third object. However, I can't help feeling that the third approach is more conceptually "correct", at least if your goal is to model "the real world".</p>
<p>In which cases do you think it is justified to introduce helper objects, such as the searcher in this example, and when should they be avoided?</p>
| [
{
"answer_id": 23756,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p>This entirely depends on what varies and what stays the same.</p>\n\n<p>For example, I am working on a (non-OOP) <a... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1709/"
] | When implementing a needle search of a haystack in an object-oriented way, you essentially have three alternatives:
```
1. needle.find(haystack)
2. haystack.find(needle)
3. searcher.find(needle, haystack)
```
Which do you prefer, and why?
I know some people prefer the second alternative because it avoids introducing a third object. However, I can't help feeling that the third approach is more conceptually "correct", at least if your goal is to model "the real world".
In which cases do you think it is justified to introduce helper objects, such as the searcher in this example, and when should they be avoided? | Usually actions should be applied to what you are doing the action on... in this case the haystack, so I think option 2 is the most appropriate.
You also have a fourth alternative that I think would be better than alternative 3:
```
haystack.find(needle, searcher)
```
In this case, it allows you to provide the manner in which you want to search as part of the action, and so you can keep the action with the object that is being operated on. |
23,763 | <p>I'm working on some code to colorize an image in Java. Basically what I'd like to do is something along the lines of GIMP's colorize command, so that if I have a BufferedImage and a Color, I can colorize the Image with the given color. Anyone got any ideas? My current best guess at doing something like this is to get the rgb value of each pixel in the BufferedImage and add the RGB value of the Color to it with some scaling factor.</p>
| [
{
"answer_id": 23795,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 3,
"selected": false,
"text": "<p>Let <code>Y = 0.3*R + 0.59*G + 0.11*B</code> for each pixel in the image, then set them to be</p>\n\n<p><code>((R1+Y)/2,(G1+Y... | 2008/08/22 | [
"https://Stackoverflow.com/questions/23763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] | I'm working on some code to colorize an image in Java. Basically what I'd like to do is something along the lines of GIMP's colorize command, so that if I have a BufferedImage and a Color, I can colorize the Image with the given color. Anyone got any ideas? My current best guess at doing something like this is to get the rgb value of each pixel in the BufferedImage and add the RGB value of the Color to it with some scaling factor. | I have never used GIMP's colorize command. However, if your getting the RGB value of each pixel and adding RGB value to it you should really use a **[LookupOp](http://docs.oracle.com/javase/7/docs/api/java/awt/image/LookupOp.html).** Here is some code that I wrote to apply a BufferedImageOp to a BufferedImage.
Using Nicks example from above heres how I would do it.
>
> Let Y = 0.3\*R + 0.59\*G + 0.11\*B for
> each pixel
>
>
> (R1,G1,B1) is what you are colorizing
> with
>
>
>
```
protected LookupOp createColorizeOp(short R1, short G1, short B1) {
short[] alpha = new short[256];
short[] red = new short[256];
short[] green = new short[256];
short[] blue = new short[256];
int Y = 0.3*R + 0.59*G + 0.11*B
for (short i = 0; i < 256; i++) {
alpha[i] = i;
red[i] = (R1 + i*.3)/2;
green[i] = (G1 + i*.59)/2;
blue[i] = (B1 + i*.11)/2;
}
short[][] data = new short[][] {
red, green, blue, alpha
};
LookupTable lookupTable = new ShortLookupTable(0, data);
return new LookupOp(lookupTable, null);
}
```
It creates a [BufferedImageOp](http://docs.oracle.com/javase/7/docs/api/java/awt/image/BufferedImageOp.html) that will mask out each color if the mask boolean is true.
Its simple to call too.
```
BufferedImageOp colorizeFilter = createColorizeOp(R1, G1, B1);
BufferedImage targetImage = colorizeFilter.filter(sourceImage, null);
```
If this is not what your looking for I suggest you look more into BufferedImageOp's.
This is would also be more efficient since you would not need to do the calculations multiple times on different images. Or do the calculations over again on different BufferedImages as long as the R1,G1,B1 values don't change. |
23,787 | <p>What is the best way to find something in a list? I know LINQ has some nice tricks, but let's also get suggestions for C# 2.0. Lets get the best refactorings for this common code pattern.</p>
<p>Currently I use code like this:</p>
<pre><code>// mObjList is a List<MyObject>
MyObject match = null;
foreach (MyObject mo in mObjList)
{
if (Criteria(mo))
{
match = mo;
break;
}
}
</code></pre>
<p>or</p>
<pre><code>// mObjList is a List<MyObject>
bool foundIt = false;
foreach (MyObject mo in mObjList)
{
if (Criteria(mo))
{
foundIt = true;
break;
}
}
</code></pre>
| [
{
"answer_id": 23794,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "<p>Put the code in a method and you save a temporary and a <code>break</code> (and you recycle code, as a bonus):</p>\... | 2008/08/23 | [
"https://Stackoverflow.com/questions/23787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1490/"
] | What is the best way to find something in a list? I know LINQ has some nice tricks, but let's also get suggestions for C# 2.0. Lets get the best refactorings for this common code pattern.
Currently I use code like this:
```
// mObjList is a List<MyObject>
MyObject match = null;
foreach (MyObject mo in mObjList)
{
if (Criteria(mo))
{
match = mo;
break;
}
}
```
or
```
// mObjList is a List<MyObject>
bool foundIt = false;
foreach (MyObject mo in mObjList)
{
if (Criteria(mo))
{
foundIt = true;
break;
}
}
``` | >
> @ Konrad: So how do you use it? Let's say I want to match mo.ID to magicNumber.
>
>
>
In C# 2.0 you'd write:
```
result = mObjList.Find(delegate(int x) { return x.ID == magicNumber; });
```
3.0 knows lambdas:
```
result = mObjList.Find(x => x.ID == magicNumber);
``` |