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
|
---|---|---|---|---|---|---|
188,184 |
<p>Here I have:</p>
<pre><code>Public Structure MyStruct
Public Name as String
Public Content as String
End Structure
Dim oStruct as MyStruct = New MyStruct()
oStruct.Name = ...
oStruct.Content = ...
Dim alList as ArrayList = new ArrayList()
alList.Add(oStruct)
</code></pre>
<p>I'd like to convert the ArrayList to a static strongly-typed Array of type MyStruct. How can I do that? I had no luck with ToArray.</p>
<p>I am using .NET Framework 2.0.</p>
|
[
{
"answer_id": 188196,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<p>You have to cast the result of <code>ToArray</code></p>\n\n<pre><code>MyStruct[] structs = (MyStruct[]) alList.ToArray(typeof(MyStruct));\n</code></pre>\n"
},
{
"answer_id": 188197,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": true,
"text": "<p>I assume that since you are using ArrayList, you are using 1.1?</p>\n\n<p>In which case, I suspect the following would work:</p>\n\n<pre><code>ArrayList list = new ArrayList();\nMyStruct[] array = new MyStruct[list.Count];\nlist.CopyTo(array); \n</code></pre>\n\n<p>(edit - Bill's ToArray usage is more convenient - I didn't know about that one, but then, I very rarely [if ever] use ArrayList)</p>\n\n<p>However, if MyStruct really is a struct, then I cannot say strongly enough that mutable structs are a bad idea - i.e. where you can set .Name and .Content after creation. Structs should almost always be immutable. In reality, your MyStruct looks like it should be a class. Also - I'm not \"up\" on VB, but are they public fields? Again - not recommended - properties would be preferable. I don't know about VB, but C# 3.0 has some very terse syntax for this:</p>\n\n<pre><code>public class SomeType\n{\n public string Name {get;set;}\n public string Content {get;set;}\n}\n</code></pre>\n\n<p>If you are using 2.0 or above, consider List<T> instead of ArrayList.</p>\n"
},
{
"answer_id": 188203,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>ToArray is the right way to go. In C# it would be:</p>\n\n<pre><code>MyStruct[] array = (MyStruct[]) alList.ToArray(typeof(MyStruct));\n</code></pre>\n\n<p>Are you stuck using 1.1, btw? If you're using 2.0, can you shift to List<T> instead?</p>\n"
},
{
"answer_id": 188215,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 0,
"selected": false,
"text": "<p>This worked for me</p>\n\n<pre><code>Dim array As MyStruct() = alList.ToArray(GetType(MyStruct))\n</code></pre>\n"
},
{
"answer_id": 188223,
"author": "John Chuckran",
"author_id": 25511,
"author_profile": "https://Stackoverflow.com/users/25511",
"pm_score": 0,
"selected": false,
"text": "<p>If you are running Visual Studio 2008 you can use a List object.</p>\n\n<pre><code> Dim alList As New List(Of MyStruct)\n alList.Add(oStruct)\n</code></pre>\n"
},
{
"answer_id": 188227,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>In case you're using 2.0 or later, you might want to define your arraylist like this:</p>\n\n<pre><code>Dim alList as New List(Of MyStruct)()\nalList.Add(oStruct)\n</code></pre>\n\n<p>This will give you the same semantics as an array (lookup by index, strong typing, IEnumerable support, etc). </p>\n\n<p>There are only two reasons in .Net 2.0 and later to use an array instead of a generic list: </p>\n\n<ol>\n<li>You know with absolute certainty the number of items you have, and know that the count won't change. This is surprisingly rare.</li>\n<li>You need to call a function that requires an array. There are still a fair number of these lurking in the BCL, but your own code should be asking for <code>IEnumerable<T>, IList<T>, or ICollection<T></code>, and only rarely an array.</li>\n</ol>\n\n<p>Finally, this is kind of nit-picky, but there are two stylistic points I want to address in the code you posted. First, note the abbreviated syntax I used to create the <code>New List<MyStruct></code>. There's no = symbol and you don't have to key in the type name twice. That was support back in 1.1 as well, so there's no excuse there. Secondly, the <a href=\"http://msdn.microsoft.com/en-us/library/ms229042.aspx\" rel=\"nofollow noreferrer\">style guidelines for .Net</a> published by Microsoft on MSDN (see the <a href=\"http://msdn.microsoft.com/en-us/library/ms229045.aspx\" rel=\"nofollow noreferrer\">general naming conventions</a> section) specifically recommend against hungarian warts like 'o' or 'a'. It was nice for VB6/VBScript, which were loosely typed, but .Net is strongly typed, making the warts, well, wart-ugly.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1508/"
] |
Here I have:
```
Public Structure MyStruct
Public Name as String
Public Content as String
End Structure
Dim oStruct as MyStruct = New MyStruct()
oStruct.Name = ...
oStruct.Content = ...
Dim alList as ArrayList = new ArrayList()
alList.Add(oStruct)
```
I'd like to convert the ArrayList to a static strongly-typed Array of type MyStruct. How can I do that? I had no luck with ToArray.
I am using .NET Framework 2.0.
|
I assume that since you are using ArrayList, you are using 1.1?
In which case, I suspect the following would work:
```
ArrayList list = new ArrayList();
MyStruct[] array = new MyStruct[list.Count];
list.CopyTo(array);
```
(edit - Bill's ToArray usage is more convenient - I didn't know about that one, but then, I very rarely [if ever] use ArrayList)
However, if MyStruct really is a struct, then I cannot say strongly enough that mutable structs are a bad idea - i.e. where you can set .Name and .Content after creation. Structs should almost always be immutable. In reality, your MyStruct looks like it should be a class. Also - I'm not "up" on VB, but are they public fields? Again - not recommended - properties would be preferable. I don't know about VB, but C# 3.0 has some very terse syntax for this:
```
public class SomeType
{
public string Name {get;set;}
public string Content {get;set;}
}
```
If you are using 2.0 or above, consider List<T> instead of ArrayList.
|
188,188 |
<p>We recently upgraded an application that that contained web services using the WSE 2.0 to .NET 3.5. When we converted the project in Visual Studio 2008, It did not mention anything about the removing and/or modifying the WSE 2.0 namespaces. Here is the basic architecture of the web services in the .NET 1.1 project.</p>
<p>Web Service Source Code:</p>
<pre><code>[WebService(Namespace="http://tempuri.org")]
public class MyWebService : BaseWebService
{
//Do some stuff
}
</code></pre>
<p>BaseWebService Source Code:</p>
<pre><code>using Microsoft.Web.Services2;
using Microsoft.Web.Services2.Security;
using Microsoft.Web.Services2.Security.Tokens;
namespace MyNameSpace
{
public class BaseWebService : System.Web.Services.WebService
{
public BaseWebService()
{
if(RequestSoapContext.Current == null)
throw new ApplicationExcpetion("Only SOAP requests are permitted.");
}
}
}
</code></pre>
<p>During the conversion, the BaseWebService.cs class was excluded from the project and the WSE2.0 namespaces were removed from the class.</p>
<p>Have anyone else experiences any issues with trying to upgrade a web service from .NET 1.1 using the WSE to .NET 3.5?</p>
<p>This is related to the previous question I had regarding a client consuming the upgraded web service:</p>
<p><a href="https://stackoverflow.com/questions/185420/issues-with-client-consuming-a-net-web-service-upgraded-from-net-11-to-35">Stack Overflow Question</a></p>
|
[
{
"answer_id": 198808,
"author": "Ricardo Villamil",
"author_id": 19314,
"author_profile": "https://Stackoverflow.com/users/19314",
"pm_score": 0,
"selected": false,
"text": "<p>the biggest problem I've found is in Javascript that had hardcoded the names of some of my server controls. in ASP.NET 2.0 with masterpages, the id's where changed to something like ctrl$_gridview1_checkbox1...\nTherefore, any hardcoded references needed to be changed and generated from the server side using the ClientID property of the control.</p>\n\n<p>I also found that .NET 2.0 was more strict about uncaught exceptions, after upgrading and just changing the minimum code so that we would get a successful compile we started getting lots of crashes and unhandled exceptions. We had very buggy and poorly written code to begin with, but is just interesting that .net 1.1 never complained or swallowed the errors happily...</p>\n"
},
{
"answer_id": 198853,
"author": "DreamSonic",
"author_id": 6531,
"author_profile": "https://Stackoverflow.com/users/6531",
"pm_score": 1,
"selected": false,
"text": "<p>As I <a href=\"https://stackoverflow.com/questions/185420/issues-with-client-consuming-a-net-web-service-upgraded-from-net-11-to-35#198806\">answered</a> to the original question:</p>\n\n<p>WCF (.net 3.5) is said to be compatible with WSE3 (.net 2.0+), but not with WSE2 (.net 1.1+).</p>\n\n<p>So if you don't want to change the client, but want it to be compatible with the service, you can leave the old service source code and keep the references to WSE2 assemblies under VS2008 solution. Thus, both the client and the service will be compatible.</p>\n"
},
{
"answer_id": 202052,
"author": "Michael Kniskern",
"author_id": 26327,
"author_profile": "https://Stackoverflow.com/users/26327",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the settings in the web.config for the service:</p>\n\n<pre><code><system.web>\n <webServices>\n <soapExtensionTypes>\n <add type=\"Microsoft.Web.Services2.WebServicesExtension, Microsoft.Web.Services2, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" priority=\"1\" group=\"0\" />\n <!--<add type=\"Microsoft.Web.Services2.Configuration.WebServicesConfiguration, Microsoft.Web.Services2, Version=2.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>-->\n </soapExtensionTypes>\n </webServices> \n</system.web> \n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26327/"
] |
We recently upgraded an application that that contained web services using the WSE 2.0 to .NET 3.5. When we converted the project in Visual Studio 2008, It did not mention anything about the removing and/or modifying the WSE 2.0 namespaces. Here is the basic architecture of the web services in the .NET 1.1 project.
Web Service Source Code:
```
[WebService(Namespace="http://tempuri.org")]
public class MyWebService : BaseWebService
{
//Do some stuff
}
```
BaseWebService Source Code:
```
using Microsoft.Web.Services2;
using Microsoft.Web.Services2.Security;
using Microsoft.Web.Services2.Security.Tokens;
namespace MyNameSpace
{
public class BaseWebService : System.Web.Services.WebService
{
public BaseWebService()
{
if(RequestSoapContext.Current == null)
throw new ApplicationExcpetion("Only SOAP requests are permitted.");
}
}
}
```
During the conversion, the BaseWebService.cs class was excluded from the project and the WSE2.0 namespaces were removed from the class.
Have anyone else experiences any issues with trying to upgrade a web service from .NET 1.1 using the WSE to .NET 3.5?
This is related to the previous question I had regarding a client consuming the upgraded web service:
[Stack Overflow Question](https://stackoverflow.com/questions/185420/issues-with-client-consuming-a-net-web-service-upgraded-from-net-11-to-35)
|
As I [answered](https://stackoverflow.com/questions/185420/issues-with-client-consuming-a-net-web-service-upgraded-from-net-11-to-35#198806) to the original question:
WCF (.net 3.5) is said to be compatible with WSE3 (.net 2.0+), but not with WSE2 (.net 1.1+).
So if you don't want to change the client, but want it to be compatible with the service, you can leave the old service source code and keep the references to WSE2 assemblies under VS2008 solution. Thus, both the client and the service will be compatible.
|
188,208 |
<p>There seem to be two bash idioms for redirecting STDOUT and STDERR to a file:</p>
<pre><code>fooscript &> foo
</code></pre>
<p>... and ...</p>
<pre><code>fooscript > foo 2>&1
</code></pre>
<p>What's the difference? It seems to me that the first one is just a shortcut for the second one, but my coworker contends that the second one will produce no output even if there's an error with the initial redirect, whereas the first one will spit redirect errors to STDOUT.</p>
<p><strong>EDIT</strong>: Okay... it seems like people are not understanding what I am asking, so I will try to clarify:</p>
<p>Can anyone give me an example where the two <em>specific lines</em> lines written above will yield different behavior?</p>
|
[
{
"answer_id": 188217,
"author": "J.J.",
"author_id": 21204,
"author_profile": "https://Stackoverflow.com/users/21204",
"pm_score": 1,
"selected": false,
"text": "<pre><code>&> foo # Will take all and redirect all output to foo.\n\n2>&1 # will redirect stderr to stdout.\n</code></pre>\n"
},
{
"answer_id": 188230,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 0,
"selected": false,
"text": "<p><code>2>&1</code> might be useful for cases where you aren't redirecting stdout to somewhere else, but rather you just want stderr to be sent to the same place (such as the console) as stdout (perhaps if the command you are running is already sending stderr somewhere else other than the console).</p>\n"
},
{
"answer_id": 188278,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": 1,
"selected": false,
"text": "<p>2>&1 depends on the order in which it is specified on the command line. Where &> sends both stdout and stderr to wherever, 2>&1 sends stderr to where stdout is <strong>currently</strong> going at that point in the command line. Thus:</p>\n\n<p>command > file 2>&1</p>\n\n<p>is different than:</p>\n\n<p>command 2>&1 > file</p>\n\n<p>where the former is redirecting both stdout and stderr to file, the latter redirects stderr to where stdout is going before it is redirected to the file (in this case, probably the terminal.) This is useful if you wanted to do something like:</p>\n\n<p>command 2>&1 > file | less</p>\n\n<p>Where you want to use less to page through the output of stderr and store the output of stdout to a file.</p>\n"
},
{
"answer_id": 188307,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 2,
"selected": false,
"text": "<p><code>&>foo</code> is less typing than <code>>foo 2>&1</code>, and less error-prone (you can't get it in the wrong order), but achieves the same result.</p>\n\n<p><code>2>&1</code> is confusing, because you need to put it after the <code>1></code> redirect, unless stdout is being redirected to a <code>|</code> pipe, in which case it goes before...</p>\n\n<pre>$ some-command 2>&1 >foo # does the unexpected\n$ some-command >foo 2>&1 # does the same as\n$ some-command &>foo # this and\n$ some-command >&foo # compatible with other shells, but trouble if the filename is numeric\n$ some-command 2>&1 | less # but the redirect goes *before* the pipe here...</pre>\n"
},
{
"answer_id": 188320,
"author": "KernelM",
"author_id": 22328,
"author_profile": "https://Stackoverflow.com/users/22328",
"pm_score": 2,
"selected": false,
"text": "<p>The main reason to use <code>2>&1</code>, in my experience, is when you want to append all output to a file rather than overwrite the file. With <code>&></code> syntax, you can't append. So with <code>2>&1</code>, you can write something like <code>program >> alloutput.log 2>&1</code> and get stdout and stderr output appended to the log file.</p>\n"
},
{
"answer_id": 188326,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 4,
"selected": true,
"text": "<p>From the <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Redirections\" rel=\"noreferrer\">bash manual</a>:</p>\n\n<blockquote>\n <p>There are two formats for redirecting standard output and standard error:</p>\n\n<pre><code>&>word\n</code></pre>\n \n <p>and</p>\n\n<pre><code>>&word\n</code></pre>\n \n <p>Of the two forms, the first is preferred. This is semantically equivalent to</p>\n\n<pre><code> >word 2>&1\n</code></pre>\n</blockquote>\n\n<p>The phrase \"semantically equivalent\" should settle the issue with your coworker.</p>\n"
},
{
"answer_id": 188415,
"author": "Jouni K. Seppänen",
"author_id": 26575,
"author_profile": "https://Stackoverflow.com/users/26575",
"pm_score": 3,
"selected": false,
"text": "<p>The situation where the two lines have different behavior is when your script is not running in bash but some simpler shell in the sh family, e.g. <a href=\"http://en.wikipedia.org/wiki/Debian_Almquist_shell\" rel=\"noreferrer\">dash</a> (which I believe is used as /bin/sh in some Linux distros because it is more lightweight than bash). In that case, </p>\n\n<pre><code>fooscript &> foo\n</code></pre>\n\n<p>is interpreted as two commands: the first one runs fooscript in the background, and the second one truncates the file foo. The command</p>\n\n<pre><code>fooscript > foo 2>&1\n</code></pre>\n\n<p>runs fooscript in the foreground and redirects its output and standard error to the file foo. In bash I think the lines will always do the same thing.</p>\n"
},
{
"answer_id": 14203625,
"author": "greenearth",
"author_id": 379528,
"author_profile": "https://Stackoverflow.com/users/379528",
"pm_score": 0,
"selected": false,
"text": "<p>I know its a pretty old posting..but sharing what could answer the question :\n* ..will yield different behavior? </p>\n\n<p>Scenario:\nWhen you are trying to use \"tee\" and want to preserve the exit code using process substitution in bash...\nsomeScript.sh 2>&1 >( tee \"toALog\") # this fails to capture the out put to log</p>\n\n<p>where as :</p>\n\n<p>someScript.sh >& >( tee \"toALog\") # works fine!</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16034/"
] |
There seem to be two bash idioms for redirecting STDOUT and STDERR to a file:
```
fooscript &> foo
```
... and ...
```
fooscript > foo 2>&1
```
What's the difference? It seems to me that the first one is just a shortcut for the second one, but my coworker contends that the second one will produce no output even if there's an error with the initial redirect, whereas the first one will spit redirect errors to STDOUT.
**EDIT**: Okay... it seems like people are not understanding what I am asking, so I will try to clarify:
Can anyone give me an example where the two *specific lines* lines written above will yield different behavior?
|
From the [bash manual](http://www.gnu.org/software/bash/manual/bashref.html#Redirections):
>
> There are two formats for redirecting standard output and standard error:
>
>
>
> ```
> &>word
>
> ```
>
> and
>
>
>
> ```
> >&word
>
> ```
>
> Of the two forms, the first is preferred. This is semantically equivalent to
>
>
>
> ```
> >word 2>&1
>
> ```
>
>
The phrase "semantically equivalent" should settle the issue with your coworker.
|
188,225 |
<p>I use Visual C++ 2008 in Visual Studio 2008. I frequently use the following command to diff an open file against its most recent checked-in version:</p>
<pre><code>File | Source Control | Compare...
</code></pre>
<p>I can also do the same thing by clicking on an icon in the Source Control toolbar.</p>
<p>I'm not certain, but I believe this command is the same for any source control plugin (I happen to use the Perforce plugin.)</p>
<p>I'd like to assign a keyboard shortcut to execute this command but I can't seem to find it listed anywhere in dialog where such assignments are normally made:</p>
<pre><code>Tools | Customize... | Commands
</code></pre>
<p>Did I just not see the command in the customize dialog? Is there another method to assign such a keyboard shortcut?</p>
|
[
{
"answer_id": 188256,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 3,
"selected": true,
"text": "<p>Tools -> Options -> Keyboard -> Commands Containing \"Compare\"</p>\n"
},
{
"answer_id": 188528,
"author": "jwfearn",
"author_id": 10559,
"author_profile": "https://Stackoverflow.com/users/10559",
"pm_score": 1,
"selected": false,
"text": "<p>Nescio's <a href=\"https://stackoverflow.com/questions/188225/how-to-assign-keyboard-shortcut-to-source-control-commands-in-visual-studio-2008#188256\">answer</a> is on the money. Here's a little more info:</p>\n\n<ul>\n<li>The shortcut assignment can be made at <code>Tools | Options | Environment | Keyboard</code></li>\n<li>The command is called <code>File.Compare</code></li>\n</ul>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10559/"
] |
I use Visual C++ 2008 in Visual Studio 2008. I frequently use the following command to diff an open file against its most recent checked-in version:
```
File | Source Control | Compare...
```
I can also do the same thing by clicking on an icon in the Source Control toolbar.
I'm not certain, but I believe this command is the same for any source control plugin (I happen to use the Perforce plugin.)
I'd like to assign a keyboard shortcut to execute this command but I can't seem to find it listed anywhere in dialog where such assignments are normally made:
```
Tools | Customize... | Commands
```
Did I just not see the command in the customize dialog? Is there another method to assign such a keyboard shortcut?
|
Tools -> Options -> Keyboard -> Commands Containing "Compare"
|
188,241 |
<p>If I want to have a case-insensitive string-keyed dictionary, which version of StringComparer should I use given these constraints:</p>
<ul>
<li>The keys in the dictionary come from either C# code or config files written in english locale only (either US, or UK)</li>
<li>The software is internationalized and will run in different locales</li>
</ul>
<p>I normally use StringComparer.InvariantCultureIgnoreCase but wasn't sure if that is the correct case. Here is example code:</p>
<pre><code>Dictionary< string, object> stuff = new Dictionary< string, object>(StringComparer.InvariantCultureIgnoreCase);
</code></pre>
|
[
{
"answer_id": 188264,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>Since the keys are your known fixed values, then either InvariantCultureIgnoreCase or OrdinalIgnoreCase should work. Avoid the culture-specific one, or you could hit some of the more \"fun\" things like the \"Turkish i\" problem. Obviously, you'd use a cultured comparer if you were comparing cultured values... but it sounds like you aren't.</p>\n"
},
{
"answer_id": 188273,
"author": "Oliver Hallam",
"author_id": 19995,
"author_profile": "https://Stackoverflow.com/users/19995",
"pm_score": 2,
"selected": false,
"text": "<p>The concept of \"case insensitive\" is a linguistic one, and so it doesn't make sense without a culture.</p>\n\n<p>See this <a href=\"http://www.siao2.com/2004/12/29/344136.aspx\" rel=\"nofollow noreferrer\">blog</a> for more information.</p>\n\n<p>That said if you are just talking about strings using the latin alphabet then you will probably get away with the InvariantCulture.</p>\n\n<p>It is probably best to create the dictionary with StringComparer.CurrentCulture, though. This will allow \"ß\" to match \"ss\" in your dictionary under a German culture, for example.</p>\n"
},
{
"answer_id": 188279,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 1,
"selected": false,
"text": "<p>StringComparer.OrdinalIgnoreCase is slightly faster than InvariantCultureIgnoreCase FWIW (\"An ordinal comparison is fast, but culture-insensitive\" according to <a href=\"http://msdn.microsoft.com/en-us/library/system.stringcomparison.aspx\" rel=\"nofollow noreferrer\">MSDN</a>.</p>\n\n<p>You'd have to be doing a lot of comparisons to notice the difference of course.</p>\n"
},
{
"answer_id": 188305,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 0,
"selected": false,
"text": "<p>The Invariant Culture exists specifically to deal with strings that are internal to the program and have nothing to do with user data or UI. It sounds like this is the case for this situation.</p>\n"
},
{
"answer_id": 189071,
"author": "Michael Damatov",
"author_id": 23372,
"author_profile": "https://Stackoverflow.com/users/23372",
"pm_score": 5,
"selected": false,
"text": "<p>There are three kinds of comparers:</p>\n\n<ul>\n<li>Culture-aware</li>\n<li>Culture invariant</li>\n<li>Ordinal</li>\n</ul>\n\n<p>Each comparer has a <strong>case-sensitive</strong> as well as a <strong>case-insensitive</strong> version.</p>\n\n<p>An <strong>ordinal</strong> comparer uses ordinal values of characters. This is the fastest comparer, it should be used for internal purposes.</p>\n\n<p>A <strong>culture-aware</strong> comparer considers aspects that are specific to the culture of the current thread. It knows the \"Turkish i\", \"Spanish LL\", etc. problems. It should be used for UI strings.</p>\n\n<p>The <strong>culture invariant</strong> comparer is actually not defined and can produce unpredictable results, and thus should never be used at all.</p>\n\n<p><em>References</em></p>\n\n<ol>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms973919.aspx\" rel=\"noreferrer\">New Recommendations for Using Strings in Microsoft .NET 2.0</a></li>\n</ol>\n"
},
{
"answer_id": 189091,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms973919.aspx#stringsinnet20_topic4\" rel=\"noreferrer\">This MSDN article</a> covers everything you could possibly want to know in great depth, including the Turkish-I problem.</p>\n\n<p>It's been a while since I read it, so I'm off to do so again. See you in an hour!</p>\n"
},
{
"answer_id": 199994,
"author": "GregUzelac",
"author_id": 27068,
"author_profile": "https://Stackoverflow.com/users/27068",
"pm_score": 0,
"selected": false,
"text": "<p>System.Collections.Specialized includes StringDictionary. The Remarks section of the MSDN states \"A key cannot be null, but a value can.</p>\n\n<p>The key is handled in a case-insensitive manner; it is translated to lowercase before it is used with the string dictionary.</p>\n\n<p>In .NET Framework version 1.0, this class uses culture-sensitive string comparisons. However, in .NET Framework version 1.1 and later, this class uses CultureInfo.InvariantCulture when comparing strings. For more information about how culture affects comparisons and sorting, see Comparing and Sorting Data for a Specific Culture and Performing Culture-Insensitive String Operations.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16501/"
] |
If I want to have a case-insensitive string-keyed dictionary, which version of StringComparer should I use given these constraints:
* The keys in the dictionary come from either C# code or config files written in english locale only (either US, or UK)
* The software is internationalized and will run in different locales
I normally use StringComparer.InvariantCultureIgnoreCase but wasn't sure if that is the correct case. Here is example code:
```
Dictionary< string, object> stuff = new Dictionary< string, object>(StringComparer.InvariantCultureIgnoreCase);
```
|
[This MSDN article](http://msdn.microsoft.com/en-us/library/ms973919.aspx#stringsinnet20_topic4) covers everything you could possibly want to know in great depth, including the Turkish-I problem.
It's been a while since I read it, so I'm off to do so again. See you in an hour!
|
188,250 |
<p>I believe there is a discussion on this very topic somewhere on the net but I lost the url and I am unable to find it via googling.</p>
<p>What I might try right now would be:</p>
<pre><code>ISessionFactoryHolder factoryHolder = ActiveRecordMediator<EntityClass>.GetSessionFactoryHolder();
ISession session = factoryHolder.CreateSession(typeof(EntityClass));
try
{
IDbCommand cmd = session.Connection.CreateCommand();
cmd.CommandText = "spName";
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
}
finally
{
factoryHolder.ReleaseSession(session);
}
</code></pre>
<p>However, I am not quite sure if this is the correct way to do this or if perhaps a better way exists.</p>
|
[
{
"answer_id": 301079,
"author": "okcodemonkey",
"author_id": 38825,
"author_profile": "https://Stackoverflow.com/users/38825",
"pm_score": 1,
"selected": false,
"text": "<p>The blog I used when implementing stored procedures in my ActiveRecord code was this post by Rodj (<a href=\"http://blog.rodj.org/archive/2008/05/23/activerecord-nhibernate-and-sql-stored-procedures.aspx\" rel=\"nofollow noreferrer\">http://blog.rodj.org/archive/2008/05/23/activerecord-nhibernate-and-sql-stored-procedures.aspx</a>). Using his post and the comments I was able to get this to work. I haven't decided if this is the best way yet. </p>\n"
},
{
"answer_id": 325642,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 1,
"selected": false,
"text": "<p>You can also get an IDbConnection with:</p>\n\n<pre><code>ActiveRecordMediator.GetSessionFactoryHolder()\n .GetSessionFactory(typeof(ActiveRecordBase))\n .ConnectionProvider.GetConnection();\n</code></pre>\n"
},
{
"answer_id": 4246582,
"author": "peter miller",
"author_id": 516240,
"author_profile": "https://Stackoverflow.com/users/516240",
"pm_score": 2,
"selected": false,
"text": "<p>This works for me (stored procedure with params and dynamic result table):</p>\n\n<pre><code>// get Connection\nSystem.Data.IDbConnection con = ActiveRecordMediator.GetSessionFactoryHolder()\n .GetSessionFactory(typeof(Autocomplete))\n .ConnectionProvider.GetConnection();\n\n// set Command\nSystem.Data.IDbCommand cmd = con.CreateCommand();\ncmd.CommandText = \"name_of_stored_procedure\";\ncmd.CommandType = System.Data.CommandType.StoredProcedure;\n\n// set Parameter of Stored Procedure\nSystem.Data.SqlClient.SqlParameter param = new System.Data.SqlClient.SqlParameter(\"@parameter_name\", System.Data.SqlDbType.NVarChar);\nparam.Value = \"value_of_parameter\";\n((System.Data.SqlClient.SqlParameterCollection)cmd.Parameters).Add(param);\n\n// call Stored Procedure (without getting result)\ncmd.ExecuteNonQuery();\n\n// ... or read results\nSystem.Data.SqlClient.SqlDataReader r = (System.Data.SqlClientSqlDataReader)cmd.ExecuteReader();\nwhile(r.Read()) {\n System.Console.WriteLine(\"result first col: \" + r.GetString(0));\n}\n</code></pre>\n"
},
{
"answer_id": 5749406,
"author": "yorch",
"author_id": 443600,
"author_profile": "https://Stackoverflow.com/users/443600",
"pm_score": 0,
"selected": false,
"text": "<p>For ActiveRecord version 1, this works:</p>\n\n<pre><code>IDbConnection connection = ActiveRecordMediator.GetSessionFactoryHolder()\n .GetSessionFactory(typeof(ActiveRecordBase))\n .OpenSession().Connection;\n</code></pre>\n"
},
{
"answer_id": 23934416,
"author": "Christian",
"author_id": 3687724,
"author_profile": "https://Stackoverflow.com/users/3687724",
"pm_score": -1,
"selected": false,
"text": "<pre><code>public ArrayList DevolverCamposDeObjetoSTP(T Objeto, List<Consulta> Consultas, string StoredProcedureName)\n {\n ArrayList results;\n try\n {\n var queryString = @\"EXEC \" + StoredProcedureName;\n foreach (var consulta in Consultas)\n {\n switch (consulta.tipoCampo)\n {\n case Consulta.TipoCampo.dato:\n queryString = queryString + \" \" + consulta.Campo + \" = \" + \"'\" + consulta.Valor + \"'\";\n break;\n case Consulta.TipoCampo.numero:\n queryString = queryString + \" \" + consulta.Campo + \" = \" + consulta.Valor;\n break;\n } \n queryString = queryString + \",\";\n }\n queryString = queryString.Remove(queryString.Count() - 1, 1);\n var query = new HqlBasedQuery(typeof(T),QueryLanguage.Sql, queryString);\n results = (ArrayList)ActiveRecordMediator.ExecuteQuery(query);\n }\n catch (Exception exception)\n {\n throw new Exception(exception.Message);\n }\n return results;\n }\npublic class Consulta\n{\n public enum TipoCampo\n {\n dato,\n numero\n }\n public string Campo { get; set; }\n public TipoCampo tipoCampo { get; set; }\n public string Valor { get; set; }\n public string Indicador { get; set; }\n}\npublic void _Pruebastp()\n {\n var p = new Recurso().DevolverCamposDeObjetoSTP(\n new Recurso(),\n new List<Consulta> { new Consulta { Campo = \"@nombre\", tipoCampo = Consulta.TipoCampo.dato, Valor = \"chr\" }, new Consulta { Campo = \"@perfil\", tipoCampo = Consulta.TipoCampo.numero, Valor = \"1\" } },\n \"Ejemplo\");\n }\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15396/"
] |
I believe there is a discussion on this very topic somewhere on the net but I lost the url and I am unable to find it via googling.
What I might try right now would be:
```
ISessionFactoryHolder factoryHolder = ActiveRecordMediator<EntityClass>.GetSessionFactoryHolder();
ISession session = factoryHolder.CreateSession(typeof(EntityClass));
try
{
IDbCommand cmd = session.Connection.CreateCommand();
cmd.CommandText = "spName";
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
}
finally
{
factoryHolder.ReleaseSession(session);
}
```
However, I am not quite sure if this is the correct way to do this or if perhaps a better way exists.
|
This works for me (stored procedure with params and dynamic result table):
```
// get Connection
System.Data.IDbConnection con = ActiveRecordMediator.GetSessionFactoryHolder()
.GetSessionFactory(typeof(Autocomplete))
.ConnectionProvider.GetConnection();
// set Command
System.Data.IDbCommand cmd = con.CreateCommand();
cmd.CommandText = "name_of_stored_procedure";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
// set Parameter of Stored Procedure
System.Data.SqlClient.SqlParameter param = new System.Data.SqlClient.SqlParameter("@parameter_name", System.Data.SqlDbType.NVarChar);
param.Value = "value_of_parameter";
((System.Data.SqlClient.SqlParameterCollection)cmd.Parameters).Add(param);
// call Stored Procedure (without getting result)
cmd.ExecuteNonQuery();
// ... or read results
System.Data.SqlClient.SqlDataReader r = (System.Data.SqlClientSqlDataReader)cmd.ExecuteReader();
while(r.Read()) {
System.Console.WriteLine("result first col: " + r.GetString(0));
}
```
|
188,281 |
<p>In Delphi 2009 I'm finding that any time I use TThread.CurrentThread in an application, I'll get an error message like the following when the application closes:</p>
<pre><code>Exception EAccessViolation in module ntdll.dll at 0003DBBA.
Access violation at address 7799DBBA in module 'ntdll.dll'. Write of
address 00000014.
</code></pre>
<p>Unless it's just my machine, you can replicate this in a few seconds: create a new Delphi Forms Application, add a button to the form, and use something like the following for the button's event handler:</p>
<pre><code>procedure TForm1.Button1Click(Sender: TObject);
begin
TThread.CurrentThread;
end;
</code></pre>
<p>On both my Vista machine and my XP machine I'm finding that, if I <em>don't</em> click the button everything's fine, but if I <em>do</em> click the button I get the above error message when I close the application.</p>
<p>So... I'm wondering if this is a bug, but at the same time I think it's rather likely that I'm simply not understanding something very basic about how you're supposed to work with TThreads in Delphi. I am a bit of a Delphi newbie I'm afraid.</p>
<p>Is there something obviously wrong with using TThread.CurrentThread like that?</p>
<p>If not, and you have Delphi 2009, do you get the same problem if you implement my simple sample project?</p>
<hr>
<h2><strong>Update: As François noted below, this actually is a bug in Delphi 2009 at the moment - you can <a href="http://qc.codegear.com/wc/qcmain.aspx?d=67726" rel="noreferrer">vote for it here</a>.</strong></h2>
<hr>
<h2><strong>Update: This bug was fixed in Delphi 2010.</strong></h2>
|
[
{
"answer_id": 188421,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 0,
"selected": false,
"text": "<p>I think CurrentThread is added in 2009 (or 2007). I have 2006 at home. But are you sure it is a class property?</p>\n"
},
{
"answer_id": 188448,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 5,
"selected": true,
"text": "<p>Unfortunately it seems like a bug linked to the call order of the finalization section in the Classes unit: </p>\n\n<p><code>DoneThreadSynchronization</code> clears the <code>ThreadLock</code> structure, then<br>\n<code>FreeExternalThreads</code> wants to destroy the Thread object you just created when calling <code>CurrentThread</code>, and<br>\nthat requires the ThreadLock to be already initialized in the call to<br>\n<code>EnterCriticalSection(ThreadLock)</code> in <code>TThread.RemoveQueuedEvents</code>...</p>\n\n<p><strong>UPDATE</strong>:<br>\nThere is now a <strong>workaround patch</strong> in the <a href=\"http://qc.codegear.com/wc/qcmain.aspx?d=67726\" rel=\"nofollow noreferrer\"><strong>QC report</strong></a>.</p>\n"
},
{
"answer_id": 192027,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 4,
"selected": false,
"text": "<p>Until CodeGear issues a fix, you can use the patch below. Save it into a standalone unit and use it anywhere in your program. I'll try to add it to the QC, too.</p>\n\n<p>This version works with D2009 (original), update 1 and update 2.</p>\n\n<pre><code>{ Fix Delphi 2009's invalid finalization order in Classes.pas.\n Written by Primoz Gabrijelcic, http://gp.17slon.com.\n No rights reserved - released to public domain.\n}\nunit FixD2009Classes;\n\ninterface\n\nimplementation\n\nuses\n Windows,\n SysUtils,\n Classes;\n\ntype\n TCode = array [0..109] of byte;\n\n{$WARN SYMBOL_PLATFORM OFF}\n\nprocedure PatchClasses;\n{$IFDEF ConditionalExpressions}\n{$IF RTLVersion = 20}\nvar\n i : integer;\n oldProtect: cardinal;\n pCode : ^TCode;\n tmp : DWORD;\nconst\n COffsets_Call: array [1..12] of integer = (0, 15, 24, 34, 49, 59, 69, 79, 89, 94, 99, 109);\n COffset_UnRegisterModuleClasses = 106;\n COffset_DoneThreadSynchronization = 94;\n COffset_FreeExternalThreads = 99;\n CCallDelta = COffset_FreeExternalThreads - COffset_DoneThreadSynchronization;\n{$IFEND}\n{$ENDIF}\nbegin\n{$IFDEF ConditionalExpressions}\n{$IF RTLVersion = 20}\n pCode := pointer(cardinal(@TStreamReader.ReadToEnd) + COffset_UnRegisterModuleClasses);\n Win32Check(VirtualProtect(pCode, COffsets_Call[High(COffsets_Call)], PAGE_READWRITE, oldProtect));\n try\n for i := Low(COffsets_Call) to High(COffsets_Call) do\n if pCode^[COffsets_Call[i]] <> $E8 then\n raise Exception.Create('Unexpected version of Classes - cannot patch');\n tmp := PDword(@pCode^[COffset_DoneThreadSynchronization+1])^;\n PDword(@pCode^[COffset_DoneThreadSynchronization+1])^ :=\n PDword(@pCode^[COffset_FreeExternalThreads+1])^ + CCallDelta;\n PDword(@pCode^[COffset_FreeExternalThreads+1])^ := tmp - CCallDelta;\n finally VirtualProtect(pCode, COffsets_Call[High(COffsets_Call)], oldProtect, oldProtect); end;\n{$IFEND}\n{$ENDIF}\nend;\n\ninitialization\n PatchClasses;\nend.\n</code></pre>\n"
},
{
"answer_id": 982021,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 3,
"selected": false,
"text": "<p>Patch unit for Delphi 2009 Update 3.</p>\n\n<pre><code>{ Fix Delphi 2009's invalid finalization order in Classes.pas.\n Written by Primoz Gabrijelcic, http://gp.17slon.com.\n No rights reserved - released to public domain.\n\n D2009 update 3 only.\n}\nunit FixD2009Classes;\n\ninterface\n\nimplementation\n\nuses\n Windows,\n SysUtils,\n Classes;\n\ntype\n TCode = array [0..144] of byte;\n\n{$WARN SYMBOL_PLATFORM OFF}\n\nprocedure PatchClasses;\n{$IFDEF ConditionalExpressions}\n{$IF RTLVersion = 20}\nvar\n i : integer;\n oldProtect: cardinal;\n pCode : ^TCode;\n tmp : DWORD;\nconst\n COffsets_Call: array [1..12] of integer = (0, 15, 24, 42, 47, 58, 73, 91, 101, 111, 134, 139);\n COffset_UnRegisterModuleClasses = 107;\n COffset_DoneThreadSynchronization = 134;\n COffset_FreeExternalThreads = 139;\n CCallDelta = COffset_FreeExternalThreads - COffset_DoneThreadSynchronization;\n{$IFEND}\n{$ENDIF}\nbegin\n{$IFDEF ConditionalExpressions}\n{$IF RTLVersion = 20}\n pCode := pointer(cardinal(@TStreamReader.ReadToEnd) + COffset_UnRegisterModuleClasses);\n Win32Check(VirtualProtect(pCode, COffsets_Call[High(COffsets_Call)], PAGE_READWRITE, oldProtect));\n try\n for i := Low(COffsets_Call) to High(COffsets_Call) do\n if pCode^[COffsets_Call[i]] <> $E8 then\n raise Exception.Create('Unexpected version of Classes - cannot patch');\n tmp := PDword(@pCode^[COffset_DoneThreadSynchronization+1])^;\n PDword(@pCode^[COffset_DoneThreadSynchronization+1])^ :=\n PDword(@pCode^[COffset_FreeExternalThreads+1])^ + CCallDelta;\n PDword(@pCode^[COffset_FreeExternalThreads+1])^ := tmp - CCallDelta;\n finally VirtualProtect(pCode, COffsets_Call[High(COffsets_Call)], oldProtect, oldProtect); end;\n{$IFEND}\n{$ENDIF}\nend;\n\ninitialization\n PatchClasses;\nend.\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11961/"
] |
In Delphi 2009 I'm finding that any time I use TThread.CurrentThread in an application, I'll get an error message like the following when the application closes:
```
Exception EAccessViolation in module ntdll.dll at 0003DBBA.
Access violation at address 7799DBBA in module 'ntdll.dll'. Write of
address 00000014.
```
Unless it's just my machine, you can replicate this in a few seconds: create a new Delphi Forms Application, add a button to the form, and use something like the following for the button's event handler:
```
procedure TForm1.Button1Click(Sender: TObject);
begin
TThread.CurrentThread;
end;
```
On both my Vista machine and my XP machine I'm finding that, if I *don't* click the button everything's fine, but if I *do* click the button I get the above error message when I close the application.
So... I'm wondering if this is a bug, but at the same time I think it's rather likely that I'm simply not understanding something very basic about how you're supposed to work with TThreads in Delphi. I am a bit of a Delphi newbie I'm afraid.
Is there something obviously wrong with using TThread.CurrentThread like that?
If not, and you have Delphi 2009, do you get the same problem if you implement my simple sample project?
---
**Update: As François noted below, this actually is a bug in Delphi 2009 at the moment - you can [vote for it here](http://qc.codegear.com/wc/qcmain.aspx?d=67726).**
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
---
**Update: This bug was fixed in Delphi 2010.**
----------------------------------------------
|
Unfortunately it seems like a bug linked to the call order of the finalization section in the Classes unit:
`DoneThreadSynchronization` clears the `ThreadLock` structure, then
`FreeExternalThreads` wants to destroy the Thread object you just created when calling `CurrentThread`, and
that requires the ThreadLock to be already initialized in the call to
`EnterCriticalSection(ThreadLock)` in `TThread.RemoveQueuedEvents`...
**UPDATE**:
There is now a **workaround patch** in the [**QC report**](http://qc.codegear.com/wc/qcmain.aspx?d=67726).
|
188,299 |
<p>I have the following struct in C++:</p>
<pre><code>#define MAXCHARS 15
typedef struct
{
char data[MAXCHARS];
int prob[MAXCHARS];
} LPRData;
</code></pre>
<p>And a function that I'm p/invoking into to get an array of 3 of these structures:</p>
<pre><code>void GetData(LPRData *data);
</code></pre>
<p>In C++ I would just do something like this:</p>
<pre><code>LPRData *Results;
Results = (LPRData *)malloc(MAXRESULTS*sizeof(LPRData));
GetData( Results );
</code></pre>
<p>And it would work just fine, but in C# I can't seem to get it to work.
I've created a C# struct like this:</p>
<pre><code>public struct LPRData
{
/// char[15]
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)]
public string data;
/// int[15]
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)]
public int[] prob;
}
</code></pre>
<p>And if I initialize an array of 3 of those (and all their sub-arrays) and pass it into this:</p>
<pre><code>GetData(LPRData[] data);
</code></pre>
<p>It returns with success, but the data in the LPRData array has not changed.</p>
<p>I've even tried to create a raw byte array the size of 3 LPRData's and pass that into a function prototype like this:</p>
<p>GetData(byte[] data);</p>
<p>But in that case I will get the "data" string from the very first LPRData structure, but nothing after it, including the "prob" array from the same LPRData.</p>
<p>Any ideas of how to properly handle this?</p>
|
[
{
"answer_id": 188396,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 4,
"selected": false,
"text": "<p>One trick when dealing with pointers is to just use an IntPtr. You can then use Marshal.PtrToStructure on the pointer and increment based on the size of the structure to get your results.</p>\n\n<pre><code>static extern void GetData([Out] out IntPtr ptr);\n\nLPRData[] GetData()\n{\n IntPtr value;\n LPRData[] array = new LPRData[3];\n GetData(out value);\n for (int i = 0; i < array.Length; i++)\n {\n array[i] = Marshal.PtrToStructure(value, typeof(LPRData));\n value += Marshal.SizeOf(typeof(LPRData));\n }\n return array;\n}\n</code></pre>\n"
},
{
"answer_id": 188407,
"author": "denny",
"author_id": 27,
"author_profile": "https://Stackoverflow.com/users/27",
"pm_score": 6,
"selected": true,
"text": "<p>I would try adding some attributes to your struct decloration</p>\n\n<pre><code>[StructLayout(LayoutKind.Sequential, Size=TotalBytesInStruct),Serializable]\npublic struct LPRData\n{\n/// char[15]\n[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)]\npublic string data;\n\n/// int[15]\n[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)]\npublic int[] prob;\n}\n</code></pre>\n\n<p>*Note TotalBytesInStruct is not intended to represent a variable</p>\n\n<p>JaredPar is also correct that using the IntPtr class could be helpful, but it has been quite awhile since I have used PInvoke so I'm rusty.</p>\n"
},
{
"answer_id": 207244,
"author": "GregUzelac",
"author_id": 27068,
"author_profile": "https://Stackoverflow.com/users/27068",
"pm_score": 2,
"selected": false,
"text": "<p>The PInvoke Interop Assistant may help. <a href=\"http://clrinterop.codeplex.com/releases/view/14120\" rel=\"nofollow noreferrer\">http://clrinterop.codeplex.com/releases/view/14120</a></p>\n"
},
{
"answer_id": 215610,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 2,
"selected": false,
"text": "<p>Did you mark GetData parameter with <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.outattribute.aspx\" rel=\"nofollow noreferrer\">OutAttribute</a>?</p>\n\n<blockquote>\n <p>Combining the InAttribute and\n OutAttribute is particularly useful\n when applied to arrays and formatted,\n non-blittable types. Callers see the\n changes a callee makes to these types\n only when you apply both attributes.</p>\n</blockquote>\n"
},
{
"answer_id": 9189225,
"author": "Zenexer",
"author_id": 1188377,
"author_profile": "https://Stackoverflow.com/users/1188377",
"pm_score": 2,
"selected": false,
"text": "<p>A similar topic was discussed on <a href=\"https://stackoverflow.com/questions/9188523/marshaling-c-structures-in-c-sharp\">this question</a>, and the one of the conclusions was that the <code>CharSet</code> named parameter must be set to <code>CharSet.Ansi</code>. Otherwise, we would be making a <code>wchar_t</code> array instead of a <code>char</code> array. Thus, the correct code would be as follows:</p>\n\n<pre><code>[Serializable]\n[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\npublic struct LPRData\n{\n [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)]\n public string data;\n\n [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)]\n public int[] prob;\n}\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] |
I have the following struct in C++:
```
#define MAXCHARS 15
typedef struct
{
char data[MAXCHARS];
int prob[MAXCHARS];
} LPRData;
```
And a function that I'm p/invoking into to get an array of 3 of these structures:
```
void GetData(LPRData *data);
```
In C++ I would just do something like this:
```
LPRData *Results;
Results = (LPRData *)malloc(MAXRESULTS*sizeof(LPRData));
GetData( Results );
```
And it would work just fine, but in C# I can't seem to get it to work.
I've created a C# struct like this:
```
public struct LPRData
{
/// char[15]
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)]
public string data;
/// int[15]
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)]
public int[] prob;
}
```
And if I initialize an array of 3 of those (and all their sub-arrays) and pass it into this:
```
GetData(LPRData[] data);
```
It returns with success, but the data in the LPRData array has not changed.
I've even tried to create a raw byte array the size of 3 LPRData's and pass that into a function prototype like this:
GetData(byte[] data);
But in that case I will get the "data" string from the very first LPRData structure, but nothing after it, including the "prob" array from the same LPRData.
Any ideas of how to properly handle this?
|
I would try adding some attributes to your struct decloration
```
[StructLayout(LayoutKind.Sequential, Size=TotalBytesInStruct),Serializable]
public struct LPRData
{
/// char[15]
[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)]
public string data;
/// int[15]
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)]
public int[] prob;
}
```
\*Note TotalBytesInStruct is not intended to represent a variable
JaredPar is also correct that using the IntPtr class could be helpful, but it has been quite awhile since I have used PInvoke so I'm rusty.
|
188,327 |
<p>My question is on the ASP.NET GridView control. I am using a CommandField in the Columns tag as seen below.</p>
<pre><code><asp:CommandField ShowEditButton="True" HeaderStyle-Width="40px" UpdateText="Save" ButtonType="Link" HeaderStyle-Wrap="true" ItemStyle-Wrap="true" ItemStyle-Width="40px"/>
</code></pre>
<p>What renders is the shown in the following image (after I click on the Edit button).
</p>
<p><a href="https://i.stack.imgur.com/BUGrY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BUGrY.jpg" alt="alt text"></a></p>
<p>As you can see <strong>I am trying to have the Cancel link show up a new line and my question is how do you do what?</strong> If I change the <code>ButtonType="Link"</code> to <code>ButtonType="Button"</code>, I get it rendering correctly as shown below.</p>
<p><a href="http://i38.tinypic.com/2pqopxi.jpg" rel="nofollow noreferrer">alt text http://i38.tinypic.com/2pqopxi.jpg</a></p>
<p>I've tried Google already and maybe I'm not searching on the right tags but I couldn't see this one addressed before.</p>
|
[
{
"answer_id": 188343,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 0,
"selected": false,
"text": "<p>Don't use a command field, use a <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.templatefield.aspx\" rel=\"nofollow noreferrer\">TemplateField</a> and put your command button in that with a line break (br) before it like you want.</p>\n"
},
{
"answer_id": 188662,
"author": "denny",
"author_id": 27,
"author_profile": "https://Stackoverflow.com/users/27",
"pm_score": 3,
"selected": true,
"text": "<p>If you use a template field it will give you complete control over the look of your page, but it requires that you use the CommandName and possible CommandArgument properties, and also using the GridView's OnRowCommand.</p>\n\n<p>The aspx page:</p>\n\n<pre><code><asp:GridView id=\"gvGrid\" runat=\"server\" OnRowCommand=\"gvGrid_Command\">\n <Columns>\n <asp:TemplateField>\n <ItemTemplate>\n Some Stuff random content\n <br />\n <asp:LinkButton id=\"lbDoIt\" runat=\"server\" CommandName=\"Cancel\" CommandArgument=\"SomeIdentifierIfNecessary\" />\n </ItemTemplate>\n </asp:TemplateField>\n </Columns>\n</asp:GridView>\n</code></pre>\n\n<p>The code behind:</p>\n\n<pre><code>protected void gvGrid_Command(object sender, GridViewCommandEventArgs e)\n{\n if(e.CommandName==\"Cancel\")\n {\n // Do your cancel stuff here.\n }\n</code></pre>\n\n<p>}</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26573/"
] |
My question is on the ASP.NET GridView control. I am using a CommandField in the Columns tag as seen below.
```
<asp:CommandField ShowEditButton="True" HeaderStyle-Width="40px" UpdateText="Save" ButtonType="Link" HeaderStyle-Wrap="true" ItemStyle-Wrap="true" ItemStyle-Width="40px"/>
```
What renders is the shown in the following image (after I click on the Edit button).
[](https://i.stack.imgur.com/BUGrY.jpg)
As you can see **I am trying to have the Cancel link show up a new line and my question is how do you do what?** If I change the `ButtonType="Link"` to `ButtonType="Button"`, I get it rendering correctly as shown below.
[alt text http://i38.tinypic.com/2pqopxi.jpg](http://i38.tinypic.com/2pqopxi.jpg)
I've tried Google already and maybe I'm not searching on the right tags but I couldn't see this one addressed before.
|
If you use a template field it will give you complete control over the look of your page, but it requires that you use the CommandName and possible CommandArgument properties, and also using the GridView's OnRowCommand.
The aspx page:
```
<asp:GridView id="gvGrid" runat="server" OnRowCommand="gvGrid_Command">
<Columns>
<asp:TemplateField>
<ItemTemplate>
Some Stuff random content
<br />
<asp:LinkButton id="lbDoIt" runat="server" CommandName="Cancel" CommandArgument="SomeIdentifierIfNecessary" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
```
The code behind:
```
protected void gvGrid_Command(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName=="Cancel")
{
// Do your cancel stuff here.
}
```
}
|
188,334 |
<p>I'm attempting to create a custom calendar control that inherits from ASP.Net's built in calendar user control. </p>
<p>the code-behind file for my control looks like this:</p>
<pre><code>public partial class WeeklyEventsCalendar : Calendar
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
</code></pre>
<p>and compiles fine. </p>
<p>However, when I try to place my custom control on an aspx page:</p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeFile="testbed.aspx.cs" Inherits="testbed" %>
<%@ Register Src="UserControls/WeeklyEventsCalendar.ascx" TagName="WeeklyEventsCalendar"
TagPrefix="mvs" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
<link href="~/css/VitalSignsStyleSheet.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div>
<mvs:WeeklyEventsCalendar runat="server" />
</div>
</body>
</html>
</code></pre>
<p>I get a warning <strong>'Element WeeklyEventsCalendar is not a known element. This can occur if there is a compilation error in the web site, or the web.config file is missing.'</strong> Attempting </p>
<p>I don't get any sort of 'file not found' error like I have in the past when I mis-typed the location of the file. </p>
<p>When I attempt to load aspx page in a browser, I get error CS0115: <strong>'ASP.usercontrols_weeklyeventscalendar_ascx.FrameworkInitialize()': no suitable method found to override</strong></p>
<p>Which is even more confusing, because nowhere in my code do I attempt to define such a function. </p>
<p>This should be really simple. Where am I going wrong?</p>
|
[
{
"answer_id": 188402,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 3,
"selected": false,
"text": "<p>I think the problem is that you're attempting to inherit the Calendar control (which is a server control) from a user control (based on your ASCX extension). You can't do this. If you want to inherit from the Calendar control then you need to create a server control.</p>\n\n<p>Let me know if you need some sample code.</p>\n"
},
{
"answer_id": 188435,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 3,
"selected": true,
"text": "<p>Bryant hit on it. One thing you might consider if all you're doing is customizing the existing control is embedding an instance of the calendar on your user control and exposing the properties you need from it. This way your user control can handle all of the requisite customizations, and also provide only a limited interface back out to the consuming application. (This is composition instead of inheritance.)</p>\n\n<p>If you really do need to fully derive from asp:Calendar, then you need to create a standard class which derives from the Calendar control, and then perform your customizations. You'll have no UI design for that, however -- everything you do will need to be custom code. (And if you need to change the HTML being emitted, you'll need to write those custom streams out as well -- which, with a calendar control, could be painful.)</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17917/"
] |
I'm attempting to create a custom calendar control that inherits from ASP.Net's built in calendar user control.
the code-behind file for my control looks like this:
```
public partial class WeeklyEventsCalendar : Calendar
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
```
and compiles fine.
However, when I try to place my custom control on an aspx page:
```
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="testbed.aspx.cs" Inherits="testbed" %>
<%@ Register Src="UserControls/WeeklyEventsCalendar.ascx" TagName="WeeklyEventsCalendar"
TagPrefix="mvs" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
<link href="~/css/VitalSignsStyleSheet.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div>
<mvs:WeeklyEventsCalendar runat="server" />
</div>
</body>
</html>
```
I get a warning **'Element WeeklyEventsCalendar is not a known element. This can occur if there is a compilation error in the web site, or the web.config file is missing.'** Attempting
I don't get any sort of 'file not found' error like I have in the past when I mis-typed the location of the file.
When I attempt to load aspx page in a browser, I get error CS0115: **'ASP.usercontrols\_weeklyeventscalendar\_ascx.FrameworkInitialize()': no suitable method found to override**
Which is even more confusing, because nowhere in my code do I attempt to define such a function.
This should be really simple. Where am I going wrong?
|
Bryant hit on it. One thing you might consider if all you're doing is customizing the existing control is embedding an instance of the calendar on your user control and exposing the properties you need from it. This way your user control can handle all of the requisite customizations, and also provide only a limited interface back out to the consuming application. (This is composition instead of inheritance.)
If you really do need to fully derive from asp:Calendar, then you need to create a standard class which derives from the Calendar control, and then perform your customizations. You'll have no UI design for that, however -- everything you do will need to be custom code. (And if you need to change the HTML being emitted, you'll need to write those custom streams out as well -- which, with a calendar control, could be painful.)
|
188,349 |
<p>I need to knock out a quick animation in C#/Windows Forms for a Halloween display. Just some 2D shapes moving about on a solid background. Since this is just a quick one-off project I <strong><em>really</em></strong> don't want to install and learn an entire new set of tools for this. (DirectX dev kits, Silverlight, Flash, etc..) I also have to install this on multiple computers so anything beyond the basic .Net framework (2.0) would be a pain in the arse.</p>
<p>For tools I've got VS2k8, 25 years of development experience, a wheelbarrow, holocaust cloak, and about 2 days to knock this out. I haven't done animation since using assembler on my Atari 130XE (hooray for page flipping and player/missile graphics!)</p>
<p>Advice? Here's some of the things I'd like to know:</p>
<ul>
<li>I can draw on any empty widget (like a panel) by fiddling with it's OnPaint handler, right? That's how I'd draw a custom widget. Is there a better technique than this?</li>
<li>Is there a page-flipping technique for this kind of thing in Windows Forms? I'm not looking for a high frame rate, just as little flicker/drawing as necessary.</li>
</ul>
<p>Thanks.</p>
<p><strong>Post Mortem Edit ... "a couple of coding days later"</strong></p>
<p>Well, the project is done. The links below came in handy although a couple of them were 404. (I wish SO would allow more than one reply to be marked "correct"). The biggest problem I had to overcome was flickering, and a persistent bug when I tried to draw on the form directly.</p>
<ul>
<li>Using the OnPaint event for the Form: bad idea. I never got that to work; lots of mysterious errors (stack overflows, or ArgumentNullExceptions). I wound up using a panel sized to fill the form and that worked fine.</li>
<li>Using the OnPaint method is slow anyway. Somewhere online I read that building the PaintEventArgs was slow, and they weren't kidding. Lots of flickering went away when I abandoned this. Skip the OnPaint/Invalidate() and just paint it yourself. </li>
<li><p>Setting all of the "double buffering" options on the form still left some flicker that had to be fixed. (And I found conflicting docs that said "set them on the control" and "set them on the form". Well controls don't have a .SetStyle() method.) I haven't tested without them, so they might be doing something (<code>this</code> is the form):</p>
<pre><code> this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
</code></pre></li>
</ul>
<p>So the workhorse of the code wound up looking like (<code>pf</code> is the panel control):</p>
<pre><code> void PaintPlayField()
{
Bitmap bufl = new Bitmap(pf.Width, pf.Height);
using (Graphics g = Graphics.FromImage(bufl))
{
g.FillRectangle(Brushes.Black, new Rectangle(0, 0, pf.Width, pf.Height));
DrawItems(g);
DrawMoreItems(g);
pf.CreateGraphics().DrawImageUnscaled(bufl, 0, 0);
}
}
</code></pre>
<p>And I just called PaintPlayField from the inside of my Timer loop. No flicker at all.</p>
|
[
{
"answer_id": 188377,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 5,
"selected": true,
"text": "<p>Set off a timer at your desired frame rate. At each timer firing twiddle the internal representation of the shapes on the screen (your model) per the animation motion you want to achieve, then call <code>Invalidate(true)</code>. Inside the OnPaint just draw the model on the screen.</p>\n\n<p>Oh yeah, and you probably want to turn Double Buffering on (this is like automatic page flipping).</p>\n"
},
{
"answer_id": 188505,
"author": "StubbornMule",
"author_id": 13341,
"author_profile": "https://Stackoverflow.com/users/13341",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://channel9.msdn.com/coding4fun/articles/2D-Game-Primer-Visual-C\" rel=\"nofollow noreferrer\">2d Game Primer</a></p>\n\n<p><a href=\"http://www.java2s.com/Code/CSharp/2D-Graphics/Timerbasedanimation.htm\" rel=\"nofollow noreferrer\">Timer Based Animation</a></p>\n\n<p>Both of these give good examples of animation. The code is fairly straightforward. i used these when I needed to do a quick animation for my son.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8173/"
] |
I need to knock out a quick animation in C#/Windows Forms for a Halloween display. Just some 2D shapes moving about on a solid background. Since this is just a quick one-off project I ***really*** don't want to install and learn an entire new set of tools for this. (DirectX dev kits, Silverlight, Flash, etc..) I also have to install this on multiple computers so anything beyond the basic .Net framework (2.0) would be a pain in the arse.
For tools I've got VS2k8, 25 years of development experience, a wheelbarrow, holocaust cloak, and about 2 days to knock this out. I haven't done animation since using assembler on my Atari 130XE (hooray for page flipping and player/missile graphics!)
Advice? Here's some of the things I'd like to know:
* I can draw on any empty widget (like a panel) by fiddling with it's OnPaint handler, right? That's how I'd draw a custom widget. Is there a better technique than this?
* Is there a page-flipping technique for this kind of thing in Windows Forms? I'm not looking for a high frame rate, just as little flicker/drawing as necessary.
Thanks.
**Post Mortem Edit ... "a couple of coding days later"**
Well, the project is done. The links below came in handy although a couple of them were 404. (I wish SO would allow more than one reply to be marked "correct"). The biggest problem I had to overcome was flickering, and a persistent bug when I tried to draw on the form directly.
* Using the OnPaint event for the Form: bad idea. I never got that to work; lots of mysterious errors (stack overflows, or ArgumentNullExceptions). I wound up using a panel sized to fill the form and that worked fine.
* Using the OnPaint method is slow anyway. Somewhere online I read that building the PaintEventArgs was slow, and they weren't kidding. Lots of flickering went away when I abandoned this. Skip the OnPaint/Invalidate() and just paint it yourself.
* Setting all of the "double buffering" options on the form still left some flicker that had to be fixed. (And I found conflicting docs that said "set them on the control" and "set them on the form". Well controls don't have a .SetStyle() method.) I haven't tested without them, so they might be doing something (`this` is the form):
```
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
```
So the workhorse of the code wound up looking like (`pf` is the panel control):
```
void PaintPlayField()
{
Bitmap bufl = new Bitmap(pf.Width, pf.Height);
using (Graphics g = Graphics.FromImage(bufl))
{
g.FillRectangle(Brushes.Black, new Rectangle(0, 0, pf.Width, pf.Height));
DrawItems(g);
DrawMoreItems(g);
pf.CreateGraphics().DrawImageUnscaled(bufl, 0, 0);
}
}
```
And I just called PaintPlayField from the inside of my Timer loop. No flicker at all.
|
Set off a timer at your desired frame rate. At each timer firing twiddle the internal representation of the shapes on the screen (your model) per the animation motion you want to achieve, then call `Invalidate(true)`. Inside the OnPaint just draw the model on the screen.
Oh yeah, and you probably want to turn Double Buffering on (this is like automatic page flipping).
|
188,366 |
<p>I am trying to run a query that will give time averages but when I do... some duplicate records are in the calculation. how can I remove duplicates?</p>
<p>ex.</p>
<p>Column 1 / 07-5794 / 07-5794 / 07-5766 / 07-8423 / 07-4259</p>
<p>Column 2 / 00:59:59 / 00:48:22 / 00:42:48/ 00:51:47 / 00:52:12</p>
<p>I can get the average of the column 2 but I don't want identical values in column 1 to be calculated twice (07-5794) ???</p>
|
[
{
"answer_id": 188380,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 1,
"selected": false,
"text": "<p>To get the average of the minimum values for each incnum, you could write this SQL</p>\n\n<pre><code>select avg(min_time) as avg_time from\n (select incnum, min(col2) as min_time from inc group by incnum)\n</code></pre>\n\n<p>using the correct average function for your brand of SQL.</p>\n\n<p>If you're doing this in Access, you'll want to paste this into the SQL view; when you use a subquery, you can't do that directly in design view.</p>\n"
},
{
"answer_id": 188385,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 0,
"selected": false,
"text": "<p>SELECT DISTINCT()</p>\n\n<p>or</p>\n\n<p>GROUP BY ()</p>\n\n<p>or</p>\n\n<p>SELECT UNIQUE()</p>\n\n<p>... but usually averages <em>have</em> duplicates included. Just tell me this isn't for financial software, I wont stand for <a href=\"http://scienceblogs.com/goodmath/2008/09/bad_probability_and_economic_d.php\" rel=\"nofollow noreferrer\">another abuse of statistics</a>!</p>\n"
},
{
"answer_id": 188386,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "<p>I believe you're looking for the DISTINCT.</p>\n\n<p><a href=\"http://www.sql-tutorial.com/sql-distinct-sql-tutorial\" rel=\"nofollow noreferrer\">http://www.sql-tutorial.com/sql-distinct-sql-tutorial</a> && <a href=\"http://www.w3schools.com/SQL/sql_distinct.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/SQL/sql_distinct.asp</a></p>\n"
},
{
"answer_id": 188394,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 0,
"selected": false,
"text": "<p>Do you want to eliminate all entries that are duplicates? That is, should neither of the rows with \"07-5794\" be included in the calculation. If that is the case, I think this would work (in Oracle at least):</p>\n\n<pre><code>SELECT AVG(col2)\n FROM (\n SELECT col1, MAX(col2) AS col2\n FROM table\n GROUP BY col1\n HAVING COUNT(*) = 1\n )\n</code></pre>\n\n<p>However, if you want to retain one of the duplicates, you need to specify how to pick which one to keep.</p>\n"
},
{
"answer_id": 188436,
"author": "Jason Stevenson",
"author_id": 13368,
"author_profile": "https://Stackoverflow.com/users/13368",
"pm_score": 0,
"selected": false,
"text": "<p>Anastasia,</p>\n\n<p>Assuming you have the calculation for the average and a unique key in the table, you could do something like this to get just the latest occurrence of the timing for each unique 07-xxx result:</p>\n\n<pre><code>select Column1, Avg(Convert(decimal,Column2)) \nfrom Table1\nwhere TableId in\n(\nselect Max(TableId)\nfrom Table1\ngroup by Column1\n)\ngroup by column1\n</code></pre>\n\n<p>This was assuming the following table structure in MS SQL:</p>\n\n<pre><code>CREATE TABLE [dbo].[Table1] (\n[TableId] [int] IDENTITY (1, 1) NOT NULL ,\n[Column1] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\n[Column2] [int] NULL ) ON [PRIMARY]\n</code></pre>\n\n<p>Good Luck!</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am trying to run a query that will give time averages but when I do... some duplicate records are in the calculation. how can I remove duplicates?
ex.
Column 1 / 07-5794 / 07-5794 / 07-5766 / 07-8423 / 07-4259
Column 2 / 00:59:59 / 00:48:22 / 00:42:48/ 00:51:47 / 00:52:12
I can get the average of the column 2 but I don't want identical values in column 1 to be calculated twice (07-5794) ???
|
To get the average of the minimum values for each incnum, you could write this SQL
```
select avg(min_time) as avg_time from
(select incnum, min(col2) as min_time from inc group by incnum)
```
using the correct average function for your brand of SQL.
If you're doing this in Access, you'll want to paste this into the SQL view; when you use a subquery, you can't do that directly in design view.
|
188,373 |
<p>I'd like to re-brand (and send error emails) for all of the SSRS default error pages (picture below) when you access reports via /ReportServer/. I'm already handling the ASP OnError event and <em>some</em> of the default SSRS errors appear to catch their own exceptions and then render this page cancel the response all before the OnError event is ever fired.</p>
<p>Any idea on how I can get a handle into SSRS to brand all error pages?</p>
<p><img src="https://www.jazz2online.com/junk/reporting_error.gif" alt="Reporting Services Error"></p>
|
[
{
"answer_id": 188380,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 1,
"selected": false,
"text": "<p>To get the average of the minimum values for each incnum, you could write this SQL</p>\n\n<pre><code>select avg(min_time) as avg_time from\n (select incnum, min(col2) as min_time from inc group by incnum)\n</code></pre>\n\n<p>using the correct average function for your brand of SQL.</p>\n\n<p>If you're doing this in Access, you'll want to paste this into the SQL view; when you use a subquery, you can't do that directly in design view.</p>\n"
},
{
"answer_id": 188385,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 0,
"selected": false,
"text": "<p>SELECT DISTINCT()</p>\n\n<p>or</p>\n\n<p>GROUP BY ()</p>\n\n<p>or</p>\n\n<p>SELECT UNIQUE()</p>\n\n<p>... but usually averages <em>have</em> duplicates included. Just tell me this isn't for financial software, I wont stand for <a href=\"http://scienceblogs.com/goodmath/2008/09/bad_probability_and_economic_d.php\" rel=\"nofollow noreferrer\">another abuse of statistics</a>!</p>\n"
},
{
"answer_id": 188386,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "<p>I believe you're looking for the DISTINCT.</p>\n\n<p><a href=\"http://www.sql-tutorial.com/sql-distinct-sql-tutorial\" rel=\"nofollow noreferrer\">http://www.sql-tutorial.com/sql-distinct-sql-tutorial</a> && <a href=\"http://www.w3schools.com/SQL/sql_distinct.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/SQL/sql_distinct.asp</a></p>\n"
},
{
"answer_id": 188394,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 0,
"selected": false,
"text": "<p>Do you want to eliminate all entries that are duplicates? That is, should neither of the rows with \"07-5794\" be included in the calculation. If that is the case, I think this would work (in Oracle at least):</p>\n\n<pre><code>SELECT AVG(col2)\n FROM (\n SELECT col1, MAX(col2) AS col2\n FROM table\n GROUP BY col1\n HAVING COUNT(*) = 1\n )\n</code></pre>\n\n<p>However, if you want to retain one of the duplicates, you need to specify how to pick which one to keep.</p>\n"
},
{
"answer_id": 188436,
"author": "Jason Stevenson",
"author_id": 13368,
"author_profile": "https://Stackoverflow.com/users/13368",
"pm_score": 0,
"selected": false,
"text": "<p>Anastasia,</p>\n\n<p>Assuming you have the calculation for the average and a unique key in the table, you could do something like this to get just the latest occurrence of the timing for each unique 07-xxx result:</p>\n\n<pre><code>select Column1, Avg(Convert(decimal,Column2)) \nfrom Table1\nwhere TableId in\n(\nselect Max(TableId)\nfrom Table1\ngroup by Column1\n)\ngroup by column1\n</code></pre>\n\n<p>This was assuming the following table structure in MS SQL:</p>\n\n<pre><code>CREATE TABLE [dbo].[Table1] (\n[TableId] [int] IDENTITY (1, 1) NOT NULL ,\n[Column1] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\n[Column2] [int] NULL ) ON [PRIMARY]\n</code></pre>\n\n<p>Good Luck!</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15050/"
] |
I'd like to re-brand (and send error emails) for all of the SSRS default error pages (picture below) when you access reports via /ReportServer/. I'm already handling the ASP OnError event and *some* of the default SSRS errors appear to catch their own exceptions and then render this page cancel the response all before the OnError event is ever fired.
Any idea on how I can get a handle into SSRS to brand all error pages?

|
To get the average of the minimum values for each incnum, you could write this SQL
```
select avg(min_time) as avg_time from
(select incnum, min(col2) as min_time from inc group by incnum)
```
using the correct average function for your brand of SQL.
If you're doing this in Access, you'll want to paste this into the SQL view; when you use a subquery, you can't do that directly in design view.
|
188,389 |
<p>I try to define a schema for XML documents I receive.</p>
<p>The documents look like:</p>
<pre><code><root>
<items>
<group name="G-1">
<item name="I-1"/>
<item name="I-2"/>
<item name="I-3"/>
<item name="I-4"/>
</group>
</items>
<data>
<group name="G-1" place="here">
<customer name="C-1">
<item name="I-1" count="3"/>
<item name="I-2" count="4"/>
</customer>
<customer name="C-2">
<item name="I-3" count="7"/>
</customer>
</group>
</data>
</root>
</code></pre>
<p>I tried XmlSpy and xsd.exe from .NET 2.0. Both created schema definitions which allow below <code><group></code> any number of <code><item></code> and <code><customer></code> elements. But what I'm looking for should restrict <code><group></code> below <code><items></code> to <code><item></code> elements, and <code><group></code> below <code><data></code> to <code><customer></code> elements.</p>
<p>Is this something xml schema is not capable at all?</p>
|
[
{
"answer_id": 188430,
"author": "Peter Meyer",
"author_id": 1875,
"author_profile": "https://Stackoverflow.com/users/1875",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, XSD can handle this. I generated this schema from Visual Studio 2008 (much faster than doing it by hand) and it will do what you're looking for:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xs:schema attributeFormDefault=\"unqualified\" elementFormDefault=\"qualified\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n <xs:element name=\"root\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"items\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"group\">\n <xs:complexType>\n <xs:sequence>\n <xs:element maxOccurs=\"unbounded\" name=\"item\">\n <xs:complexType>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n <xs:element name=\"data\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"group\">\n <xs:complexType>\n <xs:sequence>\n <xs:element maxOccurs=\"unbounded\" name=\"customer\">\n <xs:complexType>\n <xs:sequence>\n <xs:element maxOccurs=\"unbounded\" name=\"item\">\n <xs:complexType>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"count\" type=\"xs:unsignedByte\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"optional\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"place\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n</xs:schema>\n</code></pre>\n"
},
{
"answer_id": 233093,
"author": "6eorge Jetson",
"author_id": 23422,
"author_profile": "https://Stackoverflow.com/users/23422",
"pm_score": 3,
"selected": false,
"text": "<p>The key points (see <a href=\"http://msdn.microsoft.com/en-us/library/aa468563.aspx#xmlschmachng_topic04\" rel=\"noreferrer\">XML Schema Runtime Polymorphism via xsi:type and Abstract Types</a> for complete and correct context/placement/usage) are:</p>\n\n<ol>\n<li><p>Create a base type with (abstract=\"true\" to prevent it from being used directly)</p>\n\n<p>Note: the ref attribute replaces the name attribute for elements defined elsewhere</p>\n\n<pre><code><xs:complexType name=\"CustomerType\" abstract=\"true\" > \n <xs:sequence> \n <xs:element ref=\"cust:FirstName\" /> \n <xs:element ref=\"cust:LastName\" /> \n <xs:element ref=\"cust:PhoneNumber\" minOccurs=\"0\"/> \n </xs:sequence> \n <xs:attribute name=\"customerID\" type=\"xs:integer\" /> \n</xs:complexType>\n</code></pre></li>\n<li><p>Create two or more derived types by extending or restricting the base type</p>\n\n<pre><code><xs:complexType name=\"MandatoryPhoneCustomerType\" > \n <xs:complexContent> \n <xs:restriction base=\"cust:CustomerType\"> \n <xs:sequence> \n <xs:element ref=\"cust:FirstName\" /> \n <xs:element ref=\"cust:LastName\" /> \n <xs:element ref=\"cust:PhoneNumber\" minOccurs=\"1\" /> \n </xs:sequence> \n </xs:restriction> \n </xs:complexContent> \n</xs:complexType>\n</code></pre>\n\n<p>and</p>\n\n<pre><code><xs:complexType name=\"AddressableCustomerType\" > \n <xs:complexContent> \n <xs:extension base=\"cust:CustomerType\"> \n <xs:sequence> \n <xs:element ref=\"cust:Address\" /> \n <xs:element ref=\"cust:City\" /> \n <xs:element ref=\"cust:State\" /> \n <xs:element ref=\"cust:Zip\" /> \n </xs:sequence> \n </xs:extension> \n </xs:complexContent> \n</xs:complexType>\n</code></pre></li>\n<li><p>Reference the base type in an element</p>\n\n<pre><code><xs:element name=\"Customer\" type=\"cust:CustomerType\" />\n</code></pre></li>\n<li><p>In your instance XML document, specify the specific derived type as an xsi:type attribute</p>\n\n<pre><code><cust:Customer customerID=\"12345\" xsi:type=\"cust:MandatoryPhoneCustomerType\" > \n <cust:FirstName>Dare</cust:FirstName> \n <cust:LastName>Obasanjo</cust:LastName> \n <cust:PhoneNumber>425-555-1234</cust:PhoneNumber> \n</cust:Customer>\n</code></pre>\n\n<p>or:</p>\n\n<pre><code><cust:Customer customerID=\"67890\" xsi:type=\"cust:AddressableCustomerType\" > \n <cust:FirstName>John</cust:FirstName> \n <cust:LastName>Smith</cust:LastName> \n <cust:Address>2001</cust:Address> \n <cust:City>Redmond</cust:City> \n <cust:State>WA</cust:State> \n <cust:Zip>98052</cust:Zip> \n</cust:Customer>\n</code></pre></li>\n</ol>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23772/"
] |
I try to define a schema for XML documents I receive.
The documents look like:
```
<root>
<items>
<group name="G-1">
<item name="I-1"/>
<item name="I-2"/>
<item name="I-3"/>
<item name="I-4"/>
</group>
</items>
<data>
<group name="G-1" place="here">
<customer name="C-1">
<item name="I-1" count="3"/>
<item name="I-2" count="4"/>
</customer>
<customer name="C-2">
<item name="I-3" count="7"/>
</customer>
</group>
</data>
</root>
```
I tried XmlSpy and xsd.exe from .NET 2.0. Both created schema definitions which allow below `<group>` any number of `<item>` and `<customer>` elements. But what I'm looking for should restrict `<group>` below `<items>` to `<item>` elements, and `<group>` below `<data>` to `<customer>` elements.
Is this something xml schema is not capable at all?
|
Yes, XSD can handle this. I generated this schema from Visual Studio 2008 (much faster than doing it by hand) and it will do what you're looking for:
```
<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
<xs:complexType>
<xs:sequence>
<xs:element name="items">
<xs:complexType>
<xs:sequence>
<xs:element name="group">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="item">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="data">
<xs:complexType>
<xs:sequence>
<xs:element name="group">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="customer">
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" name="item">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="count" type="xs:unsignedByte" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="optional" />
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
<xs:attribute name="place" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
```
|
188,444 |
<p>Is it possible to read and write Word (2003 and 2007) files in Python without using a COM object?<br />
I know that I can:</p>
<pre><code>f = open('c:\file.doc', "w")
f.write(text)
f.close()
</code></pre>
<p>but Word will read it as an HTML file not a native .doc file.</p>
|
[
{
"answer_id": 188608,
"author": "fuentesjr",
"author_id": 10708,
"author_profile": "https://Stackoverflow.com/users/10708",
"pm_score": 2,
"selected": false,
"text": "<p>doc (Word 2003 in this case) and docx (Word 2007) are different formats, where the latter is usually just an archive of xml and image files. I would imagine that it is very possible to write to docx files by manipulating the contents of those xml files. However I don't see how you could read and write to a doc file without some type of COM component interface. </p>\n"
},
{
"answer_id": 188620,
"author": "auramo",
"author_id": 4110,
"author_profile": "https://Stackoverflow.com/users/4110",
"pm_score": 4,
"selected": true,
"text": "<p>I'd look into <a href=\"http://ironpython.net/\" rel=\"nofollow noreferrer\">IronPython</a> which intrinsically has access to windows/office APIs because it runs on .NET runtime.</p>\n"
},
{
"answer_id": 7848324,
"author": "Damian",
"author_id": 288183,
"author_profile": "https://Stackoverflow.com/users/288183",
"pm_score": 5,
"selected": false,
"text": "<p>See <a href=\"https://github.com/python-openxml/python-docx\" rel=\"nofollow noreferrer\">python-docx</a>, its official documentation is available <a href=\"https://python-docx.readthedocs.org/en/latest/\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>This has worked very well for me.</p>\n<p>Note that this does not work for .doc files, only .docx files.</p>\n"
},
{
"answer_id": 30122394,
"author": "markling",
"author_id": 2455413,
"author_profile": "https://Stackoverflow.com/users/2455413",
"pm_score": 4,
"selected": false,
"text": "<p>If you only what to read, it is <a href=\"https://stackoverflow.com/questions/16516044/is-it-possible-to-read-word-files-doc-docx-in-python/30122239#30122239\">simplest</a> to use the linux soffice command to convert it to text, and then load the text into python: </p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
Is it possible to read and write Word (2003 and 2007) files in Python without using a COM object?
I know that I can:
```
f = open('c:\file.doc', "w")
f.write(text)
f.close()
```
but Word will read it as an HTML file not a native .doc file.
|
I'd look into [IronPython](http://ironpython.net/) which intrinsically has access to windows/office APIs because it runs on .NET runtime.
|
188,452 |
<p>Is it possible to read and write Word (2003 and 2007) files in PHP without using a COM object?
I know that I can:</p>
<pre><code>$file = fopen('c:\file.doc', 'w+');
fwrite($file, $text);
fclose();
</code></pre>
<p>but Word will read it as an HTML file not a native .doc file.</p>
|
[
{
"answer_id": 189683,
"author": "Joe Lencioni",
"author_id": 18986,
"author_profile": "https://Stackoverflow.com/users/18986",
"pm_score": 3,
"selected": false,
"text": "<p>I don't know about reading native Word documents in PHP, but if you want to write a Word document in PHP, <a href=\"http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats#Word_XML_Format_example\" rel=\"noreferrer\">WordprocessingML (aka WordML)</a> might be a good solution. All you have to do is create an XML document in the correct format. I believe Word 2003 and 2007 both support WordML.</p>\n"
},
{
"answer_id": 189894,
"author": "Sergey Kornilov",
"author_id": 10969,
"author_profile": "https://Stackoverflow.com/users/10969",
"pm_score": 3,
"selected": false,
"text": "<p>Most probably you won't be able to read Word documents without COM.</p>\n\n<p>Writing was covered in this <a href=\"https://stackoverflow.com/questions/124959/create-word-document-using-php-in-linux\">topic</a></p>\n"
},
{
"answer_id": 189959,
"author": "acrosman",
"author_id": 24215,
"author_profile": "https://Stackoverflow.com/users/24215",
"pm_score": 1,
"selected": false,
"text": "<p>Office 2007 .docx should be possible since it's an XML standard. Word 2003 most likely requires COM to read, even with the standards now published by MS, since those standards are huge. I haven't seen many libraries written to match them yet.</p>\n"
},
{
"answer_id": 191849,
"author": "databyss",
"author_id": 9094,
"author_profile": "https://Stackoverflow.com/users/9094",
"pm_score": 2,
"selected": false,
"text": "<p>2007 might be a bit complicated as well.</p>\n\n<p>The .docx format is a zip file that contains a few folders with other files in them for formatting and other stuff.</p>\n\n<p>Rename a .docx file to .zip and you'll see what I mean.</p>\n\n<p>So if you can work within zip files in PHP, you should be on the right path.</p>\n"
},
{
"answer_id": 191853,
"author": "fijter",
"author_id": 3215,
"author_profile": "https://Stackoverflow.com/users/3215",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know what you are going to use it for, but I needed .doc support for search indexing; What I did was use a little commandline tool called \"catdoc\"; This transfers the contents of the Word document to plain text so it can be indexed. If you need to keep formatting and stuff this is not your tool.</p>\n"
},
{
"answer_id": 265017,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>this works with vs < office 2007 and its pure PHP, no COM crap, still trying to figure 2007</p>\n\n<pre><code><?php\n\n\n\n/*****************************************************************\nThis approach uses detection of NUL (chr(00)) and end line (chr(13))\nto decide where the text is:\n- divide the file contents up by chr(13)\n- reject any slices containing a NUL\n- stitch the rest together again\n- clean up with a regular expression\n*****************************************************************/\n\nfunction parseWord($userDoc) \n{\n $fileHandle = fopen($userDoc, \"r\");\n $line = @fread($fileHandle, filesize($userDoc)); \n $lines = explode(chr(0x0D),$line);\n $outtext = \"\";\n foreach($lines as $thisline)\n {\n $pos = strpos($thisline, chr(0x00));\n if (($pos !== FALSE)||(strlen($thisline)==0))\n {\n } else {\n $outtext .= $thisline.\" \";\n }\n }\n $outtext = preg_replace(\"/[^a-zA-Z0-9\\s\\,\\.\\-\\n\\r\\t@\\/\\_\\(\\)]/\",\"\",$outtext);\n return $outtext;\n} \n\n$userDoc = \"cv.doc\";\n\n$text = parseWord($userDoc);\necho $text;\n\n\n?>\n</code></pre>\n"
},
{
"answer_id": 265079,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 6,
"selected": true,
"text": "<p>Reading binary Word documents would involve creating a parser according to the published file format specifications for the DOC format. I think this is no real feasible solution.</p>\n\n<p>You could use the <a href=\"http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats#Word_XML_Format_example\" rel=\"nofollow noreferrer\">Microsoft Office XML formats</a> for reading and writing Word files - this is compatible with the 2003 and 2007 version of Word. For reading you have to ensure that the Word documents are saved in the correct format (it's called Word 2003 XML-Document in Word 2007). For writing you just have to follow the openly available XML schema. I've never used this format for writing out Office documents from PHP, but I'm using it for reading in an Excel worksheet (naturally saved as XML-Spreadsheet 2003) and displaying its data on a web page. As the files are plainly XML data it's no problem to navigate within and figure out how to extract the data you need.</p>\n\n<p>The other option - a Word 2007 only option (if the OpenXML file formats are not installed in your Word 2003) - would be to ressort to <a href=\"http://en.wikipedia.org/wiki/Office_Open_XML\" rel=\"nofollow noreferrer\">OpenXML</a>. As <a href=\"https://stackoverflow.com/users/9094/databyss\">databyss</a> pointed out <a href=\"https://stackoverflow.com/questions/188452/readingwriting-a-ms-word-file-in-php#191849\">here</a> the DOCX file format is just a ZIP archive with XML files included. There are a lot of resources on <a href=\"http://msdn.microsoft.com/en-us/office/default.aspx\" rel=\"nofollow noreferrer\">MSDN</a> regarding the OpenXML file format, so you should be able to figure out how to read the data you want. Writing will be much more complicated I think - it just depends on how much time you'll invest.</p>\n\n<p><strong>Perhaps you can have a look at <a href=\"http://www.codeplex.com/PHPExcel/\" rel=\"nofollow noreferrer\">PHPExcel</a> which is a library able to write to Excel 2007 files and read from Excel 2007 files using the OpenXML standard. You could get an idea of the work involved when trying to read and write OpenXML Word documents.</strong></p>\n"
},
{
"answer_id": 475547,
"author": "Josh Smeaton",
"author_id": 10583,
"author_profile": "https://Stackoverflow.com/users/10583",
"pm_score": 0,
"selected": false,
"text": "<p>Would the .rtf format work for your purposes? .rtf can easily be converted to and from .doc format, but it is written in plaintext (with control commands embedded). This is how I plan to integrate my application with Word documents.</p>\n"
},
{
"answer_id": 861928,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p><strong>phpLiveDocx</strong> is a Zend Framework component and can read and write DOC and DOCX files in PHP on Linux, Windows and Mac.</p>\n\n<p>See the project web site at:</p>\n\n<p><a href=\"http://www.phplivedocx.org\" rel=\"nofollow noreferrer\">http://www.phplivedocx.org</a></p>\n"
},
{
"answer_id": 900581,
"author": "Mantichora",
"author_id": 79147,
"author_profile": "https://Stackoverflow.com/users/79147",
"pm_score": 3,
"selected": false,
"text": "<p>You can use Antiword, it is a free MS Word reader for Linux and most popular OS.</p>\n\n<pre><code>$document_file = 'c:\\file.doc';\n$text_from_doc = shell_exec('/usr/local/bin/antiword '.$document_file);\n</code></pre>\n"
},
{
"answer_id": 1418354,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>www.phplivedocx.org is a SOAP based service that means that you always need to be online for testing the Files also does not have enough examples for its use . Strangely I found only after 2 days of downloading (requires additionaly zend framework too) that its a SOAP based program(cursed me !!!)...I think without COM its just not possible on a Linux server and the only idea is to change the doc file in another usable file which PHP can parse...</p>\n"
},
{
"answer_id": 3646367,
"author": "Noddy Cha",
"author_id": 438006,
"author_profile": "https://Stackoverflow.com/users/438006",
"pm_score": 0,
"selected": false,
"text": "<p>even i'm working on same kind of project [An Onlinw Word Processor]!\nBut i've choosen c#.net and ASP.net. But through the survey i did; i got to know that </p>\n\n<blockquote>\n <p>By Using Open XML SDK and VSTO [Visual Studio Tools For Office]</p>\n</blockquote>\n\n<p>we may easily work with a word file manipulate them and even convert internally to different into several formats such as .odt,.pdf,.docx etc..</p>\n\n<blockquote>\n <p><strong>So, goto msdn.microsoft.com and be thorough about the office development tab. Its the easiest way to do this as all functions we need to implement are already available in .net!!</strong></p>\n</blockquote>\n\n<p>But as u want to do ur project in PHP, u can do it in Visual Studio and .net as PHP is also one of the .net Compliant Language!!</p>\n"
},
{
"answer_id": 3909201,
"author": "Omer",
"author_id": 472618,
"author_profile": "https://Stackoverflow.com/users/472618",
"pm_score": 0,
"selected": false,
"text": "<p>I have the same case\nI guess I am going to use a cheap 50 mega windows based hosting with free domain to use it to convert my files on, for PHP server. And linking them is easy.\nAll you need is make an ASP.NET page that recieves the doc file via post and replies it via HTTP\nso simple CURL would do it.</p>\n"
},
{
"answer_id": 5534093,
"author": "WIlson",
"author_id": 690471,
"author_profile": "https://Stackoverflow.com/users/690471",
"pm_score": 3,
"selected": false,
"text": "<p>Just updating the code</p>\n\n<pre><code><?php\n\n/*****************************************************************\nThis approach uses detection of NUL (chr(00)) and end line (chr(13))\nto decide where the text is:\n- divide the file contents up by chr(13)\n- reject any slices containing a NUL\n- stitch the rest together again\n- clean up with a regular expression\n*****************************************************************/\n\nfunction parseWord($userDoc) \n{\n $fileHandle = fopen($userDoc, \"r\");\n $word_text = @fread($fileHandle, filesize($userDoc));\n $line = \"\";\n $tam = filesize($userDoc);\n $nulos = 0;\n $caracteres = 0;\n for($i=1536; $i<$tam; $i++)\n {\n $line .= $word_text[$i];\n\n if( $word_text[$i] == 0)\n {\n $nulos++;\n }\n else\n {\n $nulos=0;\n $caracteres++;\n }\n\n if( $nulos>1996)\n { \n break; \n }\n }\n\n //echo $caracteres;\n\n $lines = explode(chr(0x0D),$line);\n //$outtext = \"<pre>\";\n\n $outtext = \"\";\n foreach($lines as $thisline)\n {\n $tam = strlen($thisline);\n if( !$tam )\n {\n continue;\n }\n\n $new_line = \"\"; \n for($i=0; $i<$tam; $i++)\n {\n $onechar = $thisline[$i];\n if( $onechar > chr(240) )\n {\n continue;\n }\n\n if( $onechar >= chr(0x20) )\n {\n $caracteres++;\n $new_line .= $onechar;\n }\n\n if( $onechar == chr(0x14) )\n {\n $new_line .= \"</a>\";\n }\n\n if( $onechar == chr(0x07) )\n {\n $new_line .= \"\\t\";\n if( isset($thisline[$i+1]) )\n {\n if( $thisline[$i+1] == chr(0x07) )\n {\n $new_line .= \"\\n\";\n }\n }\n }\n }\n //troca por hiperlink\n $new_line = str_replace(\"HYPERLINK\" ,\"<a href=\",$new_line); \n $new_line = str_replace(\"\\o\" ,\">\",$new_line); \n $new_line .= \"\\n\";\n\n //link de imagens\n $new_line = str_replace(\"INCLUDEPICTURE\" ,\"<br><img src=\",$new_line); \n $new_line = str_replace(\"\\*\" ,\"><br>\",$new_line); \n $new_line = str_replace(\"MERGEFORMATINET\" ,\"\",$new_line); \n\n\n $outtext .= nl2br($new_line);\n }\n\n return $outtext;\n} \n\n$userDoc = \"custo.doc\";\n$userDoc = \"Cultura.doc\";\n$text = parseWord($userDoc);\n\necho $text;\n\n\n?>\n</code></pre>\n"
},
{
"answer_id": 12644103,
"author": "Eduardo",
"author_id": 1640443,
"author_profile": "https://Stackoverflow.com/users/1640443",
"pm_score": 1,
"selected": false,
"text": "<p>One way to manipulate Word files with PHP that you may find interesting is with the help of PHPDocX.\nYou may see how it works having a look at its <a href=\"http://www.phpdocx.com/documentation/tutorial\" rel=\"nofollow\">online tutorial</a>.\nYou can insert or extract contents or even merge multiple Word files into a asingle one.</p>\n"
},
{
"answer_id": 56868010,
"author": "Mohamed Faalil",
"author_id": 10422340,
"author_profile": "https://Stackoverflow.com/users/10422340",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://www.quora.com/How-can-I-read-docx-file-in-PHP-with-it-s-orignal-table-format\" rel=\"nofollow noreferrer\">Source gotten from</a></p>\n\n<blockquote>\n <p>Use following class directly to read word document</p>\n</blockquote>\n\n<pre><code>class DocxConversion{\n private $filename;\n\n public function __construct($filePath) {\n $this->filename = $filePath;\n }\n\n private function read_doc() {\n $fileHandle = fopen($this->filename, \"r\");\n $line = @fread($fileHandle, filesize($this->filename)); \n $lines = explode(chr(0x0D),$line);\n $outtext = \"\";\n foreach($lines as $thisline)\n {\n $pos = strpos($thisline, chr(0x00));\n if (($pos !== FALSE)||(strlen($thisline)==0))\n {\n } else {\n $outtext .= $thisline.\" \";\n }\n }\n $outtext = preg_replace(\"/[^a-zA-Z0-9\\s\\,\\.\\-\\n\\r\\t@\\/\\_\\(\\)]/\",\"\",$outtext);\n return $outtext;\n }\n\n private function read_docx(){\n\n $striped_content = '';\n $content = '';\n\n $zip = zip_open($this->filename);\n\n if (!$zip || is_numeric($zip)) return false;\n\n while ($zip_entry = zip_read($zip)) {\n\n if (zip_entry_open($zip, $zip_entry) == FALSE) continue;\n\n if (zip_entry_name($zip_entry) != \"word/document.xml\") continue;\n\n $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));\n\n zip_entry_close($zip_entry);\n }// end while\n\n zip_close($zip);\n\n $content = str_replace('</w:r></w:p></w:tc><w:tc>', \" \", $content);\n $content = str_replace('</w:r></w:p>', \"\\r\\n\", $content);\n $striped_content = strip_tags($content);\n\n return $striped_content;\n }\n\n /************************excel sheet************************************/\n\nfunction xlsx_to_text($input_file){\n $xml_filename = \"xl/sharedStrings.xml\"; //content file name\n $zip_handle = new ZipArchive;\n $output_text = \"\";\n if(true === $zip_handle->open($input_file)){\n if(($xml_index = $zip_handle->locateName($xml_filename)) !== false){\n $xml_datas = $zip_handle->getFromIndex($xml_index);\n $xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);\n $output_text = strip_tags($xml_handle->saveXML());\n }else{\n $output_text .=\"\";\n }\n $zip_handle->close();\n }else{\n $output_text .=\"\";\n }\n return $output_text;\n}\n\n/*************************power point files*****************************/\nfunction pptx_to_text($input_file){\n $zip_handle = new ZipArchive;\n $output_text = \"\";\n if(true === $zip_handle->open($input_file)){\n $slide_number = 1; //loop through slide files\n while(($xml_index = $zip_handle->locateName(\"ppt/slides/slide\".$slide_number.\".xml\")) !== false){\n $xml_datas = $zip_handle->getFromIndex($xml_index);\n $xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);\n $output_text .= strip_tags($xml_handle->saveXML());\n $slide_number++;\n }\n if($slide_number == 1){\n $output_text .=\"\";\n }\n $zip_handle->close();\n }else{\n $output_text .=\"\";\n }\n return $output_text;\n}\n\n\n public function convertToText() {\n\n if(isset($this->filename) && !file_exists($this->filename)) {\n return \"File Not exists\";\n }\n\n $fileArray = pathinfo($this->filename);\n $file_ext = $fileArray['extension'];\n if($file_ext == \"doc\" || $file_ext == \"docx\" || $file_ext == \"xlsx\" || $file_ext == \"pptx\")\n {\n if($file_ext == \"doc\") {\n return $this->read_doc();\n } elseif($file_ext == \"docx\") {\n return $this->read_docx();\n } elseif($file_ext == \"xlsx\") {\n return $this->xlsx_to_text();\n }elseif($file_ext == \"pptx\") {\n return $this->pptx_to_text();\n }\n } else {\n return \"Invalid File Type\";\n }\n }\n\n}\n\n$docObj = new DocxConversion(\"test.docx\"); //replace your document name with correct extension doc or docx \necho $docText= $docObj->convertToText();\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
Is it possible to read and write Word (2003 and 2007) files in PHP without using a COM object?
I know that I can:
```
$file = fopen('c:\file.doc', 'w+');
fwrite($file, $text);
fclose();
```
but Word will read it as an HTML file not a native .doc file.
|
Reading binary Word documents would involve creating a parser according to the published file format specifications for the DOC format. I think this is no real feasible solution.
You could use the [Microsoft Office XML formats](http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats#Word_XML_Format_example) for reading and writing Word files - this is compatible with the 2003 and 2007 version of Word. For reading you have to ensure that the Word documents are saved in the correct format (it's called Word 2003 XML-Document in Word 2007). For writing you just have to follow the openly available XML schema. I've never used this format for writing out Office documents from PHP, but I'm using it for reading in an Excel worksheet (naturally saved as XML-Spreadsheet 2003) and displaying its data on a web page. As the files are plainly XML data it's no problem to navigate within and figure out how to extract the data you need.
The other option - a Word 2007 only option (if the OpenXML file formats are not installed in your Word 2003) - would be to ressort to [OpenXML](http://en.wikipedia.org/wiki/Office_Open_XML). As [databyss](https://stackoverflow.com/users/9094/databyss) pointed out [here](https://stackoverflow.com/questions/188452/readingwriting-a-ms-word-file-in-php#191849) the DOCX file format is just a ZIP archive with XML files included. There are a lot of resources on [MSDN](http://msdn.microsoft.com/en-us/office/default.aspx) regarding the OpenXML file format, so you should be able to figure out how to read the data you want. Writing will be much more complicated I think - it just depends on how much time you'll invest.
**Perhaps you can have a look at [PHPExcel](http://www.codeplex.com/PHPExcel/) which is a library able to write to Excel 2007 files and read from Excel 2007 files using the OpenXML standard. You could get an idea of the work involved when trying to read and write OpenXML Word documents.**
|
188,461 |
<p>For as long as I can remember I have avoided using switch statement fall-through. Actually, I can't remember it ever entering my consciousness as a possible way to do things as it was drilled into my head early on that it was nothing more than a bug in the switch statement. However, today I ran across some code that uses it by design, which got me immediately wondering what everyone in the community thinks about switch statement fall-through.</p>
<p>Is it something that a programming language should explicitly not allow (like C# does, though it supplies a workaround) or is it a feature of any language that is powerful enough to leave in the programmer's hands?</p>
<p><strong>Edit:</strong>
I wasn't specific enough to what I meant by fall-through. I use this type a lot:</p>
<pre class="lang-js prettyprint-override"><code> switch(m_loadAnimSubCt){
case 0:
case 1:
// Do something
break;
case 2:
case 3:
case 4:
// Do something
break;
}
</code></pre>
<p>However, I'm concerned about something like this.</p>
<pre class="lang-js prettyprint-override"><code> switch(m_loadAnimSubCt){
case 0:
case 1:
// Do something, but fall through to the other cases
// after doing it.
case 2:
case 3:
case 4:
// Do something else.
break;
}
</code></pre>
<p>This way whenever the case is 0, 1 it will do everything in the switch statement. I've seen this by design and I just don't know if I agree that switch statements should be used this way. I think the first code example is very useful and safe. The second seems kind of dangerous.</p>
|
[
{
"answer_id": 188477,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": 5,
"selected": false,
"text": "<p>Fall-through is really a handy thing, depending on what you're doing. Consider this neat and understandable way to arrange options:</p>\n\n<pre><code>switch ($someoption) {\n case 'a':\n case 'b':\n case 'c':\n // Do something\n break;\n\n case 'd':\n case 'e':\n // Do something else\n break;\n}\n</code></pre>\n\n<p>Imagine doing this with if/else. It would be a mess.</p>\n"
},
{
"answer_id": 188481,
"author": "Dan Hulton",
"author_id": 8327,
"author_profile": "https://Stackoverflow.com/users/8327",
"pm_score": 3,
"selected": false,
"text": "<p>It is powerful and dangerous. The biggest problem with fall-through is that it's not explicit. For example, if you come across frequently-edited code that has a switch with fall-throughs, how do you know that's intentional and not a bug?</p>\n\n<p>Anywhere I use it, I ensure that it's properly commented:</p>\n\n<pre><code>switch($var) {\n case 'first':\n // Fall-through\n case 'second':\n i++;\n break;\n }\n</code></pre>\n"
},
{
"answer_id": 188484,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 5,
"selected": false,
"text": "<p>Have you heard of <a href=\"http://en.wikipedia.org/wiki/Duff%27s_device\" rel=\"noreferrer\">Duff's device</a>? This is a great example of using switch fallthrough.</p>\n\n<p>It's a feature that can be used and it can be abused, like almost all language features.</p>\n"
},
{
"answer_id": 188490,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 1,
"selected": false,
"text": "<p>In some instances, using fall-throughs is an act of laziness on the part of the programmer - they could use a series of || statements, for example, but instead use a series of 'catch-all' switch cases.</p>\n\n<p>That being said, I've found them to be especially helpful when I know that <em>eventually</em> I'm going to need the options anyway (for example in a menu response), but have not yet implemented all the choices. Likewise, if you're doing a fall-through for both 'a' and 'A', I find it substantially cleaner to use the switch fall-through than a compound if statement.</p>\n\n<p>It's probably a matter of style and how the programmers think, but I'm not generally fond of removing components of a language in the name of 'safety' - which is why I tend towards C and its variants/descendants more than, say, Java. I like being able to monkey-around with pointers and the like, even when I have no \"reason\" to.</p>\n"
},
{
"answer_id": 188492,
"author": "steffenj",
"author_id": 15328,
"author_profile": "https://Stackoverflow.com/users/15328",
"pm_score": 3,
"selected": false,
"text": "<p>As with anything: if used with care, it can be an elegant tool.</p>\n\n<p>However, I think the drawbacks more than justify <em>not</em> to use it, and finally not to allow it anymore (C#). Among the problems are:</p>\n\n<ul>\n<li>it's easy to \"forget\" a break</li>\n<li>it's not always obvious for code maintainers <em>that</em> an omitted break was intentional</li>\n</ul>\n\n<p>Good use of a switch/case fall-through:</p>\n\n<pre><code>switch (x)\n{\ncase 1:\ncase 2:\ncase 3:\n Do something\n break;\n}\n</code></pre>\n\n<p><em>Baaaaad</em> use of a switch/case fall-through:</p>\n\n<pre><code>switch (x)\n{\ncase 1:\n Some code\ncase 2:\n Some more code\ncase 3:\n Even more code\n break;\n}\n</code></pre>\n\n<p>This can be rewritten using if/else constructs with no loss at all in my opinion.</p>\n\n<p>My final word: stay away from fall-through case labels as in the <em>bad</em> example, unless you are maintaining legacy code where this style is used and well understood.</p>\n"
},
{
"answer_id": 188493,
"author": "John M",
"author_id": 20734,
"author_profile": "https://Stackoverflow.com/users/20734",
"pm_score": 6,
"selected": false,
"text": "<p>It's a double-edged sword. It is sometimes very useful, but often dangerous.</p>\n\n<p>When is it good? When you want 10 cases all processed the same way...</p>\n\n<pre><code>switch (c) {\n case 1:\n case 2:\n ... Do some of the work ...\n /* FALLTHROUGH */\n case 17:\n ... Do something ...\n break;\n case 5:\n case 43:\n ... Do something else ...\n break;\n}\n</code></pre>\n\n<p>The one rule I like is that if you ever do anything fancy where you exclude the break, you need a clear comment /* FALLTHROUGH */ to indicate that was your intention.</p>\n"
},
{
"answer_id": 188498,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 2,
"selected": false,
"text": "<p>I don't like my <code>switch</code> statements to fall through - it's far too error prone and hard to read. The only exception is when multiple <code>case</code> statements all do <em>exactly</em> the same thing.</p>\n\n<p>If there is some common code that multiple branches of a switch statement want to use, I extract that into a separate common function that can be called in any branch.</p>\n"
},
{
"answer_id": 188506,
"author": "Fred Larson",
"author_id": 10077,
"author_profile": "https://Stackoverflow.com/users/10077",
"pm_score": 8,
"selected": true,
"text": "<p>It may depend on what you consider fallthrough. I'm ok with this sort of thing:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>switch (value)\n{\n case 0:\n result = ZERO_DIGIT;\n break;\n\n case 1:\n case 3:\n case 5:\n case 7:\n case 9:\n result = ODD_DIGIT;\n break;\n\n case 2:\n case 4:\n case 6:\n case 8:\n result = EVEN_DIGIT;\n break;\n}\n</code></pre>\n\n<p>But if you have a case label followed by code that falls through to another case label, I'd pretty much always consider that evil. Perhaps moving the common code to a function and calling from both places would be a better idea.</p>\n\n<p>And please note that I use the <a href=\"https://isocpp.org/wiki/faq\" rel=\"noreferrer\">C++ FAQ</a> definition of <a href=\"https://isocpp.org/wiki/faq/big-picture#defn-evil\" rel=\"noreferrer\">\"evil\"</a></p>\n"
},
{
"answer_id": 188848,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>It can be very useful a few times, but in general, no fall-through is the desired behavior. Fall-through should be allowed, but not implicit.</p>\n\n<p>An example, to update old versions of some data:</p>\n\n<pre><code>switch (version) {\n case 1:\n // Update some stuff\n case 2:\n // Update more stuff\n case 3:\n // Update even more stuff\n case 4:\n // And so on\n}\n</code></pre>\n"
},
{
"answer_id": 530481,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 1,
"selected": false,
"text": "<p>Fall-through should be used only when it is used as a jump table into a block of code. If there is any part of the code with an unconditional break before more cases, all the case groups should end that way.</p>\n\n<p>Anything else is \"evil\".</p>\n"
},
{
"answer_id": 530616,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 3,
"selected": false,
"text": "<p>I'd love a different syntax for fallbacks in switches, something like, errr..</p>\n\n<pre><code>switch(myParam)\n{\n case 0 or 1 or 2:\n // Do something;\n break;\n case 3 or 4:\n // Do something else;\n break;\n}\n</code></pre>\n\n<p><strong>Note: This would already be possible with enums, if you declare all cases on your enum using flags, right? It doesn't sound so bad either; the cases could (should?) very well be part of your enum already.</strong></p>\n\n<p>Maybe this would be a nice case (no pun intended) for a fluent interface using extension methods? Something like, errr...</p>\n\n<pre><code>int value = 10;\nvalue.Switch()\n .Case(() => { /* Do something; */ }, new {0, 1, 2})\n .Case(() => { /* Do something else */ } new {3, 4})\n .Default(() => { /* Do the default case; */ });\n</code></pre>\n\n<p>Although that's probably even less readable :P</p>\n"
},
{
"answer_id": 7374717,
"author": "Wouter van Ooijen",
"author_id": 938140,
"author_profile": "https://Stackoverflow.com/users/938140",
"pm_score": 2,
"selected": false,
"text": "<p>Using fall-through like in your first example is clearly OK, and I would not consider it a real fall-through.</p>\n\n<p>The second example is dangerous and (if not commented extensively) non-obvious. I teach my students not to use such constructs <em>unless</em> they consider it worth the effort to devote a comment block to it, which describes that this is an intentional fall-through, and why this solution is better than the alternatives. This discourages sloppy use, but it still makes it allowed in the cases where it is used to an advantage.</p>\n\n<p>This is more or less equivalent to what we did in space projects when someone wanted to violate the coding standard: they had to apply for dispensation (and I was called on to advise about the ruling).</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16524/"
] |
For as long as I can remember I have avoided using switch statement fall-through. Actually, I can't remember it ever entering my consciousness as a possible way to do things as it was drilled into my head early on that it was nothing more than a bug in the switch statement. However, today I ran across some code that uses it by design, which got me immediately wondering what everyone in the community thinks about switch statement fall-through.
Is it something that a programming language should explicitly not allow (like C# does, though it supplies a workaround) or is it a feature of any language that is powerful enough to leave in the programmer's hands?
**Edit:**
I wasn't specific enough to what I meant by fall-through. I use this type a lot:
```js
switch(m_loadAnimSubCt){
case 0:
case 1:
// Do something
break;
case 2:
case 3:
case 4:
// Do something
break;
}
```
However, I'm concerned about something like this.
```js
switch(m_loadAnimSubCt){
case 0:
case 1:
// Do something, but fall through to the other cases
// after doing it.
case 2:
case 3:
case 4:
// Do something else.
break;
}
```
This way whenever the case is 0, 1 it will do everything in the switch statement. I've seen this by design and I just don't know if I agree that switch statements should be used this way. I think the first code example is very useful and safe. The second seems kind of dangerous.
|
It may depend on what you consider fallthrough. I'm ok with this sort of thing:
```js
switch (value)
{
case 0:
result = ZERO_DIGIT;
break;
case 1:
case 3:
case 5:
case 7:
case 9:
result = ODD_DIGIT;
break;
case 2:
case 4:
case 6:
case 8:
result = EVEN_DIGIT;
break;
}
```
But if you have a case label followed by code that falls through to another case label, I'd pretty much always consider that evil. Perhaps moving the common code to a function and calling from both places would be a better idea.
And please note that I use the [C++ FAQ](https://isocpp.org/wiki/faq) definition of ["evil"](https://isocpp.org/wiki/faq/big-picture#defn-evil)
|
188,473 |
<p>I have a C# object with a critical resource that needs to be flushed very specific points in time making it a bad candidate to leave around for the garbage collector to take care of whenever it gets around to it, how should I handle this? Is there something like C++'s delete operator that will let me manually kill the instance of this object when needed?</p>
|
[
{
"answer_id": 188501,
"author": "David",
"author_id": 26144,
"author_profile": "https://Stackoverflow.com/users/26144",
"pm_score": 2,
"selected": false,
"text": "<p>This is precisely what the <a href=\"http://msdn.microsoft.com/en-us/library/system.idisposable.aspx\" rel=\"nofollow noreferrer\"><code>IDiposable</code></a> interface is for. You release the critical resources in the <code>Dispose()</code> method, and then leave the object around for the garbage disposer to deal with deallocating the memory.</p>\n"
},
{
"answer_id": 188508,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 0,
"selected": false,
"text": "<p>Google for the IDisposable interface. This is the only mechanism available to you. It's tailor made if your critical resource is unmanaged. If it's a managed resource, could you be more specific about what needs to be \"flushed\".</p>\n"
},
{
"answer_id": 188514,
"author": "Nick",
"author_id": 26240,
"author_profile": "https://Stackoverflow.com/users/26240",
"pm_score": 0,
"selected": false,
"text": "<p>The IDisposable interface was added to support deterministic destruction in C++/CLI, and you can use it from any .NET language. It's what you want.</p>\n"
},
{
"answer_id": 188521,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<p>If you are talking about a specific managed resource that you feel \"MUST\" be released at a specific time, you could specifcally call the Garbage Collectors' Collect method, after de-referencing the object, but there are performance considerations to be thought of, as normally the garbage collector knows when to collect items. And in general it is a bad idea.</p>\n\n<p>As others are mentioning above, the IDisposable pattern is helpful for releasing unmanaged resources when needed.</p>\n\n<p><strong>NOTE:</strong> I'm going to repeat, you COULD call GC.Collect() but it is NOT a good thing, but a valid answer for the question!</p>\n"
},
{
"answer_id": 188538,
"author": "Greg D",
"author_id": 6932,
"author_profile": "https://Stackoverflow.com/users/6932",
"pm_score": 2,
"selected": false,
"text": "<p>The IDisposable interface exists for deterministic destruction. There's a pattern for implementing it correctly on <a href=\"http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx\" rel=\"nofollow noreferrer\" title=\"MSDN\">MSDN</a>.</p>\n\n<p>In tandem, you should also consider using the <a href=\"http://msdn.microsoft.com/en-us/library/yh598w02.aspx\" rel=\"nofollow noreferrer\">using statement</a> when your object's lifetime does not span multiple scopes.</p>\n"
},
{
"answer_id": 188575,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 5,
"selected": false,
"text": "<p>You are looking for <a href=\"http://msdn.microsoft.com/en-us/library/system.idisposable.aspx\" rel=\"noreferrer\"><code>IDisposable</code></a>. Here is an example class that implements this.</p>\n\n<pre><code>class MyDisposableObject : IDisposable\n{\n public MyDisposableObject()\n {\n }\n\n ~MyDisposableObject()\n {\n Dispose(false);\n }\n\n private bool disposed;\n private void Dispose(bool disposing)\n {\n if (!this.disposed)\n {\n if (disposing)\n {\n // Dispose of your managed resources here.\n }\n\n // Dispose of your unmanaged resources here.\n\n this.disposed = true;\n }\n }\n\n void IDisposable.Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n}\n</code></pre>\n\n<p>To use it, you can do something like this:</p>\n\n<pre><code>public void DoingMyThing()\n{\n using (MyDisposableObject obj = new MyDisposableObject())\n {\n // Use obj here.\n }\n}\n</code></pre>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/yh598w02.aspx\" rel=\"noreferrer\"><code>using</code></a> keyword makes sure that the <a href=\"http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx\" rel=\"noreferrer\"><code>Dispose()</code></a> method on <a href=\"http://msdn.microsoft.com/en-us/library/system.idisposable.aspx\" rel=\"noreferrer\"><code>IDisposable</code></a> gets called at the end of its scope.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a C# object with a critical resource that needs to be flushed very specific points in time making it a bad candidate to leave around for the garbage collector to take care of whenever it gets around to it, how should I handle this? Is there something like C++'s delete operator that will let me manually kill the instance of this object when needed?
|
You are looking for [`IDisposable`](http://msdn.microsoft.com/en-us/library/system.idisposable.aspx). Here is an example class that implements this.
```
class MyDisposableObject : IDisposable
{
public MyDisposableObject()
{
}
~MyDisposableObject()
{
Dispose(false);
}
private bool disposed;
private void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
// Dispose of your managed resources here.
}
// Dispose of your unmanaged resources here.
this.disposed = true;
}
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
```
To use it, you can do something like this:
```
public void DoingMyThing()
{
using (MyDisposableObject obj = new MyDisposableObject())
{
// Use obj here.
}
}
```
The [`using`](http://msdn.microsoft.com/en-us/library/yh598w02.aspx) keyword makes sure that the [`Dispose()`](http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx) method on [`IDisposable`](http://msdn.microsoft.com/en-us/library/system.idisposable.aspx) gets called at the end of its scope.
|
188,488 |
<p>The problem is following: I want to automate the way my emacs starts.
It has to be split in two buffers and the slime-repl has to be started in the smallest (bottom) buffer. Plus, I want my file to be opened in the bigger (upper) buffer.
In my .emacs there are lines:</p>
<pre><code>(slime)
...
(split-window-vertically -6)
(switch-to-buffer (other-buffer))
(find-file "g:/Private/pa/pa2.lsp")
</code></pre>
<p>SLIME opens o.k. in the bottom buffer, but the file is opened in one of the background buffers, while I want it to be in front.</p>
<p>How to fix this?</p>
|
[
{
"answer_id": 188641,
"author": "EfForEffort",
"author_id": 14113,
"author_profile": "https://Stackoverflow.com/users/14113",
"pm_score": 0,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>(other-window 1)\n(find-file \"g:/Private/pa/pa2.lsp\")\n</code></pre>\n\n<p>instead of your last two lines.</p>\n"
},
{
"answer_id": 261273,
"author": "Alex Ott",
"author_id": 18627,
"author_profile": "https://Stackoverflow.com/users/18627",
"pm_score": 1,
"selected": false,
"text": "<p>You can look to the function set-window-configuration...</p>\n\n<p>But for slime you can use following functions - slime-complete-maybe-save-window-configuration & slime-complete-restore-window-configuration</p>\n"
},
{
"answer_id": 906559,
"author": "viam0Zah",
"author_id": 73603,
"author_profile": "https://Stackoverflow.com/users/73603",
"pm_score": 2,
"selected": true,
"text": "<p>Instead of <code>switch-to-buffer</code>, use function <code>pop-to-buffer</code>.</p>\n\n<blockquote>\n <p><code>(pop-to-buffer BUFFER-OR-NAME &optional OTHER-WINDOW NORECORD)</code></p>\n \n <p>Select buffer <code>BUFFER-OR-NAME</code> in some window, preferably a different one.</p>\n</blockquote>\n"
},
{
"answer_id": 1655455,
"author": "Łukasz Lew",
"author_id": 61342,
"author_profile": "https://Stackoverflow.com/users/61342",
"pm_score": 0,
"selected": false,
"text": "<p>Try to add</p>\n\n<pre><code>(ido-mode 1)\n</code></pre>\n\n<p>to your .emacs, and enjoy the result :)</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20514/"
] |
The problem is following: I want to automate the way my emacs starts.
It has to be split in two buffers and the slime-repl has to be started in the smallest (bottom) buffer. Plus, I want my file to be opened in the bigger (upper) buffer.
In my .emacs there are lines:
```
(slime)
...
(split-window-vertically -6)
(switch-to-buffer (other-buffer))
(find-file "g:/Private/pa/pa2.lsp")
```
SLIME opens o.k. in the bottom buffer, but the file is opened in one of the background buffers, while I want it to be in front.
How to fix this?
|
Instead of `switch-to-buffer`, use function `pop-to-buffer`.
>
> `(pop-to-buffer BUFFER-OR-NAME &optional OTHER-WINDOW NORECORD)`
>
>
> Select buffer `BUFFER-OR-NAME` in some window, preferably a different one.
>
>
>
|
188,503 |
<p>How do you detect the number of physical processors/cores in .net?</p>
|
[
{
"answer_id": 188516,
"author": "Tsvetomir Tsonev",
"author_id": 25449,
"author_profile": "https://Stackoverflow.com/users/25449",
"pm_score": 2,
"selected": false,
"text": "<p>System.Environment.ProcessorCount is what you need</p>\n"
},
{
"answer_id": 188522,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 2,
"selected": false,
"text": "<p>Environment.ProcessorCount</p>\n\n<p>EDIT: available in .NET 2.0, not in .NET 1.1</p>\n"
},
{
"answer_id": 188526,
"author": "stephbu",
"author_id": 12702,
"author_profile": "https://Stackoverflow.com/users/12702",
"pm_score": 6,
"selected": true,
"text": "<pre><code>System.Environment.ProcessorCount\n</code></pre>\n\n<p>returns the number of logical processors</p>\n\n<blockquote>\n <p><a href=\"http://msdn.microsoft.com/en-us/library/system.environment.processorcount.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.environment.processorcount.aspx</a></p>\n</blockquote>\n\n<p>For physical processor count you'd probably need to use WMI - the following metadata is supported in XP/Win2k3 upwards (Functionality enabled in SP's prior to Vista/Win2k8).</p>\n\n<blockquote>\n <p><b>Win32_ComputerSystem.NumberOfProcessors</b> returns physical count</p>\n \n <p><b>Win32_ComputerSystem.NumberOfLogicalProcessors</b> returns logical (duh!)</p>\n</blockquote>\n\n<p>Be cautious that HyperThreaded CPUs appear identical to multicore'd CPU's yet the performance characteristics are <em>very</em> different. </p>\n\n<p>To check for HT-enabled CPUs examine each instance of Win32_Processor and compare these two properties.</p>\n\n<blockquote>\n <p><b>Win32_Processor.NumberOfLogicalProcessors</b></p>\n \n <p><b>Win32_Processor.NumberOfCores</b></p>\n</blockquote>\n\n<p>On multicore systems these are typically the same the value.</p>\n\n<p>Also, be aware of systems that may have multiple <strong>Processor Groups</strong>, which is often seen on computers with a large number of processors. By default <a href=\"https://stackoverflow.com/questions/27965962/c-sharp-environment-processorcount-does-not-always-return-the-full-number-of-log\">.Net will only using the first processor group</a> - which means that by default, threads will utilize only CPUs from the first processor group, and <code>Environment.ProcessorCount</code> will return only the number of CPUs in this group. According to <a href=\"https://stackoverflow.com/questions/27965962/c-sharp-environment-processorcount-does-not-always-return-the-full-number-of-log/30456753#30456753\">Alastair Maw's answer</a>, this behavior can be changed by altering the app.config as follows:</p>\n\n<pre><code><configuration>\n <runtime>\n <Thread_UseAllCpuGroups enabled=\"true\"/>\n <GCCpuGroup enabled=\"true\"/>\n <gcServer enabled=\"true\"/>\n </runtime>\n</configuration>\n</code></pre>\n"
},
{
"answer_id": 188553,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>Environment.ProcessorCount will also include any hyperthreaded processors.</p>\n\n<p>There is no way (at least up through Windows 2003) to distinguish a hyperthreaded processor from one with two cores.</p>\n"
},
{
"answer_id": 189013,
"author": "Rick Minerich",
"author_id": 9251,
"author_profile": "https://Stackoverflow.com/users/9251",
"pm_score": 2,
"selected": false,
"text": "<p>This actually varies quite a bit depending on the target platform. Stephbu's answer will work great on XP SP3 and newer. </p>\n\n<p>If you are targeting older platforms, you may want to check out <a href=\"http://www.atalasoft.com/cs/blogs/rickm/archive/2008/04/01/counting-processors-in-net-the-pros-and-cons-of-five-different-methods.aspx\" rel=\"nofollow noreferrer\">this article</a>. I wrote it about half a year ago and in it I discuss several different ways to do this as well as the individual pros and cons of each method.</p>\n\n<p>You may also want to check out <a href=\"http://www.codeproject.com/KB/system/countingprocessors.aspx\" rel=\"nofollow noreferrer\">this code project article</a> if you are interested in differentiating shadow cores from hyperthreading from real ones.</p>\n"
},
{
"answer_id": 189371,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 4,
"selected": false,
"text": "<p>While <code>Environment.ProcessorCount</code> will indeed get you the number of virtual processors in the system, that may not be the number of processors available to your process. I whipped up a quick little static class/property to get exactly that:</p>\n\n<pre><code>using System;\nusing System.Diagnostics;\n\n/// <summary>\n/// Provides a single property which gets the number of processor threads\n/// available to the currently executing process.\n/// </summary>\ninternal static class ProcessInfo\n{\n /// <summary>\n /// Gets the number of processors.\n /// </summary>\n /// <value>The number of processors.</value>\n internal static uint NumberOfProcessorThreads\n {\n get\n {\n uint processAffinityMask;\n\n using (var currentProcess = Process.GetCurrentProcess())\n {\n processAffinityMask = (uint)currentProcess.ProcessorAffinity;\n }\n\n const uint BitsPerByte = 8;\n var loop = BitsPerByte * sizeof(uint);\n uint result = 0;\n\n while (--loop > 0)\n {\n result += processAffinityMask & 1;\n processAffinityMask >>= 1;\n }\n\n return (result == 0) ? 1 : result;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1260223,
"author": "aristippus303",
"author_id": 45822,
"author_profile": "https://Stackoverflow.com/users/45822",
"pm_score": 1,
"selected": false,
"text": "<p>Don't have enough rep for the wiki, but note that in addition to XPSP2, Windows 2003 Server SP1 and SP2 also need a hotfix to enable this functionality:</p>\n\n<p><a href=\"http://support.microsoft.com/kb/932370\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/932370</a></p>\n"
},
{
"answer_id": 20097109,
"author": "bahrep",
"author_id": 761095,
"author_profile": "https://Stackoverflow.com/users/761095",
"pm_score": 1,
"selected": false,
"text": "<p>You can use PowerShell to access comprehensive processor information. For example, you can run the following command to get the number of CPU cores:</p>\n\n<pre><code>Get-WmiObject -namespace root\\CIMV2 -class Win32_Processor -Property NumberOfCores\n</code></pre>\n\n<p>It's much easier to research WMI when using some kind of explorer tool. So, I can suggest using WMI browsing tool (e.g. <a href=\"http://www.ks-soft.net/hostmon.eng/wmi/\" rel=\"nofollow\">WMIExplorer</a> or <a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=24045\" rel=\"nofollow\">WMI CIM Studio</a>) to explore WMI classes, properties and methods.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1952/"
] |
How do you detect the number of physical processors/cores in .net?
|
```
System.Environment.ProcessorCount
```
returns the number of logical processors
>
> <http://msdn.microsoft.com/en-us/library/system.environment.processorcount.aspx>
>
>
>
For physical processor count you'd probably need to use WMI - the following metadata is supported in XP/Win2k3 upwards (Functionality enabled in SP's prior to Vista/Win2k8).
>
> **Win32\_ComputerSystem.NumberOfProcessors** returns physical count
>
>
> **Win32\_ComputerSystem.NumberOfLogicalProcessors** returns logical (duh!)
>
>
>
Be cautious that HyperThreaded CPUs appear identical to multicore'd CPU's yet the performance characteristics are *very* different.
To check for HT-enabled CPUs examine each instance of Win32\_Processor and compare these two properties.
>
> **Win32\_Processor.NumberOfLogicalProcessors**
>
>
> **Win32\_Processor.NumberOfCores**
>
>
>
On multicore systems these are typically the same the value.
Also, be aware of systems that may have multiple **Processor Groups**, which is often seen on computers with a large number of processors. By default [.Net will only using the first processor group](https://stackoverflow.com/questions/27965962/c-sharp-environment-processorcount-does-not-always-return-the-full-number-of-log) - which means that by default, threads will utilize only CPUs from the first processor group, and `Environment.ProcessorCount` will return only the number of CPUs in this group. According to [Alastair Maw's answer](https://stackoverflow.com/questions/27965962/c-sharp-environment-processorcount-does-not-always-return-the-full-number-of-log/30456753#30456753), this behavior can be changed by altering the app.config as follows:
```
<configuration>
<runtime>
<Thread_UseAllCpuGroups enabled="true"/>
<GCCpuGroup enabled="true"/>
<gcServer enabled="true"/>
</runtime>
</configuration>
```
|
188,510 |
<p>I have a string "1112224444' it is a telephone number. I want to format as 111-222-4444 before I store it in a file. It is on a datarecord and I would prefer to be able to do this without assigning a new variable.</p>
<p>I was thinking:</p>
<pre><code>String.Format("{0:###-###-####}", i["MyPhone"].ToString() );
</code></pre>
<p>but that does not seem to do the trick.</p>
<p>** UPDATE **</p>
<p>Ok. I went with this solution</p>
<pre><code>Convert.ToInt64(i["Customer Phone"]).ToString("###-###-#### ####")
</code></pre>
<p>Now its gets messed up when the extension is less than 4 digits. It will fill in the numbers from the right. so</p>
<pre><code>1112224444 333 becomes
11-221-244 3334
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 188543,
"author": "mattruma",
"author_id": 1768,
"author_profile": "https://Stackoverflow.com/users/1768",
"pm_score": 5,
"selected": false,
"text": "<p>As far as I know you can't do this with string.Format ... you would have to handle this yourself. You could just strip out all non-numeric characters and then do something like:</p>\n\n<pre><code>string.Format(\"({0}) {1}-{2}\",\n phoneNumber.Substring(0, 3),\n phoneNumber.Substring(3, 3),\n phoneNumber.Substring(6));\n</code></pre>\n\n<p>This assumes the data has been entered correctly, which you could use regular expressions to validate.</p>\n"
},
{
"answer_id": 188544,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "<p>You'll need to break it into substrings. While you <em>could</em> do that without any extra variables, it wouldn't be particularly nice. Here's one potential solution:</p>\n\n<pre><code>string phone = i[\"MyPhone\"].ToString();\nstring area = phone.Substring(0, 3);\nstring major = phone.Substring(3, 3);\nstring minor = phone.Substring(6);\nstring formatted = string.Format(\"{0}-{1}-{2}\", area, major, minor);\n</code></pre>\n"
},
{
"answer_id": 188551,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": false,
"text": "<p>If you can get <code>i[\"MyPhone\"]</code> as a <code>long</code>, you can use the <code>long.ToString()</code> method to format it:</p>\n\n<pre><code>Convert.ToLong(i[\"MyPhone\"]).ToString(\"###-###-####\");\n</code></pre>\n\n<p>See the MSDN page on <a href=\"http://msdn.microsoft.com/en-us/library/427bttx3.aspx\" rel=\"noreferrer\">Numeric Format Strings</a>.</p>\n\n<p>Be careful to use long rather than int: int could overflow.</p>\n"
},
{
"answer_id": 188607,
"author": "Ryan Duffield",
"author_id": 2696,
"author_profile": "https://Stackoverflow.com/users/2696",
"pm_score": 8,
"selected": false,
"text": "<p>I prefer to use regular expressions:</p>\n\n<pre><code>Regex.Replace(\"1112224444\", @\"(\\d{3})(\\d{3})(\\d{4})\", \"$1-$2-$3\");\n</code></pre>\n"
},
{
"answer_id": 188616,
"author": "Sean",
"author_id": 4919,
"author_profile": "https://Stackoverflow.com/users/4919",
"pm_score": 8,
"selected": false,
"text": "<p>Please note, this answer works with numeric data types (int, long). If you are starting with a string, you'll need to convert it to a number first. Also, please take into account that you'll need to validate that the initial string is at least 10 characters in length.</p>\n\n<p>From a <a href=\"http://blog.stevex.net/index.php/string-formatting-in-csharp/\" rel=\"noreferrer\">good page</a> full of examples:</p>\n\n<pre><code>String.Format(\"{0:(###) ###-####}\", 8005551212);\n\n This will output \"(800) 555-1212\".\n</code></pre>\n\n<p>Although a regex may work even better, keep in mind the old programming quote:</p>\n\n<blockquote>\n <p>Some people, when confronted with a\n problem, think “I know, I’ll use\n regular expressions.” Now they have\n two problems.<br>\n --Jamie Zawinski, in comp.lang.emacs</p>\n</blockquote>\n"
},
{
"answer_id": 302889,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Use Match in Regex to split, then output formatted string with match.groups</p>\n\n<pre><code>Regex regex = new Regex(@\"(?<first3chr>\\d{3})(?<next3chr>\\d{3})(?<next4chr>\\d{4})\");\nMatch match = regex.Match(phone);\nif (match.Success) return \"(\" + match.Groups[\"first3chr\"].ToString() + \")\" + \" \" + \n match.Groups[\"next3chr\"].ToString() + \"-\" + match.Groups[\"next4chr\"].ToString();\n</code></pre>\n"
},
{
"answer_id": 1428591,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Function FormatPhoneNumber(ByVal myNumber As String)\n Dim mynewNumber As String\n mynewNumber = \"\"\n myNumber = myNumber.Replace(\"(\", \"\").Replace(\")\", \"\").Replace(\"-\", \"\")\n If myNumber.Length < 10 Then\n mynewNumber = myNumber\n ElseIf myNumber.Length = 10 Then\n mynewNumber = \"(\" & myNumber.Substring(0, 3) & \") \" &\n myNumber.Substring(3, 3) & \"-\" & myNumber.Substring(6, 3)\n ElseIf myNumber.Length > 10 Then\n mynewNumber = \"(\" & myNumber.Substring(0, 3) & \") \" &\n myNumber.Substring(3, 3) & \"-\" & myNumber.Substring(6, 3) & \" \" &\n myNumber.Substring(10)\n End If\n Return mynewNumber\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 3709252,
"author": "Mak",
"author_id": 447391,
"author_profile": "https://Stackoverflow.com/users/447391",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public string phoneformat(string phnumber)\n{\nString phone=phnumber;\nstring countrycode = phone.Substring(0, 3); \nstring Areacode = phone.Substring(3, 3); \nstring number = phone.Substring(6,phone.Length); \n\nphnumber=\"(\"+countrycode+\")\" +Areacode+\"-\" +number ;\n\nreturn phnumber;\n}\n</code></pre>\n\n<p>Output will be :001-568-895623</p>\n"
},
{
"answer_id": 3791026,
"author": "Larry Smithmier",
"author_id": 4911,
"author_profile": "https://Stackoverflow.com/users/4911",
"pm_score": 0,
"selected": false,
"text": "<p>To take care of your extension issue, how about:</p>\n\n<pre><code>string formatString = \"###-###-#### ####\";\nreturnValue = Convert.ToInt64(phoneNumber)\n .ToString(formatString.Substring(0,phoneNumber.Length+3))\n .Trim();\n</code></pre>\n"
},
{
"answer_id": 3867716,
"author": "Vivek Shenoy",
"author_id": 467315,
"author_profile": "https://Stackoverflow.com/users/467315",
"pm_score": 4,
"selected": false,
"text": "<p>This should work:</p>\n\n<pre><code>String.Format(\"{0:(###)###-####}\", Convert.ToInt64(\"1112224444\"));\n</code></pre>\n\n<p>OR in your case:</p>\n\n<pre><code>String.Format(\"{0:###-###-####}\", Convert.ToInt64(\"1112224444\"));\n</code></pre>\n"
},
{
"answer_id": 7952302,
"author": "Humberto Moreno",
"author_id": 1021759,
"author_profile": "https://Stackoverflow.com/users/1021759",
"pm_score": 2,
"selected": false,
"text": "<p>Try this</p>\n\n<pre><code>string result;\nif ( (!string.IsNullOrEmpty(phoneNumber)) && (phoneNumber.Length >= 10 ) )\n result = string.Format(\"{0:(###)###-\"+new string('#',phoneNumber.Length-6)+\"}\",\n Convert.ToInt64(phoneNumber)\n );\nelse\n result = phoneNumber;\nreturn result;\n</code></pre>\n\n<p>Cheers.</p>\n"
},
{
"answer_id": 8403040,
"author": "Jerry Nixon",
"author_id": 265706,
"author_profile": "https://Stackoverflow.com/users/265706",
"pm_score": 5,
"selected": false,
"text": "<p>I suggest this as a clean solution for US numbers.</p>\n\n<pre><code>public static string PhoneNumber(string value)\n{ \n if (string.IsNullOrEmpty(value)) return string.Empty;\n value = new System.Text.RegularExpressions.Regex(@\"\\D\")\n .Replace(value, string.Empty);\n value = value.TrimStart('1');\n if (value.Length == 7)\n return Convert.ToInt64(value).ToString(\"###-####\");\n if (value.Length == 10)\n return Convert.ToInt64(value).ToString(\"###-###-####\");\n if (value.Length > 10)\n return Convert.ToInt64(value)\n .ToString(\"###-###-#### \" + new String('#', (value.Length - 10)));\n return value;\n}\n</code></pre>\n"
},
{
"answer_id": 22539701,
"author": "underscore",
"author_id": 539698,
"author_profile": "https://Stackoverflow.com/users/539698",
"pm_score": 3,
"selected": false,
"text": "<pre><code>static string FormatPhoneNumber( string phoneNumber ) {\n\n if ( String.IsNullOrEmpty(phoneNumber) )\n return phoneNumber;\n\n Regex phoneParser = null;\n string format = \"\";\n\n switch( phoneNumber.Length ) {\n\n case 5 :\n phoneParser = new Regex(@\"(\\d{3})(\\d{2})\");\n format = \"$1 $2\";\n break;\n\n case 6 :\n phoneParser = new Regex(@\"(\\d{2})(\\d{2})(\\d{2})\");\n format = \"$1 $2 $3\";\n break;\n\n case 7 :\n phoneParser = new Regex(@\"(\\d{3})(\\d{2})(\\d{2})\");\n format = \"$1 $2 $3\";\n break;\n\n case 8 :\n phoneParser = new Regex(@\"(\\d{4})(\\d{2})(\\d{2})\");\n format = \"$1 $2 $3\";\n break;\n\n case 9 :\n phoneParser = new Regex(@\"(\\d{4})(\\d{3})(\\d{2})(\\d{2})\");\n format = \"$1 $2 $3 $4\";\n break;\n\n case 10 :\n phoneParser = new Regex(@\"(\\d{3})(\\d{3})(\\d{2})(\\d{2})\");\n format = \"$1 $2 $3 $4\";\n break;\n\n case 11 :\n phoneParser = new Regex(@\"(\\d{4})(\\d{3})(\\d{2})(\\d{2})\");\n format = \"$1 $2 $3 $4\";\n break;\n\n default:\n return phoneNumber;\n\n }//switch\n\n return phoneParser.Replace( phoneNumber, format );\n\n}//FormatPhoneNumber\n\n enter code here\n</code></pre>\n"
},
{
"answer_id": 30271625,
"author": "Kent Cooper",
"author_id": 2725843,
"author_profile": "https://Stackoverflow.com/users/2725843",
"pm_score": 0,
"selected": false,
"text": "<p>Not to resurrect an old question but figured I might offer at least a slightly easier to use method, if a little more complicated of a setup.</p>\n\n<p>So if we create a new custom formatter we can use the simpler formatting of <code>string.Format</code> without having to convert our phone number to a <code>long</code></p>\n\n<p>So first lets create the custom formatter:</p>\n\n<pre><code>using System;\nusing System.Globalization;\nusing System.Text;\n\nnamespace System\n{\n /// <summary>\n /// A formatter that will apply a format to a string of numeric values.\n /// </summary>\n /// <example>\n /// The following example converts a string of numbers and inserts dashes between them.\n /// <code>\n /// public class Example\n /// {\n /// public static void Main()\n /// { \n /// string stringValue = \"123456789\";\n /// \n /// Console.WriteLine(String.Format(new NumericStringFormatter(),\n /// \"{0} (formatted: {0:###-##-####})\",stringValue));\n /// }\n /// }\n /// // The example displays the following output:\n /// // 123456789 (formatted: 123-45-6789)\n /// </code>\n /// </example>\n public class NumericStringFormatter : IFormatProvider, ICustomFormatter\n {\n /// <summary>\n /// Converts the value of a specified object to an equivalent string representation using specified format and\n /// culture-specific formatting information.\n /// </summary>\n /// <param name=\"format\">A format string containing formatting specifications.</param>\n /// <param name=\"arg\">An object to format.</param>\n /// <param name=\"formatProvider\">An object that supplies format information about the current instance.</param>\n /// <returns>\n /// The string representation of the value of <paramref name=\"arg\" />, formatted as specified by\n /// <paramref name=\"format\" /> and <paramref name=\"formatProvider\" />.\n /// </returns>\n /// <exception cref=\"System.NotImplementedException\"></exception>\n public string Format(string format, object arg, IFormatProvider formatProvider)\n {\n var strArg = arg as string;\n\n // If the arg is not a string then determine if it can be handled by another formatter\n if (strArg == null)\n {\n try\n {\n return HandleOtherFormats(format, arg);\n }\n catch (FormatException e)\n {\n throw new FormatException(string.Format(\"The format of '{0}' is invalid.\", format), e);\n }\n }\n\n // If the format is not set then determine if it can be handled by another formatter\n if (string.IsNullOrEmpty(format))\n {\n try\n {\n return HandleOtherFormats(format, arg);\n }\n catch (FormatException e)\n {\n throw new FormatException(string.Format(\"The format of '{0}' is invalid.\", format), e);\n }\n }\n var sb = new StringBuilder();\n var i = 0;\n\n foreach (var c in format)\n {\n if (c == '#')\n {\n if (i < strArg.Length)\n {\n sb.Append(strArg[i]);\n }\n i++;\n }\n else\n {\n sb.Append(c);\n }\n }\n\n return sb.ToString();\n }\n\n /// <summary>\n /// Returns an object that provides formatting services for the specified type.\n /// </summary>\n /// <param name=\"formatType\">An object that specifies the type of format object to return.</param>\n /// <returns>\n /// An instance of the object specified by <paramref name=\"formatType\" />, if the\n /// <see cref=\"T:System.IFormatProvider\" /> implementation can supply that type of object; otherwise, null.\n /// </returns>\n public object GetFormat(Type formatType)\n {\n // Determine whether custom formatting object is requested. \n return formatType == typeof(ICustomFormatter) ? this : null;\n }\n\n private string HandleOtherFormats(string format, object arg)\n {\n if (arg is IFormattable)\n return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);\n else if (arg != null)\n return arg.ToString();\n else\n return string.Empty;\n }\n }\n}\n</code></pre>\n\n<p>So then if you want to use this you would do something this:</p>\n\n<pre><code>String.Format(new NumericStringFormatter(),\"{0:###-###-####}\", i[\"MyPhone\"].ToString());\n</code></pre>\n\n<p><strong>Some other things to think about:</strong></p>\n\n<p>Right now if you specified a longer formatter than you did a string to format it will just ignore the additional # signs. For example this <code>String.Format(new NumericStringFormatter(),\"{0:###-###-####}\", \"12345\");</code> would result in 123-45-\nso you might want to have it take some kind of possible filler character in the constructor.</p>\n\n<p>Also I didn't provide a way to escape a # sign so if you wanted to include that in your output string you wouldn't be able to the way it is right now.</p>\n\n<p>The reason I prefer this method over Regex is I often have requirements to allow users to specify the format themselves and it is considerably easier for me to explain how to use this format than trying to teach a user regex.</p>\n\n<p>Also the class name is a bit of misnomer since it actually works to format any string as long as you want to keep it in the same order and just inject characters inside of it.</p>\n"
},
{
"answer_id": 34273619,
"author": "Rama Krshna Ila",
"author_id": 5498737,
"author_profile": "https://Stackoverflow.com/users/5498737",
"pm_score": 2,
"selected": false,
"text": "<p>The following will work with out use of regular expression</p>\n\n<pre><code>string primaryContactNumber = !string.IsNullOrEmpty(formData.Profile.Phone) ? String.Format(\"{0:###-###-####}\", long.Parse(formData.Profile.Phone)) : \"\";\n</code></pre>\n\n<p>If we dont use long.Parse , the string.format will not work.</p>\n"
},
{
"answer_id": 36166198,
"author": "James Copeland",
"author_id": 4897761,
"author_profile": "https://Stackoverflow.com/users/4897761",
"pm_score": 3,
"selected": false,
"text": "<p>If your looking for a (US) phone number to be converted in real time. I suggest using this extension. This method works perfectly without filling in the numbers backwards. The <code>String.Format</code> solution appears to work backwards. Just apply this extension to your string.</p>\n\n<pre><code>public static string PhoneNumberFormatter(this string value)\n{\n value = new Regex(@\"\\D\").Replace(value, string.Empty);\n value = value.TrimStart('1');\n\n if (value.Length == 0)\n value = string.Empty;\n else if (value.Length < 3)\n value = string.Format(\"({0})\", value.Substring(0, value.Length));\n else if (value.Length < 7)\n value = string.Format(\"({0}) {1}\", value.Substring(0, 3), value.Substring(3, value.Length - 3));\n else if (value.Length < 11)\n value = string.Format(\"({0}) {1}-{2}\", value.Substring(0, 3), value.Substring(3, 3), value.Substring(6));\n else if (value.Length > 10)\n {\n value = value.Remove(value.Length - 1, 1);\n value = string.Format(\"({0}) {1}-{2}\", value.Substring(0, 3), value.Substring(3, 3), value.Substring(6));\n }\n return value;\n}\n</code></pre>\n"
},
{
"answer_id": 45587547,
"author": "Mohammad Atiour Islam",
"author_id": 1077346,
"author_profile": "https://Stackoverflow.com/users/1077346",
"pm_score": 2,
"selected": false,
"text": "<p>You can also try this:</p>\n\n<pre><code> public string GetFormattedPhoneNumber(string phone)\n {\n if (phone != null && phone.Trim().Length == 10)\n return string.Format(\"({0}) {1}-{2}\", phone.Substring(0, 3), phone.Substring(3, 3), phone.Substring(6, 4));\n return phone;\n }\n</code></pre>\n\n<p>Output:</p>\n\n<p><a href=\"https://i.stack.imgur.com/fg3BP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fg3BP.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 47658381,
"author": "Victor Johnson",
"author_id": 9057363,
"author_profile": "https://Stackoverflow.com/users/9057363",
"pm_score": 3,
"selected": false,
"text": "<p>You may get find yourself in the situation where you have users trying to enter phone numbers with all sorts of separators between area code and the main number block (e.g., spaces, dashes, periods, ect...) So you'll want to strip the input of all characters that are not numbers so you can sterilize the input you are working with. The easiest way to do this is with a RegEx expression.</p>\n\n<pre><code>string formattedPhoneNumber = new System.Text.RegularExpressions.Regex(@\"\\D\")\n .Replace(originalPhoneNumber, string.Empty);\n</code></pre>\n\n<p>Then the answer you have listed should work in most cases.</p>\n\n<p>To answer what you have about your extension issue, you can strip anything that is longer than the expected length of ten (for a regular phone number) and add that to the end using</p>\n\n<pre><code>formattedPhoneNumber = Convert.ToInt64(formattedPhoneNumber)\n .ToString(\"###-###-#### \" + new String('#', (value.Length - 10)));\n</code></pre>\n\n<p>You will want to do an 'if' check to determine if the length of your input is greater than 10 before doing this, if not, just use:</p>\n\n<pre><code>formattedPhoneNumber = Convert.ToInt64(value).ToString(\"###-###-####\");\n</code></pre>\n"
},
{
"answer_id": 50338647,
"author": "Mohammed Hossen",
"author_id": 9790698,
"author_profile": "https://Stackoverflow.com/users/9790698",
"pm_score": 1,
"selected": false,
"text": "<p>Please use the following link for C#\n<a href=\"http://www.beansoftware.com/NET-Tutorials/format-string-phone-number.aspx\" rel=\"nofollow noreferrer\">http://www.beansoftware.com/NET-Tutorials/format-string-phone-number.aspx</a></p>\n\n<p>The easiest way to do format is using Regex.</p>\n\n<pre><code>private string FormatPhoneNumber(string phoneNum)\n{\n string phoneFormat = \"(###) ###-#### x####\";\n\n Regex regexObj = new Regex(@\"[^\\d]\");\n phoneNum = regexObj.Replace(phoneNum, \"\");\n if (phoneNum.Length > 0)\n {\n phoneNum = Convert.ToInt64(phoneNum).ToString(phoneFormat);\n }\n return phoneNum;\n}\n</code></pre>\n\n<p>Pass your phoneNum as string 2021231234 up to 15 char.</p>\n\n<pre><code>FormatPhoneNumber(string phoneNum)\n</code></pre>\n\n<p>Another approach would be to use Substring</p>\n\n<pre><code>private string PhoneFormat(string phoneNum)\n {\n int max = 15, min = 10;\n string areaCode = phoneNum.Substring(0, 3);\n string mid = phoneNum.Substring(3, 3);\n string lastFour = phoneNum.Substring(6, 4);\n string extension = phoneNum.Substring(10, phoneNum.Length - min);\n if (phoneNum.Length == min)\n {\n return $\"({areaCode}) {mid}-{lastFour}\";\n }\n else if (phoneNum.Length > min && phoneNum.Length <= max)\n {\n return $\"({areaCode}) {mid}-{lastFour} x{extension}\";\n }\n return phoneNum;\n }\n</code></pre>\n"
},
{
"answer_id": 57481434,
"author": "Alice Guo",
"author_id": 11860587,
"author_profile": "https://Stackoverflow.com/users/11860587",
"pm_score": 1,
"selected": false,
"text": "<p>You can try {0: (000) 000-####} if your target number starts with 0.</p>\n"
},
{
"answer_id": 59109558,
"author": "Neil Garcia",
"author_id": 2030079,
"author_profile": "https://Stackoverflow.com/users/2030079",
"pm_score": 1,
"selected": false,
"text": "<p>Here is another way of doing it. </p>\n\n<pre><code>public string formatPhoneNumber(string _phoneNum)\n{\n string phoneNum = _phoneNum;\n if (phoneNum == null)\n phoneNum = \"\";\n phoneNum = phoneNum.PadRight(10 - phoneNum.Length);\n phoneNum = phoneNum.Insert(0, \"(\").Insert(4,\") \").Insert(9,\"-\");\n return phoneNum;\n}\n</code></pre>\n"
},
{
"answer_id": 61264621,
"author": "nirav gandhi",
"author_id": 6580613,
"author_profile": "https://Stackoverflow.com/users/6580613",
"pm_score": 2,
"selected": false,
"text": "<pre><code> string phoneNum;\n string phoneFormat = \"0#-###-###-####\";\n phoneNum = Convert.ToInt64(\"011234567891\").ToString(phoneFormat);\n</code></pre>\n"
},
{
"answer_id": 63252501,
"author": "Leoabarca",
"author_id": 12274857,
"author_profile": "https://Stackoverflow.com/users/12274857",
"pm_score": 0,
"selected": false,
"text": "<pre><code> Label12.Text = Convert.ToInt64(reader[6]).ToString("(###) ###-#### ");\n</code></pre>\n<p>This is my example! I hope can help you with this.\nregards</p>\n"
},
{
"answer_id": 65500642,
"author": "Fred Spataro",
"author_id": 14910402,
"author_profile": "https://Stackoverflow.com/users/14910402",
"pm_score": 2,
"selected": false,
"text": "<p>using string interpolation and the new array <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/tutorials/ranges-indexes\" rel=\"nofollow noreferrer\">index/range</a></p>\n<pre><code>var p = "1234567890";\nvar formatted = $"({p[0..3]}) {p[3..6]}-{p[6..10]}"\n</code></pre>\n<p>Output: (123) 456-7890</p>\n"
},
{
"answer_id": 67878347,
"author": "revobtz",
"author_id": 3554970,
"author_profile": "https://Stackoverflow.com/users/3554970",
"pm_score": -1,
"selected": false,
"text": "<p>Here is an improved version of @Jon Skeet answer with null checks and has a extension method.</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>public static string ToTelephoneNumberFormat(this string value, string format = "({0}) {1}-{2}") {\n if (string.IsNullOrWhiteSpace(value)) \n {\n return value;\n } \n else \n {\n string area = value.Substring(0, 3) ?? "";\n string major = value.Substring(3, 3) ?? "";\n string minor = value.Substring(6) ?? "";\n return string.Format(format, area, major, minor);\n }\n}\n</code></pre>\n\n"
},
{
"answer_id": 69243648,
"author": "KuroCoder",
"author_id": 14114788,
"author_profile": "https://Stackoverflow.com/users/14114788",
"pm_score": 0,
"selected": false,
"text": "<pre><code>static void Main(string[] args)\n {\n Regex phonenumber = new(@"([0-9]{11})$");\n Console.WriteLine("Enter a Number: ");\n var number = Console.ReadLine();\n if(number.Length == 11)\n {\n if (phonenumber.IsMatch(number))\n {\n Console.WriteLine("Your Number is: "+number);\n }\n else\n Console.WriteLine("Nooob...");\n }\n else\n Console.WriteLine("Nooob...");\n }\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
I have a string "1112224444' it is a telephone number. I want to format as 111-222-4444 before I store it in a file. It is on a datarecord and I would prefer to be able to do this without assigning a new variable.
I was thinking:
```
String.Format("{0:###-###-####}", i["MyPhone"].ToString() );
```
but that does not seem to do the trick.
\*\* UPDATE \*\*
Ok. I went with this solution
```
Convert.ToInt64(i["Customer Phone"]).ToString("###-###-#### ####")
```
Now its gets messed up when the extension is less than 4 digits. It will fill in the numbers from the right. so
```
1112224444 333 becomes
11-221-244 3334
```
Any ideas?
|
I prefer to use regular expressions:
```
Regex.Replace("1112224444", @"(\d{3})(\d{3})(\d{4})", "$1-$2-$3");
```
|
188,532 |
<p>I want to make sure that a set of functions have the same signature in some C code. Ideally I would be able to define a new type that described the return value and arguments of a function and then declare my set of functions using this new type. </p>
<p>Additionally, is there a way to specify default values for the arguments to this function typedef?</p>
|
[
{
"answer_id": 188559,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 5,
"selected": true,
"text": "<pre><code>/* define a typedef for function_t - functions that return void */\n/* and take an int and char parameter */\n\ntypedef void function_t( int param1, char param2);\n\n/* declare some functions that use that signature */\n\nfunction_t foo;\nfunction_t bar;\n</code></pre>\n\n<p>Now when you define the functions there will be an error if they do not use the same signature as in the typedef.</p>\n\n<pre><code>void foo( int x, char c)\n{\n /* do some stuff */\n\n return;\n}\n\n/* this will result in a compiler error */\nint bar( int x, char c)\n{\n /* do some stuff */\n\n return 1;\n}\n</code></pre>\n\n<hr>\n\n<p>As for your new question (added 20 Oct 08): \"Additionally, is there a way to specify default values for the arguments to this function typedef?\"</p>\n\n<p>No, there's no way to add default parameters to the typedef. Certainly not in C, which doesn't support default parameters at all. Even in C++ you can't do this because the default value of a parameter is not part of the type. In fact, a class that overrides a virtual method from a base class can specify a different value for a default parameter (or even remove the default altogether) - however, this is something that should not be done in general as it will simply cause confusion (<a href=\"http://www.gotw.ca/gotw/005.htm\" rel=\"nofollow noreferrer\">http://www.gotw.ca/gotw/005.htm</a>).</p>\n\n<p>If you're using C++ you might be able to get the behavior you want using one of (or a combination of) the following:</p>\n\n<ul>\n<li>abstract base classes</li>\n<li>overloading</li>\n<li>template functions</li>\n<li>macros</li>\n</ul>\n\n<p>But it would be difficult to suggest something without knowing more specifics about exactly what you're trying to accomplish. And I think it's likely that the result might well be pretty hacky.</p>\n"
},
{
"answer_id": 188567,
"author": "JayG",
"author_id": 5823,
"author_profile": "https://Stackoverflow.com/users/5823",
"pm_score": 0,
"selected": false,
"text": "<p>This is similar to how a function pointer works:</p>\n\n<pre><code> // Declaration of function with int arg returning int\n typedef int (*CALLBACK)(int);\n\n //Definition\n int myFunc(int arg)\n {\n return 0;\n }\n\n // Function pointer usage\n CALLBACK pFunc = myFunc;\n</code></pre>\n"
},
{
"answer_id": 188572,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think you can do this directly, but you could declare a function pointer type and then collect all your functions into an array. The compiler will let you know which ones don't match.</p>\n\n<pre><code>typedef void (*MethodSig)(int, int);\n\nstatic MethodSig x[] = { fnA, fnB, ... };\n</code></pre>\n\n<p>Or use a macro to declare the function signature</p>\n\n<pre><code>#define MyFunc(X) void X(int a, int b)\n</code></pre>\n\n<p>That way they will all be the same.</p>\n"
},
{
"answer_id": 188595,
"author": "mstrobl",
"author_id": 25965,
"author_profile": "https://Stackoverflow.com/users/25965",
"pm_score": 0,
"selected": false,
"text": "<p>You cannot really prevent anyone from making a function have any signature. But you can control what you will call. So I assume that is what you want.</p>\n\n<p>Have the function that will call the arbitrary functions take a pointer to a function as a parameter. Since you mentioned typedef, you can define a typedef earlier in the program, like so:</p>\n\n<p><strong>Assume you only want functions of the signature \"unsigned short id_for_allowed_functions (int x, char* y)\":</strong></p>\n\n<pre><code>typedef unsigned short (*id_for_allowed_functions)(int, char*);\n</code></pre>\n\n<p>Then, your calling function:</p>\n\n<pre><code>void calling_function (id_for_allowed_function x) { (*x)(3, \"bla\"); }\n</code></pre>\n\n<p>And to supply function foo to it:</p>\n\n<pre><code>unsigned short foo(int x, char* y) { /* ... */ }\ncalling_function(&foo);\n</code></pre>\n"
},
{
"answer_id": 7739336,
"author": "Henry Rusted",
"author_id": 989271,
"author_profile": "https://Stackoverflow.com/users/989271",
"pm_score": 0,
"selected": false,
"text": "<p>Here's an example of creating a list of functions mapped to a simple string.</p>\n\n<p>First the typedefs:</p>\n\n<pre><code>typedef GenList *(*DBLISTLOADER)(Database *pDB, char *quellCD, char *profilName);\ntypedef ObjDescription *(*DBCOLUMNLOADER)();\n\ntypedef struct dbinfo\n{\n char *dbName;\n DBLISTLOADER dbListLoader;\n DBCOLUMNLOADER dbColumnLoader;\n char *options;\n} DBINFO;\n</code></pre>\n\n<p>Then the mapping table:</p>\n\n<pre><code>DBINFO dbInfoList[] =\n{\n { \"SRCDOC\", loadSRCDOC, colSRCDOC, \"q\" },\n { \"PRF_CD\", loadPRF_CD, colPRF_CD, \"\" },\n { \"MEDIA\", loadMEDIA, colMEDIA, \"\" },\n\n { NULL, NULL, NULL }\n};\n</code></pre>\n\n<p>Now to lookup a function from that table and call it:</p>\n\n<pre><code>while (dbInfoList[i].dbName != NULL)\n{\n if (strcmp(dbInfoList[i].dbName, szDatabase) == 0)\n {\n return (dbInfoList[i].dbListLoader)(pDB, quellCD, profilName);\n }\n\n i++;\n}\n</code></pre>\n\n<p>Sorry if it's a bit 'raw'. Pasted straight from our code ;-)</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26551/"
] |
I want to make sure that a set of functions have the same signature in some C code. Ideally I would be able to define a new type that described the return value and arguments of a function and then declare my set of functions using this new type.
Additionally, is there a way to specify default values for the arguments to this function typedef?
|
```
/* define a typedef for function_t - functions that return void */
/* and take an int and char parameter */
typedef void function_t( int param1, char param2);
/* declare some functions that use that signature */
function_t foo;
function_t bar;
```
Now when you define the functions there will be an error if they do not use the same signature as in the typedef.
```
void foo( int x, char c)
{
/* do some stuff */
return;
}
/* this will result in a compiler error */
int bar( int x, char c)
{
/* do some stuff */
return 1;
}
```
---
As for your new question (added 20 Oct 08): "Additionally, is there a way to specify default values for the arguments to this function typedef?"
No, there's no way to add default parameters to the typedef. Certainly not in C, which doesn't support default parameters at all. Even in C++ you can't do this because the default value of a parameter is not part of the type. In fact, a class that overrides a virtual method from a base class can specify a different value for a default parameter (or even remove the default altogether) - however, this is something that should not be done in general as it will simply cause confusion (<http://www.gotw.ca/gotw/005.htm>).
If you're using C++ you might be able to get the behavior you want using one of (or a combination of) the following:
* abstract base classes
* overloading
* template functions
* macros
But it would be difficult to suggest something without knowing more specifics about exactly what you're trying to accomplish. And I think it's likely that the result might well be pretty hacky.
|
188,545 |
<p>I was looking for a way to remove text from and RTF string and I found the following regex:</p>
<pre><code>({\\)(.+?)(})|(\\)(.+?)(\b)
</code></pre>
<p>However the resulting string has two right angle brackets "}"</p>
<p><strong>Before:</strong> <code>{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 MS Shell Dlg 2;}{\f1\fnil MS Shell Dlg 2;}} {\colortbl ;\red0\green0\blue0;} {\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\tx720\cf1\f0\fs20 can u send me info for the call pls\f1\par }</code></p>
<p><strong>After:</strong> <code>} can u send me info for the call pls }</code></p>
<p>Any thoughts on how to improve the regex?</p>
<p><strong>Edit:</strong> A more complicated string such as this one does not work: <code>{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 MS Shell Dlg 2;}} {\colortbl ;\red0\green0\blue0;} {\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\tx720\cf1\f0\fs20 HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\test\\myapp\\Apps\\\{3423234-283B-43d2-BCE6-A324B84CC70E\}\par }</code></p>
|
[
{
"answer_id": 188667,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "<p>According to <a href=\"http://regexpal.com\" rel=\"nofollow noreferrer\">RegexPal</a>, the two }'s are the ones bolded below:</p>\n\n<blockquote>\n <p>{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fnil\\fcharset0 MS Shell Dlg 2;}{\\f1\\fnil MS Shell Dlg 2;}<strong>}</strong> {\\colortbl ;\\red0\\green0\\blue0;} {\\generator Msftedit 5.41.15.1507;}\\viewkind4\\uc1\\pard\\tx720\\cf1\\f0\\fs20 can u send me info for the call pls\\f1\\par <strong>}</strong></p>\n</blockquote>\n\n<p>I was able to fix the first curly brace by adding a plus sign to the regex:</p>\n\n<pre><code>({\\\\)(.+?)(}+)|(\\\\)(.+?)(\\b)\n ^\n plus sign added here\n</code></pre>\n\n<p>And to fix the curly brace at the end, I did this:</p>\n\n<pre><code>({\\\\)(.+?)(})|(\\\\)(.+?)(\\b)|}$\n ^\n this checks if there is a curly brace at the end\n</code></pre>\n\n<p>I don't know the RTF format very well so this might not work in all cases, but it works on your example...</p>\n"
},
{
"answer_id": 188725,
"author": "John Chuckran",
"author_id": 25511,
"author_profile": "https://Stackoverflow.com/users/25511",
"pm_score": 3,
"selected": false,
"text": "<p>I've used this before and it worked for me:</p>\n\n<pre><code>\\\\\\w+|\\{.*?\\}|}\n</code></pre>\n\n<p>You will probably want to trim the ends of the result to get rid of the extra spaces left over.</p>\n"
},
{
"answer_id": 188877,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 6,
"selected": false,
"text": "<p>In RTF, { and } marks a group. Groups can be nested. \\ marks beginning of a control word. Control words end with either a space or a non alphabetic character. A control word can have a numeric parameter following, without any delimiter in between. Some control words also take text parameters, separated by ';'. Those control words are usually in their own groups.</p>\n\n<p>I think I have managed to make a pattern that takes care of most the cases.</p>\n\n<pre><code>\\{\\*?\\\\[^{}]+}|[{}]|\\\\\\n?[A-Za-z]+\\n?(?:-?\\d+)?[ ]?\n</code></pre>\n\n<p>It leaves a few spaces when run on your pattern though.</p>\n\n<hr>\n\n<p>Going trough the <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=DD422B8D-FF06-4207-B476-6B5396A18A2B&displaylang=en\" rel=\"noreferrer\">RTF specification</a> (some of it), I see that there are a lot of pitfalls for pure regex based strippers. The most obvious one are that some groups should be ignored (headers, footers, etc.), while others should be rendered (formatting).</p>\n\n<p>I have written a Python script that should work better than my regex above:</p>\n\n<pre><code>def striprtf(text):\n pattern = re.compile(r\"\\\\([a-z]{1,32})(-?\\d{1,10})?[ ]?|\\\\'([0-9a-f]{2})|\\\\([^a-z])|([{}])|[\\r\\n]+|(.)\", re.I)\n # control words which specify a \"destionation\".\n destinations = frozenset((\n 'aftncn','aftnsep','aftnsepc','annotation','atnauthor','atndate','atnicn','atnid',\n 'atnparent','atnref','atntime','atrfend','atrfstart','author','background',\n 'bkmkend','bkmkstart','blipuid','buptim','category','colorschememapping',\n 'colortbl','comment','company','creatim','datafield','datastore','defchp','defpap',\n 'do','doccomm','docvar','dptxbxtext','ebcend','ebcstart','factoidname','falt',\n 'fchars','ffdeftext','ffentrymcr','ffexitmcr','ffformat','ffhelptext','ffl',\n 'ffname','ffstattext','field','file','filetbl','fldinst','fldrslt','fldtype',\n 'fname','fontemb','fontfile','fonttbl','footer','footerf','footerl','footerr',\n 'footnote','formfield','ftncn','ftnsep','ftnsepc','g','generator','gridtbl',\n 'header','headerf','headerl','headerr','hl','hlfr','hlinkbase','hlloc','hlsrc',\n 'hsv','htmltag','info','keycode','keywords','latentstyles','lchars','levelnumbers',\n 'leveltext','lfolevel','linkval','list','listlevel','listname','listoverride',\n 'listoverridetable','listpicture','liststylename','listtable','listtext',\n 'lsdlockedexcept','macc','maccPr','mailmerge','maln','malnScr','manager','margPr',\n 'mbar','mbarPr','mbaseJc','mbegChr','mborderBox','mborderBoxPr','mbox','mboxPr',\n 'mchr','mcount','mctrlPr','md','mdeg','mdegHide','mden','mdiff','mdPr','me',\n 'mendChr','meqArr','meqArrPr','mf','mfName','mfPr','mfunc','mfuncPr','mgroupChr',\n 'mgroupChrPr','mgrow','mhideBot','mhideLeft','mhideRight','mhideTop','mhtmltag',\n 'mlim','mlimloc','mlimlow','mlimlowPr','mlimupp','mlimuppPr','mm','mmaddfieldname',\n 'mmath','mmathPict','mmathPr','mmaxdist','mmc','mmcJc','mmconnectstr',\n 'mmconnectstrdata','mmcPr','mmcs','mmdatasource','mmheadersource','mmmailsubject',\n 'mmodso','mmodsofilter','mmodsofldmpdata','mmodsomappedname','mmodsoname',\n 'mmodsorecipdata','mmodsosort','mmodsosrc','mmodsotable','mmodsoudl',\n 'mmodsoudldata','mmodsouniquetag','mmPr','mmquery','mmr','mnary','mnaryPr',\n 'mnoBreak','mnum','mobjDist','moMath','moMathPara','moMathParaPr','mopEmu',\n 'mphant','mphantPr','mplcHide','mpos','mr','mrad','mradPr','mrPr','msepChr',\n 'mshow','mshp','msPre','msPrePr','msSub','msSubPr','msSubSup','msSubSupPr','msSup',\n 'msSupPr','mstrikeBLTR','mstrikeH','mstrikeTLBR','mstrikeV','msub','msubHide',\n 'msup','msupHide','mtransp','mtype','mvertJc','mvfmf','mvfml','mvtof','mvtol',\n 'mzeroAsc','mzeroDesc','mzeroWid','nesttableprops','nextfile','nonesttables',\n 'objalias','objclass','objdata','object','objname','objsect','objtime','oldcprops',\n 'oldpprops','oldsprops','oldtprops','oleclsid','operator','panose','password',\n 'passwordhash','pgp','pgptbl','picprop','pict','pn','pnseclvl','pntext','pntxta',\n 'pntxtb','printim','private','propname','protend','protstart','protusertbl','pxe',\n 'result','revtbl','revtim','rsidtbl','rxe','shp','shpgrp','shpinst',\n 'shppict','shprslt','shptxt','sn','sp','staticval','stylesheet','subject','sv',\n 'svb','tc','template','themedata','title','txe','ud','upr','userprops',\n 'wgrffmtfilter','windowcaption','writereservation','writereservhash','xe','xform',\n 'xmlattrname','xmlattrvalue','xmlclose','xmlname','xmlnstbl',\n 'xmlopen',\n ))\n # Translation of some special characters.\n specialchars = {\n 'par': '\\n',\n 'sect': '\\n\\n',\n 'page': '\\n\\n',\n 'line': '\\n',\n 'tab': '\\t',\n 'emdash': u'\\u2014',\n 'endash': u'\\u2013',\n 'emspace': u'\\u2003',\n 'enspace': u'\\u2002',\n 'qmspace': u'\\u2005',\n 'bullet': u'\\u2022',\n 'lquote': u'\\u2018',\n 'rquote': u'\\u2019',\n 'ldblquote': u'\\201C',\n 'rdblquote': u'\\u201D', \n }\n stack = []\n ignorable = False # Whether this group (and all inside it) are \"ignorable\".\n ucskip = 1 # Number of ASCII characters to skip after a unicode character.\n curskip = 0 # Number of ASCII characters left to skip\n out = [] # Output buffer.\n for match in pattern.finditer(text):\n word,arg,hex,char,brace,tchar = match.groups()\n if brace:\n curskip = 0\n if brace == '{':\n # Push state\n stack.append((ucskip,ignorable))\n elif brace == '}':\n # Pop state\n ucskip,ignorable = stack.pop()\n elif char: # \\x (not a letter)\n curskip = 0\n if char == '~':\n if not ignorable:\n out.append(u'\\xA0')\n elif char in '{}\\\\':\n if not ignorable:\n out.append(char)\n elif char == '*':\n ignorable = True\n elif word: # \\foo\n curskip = 0\n if word in destinations:\n ignorable = True\n elif ignorable:\n pass\n elif word in specialchars:\n out.append(specialchars[word])\n elif word == 'uc':\n ucskip = int(arg)\n elif word == 'u':\n c = int(arg)\n if c < 0: c += 0x10000\n if c > 127: out.append(unichr(c))\n else: out.append(chr(c))\n curskip = ucskip\n elif hex: # \\'xx\n if curskip > 0:\n curskip -= 1\n elif not ignorable:\n c = int(hex,16)\n if c > 127: out.append(unichr(c))\n else: out.append(chr(c))\n elif tchar:\n if curskip > 0:\n curskip -= 1\n elif not ignorable:\n out.append(tchar)\n return ''.join(out)\n</code></pre>\n\n<p>It works by parsing the RTF code, and skipping any groups which has a \"destination\" specified, and all \"ignorable\" groups (<code>{\\*</code>...<code>}</code>). I also added handling of some special characters.</p>\n\n<p>There are lots of features missing to make this a full parser, but should be enough for simple documents.</p>\n\n<p><strong>UPDATED:</strong> This url have this script updated to run on Python 3.x:</p>\n\n<p><a href=\"https://gist.github.com/gilsondev/7c1d2d753ddb522e7bc22511cfb08676\" rel=\"noreferrer\">https://gist.github.com/gilsondev/7c1d2d753ddb522e7bc22511cfb08676</a></p>\n"
},
{
"answer_id": 735942,
"author": "adeel825",
"author_id": 324,
"author_profile": "https://Stackoverflow.com/users/324",
"pm_score": 1,
"selected": false,
"text": "<p>None of the answers were sufficient, so my solution was to use the RichTextBox control (yes, even in a non-Winform app) to extract text from RTF</p>\n"
},
{
"answer_id": 2229443,
"author": "Orian",
"author_id": 269517,
"author_profile": "https://Stackoverflow.com/users/269517",
"pm_score": 1,
"selected": false,
"text": "<p>The following solution allows you to extract text from an RTF string:</p>\n\n<pre><code>FareRule = Encoding.ASCII.GetString(FareRuleInfoRS.Data);\n System.Windows.Forms.RichTextBox rtf = new System.Windows.Forms.RichTextBox();\n rtf.Rtf = FareRule;\n FareRule = rtf.Text;\n</code></pre>\n"
},
{
"answer_id": 3577127,
"author": "Steven King",
"author_id": 198457,
"author_profile": "https://Stackoverflow.com/users/198457",
"pm_score": 3,
"selected": false,
"text": "<p>So far, we haven't found a good answer to this either, other than using a RichTextBox control:</p>\n\n<pre><code> /// <summary>\n /// Strip RichTextFormat from the string\n /// </summary>\n /// <param name=\"rtfString\">The string to strip RTF from</param>\n /// <returns>The string without RTF</returns>\n public static string StripRTF(string rtfString)\n {\n string result = rtfString;\n\n try\n {\n if (IsRichText(rtfString))\n {\n // Put body into a RichTextBox so we can strip RTF\n using (System.Windows.Forms.RichTextBox rtfTemp = new System.Windows.Forms.RichTextBox())\n {\n rtfTemp.Rtf = rtfString;\n result = rtfTemp.Text;\n }\n }\n else\n {\n result = rtfString;\n }\n }\n catch\n {\n throw;\n }\n\n return result;\n }\n\n /// <summary>\n /// Checks testString for RichTextFormat\n /// </summary>\n /// <param name=\"testString\">The string to check</param>\n /// <returns>True if testString is in RichTextFormat</returns>\n public static bool IsRichText(string testString)\n {\n if ((testString != null) &&\n (testString.Trim().StartsWith(\"{\\\\rtf\")))\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n</code></pre>\n\n<p>Edit: Added IsRichText method.</p>\n"
},
{
"answer_id": 9717469,
"author": "jdearana",
"author_id": 207949,
"author_profile": "https://Stackoverflow.com/users/207949",
"pm_score": 2,
"selected": false,
"text": "<p>Regex won't never 100% solve this problem, you need a parser. \nCheck this implementation in CodeProject (it's in C# though): \n<a href=\"http://www.codeproject.com/Articles/27431/Writing-Your-Own-RTF-Converter\" rel=\"nofollow\">http://www.codeproject.com/Articles/27431/Writing-Your-Own-RTF-Converter</a></p>\n"
},
{
"answer_id": 14351163,
"author": "FiniteLooper",
"author_id": 79677,
"author_profile": "https://Stackoverflow.com/users/79677",
"pm_score": 3,
"selected": false,
"text": "<p>I made this helper function to do this in JavaScript. So far this has worked well for simple RTF formatting removal for me.</p>\n\n<pre><code>function stripRtf(str){\n var basicRtfPattern = /\\{\\*?\\\\[^{}]+;}|[{}]|\\\\[A-Za-z]+\\n?(?:-?\\d+)?[ ]?/g;\n var newLineSlashesPattern = /\\\\\\n/g;\n var ctrlCharPattern = /\\n\\\\f[0-9]\\s/g;\n\n //Remove RTF Formatting, replace RTF new lines with real line breaks, and remove whitespace\n return str\n .replace(ctrlCharPattern, \"\")\n .replace(basicRtfPattern, \"\")\n .replace(newLineSlashesPattern, \"\\n\")\n .trim();\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Of Note:</strong></p>\n\n<ul>\n<li>I slightly modified the regex written by <em>@Markus Jarderot</em> above. It now removes slashes at the end of new lines in two step to avoid a more complex regex.</li>\n<li><code>.trim()</code> is only supported in newer browsers. If you need to have support for these then see this: <a href=\"https://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript\">Trim string in JavaScript?</a></li>\n</ul>\n\n<hr>\n\n<p>EDIT: I've updated the regex to work around some issues I've found since posting this originally. I'm using this in a project, see it in context here: <a href=\"https://github.com/chrismbarr/LyricConverter/blob/865f17613ee8f43fbeedeba900009051c0aa2826/scripts/parser.js#L26-L37\" rel=\"nofollow noreferrer\">https://github.com/chrismbarr/LyricConverter/blob/865f17613ee8f43fbeedeba900009051c0aa2826/scripts/parser.js#L26-L37</a></p>\n"
},
{
"answer_id": 21987039,
"author": "KevHun",
"author_id": 3346537,
"author_profile": "https://Stackoverflow.com/users/3346537",
"pm_score": 2,
"selected": false,
"text": "<p>Late contributor but the regex below helped us with the RTF code we found in our DB (we're using it within an RDL via SSRS).</p>\n\n<p>This expression removed it for our team. Although it may just resolve our specific RTF, it may be a helpful base for someone. Although this webby is incredible handy for live testing.</p>\n\n<p><a href=\"http://regexpal.com/\" rel=\"nofollow\">http://regexpal.com/</a></p>\n\n<pre><code>{\\*?\\\\.+(;})|\\s?\\\\[A-Za-z0-9]+|\\s?{\\s?\\\\[A-Za-z0-9]+\\s?|\\s?}\\s?\n</code></pre>\n\n<p>Hope this helps,\nK</p>\n"
},
{
"answer_id": 42572518,
"author": "Malvineous",
"author_id": 308237,
"author_profile": "https://Stackoverflow.com/users/308237",
"pm_score": 1,
"selected": false,
"text": "<p>Here's an Oracle SQL statement that can strip RTF from an Oracle field:</p>\n\n<pre><code>SELECT REGEXP_REPLACE(\n REGEXP_REPLACE(\n CONTENT,\n '\\\\(fcharset|colortbl)[^;]+;', ''\n ),\n '(\\\\[^ ]+ ?)|[{}]', ''\n) TEXT\nFROM EXAMPLE WHERE CONTENT LIKE '{\\rtf%';\n</code></pre>\n\n<p>This is designed for data from Windows rich text controls, not RTF files. \nLimitations are:</p>\n\n<ul>\n<li><code>\\{</code> and <code>\\}</code> are not replaced with <code>{</code> and <code>}</code></li>\n<li>Headers and footers are not handled specially</li>\n<li>Images and other embedded objects are not handled specially (no idea what will happen if one of these is encountered!)</li>\n</ul>\n\n<p>It works by first removing the <code>\\fcharset</code> and <code>\\colourtbl</code> tags, which are special because data follows them until <code>;</code> is reached. Then it removes all the <code>\\xxx</code> tags (including a single optional trailing space), followed by all the <code>{</code> and <code>}</code> characters. This handles most simple RTF such as what you get from the rich text control.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/324/"
] |
I was looking for a way to remove text from and RTF string and I found the following regex:
```
({\\)(.+?)(})|(\\)(.+?)(\b)
```
However the resulting string has two right angle brackets "}"
**Before:** `{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 MS Shell Dlg 2;}{\f1\fnil MS Shell Dlg 2;}} {\colortbl ;\red0\green0\blue0;} {\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\tx720\cf1\f0\fs20 can u send me info for the call pls\f1\par }`
**After:** `} can u send me info for the call pls }`
Any thoughts on how to improve the regex?
**Edit:** A more complicated string such as this one does not work: `{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 MS Shell Dlg 2;}} {\colortbl ;\red0\green0\blue0;} {\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\tx720\cf1\f0\fs20 HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\test\\myapp\\Apps\\\{3423234-283B-43d2-BCE6-A324B84CC70E\}\par }`
|
In RTF, { and } marks a group. Groups can be nested. \ marks beginning of a control word. Control words end with either a space or a non alphabetic character. A control word can have a numeric parameter following, without any delimiter in between. Some control words also take text parameters, separated by ';'. Those control words are usually in their own groups.
I think I have managed to make a pattern that takes care of most the cases.
```
\{\*?\\[^{}]+}|[{}]|\\\n?[A-Za-z]+\n?(?:-?\d+)?[ ]?
```
It leaves a few spaces when run on your pattern though.
---
Going trough the [RTF specification](http://www.microsoft.com/downloads/details.aspx?FamilyId=DD422B8D-FF06-4207-B476-6B5396A18A2B&displaylang=en) (some of it), I see that there are a lot of pitfalls for pure regex based strippers. The most obvious one are that some groups should be ignored (headers, footers, etc.), while others should be rendered (formatting).
I have written a Python script that should work better than my regex above:
```
def striprtf(text):
pattern = re.compile(r"\\([a-z]{1,32})(-?\d{1,10})?[ ]?|\\'([0-9a-f]{2})|\\([^a-z])|([{}])|[\r\n]+|(.)", re.I)
# control words which specify a "destionation".
destinations = frozenset((
'aftncn','aftnsep','aftnsepc','annotation','atnauthor','atndate','atnicn','atnid',
'atnparent','atnref','atntime','atrfend','atrfstart','author','background',
'bkmkend','bkmkstart','blipuid','buptim','category','colorschememapping',
'colortbl','comment','company','creatim','datafield','datastore','defchp','defpap',
'do','doccomm','docvar','dptxbxtext','ebcend','ebcstart','factoidname','falt',
'fchars','ffdeftext','ffentrymcr','ffexitmcr','ffformat','ffhelptext','ffl',
'ffname','ffstattext','field','file','filetbl','fldinst','fldrslt','fldtype',
'fname','fontemb','fontfile','fonttbl','footer','footerf','footerl','footerr',
'footnote','formfield','ftncn','ftnsep','ftnsepc','g','generator','gridtbl',
'header','headerf','headerl','headerr','hl','hlfr','hlinkbase','hlloc','hlsrc',
'hsv','htmltag','info','keycode','keywords','latentstyles','lchars','levelnumbers',
'leveltext','lfolevel','linkval','list','listlevel','listname','listoverride',
'listoverridetable','listpicture','liststylename','listtable','listtext',
'lsdlockedexcept','macc','maccPr','mailmerge','maln','malnScr','manager','margPr',
'mbar','mbarPr','mbaseJc','mbegChr','mborderBox','mborderBoxPr','mbox','mboxPr',
'mchr','mcount','mctrlPr','md','mdeg','mdegHide','mden','mdiff','mdPr','me',
'mendChr','meqArr','meqArrPr','mf','mfName','mfPr','mfunc','mfuncPr','mgroupChr',
'mgroupChrPr','mgrow','mhideBot','mhideLeft','mhideRight','mhideTop','mhtmltag',
'mlim','mlimloc','mlimlow','mlimlowPr','mlimupp','mlimuppPr','mm','mmaddfieldname',
'mmath','mmathPict','mmathPr','mmaxdist','mmc','mmcJc','mmconnectstr',
'mmconnectstrdata','mmcPr','mmcs','mmdatasource','mmheadersource','mmmailsubject',
'mmodso','mmodsofilter','mmodsofldmpdata','mmodsomappedname','mmodsoname',
'mmodsorecipdata','mmodsosort','mmodsosrc','mmodsotable','mmodsoudl',
'mmodsoudldata','mmodsouniquetag','mmPr','mmquery','mmr','mnary','mnaryPr',
'mnoBreak','mnum','mobjDist','moMath','moMathPara','moMathParaPr','mopEmu',
'mphant','mphantPr','mplcHide','mpos','mr','mrad','mradPr','mrPr','msepChr',
'mshow','mshp','msPre','msPrePr','msSub','msSubPr','msSubSup','msSubSupPr','msSup',
'msSupPr','mstrikeBLTR','mstrikeH','mstrikeTLBR','mstrikeV','msub','msubHide',
'msup','msupHide','mtransp','mtype','mvertJc','mvfmf','mvfml','mvtof','mvtol',
'mzeroAsc','mzeroDesc','mzeroWid','nesttableprops','nextfile','nonesttables',
'objalias','objclass','objdata','object','objname','objsect','objtime','oldcprops',
'oldpprops','oldsprops','oldtprops','oleclsid','operator','panose','password',
'passwordhash','pgp','pgptbl','picprop','pict','pn','pnseclvl','pntext','pntxta',
'pntxtb','printim','private','propname','protend','protstart','protusertbl','pxe',
'result','revtbl','revtim','rsidtbl','rxe','shp','shpgrp','shpinst',
'shppict','shprslt','shptxt','sn','sp','staticval','stylesheet','subject','sv',
'svb','tc','template','themedata','title','txe','ud','upr','userprops',
'wgrffmtfilter','windowcaption','writereservation','writereservhash','xe','xform',
'xmlattrname','xmlattrvalue','xmlclose','xmlname','xmlnstbl',
'xmlopen',
))
# Translation of some special characters.
specialchars = {
'par': '\n',
'sect': '\n\n',
'page': '\n\n',
'line': '\n',
'tab': '\t',
'emdash': u'\u2014',
'endash': u'\u2013',
'emspace': u'\u2003',
'enspace': u'\u2002',
'qmspace': u'\u2005',
'bullet': u'\u2022',
'lquote': u'\u2018',
'rquote': u'\u2019',
'ldblquote': u'\201C',
'rdblquote': u'\u201D',
}
stack = []
ignorable = False # Whether this group (and all inside it) are "ignorable".
ucskip = 1 # Number of ASCII characters to skip after a unicode character.
curskip = 0 # Number of ASCII characters left to skip
out = [] # Output buffer.
for match in pattern.finditer(text):
word,arg,hex,char,brace,tchar = match.groups()
if brace:
curskip = 0
if brace == '{':
# Push state
stack.append((ucskip,ignorable))
elif brace == '}':
# Pop state
ucskip,ignorable = stack.pop()
elif char: # \x (not a letter)
curskip = 0
if char == '~':
if not ignorable:
out.append(u'\xA0')
elif char in '{}\\':
if not ignorable:
out.append(char)
elif char == '*':
ignorable = True
elif word: # \foo
curskip = 0
if word in destinations:
ignorable = True
elif ignorable:
pass
elif word in specialchars:
out.append(specialchars[word])
elif word == 'uc':
ucskip = int(arg)
elif word == 'u':
c = int(arg)
if c < 0: c += 0x10000
if c > 127: out.append(unichr(c))
else: out.append(chr(c))
curskip = ucskip
elif hex: # \'xx
if curskip > 0:
curskip -= 1
elif not ignorable:
c = int(hex,16)
if c > 127: out.append(unichr(c))
else: out.append(chr(c))
elif tchar:
if curskip > 0:
curskip -= 1
elif not ignorable:
out.append(tchar)
return ''.join(out)
```
It works by parsing the RTF code, and skipping any groups which has a "destination" specified, and all "ignorable" groups (`{\*`...`}`). I also added handling of some special characters.
There are lots of features missing to make this a full parser, but should be enough for simple documents.
**UPDATED:** This url have this script updated to run on Python 3.x:
<https://gist.github.com/gilsondev/7c1d2d753ddb522e7bc22511cfb08676>
|
188,547 |
<p>Is it possible for Eclipse to read stdin from a file?</p>
|
[
{
"answer_id": 188654,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 6,
"selected": false,
"text": "<h3>Pure Java</h3>\n<p>You can redirect System.in with a single line of code:</p>\n<pre><code>System.setIn(new FileInputStream(filename));\n</code></pre>\n<p>See <a href=\"http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#setIn-java.io.InputStream-\" rel=\"noreferrer\">System.setIn()</a>.</p>\n<h3>Eclipse config</h3>\n<p>In Eclipse 4.5 or later, the launch configuration dialog can set System.in to read from a file. See <a href=\"http://www.eclipse.org/mars/noteworthy/#_assigning_stdin_to_a_file\" rel=\"noreferrer\">the announcement here</a>.</p>\n<p><a href=\"https://i.stack.imgur.com/63POd.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/63POd.png\" alt=\"Common tab of Launch Configuration dialog\" /></a></p>\n"
},
{
"answer_id": 188766,
"author": "KC Baltz",
"author_id": 9910,
"author_profile": "https://Stackoverflow.com/users/9910",
"pm_score": 2,
"selected": false,
"text": "<p>I don't see a nice way to do it using the standard Eclipse Run dialog. However, you might be able to do it with an External tool launcher and either use the standard \"< infile\" syntax or call a .bat/.sh script to do it for you. </p>\n\n<p>It's not automated, which is what I'm guessing you want, but you can copy & paste the contents of your infile to the Eclipse console when you launch your program. </p>\n"
},
{
"answer_id": 188866,
"author": "John Gardner",
"author_id": 13687,
"author_profile": "https://Stackoverflow.com/users/13687",
"pm_score": 3,
"selected": false,
"text": "<p>On the \"common\" tab of the run dialog, under \"Standard Input and Output\" there's a checkbox for \"file\". but it appears to be only for output...</p>\n\n<p>I'd expect to see 2 file fields there, one for standard in, one for standard out with the append options.</p>\n"
},
{
"answer_id": 6004393,
"author": "lanoxx",
"author_id": 474034,
"author_profile": "https://Stackoverflow.com/users/474034",
"pm_score": 4,
"selected": false,
"text": "<p><strong>[Update]</strong> As it has been pointed out in the comments, this answer was misleading so I have updated it to correct the errors. <strong>[/Update]</strong></p>\n\n<p>On bash or command prompt you can do:\n<code>C:\\myprogramm < file.txt</code> (Windows) or <code>./myprogramm < file.txt</code> (Linux)</p>\n\n<p>Unfortunately in Eclipse it is not possible to achieve the same result, since there is no option to bind the stdin to a file in eclipse. Instead you will have to manually open a file stream in your code, and then read from it instead. One way to do this is by using a program argument to enable it and another one with the file parameter. See Scott's answer on what kind of code you need to add to parse the -d option from the program arguments array.</p>\n\n<p>When you want to point to some file inside your Eclipse Project, you need to be careful to get the location right and use the ${resource_loc:} variable:</p>\n\n<pre><code>-d ${resource_loc:/MyProject/file}\n</code></pre>\n\n<p>of course you can also put an absolute path:</p>\n\n<pre><code>-d path/to/file or -d C:\\path\\to\\file\n</code></pre>\n\n<p>The resource_loc parameter refers to your workspace. That is the folder where all you eclipse projects are stored in. From there you still have to reference your project folder and then the file that you want to load.</p>\n\n<p>You may have to tweak the slash direction, depending if you use Linux or Winodws.</p>\n"
},
{
"answer_id": 6041960,
"author": "Stewart Stevens",
"author_id": 758538,
"author_profile": "https://Stackoverflow.com/users/758538",
"pm_score": 3,
"selected": false,
"text": "<p>The solution for me (running on a Mac, using Eclipse CDT for a C application) was to add \"< path/to/somefile\" at the end of other arguments in the \"Arguments\" tab of the \"Run Configuration\" dialog.</p>\n\n<p>Also check this <a href=\"https://stackoverflow.com/questions/1580758/javaeclipse-how-do-you-debug-a-java-program-that-is-receiving-piped-redirected\">other question</a> for an answer involving launching a Java program in a suspended state and then attaching the debugger using Eclipse.</p>\n"
},
{
"answer_id": 10872607,
"author": "Vlad",
"author_id": 878537,
"author_profile": "https://Stackoverflow.com/users/878537",
"pm_score": 2,
"selected": false,
"text": "<pre><code>< ${workspace_loc:/MyProject/file}\n</code></pre>\n\n<p>in debug configuration/arguments/program arguments:</p>\n\n<p>works well for me.</p>\n"
},
{
"answer_id": 10957131,
"author": "Scott",
"author_id": 311525,
"author_profile": "https://Stackoverflow.com/users/311525",
"pm_score": 3,
"selected": false,
"text": "<p>You will need to tweak your code some to get this working within eclipse. The other answers above did not work when I tried. Another I've seen saying to change Run..>Common tab>Standard Input and Output>File only changed the the stdout behavior to the file, not the input.</p>\n\n<p>The solution was to take the \"-d\" option to a workable solution. If you put anything in the program arguments it's just going to be passed into your main. So what you can do at the beginning of main is something like this:</p>\n\n<pre><code> Scanner in;\n if (args!=null && args.length>0 && args[0].equals(\"-d\")){\n in = new Scanner(new File(args[1]));\n } else {\n in = new Scanner(System.in);\n }\n</code></pre>\n\n<p>You will still need to set your program arguments in the Run.. menu as described in <a href=\"https://stackoverflow.com/a/6004393/311525\">this</a> answer.</p>\n"
},
{
"answer_id": 15316090,
"author": "studgeek",
"author_id": 255961,
"author_profile": "https://Stackoverflow.com/users/255961",
"pm_score": 1,
"selected": false,
"text": "<p>This is surprisingly not supported in Eclipse and it seems there are no current plans to add it. See <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=155411\" rel=\"nofollow\">https://bugs.eclipse.org/bugs/show_bug.cgi?id=155411</a> to follow and vote.</p>\n\n<p>I will update here if it they do implement it.</p>\n"
},
{
"answer_id": 15626780,
"author": "drverboten",
"author_id": 1324444,
"author_profile": "https://Stackoverflow.com/users/1324444",
"pm_score": 0,
"selected": false,
"text": "<p>What I did was to create an Ant target and launch it as \"Run External\" from Eclipse, here are the steps:</p>\n\n<ul>\n<li>I have one input file to read from: <code>res\\in.txt</code> and one for the output: <code>res\\out.txt</code></li>\n<li><p>Create a <code>build.xml</code> with the targets you require (this is just an example):</p>\n\n<pre><code><project basedir=\".\" default=\"run\" name=\"Tests\">\n<target name=\"clean\">\n<delete dir=\"bin\"/>\n</target>\n\n<target name=\"compile\">\n<mkdir dir=\"bin\"/>\n<javac srcdir=\"src\" destdir=\"bin\" includeantruntime=\"false\"/>\n</target>\n\n<target name=\"build\" depends=\"clean,compile\"/>\n\n<target name=\"run\" depends=\"build\">\n<java classname=\"Main\" input=\"res\\in.txt\" output=\"res\\out.txt\" classpath=\"bin\" />\n</target>\n</project>\n</code></pre></li>\n<li><p>In Eclipse go to: <code>Run->External Tools->External Tools Configurations->Ant Build-> New Launch Configuration</code> use the following configuration:</p></li>\n</ul>\n\n<p><code>Section Main</code></p>\n\n<p>Buildfile: <code>${workspace_loc:/Tests/build.xml}</code></p>\n\n<p>Base Directory: <code>${workspace_loc:/Tests}</code></p>\n\n<p>*Note: Tests is the name of my Eclipse project</p>\n\n<p>Now you can run your project by clicking in the Run Extenal tool bar button and change the input or output files as you needed</p>\n"
},
{
"answer_id": 19767979,
"author": "Ruslan Mavlyutov",
"author_id": 1432219,
"author_profile": "https://Stackoverflow.com/users/1432219",
"pm_score": 2,
"selected": false,
"text": "<p>For linux: \nI think, the easiest way is to write an sh-script.</p>\n\n<p>1) write run.sh like this:</p>\n\n<p><em>your program with params</em> < input.txt</p>\n\n<p>2) In the Eclipse profile configuration specify </p>\n\n<p>[tab Main] C++ Run Application = /bin/sh</p>\n\n<p>[tab Arguments] Program Arguments = run.sh</p>\n\n<p>That's it. When you will run your project, you will see the script's output in the eclipse console.\nYou can do something similar in Windows.</p>\n"
},
{
"answer_id": 31287791,
"author": "Petr Janeček",
"author_id": 1273080,
"author_profile": "https://Stackoverflow.com/users/1273080",
"pm_score": 4,
"selected": false,
"text": "<h1>2015 update</h1>\n\n<p>There is a new Eclipse version, Eclipse 4.5 (Mars) which has fixed <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=155411\" rel=\"noreferrer\">the issue</a>!</p>\n\n<p>This is the announcement and description of the feature: <a href=\"http://eclipse.org/mars/noteworthy/#_assigning_stdin_to_a_file\" rel=\"noreferrer\">http://eclipse.org/mars/noteworthy/#_assigning_stdin_to_a_file</a></p>\n\n<blockquote>\n <p>Stdin can now be assigned to a file in the <strong>Common</strong> tab of launch\n configuration dialogs.\n <img src=\"https://i.stack.imgur.com/WCWSD.png\" alt=\"enter image description here\"></p>\n</blockquote>\n\n<p>As expected, this is a new feature of the just released eclipse 4.5 and will therefore not work in an older version.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is it possible for Eclipse to read stdin from a file?
|
### Pure Java
You can redirect System.in with a single line of code:
```
System.setIn(new FileInputStream(filename));
```
See [System.setIn()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#setIn-java.io.InputStream-).
### Eclipse config
In Eclipse 4.5 or later, the launch configuration dialog can set System.in to read from a file. See [the announcement here](http://www.eclipse.org/mars/noteworthy/#_assigning_stdin_to_a_file).
[](https://i.stack.imgur.com/63POd.png)
|
188,569 |
<p>Just starting out in asp.net.
Have just created a login.aspx page in my site and stuck on a asp login control - that's all I did. Now my Welcome.aspx page won't show as the start page of my site when I debug - even though it is set as this.
Plus I have even edited my web.config - (see below) - and it still does the same thing. How do I make it work so I have my Welcome.aspx page start up as default?</p>
<pre><code><authentication mode="Forms">
<forms defaultUrl="~/Welcome.aspx" loginUrl="~/login.aspx" timeout="1440" ></forms>
</authentication>
</code></pre>
|
[
{
"answer_id": 188577,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 2,
"selected": false,
"text": "<p>that's because you're accessing the site with a user that has not been authenticated-- so the framework is redirecting you to the loginurl.</p>\n"
},
{
"answer_id": 188578,
"author": "Danimal",
"author_id": 2757,
"author_profile": "https://Stackoverflow.com/users/2757",
"pm_score": 1,
"selected": false,
"text": "<p>You've set the login URL in web.config. You get sent to welcome.aspx, but that sees that you're not logged in -- so it bounces you back to login. If your login page has a \"remember me\" checkbox, try checking that off and logging in -- subsequent runs should let you right in to welcome.aspx</p>\n"
},
{
"answer_id": 188579,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 0,
"selected": false,
"text": "<p>Well, if the user isn't authenticated they will automatically be redirected to the \"loginUrl\" -- once you log in you should be redirected to Welcome.aspx, and it will be the default page as long as the credentials are valid.</p>\n"
},
{
"answer_id": 188614,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 3,
"selected": true,
"text": "<p>If you want users to access welcome.aspx without being authenticated, put welcome.aspx in a separate folder, and set up a new web.config in that sub folder. fill out the authorization section in that web.config so that the files in that folder and subfolders will be accessible by anonymous users, like this:</p>\n\n<pre><code><authorization><allow users=\"?\" /></authorization>\n</code></pre>\n"
},
{
"answer_id": 188617,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 2,
"selected": false,
"text": "<p>There are two potential causes to your problem.</p>\n\n<p>1.) The user is not authenticated, therefore they must login first. If this is the case the user will be taken to login.aspx and a returnurl parameter will exist that after login returns them to the welcome page.</p>\n\n<p>2.) You are viewing the login.aspx page when you click on \"debug\" to start visual studio, this typically launches the currently visible page if it is an aspx page.</p>\n\n<p>To get around item 1 if you DO NOT want a user to be logged in as a requirement for viewing the welcome.aspx page you can modify your authentication settings in the web.config.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5175/"
] |
Just starting out in asp.net.
Have just created a login.aspx page in my site and stuck on a asp login control - that's all I did. Now my Welcome.aspx page won't show as the start page of my site when I debug - even though it is set as this.
Plus I have even edited my web.config - (see below) - and it still does the same thing. How do I make it work so I have my Welcome.aspx page start up as default?
```
<authentication mode="Forms">
<forms defaultUrl="~/Welcome.aspx" loginUrl="~/login.aspx" timeout="1440" ></forms>
</authentication>
```
|
If you want users to access welcome.aspx without being authenticated, put welcome.aspx in a separate folder, and set up a new web.config in that sub folder. fill out the authorization section in that web.config so that the files in that folder and subfolders will be accessible by anonymous users, like this:
```
<authorization><allow users="?" /></authorization>
```
|
188,584 |
<p>In c#, how can I check to see if a link button has been clicked in the page load method? </p>
<p>I need to know if it was clicked before the click event is fired.</p>
|
[
{
"answer_id": 188603,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>Check the value of the request parameter __EVENTTARGET to see if it is the id of the link button in question.</p>\n"
},
{
"answer_id": 188605,
"author": "Jared",
"author_id": 1980,
"author_profile": "https://Stackoverflow.com/users/1980",
"pm_score": 6,
"selected": true,
"text": "<pre><code>if( IsPostBack ) \n{\n // get the target of the post-back, will be the name of the control\n // that issued the post-back\n string eTarget = Request.Params[\"__EVENTTARGET\"].ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 188611,
"author": "Tsvetomir Tsonev",
"author_id": 25449,
"author_profile": "https://Stackoverflow.com/users/25449",
"pm_score": 2,
"selected": false,
"text": "<p>The UniqueID of the button will be in Request.Form[\"__EVENTTARGET\"]</p>\n"
},
{
"answer_id": 28184452,
"author": "RealSteel",
"author_id": 2027813,
"author_profile": "https://Stackoverflow.com/users/2027813",
"pm_score": 2,
"selected": false,
"text": "<p>if that doesn't work.Try <code>UseSubmitBehavior=\"false\"</code></p>\n"
},
{
"answer_id": 34094176,
"author": "Miguel",
"author_id": 416255,
"author_profile": "https://Stackoverflow.com/users/416255",
"pm_score": 1,
"selected": false,
"text": "<p>Based on accepted answer and the answer of RealSteel this could be a more complete answer.</p>\n\n<p>First add to the .aspx a button like this:</p>\n\n<pre><code><asp:Button id=\"btnExport\" runat=\"server\" Text=\"Export\" UseSubmitBehavior=\"false\"/>\n</code></pre>\n\n<p>Then on the Page_Load method:</p>\n\n<pre><code>if(IsPostBack){\n var eventTarget = Request.Params[\"__EVENTTARGET\"]\n // Then check for the id but keep in mind that the name could be \n // something like ctl00$ContainerName$btnExport \n // if the button was clicked or null so take precautions against null\n // ... so it could be something like this\n var buttonClicked = eventTarget.Substring(eventTarget.LastIndexOf(\"$\") + 1).Equals(\"btnExport\")\n\n}\n</code></pre>\n"
},
{
"answer_id": 43508155,
"author": "Wang Jijun",
"author_id": 6388629,
"author_profile": "https://Stackoverflow.com/users/6388629",
"pm_score": 0,
"selected": false,
"text": "<p>I just got the same trouble, have to do some logic judgement in the Page_Load method to treat different event(which button was clicked).</p>\n\n<p>I realize the arm to get the as the following example.</p>\n\n<p>The front end aspx source code(I have many Buttons with IDs F2, F3, F6, F12.</p>\n\n<pre><code> <Button Style=\"display: none\" ID=\"F2\" runat=\"server\" Text=\"F2:Cancel\" OnClientClick=\"SeiGyo(this)\" OnClick=\"F2_Click\" />\n <Button Style=\"display: none\" ID=\"F3\" runat=\"server\" Text=\"F3:Return\" OnClientClick=\"SeiGyo(this)\" OnClick=\"F3_Click\" />\n <Button Style=\"display: none\" ID=\"F6\" runat=\"server\" Text=\"F6:Run\" OnClientClick=\"SeiGyo(this)\" OnClick=\"F6_Click\" />\n <Button Style=\"display: none\" ID=\"F12\" runat=\"server\" Text=\"F12:Finish\" OnClientClick=\"SeiGyo(this)\" OnClick=\"F12_Click\" />\n</code></pre>\n\n<p>The back end aspx.cs source code, what I need to do is judge which button was clicked when Page_Load was triggered. It seems a little stupid, but works. I hope that will be helpful to some others</p>\n\n<pre><code>Dictionary<string, string> dic = new Dictionary<string, string>();\nforeach(var id in new string[]{\"F2\",\"F3\",\"F6\",\"F12\"})\n{\n foreach (var key in Request.Params.AllKeys)\n {\n if (key != null && key.ToString().Contains(id))\n dic.Add(id, Request[key.ToString()].ToString()); \n }\n}\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13053/"
] |
In c#, how can I check to see if a link button has been clicked in the page load method?
I need to know if it was clicked before the click event is fired.
|
```
if( IsPostBack )
{
// get the target of the post-back, will be the name of the control
// that issued the post-back
string eTarget = Request.Params["__EVENTTARGET"].ToString();
}
```
|
188,625 |
<p>I have an object of class F. I want to output the contents of the object using Console.WriteLine for quick and dirty status updates like this:</p>
<p>Console.WriteLine(objectF);</p>
<p>This prints out only the name of the class to the console:</p>
<pre><code>F
</code></pre>
<p>I want to overload this somehow so that I can instead print out some useful information about the object and its properties.</p>
<p>I have a workaround already: To overload the ToString method in my class and then call:
Console.WriteLine(objectF.ToString());</p>
<p>But I would rather have the simpler syntax. Any ideas?</p>
|
[
{
"answer_id": 188630,
"author": "driis",
"author_id": 13627,
"author_profile": "https://Stackoverflow.com/users/13627",
"pm_score": 4,
"selected": true,
"text": "<p>Console.WriteLine(objectF)</p>\n\n<p>Should work, if you overloaded <code>ToString</code>. When the framework needs to convert an object to a string representation, it invokes <code>ToString</code>.</p>\n\n<pre><code>public override string ToString()\n{\n // replace the line below with your code\n return base.ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 188633,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 1,
"selected": false,
"text": "<p>I would continue to use ToString(). That's its purpose for existing. Also, unless you have a format string, you can just write:</p>\n\n<pre><code>Console.WriteLine(objectF)\n</code></pre>\n"
},
{
"answer_id": 188656,
"author": "Kevin P.",
"author_id": 18542,
"author_profile": "https://Stackoverflow.com/users/18542",
"pm_score": 1,
"selected": false,
"text": "<p>I found the cause of my problem. I had neglected to define my implementation of ToString() as an <strong>override</strong>. The correct syntax is:</p>\n\n<pre><code>public override string ToString()\n{\n ///Do stuff...\n return string;\n}\n</code></pre>\n\n<p>Thanks to the posters below who put me on the right track</p>\n"
},
{
"answer_id": 189297,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 2,
"selected": false,
"text": "<p>You should override ToString() though in some situations you may just find the following code useful:</p>\n\n<pre><code>public static class ObjectUtility\n{\n public static string ToDebug(this object obj)\n {\n if (obj == null)\n return \"<null>\";\n\n var type = obj.GetType();\n var props = type.GetProperties();\n\n var sb = new StringBuilder(props.Length * 20 + type.Name.Length);\n sb.Append(type.Name);\n sb.Append(\"\\r\\n\");\n\n foreach (var property in props)\n {\n if (!property.CanRead)\n continue;\n // AppendFormat defeats the point\n sb.Append(property.Name);\n sb.Append(\": \");\n sb.Append(property.GetValue(obj, null));\n sb.Append(\"\\r\\n\");\n }\n\n return sb.ToString();\n }\n}\n</code></pre>\n\n<p>Usage is to simply include the namespace containing ObjectUtility and then...</p>\n\n<pre><code>var f = new F();\nConsole.WriteLine(f.ToDebug());\n</code></pre>\n\n<p>The reflection usage above isn't very good for high performance code so don't use it in a production scenario where high performance is desired.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18542/"
] |
I have an object of class F. I want to output the contents of the object using Console.WriteLine for quick and dirty status updates like this:
Console.WriteLine(objectF);
This prints out only the name of the class to the console:
```
F
```
I want to overload this somehow so that I can instead print out some useful information about the object and its properties.
I have a workaround already: To overload the ToString method in my class and then call:
Console.WriteLine(objectF.ToString());
But I would rather have the simpler syntax. Any ideas?
|
Console.WriteLine(objectF)
Should work, if you overloaded `ToString`. When the framework needs to convert an object to a string representation, it invokes `ToString`.
```
public override string ToString()
{
// replace the line below with your code
return base.ToString();
}
```
|
188,628 |
<p>I’m getting an intermittent false negative on the following line of code in an ASP.NET 2 <a href="http://www.BugTracker.net" rel="nofollow noreferrer">web site</a>:</p>
<pre><code>if (!System.IO.Directory.Exists(folder))
</code></pre>
<p>The folder clearly exists, and even contains a log file that is written to when the CLR doesn’t lie about the folder’s existence. Any help would be appreciated.</p>
|
[
{
"answer_id": 188648,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 4,
"selected": true,
"text": "<p>Exists() returns false, rather than throwing an error, if any sort of IO error occurs. One thing to watch out for is security errors. Exists does not perform network authentication, so it requires being pre-authenticated if your accessing a network share, at least according to the docs. I haven't tried it myself.</p>\n"
},
{
"answer_id": 188650,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "<p>Is it possible to do a <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow noreferrer\">proc mon</a> on asp.net worker process and verify if it is actually checking for the existence of that particular folder? Check for the result codes too to troubleshoot any access denied errors.</p>\n"
},
{
"answer_id": 188658,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 0,
"selected": false,
"text": "<p>What is the debug time value of the variable \"folder\"?\nIs it a folder which exists outside of website directory?</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
I’m getting an intermittent false negative on the following line of code in an ASP.NET 2 [web site](http://www.BugTracker.net):
```
if (!System.IO.Directory.Exists(folder))
```
The folder clearly exists, and even contains a log file that is written to when the CLR doesn’t lie about the folder’s existence. Any help would be appreciated.
|
Exists() returns false, rather than throwing an error, if any sort of IO error occurs. One thing to watch out for is security errors. Exists does not perform network authentication, so it requires being pre-authenticated if your accessing a network share, at least according to the docs. I haven't tried it myself.
|
188,631 |
<p>How can I tell if an assembly is in use by any process?</p>
|
[
{
"answer_id": 188640,
"author": "driis",
"author_id": 13627,
"author_profile": "https://Stackoverflow.com/users/13627",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to know if your application has loaded the assembly, you can inspect the AppDomain for loaded assemblies. If you want to know if the assembly is loaded by <em>any</em> process on the machine, it gets a little bit trickier. Which of the above do you need ?</p>\n"
},
{
"answer_id": 1089035,
"author": "Scott Weinstein",
"author_id": 25201,
"author_profile": "https://Stackoverflow.com/users/25201",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an answer in PowerShell</p>\n\n<pre><code>if ( Get-Process | ? { $_.Modules | ? {$_.ModuleName -eq \"AssemblyName.dll\" } })\n{\n \"in use\"\n}\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26553/"
] |
How can I tell if an assembly is in use by any process?
|
Here's an answer in PowerShell
```
if ( Get-Process | ? { $_.Modules | ? {$_.ModuleName -eq "AssemblyName.dll" } })
{
"in use"
}
```
|
188,636 |
<p>I'm trying to find a way to force Windows to reboot, and I am running into issues. I've tried </p>
<p><pre><code><code>Set OpSysSet = GetObject("winmgmts:{authenticationlevel=Pkt," _
& "(Shutdown)}").ExecQuery("select * from Win32_OperatingSystem where "_
& "Primary=true")
for each OpSys in OpSysSet
retVal = OpSys.Reboot()
next</code></pre></code></p>
<p>I've also tried using the <code>shutdown -f -r</code> command, and in both cases I sometimes get no response, and if I try again I get an error saying "Action could not complete because the system is shutting down" even though no matter how long I leave it it doesn't shut down, it still allows me to start new programs, and doing a <code>shutdown -a</code> gives the same error. How can a script be used to force Windows to reboot?</p>
|
[
{
"answer_id": 188796,
"author": "Mike L",
"author_id": 12085,
"author_profile": "https://Stackoverflow.com/users/12085",
"pm_score": 2,
"selected": false,
"text": "<p>Well, this uses VBScript -- although truthfully it invokes the same command line shutdown that you're trying to do. I've tested it and it works.</p>\n\n<pre><code>Dim oShell \nSet oShell = CreateObject(\"WScript.Shell\")\n\n'restart, wait 5 seconds, force running apps to close\noShell.Run \"%comspec% /c shutdown /r /t 5 /f\", , TRUE\n</code></pre>\n\n<p>What OS are you running against? This test was against XP. I wonder if the server OS requires a shutdown code...</p>\n"
},
{
"answer_id": 188836,
"author": "Matt Hanson",
"author_id": 5473,
"author_profile": "https://Stackoverflow.com/users/5473",
"pm_score": 4,
"selected": true,
"text": "<p>Try replacing:</p>\n\n<pre><code>retVal = OpSys.Reboot()\n</code></pre>\n\n<p>With:</p>\n\n<pre><code>retVal = OpSys.Win32Shutdown(6)\n</code></pre>\n"
},
{
"answer_id": 190055,
"author": "Jason",
"author_id": 26347,
"author_profile": "https://Stackoverflow.com/users/26347",
"pm_score": 2,
"selected": false,
"text": "<p>You can also try the psShutdown command line utility from Sysinternals now Microsoft.\n<a href=\"http://technet.microsoft.com/en-us/sysinternals/bb897541.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/sysinternals/bb897541.aspx</a></p>\n"
},
{
"answer_id": 6273593,
"author": "Ossama ",
"author_id": 788499,
"author_profile": "https://Stackoverflow.com/users/788499",
"pm_score": 2,
"selected": false,
"text": "<pre><code>'*********************************************************\n\nOption Explicit\n\nDim objShell\n\nSet objShell = WScript.CreateObject(\"WScript.Shell\")\n\nobjShell.Run \"C:\\WINDOWS\\system32\\shutdown.exe -r -t 0\"\n\n'*********************************************************\n</code></pre>\n\n<p>This little script restarts the local computer after 0 seconds.</p>\n"
},
{
"answer_id": 55630318,
"author": "Hakan ÇELİK",
"author_id": 11345553,
"author_profile": "https://Stackoverflow.com/users/11345553",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Set Reset= WScript.CreateObject ("WScript.Shell")\n\nReset.run "shutdown -r -t 0", 0, True\n</code></pre>\n<p>Or..</p>\n<pre><code>Shell "shutdown -r -f -t 0" ' for restart\n\nShell "shutdown -s -f -t 0" ' for Shutdown\n\nShell "shutdown -l -f -t 0" ' for log off\n\nShell "shutdown -a " ' for abort\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14092/"
] |
I'm trying to find a way to force Windows to reboot, and I am running into issues. I've tried
```
`Set OpSysSet = GetObject("winmgmts:{authenticationlevel=Pkt," _
& "(Shutdown)}").ExecQuery("select * from Win32_OperatingSystem where "_
& "Primary=true")
for each OpSys in OpSysSet
retVal = OpSys.Reboot()
next`
```
I've also tried using the `shutdown -f -r` command, and in both cases I sometimes get no response, and if I try again I get an error saying "Action could not complete because the system is shutting down" even though no matter how long I leave it it doesn't shut down, it still allows me to start new programs, and doing a `shutdown -a` gives the same error. How can a script be used to force Windows to reboot?
|
Try replacing:
```
retVal = OpSys.Reboot()
```
With:
```
retVal = OpSys.Win32Shutdown(6)
```
|
188,663 |
<p>I'm curious as to if there are any best practices relating to JQuery when constructing encapsulated code blocks.</p>
<p>Generally, when I construct a page I like to encapsulate the functions used within that page inside an object. This allows me some encapsulation when building applications. There's nothing I hate more than seeing a JavaScript file with a bunch of this</p>
<pre><code>function doSomethingOnlyRelevantOnThisPage() {
// do some stuff
}
</code></pre>
<p>I this makes for messy design, and doesn't really encapsulate functionality nicely.</p>
<p>Commonly in many frameworks, there is a standard that is used to perform this encapsulation. </p>
<p>In Mootools they favor the Object Literal Notation:</p>
<pre><code>var Site = {
// properties and methods
}
</code></pre>
<p>In YUI they favor the Self Executing Function notation:</p>
<pre><code>(function() { // properties and methods })()
</code></pre>
<p>The nice thing about the second example is that a closure is created, thus allowing you to define private properties and methods.</p>
<p>My question is this: Do any JQuery aficionados have any best practices for creating these cleanly encapsulated structures? What is the rationale behind their use?</p>
|
[
{
"answer_id": 188713,
"author": "Tsvetomir Tsonev",
"author_id": 25449,
"author_profile": "https://Stackoverflow.com/users/25449",
"pm_score": 1,
"selected": false,
"text": "<p>I usually follow the prototype pattern:</p>\n\n<pre><code>MyFunction = function(param1, param2)\n{\n this.property1 = param1;\n // etc.\n}\n\nMyFunction.prototype =\n{\n memberOne: function(param1)\n {\n // ...\n },\n\n memberTwo: function(param2)\n {\n }\n}\n</code></pre>\n\n<p>You get something a \"constructor\" (the function itself) and encapsulated \"methods\" and \"fields\".</p>\n\n<p>It's easier for someone who is used to class-based OO languages :)</p>\n"
},
{
"answer_id": 188761,
"author": "Dan Hulton",
"author_id": 8327,
"author_profile": "https://Stackoverflow.com/users/8327",
"pm_score": 2,
"selected": false,
"text": "<p>I use YUI and jQuery when developing (YUI widgets and a few convenience functions, jQuery selectors and javascript \"extensions\"), and the general javascript template I use is this:</p>\n\n<pre><code>/*global YAHOO, $ */\n\n// Create the public-scope accessable namespace for this page\nYAHOO.namespace('Project');\n\nYAHOO.Project.page = function() {\n // Private members\n\n var self = {};\n\n // Public members\n var pub = {};\n\n pub.init = function() {\n\n };\n\n return pub;\n} ();\n\n// When the DOM is loaded, initialize this module\n$(document).ready(YAHOO.Project.page.init);\n</code></pre>\n\n<p>Now clearly, you can remove the YAHOO.namespace() call if you don't want to use YUI, but that's the basic outline. It uses object literal notation, but also allows you to define private properties and methods.</p>\n\n<p>Just remember that when calling private members or referencing private variables to reference them as <code>self.funcName()</code>. You can define them outside of the <code>self</code> object, but then you get a mismash everywhere in your object, where you're trying to figure out if <code>size_of()</code> is a private method or defined globally somewhere else.</p>\n"
},
{
"answer_id": 1710006,
"author": "steve_c",
"author_id": 769,
"author_profile": "https://Stackoverflow.com/users/769",
"pm_score": 5,
"selected": true,
"text": "<p>Since I've been working with jQuery for a while now, I've decided on a standard pattern that works well for me.</p>\n\n<p><strike>It's a combination of the YUI module pattern with a bit of jQuery plugin pattern mixed in.</strike>. We ended up using the self executing closure pattern. This is beneficial in a few ways:</p>\n\n<ol>\n<li>It keeps code to a minimum</li>\n<li>It enforces separation of behavior from presentation</li>\n<li>It provides a closure which prevents naming conflicts</li>\n</ol>\n\n<p>This is what it looks like:</p>\n\n<pre><code>;(function($) { \n var myPrivateFunction = function() {\n };\n\n var init = function() {\n myPrivateFunction();\n };\n\n $(init);\n})(jQuery);\n</code></pre>\n\n<p>We realized that assigning the result of the function execution, similar to the YUI module pattern, exposes code that could potentially be called from within presentation code. We want to prevent this, so this pattern fits.</p>\n\n<p>Of course we could have written the init method inline, without defining a variable for the function. We agreed that explicitly defining the init function made the code clearer to readers.</p>\n\n<p>What happens if we want to share functions between pages/external js files? We simply hook into the existing mechanism that jQuery provides for extending the jQuery object itself - the extend function.</p>\n\n<p>If the functions are static, we use $.extend, and if they operate over a wrapped set, we use the $.fn.extend function.</p>\n\n<p>Hope this helps someone.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/769/"
] |
I'm curious as to if there are any best practices relating to JQuery when constructing encapsulated code blocks.
Generally, when I construct a page I like to encapsulate the functions used within that page inside an object. This allows me some encapsulation when building applications. There's nothing I hate more than seeing a JavaScript file with a bunch of this
```
function doSomethingOnlyRelevantOnThisPage() {
// do some stuff
}
```
I this makes for messy design, and doesn't really encapsulate functionality nicely.
Commonly in many frameworks, there is a standard that is used to perform this encapsulation.
In Mootools they favor the Object Literal Notation:
```
var Site = {
// properties and methods
}
```
In YUI they favor the Self Executing Function notation:
```
(function() { // properties and methods })()
```
The nice thing about the second example is that a closure is created, thus allowing you to define private properties and methods.
My question is this: Do any JQuery aficionados have any best practices for creating these cleanly encapsulated structures? What is the rationale behind their use?
|
Since I've been working with jQuery for a while now, I've decided on a standard pattern that works well for me.
It's a combination of the YUI module pattern with a bit of jQuery plugin pattern mixed in.. We ended up using the self executing closure pattern. This is beneficial in a few ways:
1. It keeps code to a minimum
2. It enforces separation of behavior from presentation
3. It provides a closure which prevents naming conflicts
This is what it looks like:
```
;(function($) {
var myPrivateFunction = function() {
};
var init = function() {
myPrivateFunction();
};
$(init);
})(jQuery);
```
We realized that assigning the result of the function execution, similar to the YUI module pattern, exposes code that could potentially be called from within presentation code. We want to prevent this, so this pattern fits.
Of course we could have written the init method inline, without defining a variable for the function. We agreed that explicitly defining the init function made the code clearer to readers.
What happens if we want to share functions between pages/external js files? We simply hook into the existing mechanism that jQuery provides for extending the jQuery object itself - the extend function.
If the functions are static, we use $.extend, and if they operate over a wrapped set, we use the $.fn.extend function.
Hope this helps someone.
|
188,687 |
<p>Is there a way to change the way asp.net generates elements in the WSDL generated from a .asmx file? Specifically, it seems to mark all elements minoccurs="0" and there are some elements that I want to be minoccurs="1" (aka required fields). </p>
<p>One of these is an argument to the web service (e.g. foo(arg1, arg2) where I want arg2 to be generated in the WSDL as minoccurs="1") the other is a particular field in the class that corresponds to arg1. Do I have to forego auto WSDL generation and take a "contract first" approach?</p>
|
[
{
"answer_id": 189160,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 3,
"selected": false,
"text": "<p>I think that the <code>XmlElement(IsNullable = true)</code> attribute will do the job:</p>\n\n<pre><code>using System.Xml.Serialization;\n\n[WebMethod]\npublic string MyService([XmlElement(IsNullable = true)] string arg)\n{\n return \"1\";\n}\n</code></pre>\n\n<hr>\n\n<p>EDIT [VB version]</p>\n\n<pre><code>Imports System.Xml.Serialization\n\nPublic Function MyService(<XmlElement(IsNullable:=True)> ByVal arg As String) As String\n Return (\"1\")\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 727519,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Using XMLElement(IsNullable=true) generates minOccurs=1, but it also generates in WSDL nillable=\"true\", which is undesirable.</p>\n"
},
{
"answer_id": 727561,
"author": "John Saunders",
"author_id": 76337,
"author_profile": "https://Stackoverflow.com/users/76337",
"pm_score": 1,
"selected": false,
"text": "<p>The only way I know of (short of upgrading to WCF) is to use the [XmlSchemaProvider] attribute. This permits you tio indicate a method that will return the schema that will be emitted as part of the WSDL.</p>\n\n<p>By the time you get to this point, you may find it better to simply write your own WSDL, by hand, so you don't have to worry about how to coerce .NET into writing it for you. You would then simply place the WSDL in a known location on a web site (possible the same site as the service), then tell your customers to use <a href=\"http://url/service.wsdl\" rel=\"nofollow noreferrer\">http://url/service.wsdl</a> instead of service.asmx?wsdl.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7243/"
] |
Is there a way to change the way asp.net generates elements in the WSDL generated from a .asmx file? Specifically, it seems to mark all elements minoccurs="0" and there are some elements that I want to be minoccurs="1" (aka required fields).
One of these is an argument to the web service (e.g. foo(arg1, arg2) where I want arg2 to be generated in the WSDL as minoccurs="1") the other is a particular field in the class that corresponds to arg1. Do I have to forego auto WSDL generation and take a "contract first" approach?
|
I think that the `XmlElement(IsNullable = true)` attribute will do the job:
```
using System.Xml.Serialization;
[WebMethod]
public string MyService([XmlElement(IsNullable = true)] string arg)
{
return "1";
}
```
---
EDIT [VB version]
```
Imports System.Xml.Serialization
Public Function MyService(<XmlElement(IsNullable:=True)> ByVal arg As String) As String
Return ("1")
End Function
```
|
188,688 |
<p>I am looking at some code and it has this statement: </p>
<pre><code>~ConnectionManager()
{
Dispose(false);
}
</code></pre>
<p>The class implements the <code>IDisposable</code> interface, but I do not know if that is part of that the tilde(~) is used for.</p>
|
[
{
"answer_id": 188698,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 3,
"selected": false,
"text": "<p>It is used to indicate the destructor for the class.</p>\n"
},
{
"answer_id": 188699,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 3,
"selected": false,
"text": "<p>Same as C++, it is the destructor; however in C# you do not call it explicitly, it is invoked when the object gets collected by the garbage collector.</p>\n"
},
{
"answer_id": 188702,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 0,
"selected": false,
"text": "<p>~ usually represents a deconstructor. which is run right before a object dies. </p>\n\n<p><a href=\"http://www.ondotnet.com/pub/a/dotnet/2002/02/11/csharp_traps.html\" rel=\"nofollow noreferrer\">Here is a description of C# deconstructors i found</a></p>\n"
},
{
"answer_id": 188712,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "<p>This is a <a href=\"http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx\" rel=\"noreferrer\">finalizer</a>. To be honest, you should very rarely need to write a finalizer. You really only need to write one if:</p>\n\n<ul>\n<li>You have direct access to an unmanaged resource (e.g. through an <code>IntPtr</code>) and you can't use <code>SafeHandle</code> which makes it easier</li>\n<li>You are implementing <code>IDisposable</code> in a class which isn't sealed. (My preference is to seal classes unless they're designed for inheritance.) A finalizer is part of the canonical Dispose pattern in such cases.</li>\n</ul>\n"
},
{
"answer_id": 188715,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 9,
"selected": true,
"text": "<p><strong>~ is the destructor</strong></p>\n\n<ol>\n<li>Destructors are invoked automatically, and cannot be invoked explicitly.</li>\n<li>Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.</li>\n<li>Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it.</li>\n<li>Destructors cannot be used with structs. They are only used with classes.\nAn instance becomes eligible for destruction when it is no longer possible for any code to use the instance.</li>\n<li>Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.</li>\n<li>When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived.</li>\n</ol>\n\n<p><strong>Finalize</strong> </p>\n\n<p>In C#, the Finalize method performs the operations that a standard C++ destructor would do. In C#, you don't name it Finalize -- you use the C++ destructor syntax of placing a tilde ( ~ ) symbol before the name of the class. </p>\n\n<p><strong>Dispose</strong></p>\n\n<p>It is preferable to dispose of objects in a <code>Close()</code> or <code>Dispose()</code> method that can be called explicitly by the user of the class. Finalize (destructor) are called by the GC.</p>\n\n<p>The <em>IDisposable</em> interface tells the world that your class holds onto resources that need to be disposed and provides users a way to release them. If you do need to implement a finalizer in your class, your Dispose method <em>should</em> use the <code>GC.SuppressFinalize()</code> method to ensure that finalization of your instance is suppressed. </p>\n\n<p><strong>What to use?</strong></p>\n\n<p>It is not legal to call a destructor explicitly. Your destructor will be called by the garbage collector. If you do handle precious unmanaged resources (such as file handles) that you want to close and dispose of as quickly as possible, you ought to implement the IDisposable interface.</p>\n"
},
{
"answer_id": 188735,
"author": "Jeff Stong",
"author_id": 2459,
"author_profile": "https://Stackoverflow.com/users/2459",
"pm_score": 2,
"selected": false,
"text": "<p>See <a href=\"http://msdn.microsoft.com/library/66x5fx1b.aspx\" rel=\"nofollow noreferrer\">Destructors (C# Programming Guide)</a>. Be aware, however that, unlike C++, programmer has no control over when the destructor is called because this is determined by the garbage collector.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048/"
] |
I am looking at some code and it has this statement:
```
~ConnectionManager()
{
Dispose(false);
}
```
The class implements the `IDisposable` interface, but I do not know if that is part of that the tilde(~) is used for.
|
**~ is the destructor**
1. Destructors are invoked automatically, and cannot be invoked explicitly.
2. Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.
3. Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it.
4. Destructors cannot be used with structs. They are only used with classes.
An instance becomes eligible for destruction when it is no longer possible for any code to use the instance.
5. Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.
6. When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived.
**Finalize**
In C#, the Finalize method performs the operations that a standard C++ destructor would do. In C#, you don't name it Finalize -- you use the C++ destructor syntax of placing a tilde ( ~ ) symbol before the name of the class.
**Dispose**
It is preferable to dispose of objects in a `Close()` or `Dispose()` method that can be called explicitly by the user of the class. Finalize (destructor) are called by the GC.
The *IDisposable* interface tells the world that your class holds onto resources that need to be disposed and provides users a way to release them. If you do need to implement a finalizer in your class, your Dispose method *should* use the `GC.SuppressFinalize()` method to ensure that finalization of your instance is suppressed.
**What to use?**
It is not legal to call a destructor explicitly. Your destructor will be called by the garbage collector. If you do handle precious unmanaged resources (such as file handles) that you want to close and dispose of as quickly as possible, you ought to implement the IDisposable interface.
|
188,691 |
<p>I want to write something that acts just like confirm() in javascript, but I want to write it myself so I can skin the dialog box. In having trouble thinking through how I would basically force the javascript thread to wait until the user responds and then return true or false.</p>
|
[
{
"answer_id": 188708,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 4,
"selected": true,
"text": "<p>If I were you, I would look at one of the popular javascript libraries. Most contain some sort of modal dialog.</p>\n\n<p>A couple I found for JQuery are <a href=\"http://dev.iceburg.net/jquery/jqModal/\" rel=\"nofollow noreferrer\">jqModal</a> and <a href=\"http://www.ericmmartin.com/projects/simplemodal/\" rel=\"nofollow noreferrer\">SimpleModal</a>.</p>\n\n<p>When you build the modal dialog, you will have to tie events to the buttons, so you would do something like:</p>\n\n<pre><code>function askUserYesOrNo() {\n var myDialog = $('<div class=\"mydialog\"><p>Yes or No?</p><input type=\"button\" id=\"yes\" value=\"Yes\"/><input type=\"button\" id=\"no\" value=\"No\"/></div>');\n $(\"#yes\").click(handleYes);\n $(\"#no\").click(handleNo);\n myDialog.modal(); //This would have to be replaced by whatever syntax the modal framework uses\n}\n\nfunction handleYes() {\n //handle yes...\n}\n\nfunction handleNo() {\n //handle no...\n}\n</code></pre>\n"
},
{
"answer_id": 188734,
"author": "Dylan Beattie",
"author_id": 5017,
"author_profile": "https://Stackoverflow.com/users/5017",
"pm_score": 2,
"selected": false,
"text": "<p>You really want to use a framework for this, because of the number of weird cross-browser issues that you'll encounter trying to build it yourself. </p>\n\n<p>I've had good results using <a href=\"http://dev.iceburg.net/jquery/jqModal/\" rel=\"nofollow noreferrer\">jqModal</a>, a plugin for the jQuery framework that lets you define modal dialogs, but it's by no means the only option; try Googling <a href=\"http://www.google.com/search?q=jquery+modal\" rel=\"nofollow noreferrer\">jquery modal</a> or <a href=\"http://www.google.com/search?q=yui+modal\" rel=\"nofollow noreferrer\">yui modal</a> for some alternatives.</p>\n"
},
{
"answer_id": 188917,
"author": "doekman",
"author_id": 56,
"author_profile": "https://Stackoverflow.com/users/56",
"pm_score": 0,
"selected": false,
"text": "<p>You could use window.<a href=\"http://msdn.microsoft.com/en-us/library/ms536759(VS.85).aspx\" rel=\"nofollow noreferrer\">showModalDialog</a> (<a href=\"http://developer.mozilla.org/en/DOM/window.showModalDialog\" rel=\"nofollow noreferrer\">mozilla</a>), but it's a non-standard function introduced by Internet Explorer. Now it's also supported in Firefox 3 and Safari (I'm not sure which version, but at least 3.1 and highter, but not the iPhone). </p>\n"
},
{
"answer_id": 189719,
"author": "Robert Krimen",
"author_id": 25171,
"author_profile": "https://Stackoverflow.com/users/25171",
"pm_score": 0,
"selected": false,
"text": "<p>A bare-bones YUI modal lightbox (<a href=\"http://bravo9.com/journal/c5b048f5-b278-46d1-9a7e-0d3035094f52/assets/example.html#\" rel=\"nofollow noreferrer\">example</a>):</p>\n\n<p><a href=\"http://bravo9.com/journal/a-simple-lightbox-modal-dialog-with-yui-c5b048f5-b278-46d1-9a7e-0d3035094f52/\" rel=\"nofollow noreferrer\">http://bravo9.com/journal/a-simple-lightbox-modal-dialog-with-yui-c5b048f5-b278-46d1-9a7e-0d3035094f52/</a></p>\n"
},
{
"answer_id": 189775,
"author": "cheeaun",
"author_id": 20838,
"author_profile": "https://Stackoverflow.com/users/20838",
"pm_score": 1,
"selected": false,
"text": "<p>For Mootools, there are <a href=\"http://www.moord.it/examples/custom_confirm\" rel=\"nofollow noreferrer\">moo.rd's Custom.Confirm</a> and <a href=\"http://windoo.110mb.com/template/windoo.html\" rel=\"nofollow noreferrer\">Windoo.Confirm</a> for your reference.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2484/"
] |
I want to write something that acts just like confirm() in javascript, but I want to write it myself so I can skin the dialog box. In having trouble thinking through how I would basically force the javascript thread to wait until the user responds and then return true or false.
|
If I were you, I would look at one of the popular javascript libraries. Most contain some sort of modal dialog.
A couple I found for JQuery are [jqModal](http://dev.iceburg.net/jquery/jqModal/) and [SimpleModal](http://www.ericmmartin.com/projects/simplemodal/).
When you build the modal dialog, you will have to tie events to the buttons, so you would do something like:
```
function askUserYesOrNo() {
var myDialog = $('<div class="mydialog"><p>Yes or No?</p><input type="button" id="yes" value="Yes"/><input type="button" id="no" value="No"/></div>');
$("#yes").click(handleYes);
$("#no").click(handleNo);
myDialog.modal(); //This would have to be replaced by whatever syntax the modal framework uses
}
function handleYes() {
//handle yes...
}
function handleNo() {
//handle no...
}
```
|
188,692 |
<p>I recall reading, on multiple occasions and in multiple locations, that when firing the typical event:</p>
<pre><code>protected virtual OnSomethingHappened()
{
this.SomethingHappened(this, EventArgs.Empty);
}
</code></pre>
<p>e should be EventArgs.Empty if there are no interesting event args, not null.</p>
<p>I've followed the guidance in my code, but I realized that I'm not clear on why that's the preferred technique. Why does the stated contract prefer EventArgs.Empty over null?</p>
|
[
{
"answer_id": 188723,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 6,
"selected": true,
"text": "<p>I believe the reasoning behind the NOT NULL is that when passed as a parameter, it is not expected for the method to need to potentially handle a null reference exception.</p>\n\n<p>If you pass null, and the method tries to do something with e it will get a null reference exception, with EventArgs.Empty it will not.</p>\n"
},
{
"answer_id": 188737,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using a general-purpose method which has the <code>EventHandler</code> signature that's called from any event handler and is passed both the <em><code>object sender</code></em> and <em><code>EventArgs e</code></em>, it can call <code>e.ToString()</code>, e.g., for logging events, without worrying about a null pointer exception.</p>\n"
},
{
"answer_id": 188743,
"author": "ForCripeSake",
"author_id": 14833,
"author_profile": "https://Stackoverflow.com/users/14833",
"pm_score": 3,
"selected": false,
"text": "<p>I believe <code>EventArgs.Empty</code> is used to maintain the convention of passing an argument with an event, even if none are needed. </p>\n\n<p>Mitchel Sellers posted the other half of my reason halfway through my post: it prevents a null reference exception should a method try and do something with that argument (besides check if it is null).</p>\n\n<p><code>EventArgs.Empty</code> basically does the work of a globally defined Event Argument with no additional information.</p>\n\n<p>To give a similar example of maintaining a convention, our team uses <code>string.Empty</code> to initialize a string because otherwise different coders might use <code>newString = \"\"; or newString = \" \"; or newString = null;</code>, all of which may produce different results for different check conditions. </p>\n\n<p>A (slightly pedantic) reason to use <code>EventArgs.Empty</code> vs <code>new EventArgs()</code> is that the former does not initialize a new <code>EventArgs</code>, saving a slight amount of memory.</p>\n"
},
{
"answer_id": 188779,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 0,
"selected": false,
"text": "<p>I used long time \"new EventArgs()\" instead of \"EventArgs.Empty\"... I think the important is to pass something that will not cause an Null exception.</p>\n"
},
{
"answer_id": 947677,
"author": "Martin Konicek",
"author_id": 90998,
"author_profile": "https://Stackoverflow.com/users/90998",
"pm_score": 5,
"selected": false,
"text": "<p><code>EventArgs.Empty</code> is an instance of the <a href=\"http://en.wikipedia.org/wiki/Null_Object_pattern\" rel=\"noreferrer\">Null object pattern</a>.</p>\n\n<p>Basically, having an object representing \"no value\" to avoid checking for null when using it.</p>\n"
},
{
"answer_id": 22455441,
"author": "Bobak_KS",
"author_id": 2539385,
"author_profile": "https://Stackoverflow.com/users/2539385",
"pm_score": 0,
"selected": false,
"text": "<p>from Albahari book: <code>\"in order to avoid unnecessarily instantiating an instance of EventArgs.\"</code></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6932/"
] |
I recall reading, on multiple occasions and in multiple locations, that when firing the typical event:
```
protected virtual OnSomethingHappened()
{
this.SomethingHappened(this, EventArgs.Empty);
}
```
e should be EventArgs.Empty if there are no interesting event args, not null.
I've followed the guidance in my code, but I realized that I'm not clear on why that's the preferred technique. Why does the stated contract prefer EventArgs.Empty over null?
|
I believe the reasoning behind the NOT NULL is that when passed as a parameter, it is not expected for the method to need to potentially handle a null reference exception.
If you pass null, and the method tries to do something with e it will get a null reference exception, with EventArgs.Empty it will not.
|
188,693 |
<p>Looking for an answer for C# and C++. (in C#, replace 'destructor' with 'finalizer')</p>
|
[
{
"answer_id": 188722,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "<p>It does for C# (see code below) but not for C++.</p>\n\n<pre><code>using System;\n\nclass Test\n{\n Test()\n {\n throw new Exception();\n }\n\n ~Test()\n {\n Console.WriteLine(\"Finalized\");\n }\n\n static void Main()\n {\n try\n {\n new Test();\n }\n catch {}\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n}\n</code></pre>\n\n<p>This prints \"Finalized\"</p>\n"
},
{
"answer_id": 188728,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 1,
"selected": false,
"text": "<p>If the constructor doesn't finish executing, the object doesn't exist, so there's nothing to destruct. This is in C++, I have no idea about C#.</p>\n"
},
{
"answer_id": 188750,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>C++ -</p>\n\n<p>Nope. Destructor is not called for partially constructed objects. A Caveat: The destructor will be called for its member objects which are completely constructed. (Includes automatic objects, and native types)</p>\n\n<p>BTW - What you're really looking for is called \"Stack Unwinding\"</p>\n"
},
{
"answer_id": 188753,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 2,
"selected": false,
"text": "<p>In C++, the answer is no - object's destructor is <em>not</em> called.</p>\n\n<p>However, the destructors of any member data on the object <em>will</em> be called, unless the exception was thrown while constructing one of <em>them</em>. </p>\n\n<p>Member data in C++ is initialized (i.e. constructed) in the same order as it is declared, so when the constructor throws, all member data that has been initialized - either explicitly in the Member Initialization List (MIL) or otherwise - will be torn down again in reverse order.</p>\n"
},
{
"answer_id": 188762,
"author": "Robert Deml",
"author_id": 9516,
"author_profile": "https://Stackoverflow.com/users/9516",
"pm_score": 0,
"selected": false,
"text": "<p>Don't do things that cause exceptions in the constructor.</p>\n\n<p>Call an Initialize() after the constructor that can throw exceptions.</p>\n"
},
{
"answer_id": 188882,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 7,
"selected": true,
"text": "<p>Preamble: Herb Sutter has a great article on the subject:</p>\n<p><a href=\"http://herbsutter.wordpress.com/2008/07/25/constructor-exceptions-in-c-c-and-java/\" rel=\"noreferrer\">http://herbsutter.wordpress.com/2008/07/25/constructor-exceptions-in-c-c-and-java/</a></p>\n<h2>C++ : Yes and No</h2>\n<p>While an object destructor won't be called if its constructor throws (the object "never existed"), the destructors of its internal objects could be called.</p>\n<p>As a summary, every internal parts of the object (i.e. member objects) will have their destructors called in the reverse order of their construction. Every thing built inside the constructor won't have its destructor called unless RAII is used in some way.</p>\n<p>For example:</p>\n<pre><code>struct Class\n{\n Class() ;\n ~Class() ;\n \n Thing * m_pThing ;\n Object m_aObject ;\n Gizmo * m_pGizmo ;\n Data m_aData ;\n}\n\nClass::Class()\n{\n this->m_pThing = new Thing() ;\n this->m_pGizmo = new Gizmo() ;\n}\n</code></pre>\n<p>The order of creation will be:</p>\n<ol>\n<li>m_aObject will have its constructor called.</li>\n<li>m_aData will have its constructor called.</li>\n<li>Class constructor is called</li>\n<li>Inside Class constructor, m_pThing will have its new and then constructor called.</li>\n<li>Inside Class constructor, m_pGizmo will have its new and then constructor called.</li>\n</ol>\n<p>Let's say we are using the following code:</p>\n<pre><code>Class pClass = new Class() ;\n</code></pre>\n<p>Some possible cases:</p>\n<ul>\n<li><p>Should m_aData throw at construction, m_aObject will have its destructor called. Then, the memory allocated by "new Class" is deallocated.</p>\n</li>\n<li><p>Should m_pThing throw at new Thing (out of memory), m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated.</p>\n</li>\n<li><p>Should m_pThing throw at construction, the memory allocated by "new Thing" will be deallocated. Then m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated.</p>\n</li>\n<li><p>Should m_pGizmo throw at construction, the memory allocated by "new Gizmo" will be deallocated. Then m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated. <strong>Note that m_pThing leaked</strong></p>\n</li>\n</ul>\n<p>If you want to offer the Basic Exception Guarantee, you must not leak, even in the constructor. Thus, you'll have to write this this way (using STL, or even Boost):</p>\n<pre><code>struct Class\n{\n Class() ;\n ~Class() ;\n \n std::auto_ptr<Thing> m_pThing ;\n Object m_aObject ;\n std::auto_ptr<Gizmo> m_pGizmo ;\n Data m_aData ;\n}\n\nClass::Class()\n : m_pThing(new Thing())\n , m_pGizmo(new Gizmo())\n{\n}\n</code></pre>\n<p>Or even:</p>\n<pre><code>Class::Class()\n{\n this->m_pThing.reset(new Thing()) ;\n this->m_pGizmo.reset(new Gizmo()) ;\n}\n</code></pre>\n<p>if you want/need to create those objects inside the constructor.</p>\n<p>This way, no matter where the constructor throws, nothing will be leaked.</p>\n"
},
{
"answer_id": 188987,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 4,
"selected": false,
"text": "<p>The destructor of the class still being constructed is not called, because the object was never fully constructed.</p>\n\n<p>However, the destructor of its base class (if any) IS called, because the object was constructed as far as being a base class object.</p>\n\n<p>Moreover, any member variables will have their destructors called too (as others have noted).</p>\n\n<p>NB: this applies to C++</p>\n"
},
{
"answer_id": 189277,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 1,
"selected": false,
"text": "<p>For C++ this is addressed in a previous question: <a href=\"https://stackoverflow.com/questions/147572/will-the-below-code-cause-memory-leak-in-c\">Will the below code cause memory leak in c++</a></p>\n\n<p>Since in C++ when an exception is thrown in a constructor the destructor does not get called, but dtors for the object's members (that have been constructed) do get called, this is a primary reason to use smart pointer objects over raw pointers - they are a good way to prevent memory leaks in a situation like this.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22820/"
] |
Looking for an answer for C# and C++. (in C#, replace 'destructor' with 'finalizer')
|
Preamble: Herb Sutter has a great article on the subject:
<http://herbsutter.wordpress.com/2008/07/25/constructor-exceptions-in-c-c-and-java/>
C++ : Yes and No
----------------
While an object destructor won't be called if its constructor throws (the object "never existed"), the destructors of its internal objects could be called.
As a summary, every internal parts of the object (i.e. member objects) will have their destructors called in the reverse order of their construction. Every thing built inside the constructor won't have its destructor called unless RAII is used in some way.
For example:
```
struct Class
{
Class() ;
~Class() ;
Thing * m_pThing ;
Object m_aObject ;
Gizmo * m_pGizmo ;
Data m_aData ;
}
Class::Class()
{
this->m_pThing = new Thing() ;
this->m_pGizmo = new Gizmo() ;
}
```
The order of creation will be:
1. m\_aObject will have its constructor called.
2. m\_aData will have its constructor called.
3. Class constructor is called
4. Inside Class constructor, m\_pThing will have its new and then constructor called.
5. Inside Class constructor, m\_pGizmo will have its new and then constructor called.
Let's say we are using the following code:
```
Class pClass = new Class() ;
```
Some possible cases:
* Should m\_aData throw at construction, m\_aObject will have its destructor called. Then, the memory allocated by "new Class" is deallocated.
* Should m\_pThing throw at new Thing (out of memory), m\_aData, and then m\_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated.
* Should m\_pThing throw at construction, the memory allocated by "new Thing" will be deallocated. Then m\_aData, and then m\_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated.
* Should m\_pGizmo throw at construction, the memory allocated by "new Gizmo" will be deallocated. Then m\_aData, and then m\_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated. **Note that m\_pThing leaked**
If you want to offer the Basic Exception Guarantee, you must not leak, even in the constructor. Thus, you'll have to write this this way (using STL, or even Boost):
```
struct Class
{
Class() ;
~Class() ;
std::auto_ptr<Thing> m_pThing ;
Object m_aObject ;
std::auto_ptr<Gizmo> m_pGizmo ;
Data m_aData ;
}
Class::Class()
: m_pThing(new Thing())
, m_pGizmo(new Gizmo())
{
}
```
Or even:
```
Class::Class()
{
this->m_pThing.reset(new Thing()) ;
this->m_pGizmo.reset(new Gizmo()) ;
}
```
if you want/need to create those objects inside the constructor.
This way, no matter where the constructor throws, nothing will be leaked.
|
188,719 |
<p>A friend and I are about to embark on creating a machine that performs some image comparison for sorting. I know about histogram comparison and am generally confident that a small grid of histograms per image precalculated and stored in columns in a database table will generally give us pretty good matches on the first pass because we are matching like things.</p>
<p>The second comparison we want to perform is to use a <a href="http://tinyurl.com/4lo8nl" rel="nofollow noreferrer">color coherence vector</a> (CCV) of images which passed the histogram match test from our subject image to the candidate images. I know that this sort of comparison is more precise.</p>
<p>My friend is confident that he can develop CCV in C# using the <a href="http://www.codeproject.com/KB/cs/Intel_OpenCV.aspx" rel="nofollow noreferrer">C# wrapper</a> to <a href="http://sourceforge.net/projects/opencvlibrary/" rel="nofollow noreferrer">OpenCV</a>. I am pretty sure he can too. However I would like to know:</p>
<ol>
<li>Has anyone already done this in C# and released the source code? Or a C# wrapper?</li>
<li>Are we barking up the wrong tree? (Should we just use CCV and forgo histogram comparisons at the database level? Or is CCV too much?)</li>
</ol>
|
[
{
"answer_id": 188722,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "<p>It does for C# (see code below) but not for C++.</p>\n\n<pre><code>using System;\n\nclass Test\n{\n Test()\n {\n throw new Exception();\n }\n\n ~Test()\n {\n Console.WriteLine(\"Finalized\");\n }\n\n static void Main()\n {\n try\n {\n new Test();\n }\n catch {}\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n}\n</code></pre>\n\n<p>This prints \"Finalized\"</p>\n"
},
{
"answer_id": 188728,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 1,
"selected": false,
"text": "<p>If the constructor doesn't finish executing, the object doesn't exist, so there's nothing to destruct. This is in C++, I have no idea about C#.</p>\n"
},
{
"answer_id": 188750,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>C++ -</p>\n\n<p>Nope. Destructor is not called for partially constructed objects. A Caveat: The destructor will be called for its member objects which are completely constructed. (Includes automatic objects, and native types)</p>\n\n<p>BTW - What you're really looking for is called \"Stack Unwinding\"</p>\n"
},
{
"answer_id": 188753,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 2,
"selected": false,
"text": "<p>In C++, the answer is no - object's destructor is <em>not</em> called.</p>\n\n<p>However, the destructors of any member data on the object <em>will</em> be called, unless the exception was thrown while constructing one of <em>them</em>. </p>\n\n<p>Member data in C++ is initialized (i.e. constructed) in the same order as it is declared, so when the constructor throws, all member data that has been initialized - either explicitly in the Member Initialization List (MIL) or otherwise - will be torn down again in reverse order.</p>\n"
},
{
"answer_id": 188762,
"author": "Robert Deml",
"author_id": 9516,
"author_profile": "https://Stackoverflow.com/users/9516",
"pm_score": 0,
"selected": false,
"text": "<p>Don't do things that cause exceptions in the constructor.</p>\n\n<p>Call an Initialize() after the constructor that can throw exceptions.</p>\n"
},
{
"answer_id": 188882,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 7,
"selected": true,
"text": "<p>Preamble: Herb Sutter has a great article on the subject:</p>\n<p><a href=\"http://herbsutter.wordpress.com/2008/07/25/constructor-exceptions-in-c-c-and-java/\" rel=\"noreferrer\">http://herbsutter.wordpress.com/2008/07/25/constructor-exceptions-in-c-c-and-java/</a></p>\n<h2>C++ : Yes and No</h2>\n<p>While an object destructor won't be called if its constructor throws (the object "never existed"), the destructors of its internal objects could be called.</p>\n<p>As a summary, every internal parts of the object (i.e. member objects) will have their destructors called in the reverse order of their construction. Every thing built inside the constructor won't have its destructor called unless RAII is used in some way.</p>\n<p>For example:</p>\n<pre><code>struct Class\n{\n Class() ;\n ~Class() ;\n \n Thing * m_pThing ;\n Object m_aObject ;\n Gizmo * m_pGizmo ;\n Data m_aData ;\n}\n\nClass::Class()\n{\n this->m_pThing = new Thing() ;\n this->m_pGizmo = new Gizmo() ;\n}\n</code></pre>\n<p>The order of creation will be:</p>\n<ol>\n<li>m_aObject will have its constructor called.</li>\n<li>m_aData will have its constructor called.</li>\n<li>Class constructor is called</li>\n<li>Inside Class constructor, m_pThing will have its new and then constructor called.</li>\n<li>Inside Class constructor, m_pGizmo will have its new and then constructor called.</li>\n</ol>\n<p>Let's say we are using the following code:</p>\n<pre><code>Class pClass = new Class() ;\n</code></pre>\n<p>Some possible cases:</p>\n<ul>\n<li><p>Should m_aData throw at construction, m_aObject will have its destructor called. Then, the memory allocated by "new Class" is deallocated.</p>\n</li>\n<li><p>Should m_pThing throw at new Thing (out of memory), m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated.</p>\n</li>\n<li><p>Should m_pThing throw at construction, the memory allocated by "new Thing" will be deallocated. Then m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated.</p>\n</li>\n<li><p>Should m_pGizmo throw at construction, the memory allocated by "new Gizmo" will be deallocated. Then m_aData, and then m_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated. <strong>Note that m_pThing leaked</strong></p>\n</li>\n</ul>\n<p>If you want to offer the Basic Exception Guarantee, you must not leak, even in the constructor. Thus, you'll have to write this this way (using STL, or even Boost):</p>\n<pre><code>struct Class\n{\n Class() ;\n ~Class() ;\n \n std::auto_ptr<Thing> m_pThing ;\n Object m_aObject ;\n std::auto_ptr<Gizmo> m_pGizmo ;\n Data m_aData ;\n}\n\nClass::Class()\n : m_pThing(new Thing())\n , m_pGizmo(new Gizmo())\n{\n}\n</code></pre>\n<p>Or even:</p>\n<pre><code>Class::Class()\n{\n this->m_pThing.reset(new Thing()) ;\n this->m_pGizmo.reset(new Gizmo()) ;\n}\n</code></pre>\n<p>if you want/need to create those objects inside the constructor.</p>\n<p>This way, no matter where the constructor throws, nothing will be leaked.</p>\n"
},
{
"answer_id": 188987,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 4,
"selected": false,
"text": "<p>The destructor of the class still being constructed is not called, because the object was never fully constructed.</p>\n\n<p>However, the destructor of its base class (if any) IS called, because the object was constructed as far as being a base class object.</p>\n\n<p>Moreover, any member variables will have their destructors called too (as others have noted).</p>\n\n<p>NB: this applies to C++</p>\n"
},
{
"answer_id": 189277,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 1,
"selected": false,
"text": "<p>For C++ this is addressed in a previous question: <a href=\"https://stackoverflow.com/questions/147572/will-the-below-code-cause-memory-leak-in-c\">Will the below code cause memory leak in c++</a></p>\n\n<p>Since in C++ when an exception is thrown in a constructor the destructor does not get called, but dtors for the object's members (that have been constructed) do get called, this is a primary reason to use smart pointer objects over raw pointers - they are a good way to prevent memory leaks in a situation like this.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5645/"
] |
A friend and I are about to embark on creating a machine that performs some image comparison for sorting. I know about histogram comparison and am generally confident that a small grid of histograms per image precalculated and stored in columns in a database table will generally give us pretty good matches on the first pass because we are matching like things.
The second comparison we want to perform is to use a [color coherence vector](http://tinyurl.com/4lo8nl) (CCV) of images which passed the histogram match test from our subject image to the candidate images. I know that this sort of comparison is more precise.
My friend is confident that he can develop CCV in C# using the [C# wrapper](http://www.codeproject.com/KB/cs/Intel_OpenCV.aspx) to [OpenCV](http://sourceforge.net/projects/opencvlibrary/). I am pretty sure he can too. However I would like to know:
1. Has anyone already done this in C# and released the source code? Or a C# wrapper?
2. Are we barking up the wrong tree? (Should we just use CCV and forgo histogram comparisons at the database level? Or is CCV too much?)
|
Preamble: Herb Sutter has a great article on the subject:
<http://herbsutter.wordpress.com/2008/07/25/constructor-exceptions-in-c-c-and-java/>
C++ : Yes and No
----------------
While an object destructor won't be called if its constructor throws (the object "never existed"), the destructors of its internal objects could be called.
As a summary, every internal parts of the object (i.e. member objects) will have their destructors called in the reverse order of their construction. Every thing built inside the constructor won't have its destructor called unless RAII is used in some way.
For example:
```
struct Class
{
Class() ;
~Class() ;
Thing * m_pThing ;
Object m_aObject ;
Gizmo * m_pGizmo ;
Data m_aData ;
}
Class::Class()
{
this->m_pThing = new Thing() ;
this->m_pGizmo = new Gizmo() ;
}
```
The order of creation will be:
1. m\_aObject will have its constructor called.
2. m\_aData will have its constructor called.
3. Class constructor is called
4. Inside Class constructor, m\_pThing will have its new and then constructor called.
5. Inside Class constructor, m\_pGizmo will have its new and then constructor called.
Let's say we are using the following code:
```
Class pClass = new Class() ;
```
Some possible cases:
* Should m\_aData throw at construction, m\_aObject will have its destructor called. Then, the memory allocated by "new Class" is deallocated.
* Should m\_pThing throw at new Thing (out of memory), m\_aData, and then m\_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated.
* Should m\_pThing throw at construction, the memory allocated by "new Thing" will be deallocated. Then m\_aData, and then m\_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated.
* Should m\_pGizmo throw at construction, the memory allocated by "new Gizmo" will be deallocated. Then m\_aData, and then m\_aObject will have their destructors called. Then, the memory allocated by new Class is deallocated. **Note that m\_pThing leaked**
If you want to offer the Basic Exception Guarantee, you must not leak, even in the constructor. Thus, you'll have to write this this way (using STL, or even Boost):
```
struct Class
{
Class() ;
~Class() ;
std::auto_ptr<Thing> m_pThing ;
Object m_aObject ;
std::auto_ptr<Gizmo> m_pGizmo ;
Data m_aData ;
}
Class::Class()
: m_pThing(new Thing())
, m_pGizmo(new Gizmo())
{
}
```
Or even:
```
Class::Class()
{
this->m_pThing.reset(new Thing()) ;
this->m_pGizmo.reset(new Gizmo()) ;
}
```
if you want/need to create those objects inside the constructor.
This way, no matter where the constructor throws, nothing will be leaked.
|
188,720 |
<p>Is there any way in the SQL language or in MySQL (or other DBMA) to transfer a value from one cell to another? For example, say there is a table called user_cars with the following structure:</p>
<pre><code>|id| |user_name| |num_cars|
</code></pre>
<p>Bob has 5 cars, and John has 3 cars. Is there any way to in one query subtract 2 cars from Bob and add 2 to John? I know this can be done with two update queries, but I'd just like to know if there was a more efficient way.</p>
|
[
{
"answer_id": 188744,
"author": "Thorsten",
"author_id": 25320,
"author_profile": "https://Stackoverflow.com/users/25320",
"pm_score": 1,
"selected": false,
"text": "<p>That's what transactions are for ...</p>\n"
},
{
"answer_id": 188747,
"author": "KernelM",
"author_id": 22328,
"author_profile": "https://Stackoverflow.com/users/22328",
"pm_score": 0,
"selected": false,
"text": "<p>If you really want to do it in one query, you can do an update on a self join of the table, but it's both less readable and probably less efficient.</p>\n"
},
{
"answer_id": 188756,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 3,
"selected": true,
"text": "<p>For Oracle you could do this. Don't know if there is an equivalent in mysql. Obviously this particular statement is very specific to the example you stated.</p>\n\n<pre><code> UPDATE user_cars\n SET num_cars = num_cars +\n CASE WHEN user_name='Bob' THEN -2\n WHEN user_name='John' THEN +2\n END\n WHERE user_name IN ( 'Bob', 'John' )\n</code></pre>\n"
},
{
"answer_id": 188764,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "<p>This will work, but it is not pleasant:</p>\n\n<pre><code>UPDATE USER_CARS UC\nSET\n NUM_CARS = NUM_CARS + CASE WHEN UC.USER_NAME = 'Bob'\n THEN -2 --take from bob\n WHEN UC.USER_NAME = 'John'\n THEN 2 --give to John\n ELSE 0 --no change for anybody else\n END\n</code></pre>\n"
},
{
"answer_id": 195412,
"author": "bjorsig",
"author_id": 27195,
"author_profile": "https://Stackoverflow.com/users/27195",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with Jonas Klemming, there isn´t a meaningful way of doing that. This is precisely what transactions were invented to do.</p>\n"
},
{
"answer_id": 197249,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 1,
"selected": false,
"text": "<p>As others have explained, you can do it with a CASE statement.<br>\nHowever, doing so is probably unwise, as it makes the intention of the code harder to see. This will make it harder for a subsequent programmer to understand the purpose of the code. </p>\n\n<p>Unless you have some specific reason for needing to do it in one statement, the best thing to do is to use 2 update statements, wrapping them in a transaction if required. </p>\n\n<p>I often recall this quotation (although I had to look up the attribution on <a href=\"http://en.wikiquote.org/wiki/Programming\" rel=\"nofollow noreferrer\">wikiquote</a>): </p>\n\n<p>\"Programs must be written for people to read, and only incidentally for machines to execute.\"\n - Abelson & Sussman, SICP, preface to the first edition</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26603/"
] |
Is there any way in the SQL language or in MySQL (or other DBMA) to transfer a value from one cell to another? For example, say there is a table called user\_cars with the following structure:
```
|id| |user_name| |num_cars|
```
Bob has 5 cars, and John has 3 cars. Is there any way to in one query subtract 2 cars from Bob and add 2 to John? I know this can be done with two update queries, but I'd just like to know if there was a more efficient way.
|
For Oracle you could do this. Don't know if there is an equivalent in mysql. Obviously this particular statement is very specific to the example you stated.
```
UPDATE user_cars
SET num_cars = num_cars +
CASE WHEN user_name='Bob' THEN -2
WHEN user_name='John' THEN +2
END
WHERE user_name IN ( 'Bob', 'John' )
```
|
188,738 |
<p>People keep giving me examples with carp instead of warn. Why? What makes carp better than warn?</p>
|
[
{
"answer_id": 188752,
"author": "jvasak",
"author_id": 5840,
"author_profile": "https://Stackoverflow.com/users/5840",
"pm_score": 4,
"selected": false,
"text": "<p>carp works better for debugging within modules. If you are only writing a simple script, there is no benefit. From <a href=\"http://perldoc.perl.org/Carp.html\" rel=\"noreferrer\">the Carp documenation</a>:</p>\n\n<blockquote>\n <p>The Carp routines are useful in your own modules because they act like die() or warn(), but with a message which is more likely to be useful to a user of your module. In the case of cluck, confess, and longmess that context is a summary of every call in the call-stack. For a shorter message you can use carp or croak which report the error as being from where your module was called. There is no guarantee that that is where the error was, but it is a good educated guess.</p>\n</blockquote>\n"
},
{
"answer_id": 188763,
"author": "derby",
"author_id": 11790,
"author_profile": "https://Stackoverflow.com/users/11790",
"pm_score": 6,
"selected": true,
"text": "<p>carp gives you more info as to where the message comes from (context)</p>\n\n<pre><code>#!/usr/bin/perl\n\nuse Carp;\n\nfoo();\nbar();\nbaz();\n\nsub foo {\n warn \"foo\";\n}\n\nsub bar {\n carp \"bar\";\n}\n\nsub baz {\n foo();\n bar(); \n}\n</code></pre>\n\n<p>produces</p>\n\n<pre><code>foo at ./foo.pl line 9.\nbar at ./foo.pl line 13\n main::bar() called at ./foo.pl line 6\nfoo at ./foo.pl line 10.\nbar at ./foo.pl line 14\n main::bar() called at ./foo.pl line 19\n main::baz() called at ./foo.pl line 7\n</code></pre>\n\n<p>kinda silly for this small program but comes in handy when you want to know who called the method that's carp'ing.</p>\n"
},
{
"answer_id": 188846,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 5,
"selected": false,
"text": "<p>I use <code>warn</code> for scripts and simple programs, and <code>Carp</code> inside any modules. The <code>Carp</code> subroutines use the filename and line number where your current subroutine was called so it's easier to find who's causing the problem (not just where the problem manifested itself).</p>\n\n<p>Damian recommends <code>Carp</code> instead of <code>warn</code> in \"Reporting Failure\" in <i>Perl Best Practices</i>, but doesn't make the distinction between scripts as top-level code constructs and modules as components that programs use.</p>\n\n<p>I've mostly not cared about that lately because I've been using <a href=\"http://search.cpan.org/dist/Log-Log4perl\" rel=\"noreferrer\">Log::Log4perl</a> to handle all of that.</p>\n"
},
{
"answer_id": 188920,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 3,
"selected": false,
"text": "<p><code>Carp</code> reports errors from the caller's perspective. This is useful for modules where you typically want to warn about incorrect usage (e.g. a missing argument) and identify the place where the error <em>occurred</em> as opposed to where it was <em>detected.</em> This is especially important for utility functions that might be used in many places.</p>\n\n<p>Most authors use <code>warn</code> in scripts and <code>carp</code> in modules. Occasionally I use <code>warn</code> inside a module when I want the error message to reflect a problem in the module's implementation (e.g. a case that it should support but doesn't.) It's arguable that <code>cluck</code> would be better in such situations as it provides a full stack backtrace.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
] |
People keep giving me examples with carp instead of warn. Why? What makes carp better than warn?
|
carp gives you more info as to where the message comes from (context)
```
#!/usr/bin/perl
use Carp;
foo();
bar();
baz();
sub foo {
warn "foo";
}
sub bar {
carp "bar";
}
sub baz {
foo();
bar();
}
```
produces
```
foo at ./foo.pl line 9.
bar at ./foo.pl line 13
main::bar() called at ./foo.pl line 6
foo at ./foo.pl line 10.
bar at ./foo.pl line 14
main::bar() called at ./foo.pl line 19
main::baz() called at ./foo.pl line 7
```
kinda silly for this small program but comes in handy when you want to know who called the method that's carp'ing.
|
188,769 |
<p>I'm trying to show someone a use for interfaces in a crazy situation they've created. They have several unrelated objects in lists, and need to perform an operation on two string properties in each object. I'm pointing out that if they define the properties as part of an interface, they can use the interface object as the type for a method parameter that acts on it; for example:</p>
<pre><code>void PrintProperties(IEnumerable<ISpecialProperties> list)
{
foreach (var item in list)
{
Console.WriteLine("{0} {1}", item.Prop1, item.Prop2);
}
}</code></pre>
<p>This seems like it's all good, but the lists that need to be worked on aren't (and shouldn't) be declared with the interface as the type parameter. However, it doesn't seem like you can cast to a different type parameter. For example, this fails and I can't understand why:</p>
<pre><code>using System;
using System.Collections.Generic;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<Test> myList = new List<Test>();
for (int i = 0; i < 5; i++)
{
myList.Add(new Test());
}
PrintList((IEnumerable<IDoSomething>)myList);
}
static void PrintList(IEnumerable<IDoSomething> list)
{
foreach (IDoSomething item in list)
{
item.DoSomething();
}
}
}
interface IDoSomething
{
void DoSomething();
}
public class Test : IDoSomething
{
public void DoSomething()
{
Console.WriteLine("Test did it!");
}
}
}</code></pre>
<p>I <em>can</em> use the <code>Enumerable.Cast<T></code> member to do this, but I was looking for a method that might work in .NET 2.0 as well. It seems like this should be possible; what am I missing? </p>
|
[
{
"answer_id": 188797,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": true,
"text": "<p>The problem is with the method, not with how it's called.....</p>\n\n<pre><code>void PrintProperties<SP>(IEnumerable<SP> list) where SP: ISpecialProperties\n{\n foreach (var item in list)\n {\n Console.WriteLine(\"{0} {1}\", item.Prop1, item.Prop2);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 188801,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>The reason it fails is because generics don't exhibit variance in C# (yet).</p>\n\n<p>As for the fix for IEnumerable<T>, however, try this:</p>\n\n<pre><code>public static IEnumerable<TBase> SafeConvert<TBase, TDerived>(IEnumerable<TDerived> source)\n where TDerived : TBase\n{\n foreach (TDerived element in source)\n {\n yield return element; // Implicit conversion to TBase\n }\n}\n</code></pre>\n\n<p>EDIT: The other existing answer is better than the above for this particular case, but I'll leave this here as a generally useful thing if you do actually need to \"convert\" the sequence.</p>\n"
},
{
"answer_id": 188812,
"author": "tpower",
"author_id": 18107,
"author_profile": "https://Stackoverflow.com/users/18107",
"pm_score": 1,
"selected": false,
"text": "<p>You can just use a <code>foreach</code> on the lists you have. The <code>foreach</code> does a built in cast. So if you take the loop out of the function you can write something like</p>\n\n<pre><code>List<Test> myList = new List<Test>();\nfor (int i = 0; i < 5; i++)\n{\n myList.Add(new Test());\n}\n\nforeach (IDoSomething item in myList)\n{\n item.DoSomething();\n}\n</code></pre>\n"
},
{
"answer_id": 188820,
"author": "Jeff Kotula",
"author_id": 1382162,
"author_profile": "https://Stackoverflow.com/users/1382162",
"pm_score": -1,
"selected": false,
"text": "<p>This doesn't answer your question (or the point of the exercise I guess :), but I'd just use reflection in this case by attaching special attributes to the properties of interest.</p>\n"
},
{
"answer_id": 189093,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 1,
"selected": false,
"text": "<p>What you want is called \"interface covariance\" and is not supported by C# at the moment. You can read about it on <a href=\"http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx\" rel=\"nofollow noreferrer\">Eric Lippert's blog</a>.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547/"
] |
I'm trying to show someone a use for interfaces in a crazy situation they've created. They have several unrelated objects in lists, and need to perform an operation on two string properties in each object. I'm pointing out that if they define the properties as part of an interface, they can use the interface object as the type for a method parameter that acts on it; for example:
```
void PrintProperties(IEnumerable<ISpecialProperties> list)
{
foreach (var item in list)
{
Console.WriteLine("{0} {1}", item.Prop1, item.Prop2);
}
}
```
This seems like it's all good, but the lists that need to be worked on aren't (and shouldn't) be declared with the interface as the type parameter. However, it doesn't seem like you can cast to a different type parameter. For example, this fails and I can't understand why:
```
using System;
using System.Collections.Generic;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<Test> myList = new List<Test>();
for (int i = 0; i < 5; i++)
{
myList.Add(new Test());
}
PrintList((IEnumerable<IDoSomething>)myList);
}
static void PrintList(IEnumerable<IDoSomething> list)
{
foreach (IDoSomething item in list)
{
item.DoSomething();
}
}
}
interface IDoSomething
{
void DoSomething();
}
public class Test : IDoSomething
{
public void DoSomething()
{
Console.WriteLine("Test did it!");
}
}
}
```
I *can* use the `Enumerable.Cast<T>` member to do this, but I was looking for a method that might work in .NET 2.0 as well. It seems like this should be possible; what am I missing?
|
The problem is with the method, not with how it's called.....
```
void PrintProperties<SP>(IEnumerable<SP> list) where SP: ISpecialProperties
{
foreach (var item in list)
{
Console.WriteLine("{0} {1}", item.Prop1, item.Prop2);
}
}
```
|
188,787 |
<p>I need to find occurrences of "(+)" in my sql scripts, (i.e., Oracle outer join expressions). Realizing that "+", "(", and ")" are all special regex characters, I tried:</p>
<pre>
grep "\(\+\)" *
</pre>
<p>Now this does return occurrences of "(+)", but other lines as well. (Seemingly anything with open and close parens on the same line.) Recalling that parens are only special for extended grep, I tried:</p>
<pre>
grep "(\+)" *
grep "(\\+)" *
</pre>
<p>Both of these returned only lines that contain "()". So assuming that "+" can't be escaped, I tried an old trick:</p>
<pre>
grep "([+])" *
</pre>
<p>That works. I cross-checked the result with a non-regex tool.</p>
<p><strong>Question</strong>: Can someone explain what exactly is going on with the "+" character? Is there a less kludgy way to match on "(+)"?</p>
<p>(I am using the cygwin grep command.)</p>
<p><strong>EDIT</strong>: Thanks for the solutions. -- And now I see that, per the GNU grep manual that Bruno referenced, "<code>\+</code>" when used in a <em>basic</em> expression gives "+" its <em>extended</em> meaning, and therefore matches one-or-more "("s followed by a ")". And in my files that's always "()".</p>
|
[
{
"answer_id": 188795,
"author": "KernelM",
"author_id": 22328,
"author_profile": "https://Stackoverflow.com/users/22328",
"pm_score": 1,
"selected": false,
"text": "<p>You probably need to add some backslashes because the shell is swallowing them.</p>\n\n<p>ETA: Actually, I just tried on my Cygwin and <code>grep \"(+)\"</code> seems to work just fine for what you want.</p>\n"
},
{
"answer_id": 188837,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 4,
"selected": true,
"text": "<p>GNU grep (which is included in Cygwin) supports two syntaxes for regular expressions: basic and extended. <code>grep</code> uses basic regular expressions and <code>egrep</code> or <code>grep -E</code> uses extended regular expressions. The basic difference, from the <a href=\"http://www.gnu.org/software/grep/doc/grep_12.html#SEC12\" rel=\"noreferrer\">grep manual</a>, is the following:</p>\n\n<blockquote>\n <p>In basic regular expressions the metacharacters <code>?</code>, <code>+</code>, <code>{</code>, <code>|</code>, <code>(</code>, and <code>)</code> lose their special meaning; instead use the backslashed versions <code>\\?</code>, <code>\\+</code>, <code>\\{</code>, <code>\\|</code>, <code>\\(</code>, and <code>\\)</code>.</p>\n</blockquote>\n\n<p>Since you want the <em>ordinary</em> meaning of the characters <code>(</code> <code>+</code> <code>)</code>, either of the following two forms should work for your purpose:</p>\n\n<pre><code>grep \"(+)\" * # Basic\negrep \"\\(\\+\\)\" * # Extended\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14749/"
] |
I need to find occurrences of "(+)" in my sql scripts, (i.e., Oracle outer join expressions). Realizing that "+", "(", and ")" are all special regex characters, I tried:
```
grep "\(\+\)" *
```
Now this does return occurrences of "(+)", but other lines as well. (Seemingly anything with open and close parens on the same line.) Recalling that parens are only special for extended grep, I tried:
```
grep "(\+)" *
grep "(\\+)" *
```
Both of these returned only lines that contain "()". So assuming that "+" can't be escaped, I tried an old trick:
```
grep "([+])" *
```
That works. I cross-checked the result with a non-regex tool.
**Question**: Can someone explain what exactly is going on with the "+" character? Is there a less kludgy way to match on "(+)"?
(I am using the cygwin grep command.)
**EDIT**: Thanks for the solutions. -- And now I see that, per the GNU grep manual that Bruno referenced, "`\+`" when used in a *basic* expression gives "+" its *extended* meaning, and therefore matches one-or-more "("s followed by a ")". And in my files that's always "()".
|
GNU grep (which is included in Cygwin) supports two syntaxes for regular expressions: basic and extended. `grep` uses basic regular expressions and `egrep` or `grep -E` uses extended regular expressions. The basic difference, from the [grep manual](http://www.gnu.org/software/grep/doc/grep_12.html#SEC12), is the following:
>
> In basic regular expressions the metacharacters `?`, `+`, `{`, `|`, `(`, and `)` lose their special meaning; instead use the backslashed versions `\?`, `\+`, `\{`, `\|`, `\(`, and `\)`.
>
>
>
Since you want the *ordinary* meaning of the characters `(` `+` `)`, either of the following two forms should work for your purpose:
```
grep "(+)" * # Basic
egrep "\(\+\)" * # Extended
```
|
188,793 |
<p>What I'm trying to do is encode a gif file, to include in an XML document.
This is what I have now, but it doesn't seem to work.</p>
<pre><code>Function gifToBase64(strGifFilename)
On Error Resume Next
Dim strBase64
Set inputStream = WScript.CreateObject("ADODB.Stream")
inputStream.LoadFromFile strGifFilename
strBase64 = inputStream.Text
Set inputStream = Nothing
gifToBase64 = strBase64
End Function
</code></pre>
|
[
{
"answer_id": 188807,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "<p>Take a look here: <a href=\"http://www.robvanderwoude.com/vbstech_files_encode_base64.html\" rel=\"nofollow noreferrer\">Base64 Encode & Decode Files with VBScript</a>. This example relies on the free <a href=\"http://www.xstandard.com/en/documentation/xbase64/\" rel=\"nofollow noreferrer\">XBase64 component</a> and merely provides a wrapper for file handling.</p>\n\n<p>You can also go for a <a href=\"http://www.motobit.com/tips/detpg_Base64Encode/\" rel=\"nofollow noreferrer\">pure VBScript implementation</a>, but here you have to care for the file handling yourself. Should not be too difficult, but encoding performance will be not as good. For a few small image files it will be enough, though.</p>\n\n<p>Google will turn up more.</p>\n"
},
{
"answer_id": 189340,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 1,
"selected": false,
"text": "<p>In your comment to Tomalak you state you don't want to use external dlls but in your attempted example you try to use ADODB. I suspect therefore what you mean is you don't want to install dlls that aren't natively present on a vanilia windows platform.</p>\n\n<p>If that is so then MSXML may be your answer:-</p>\n\n<pre><code>Function Base64Encode(rabyt)\n\n Dim dom: Set dom = CreateObject(\"MSXML2.DOMDocument.3.0\")\n Dim elem: Set elem = dom.appendChild(dom.createElement(\"root\"))\n elem.dataType = \"bin.base64\"\n elem.nodeTypedValue = rabyt\n\n Base64Encode = elem.Text\n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 19131358,
"author": "Chris West",
"author_id": 657132,
"author_profile": "https://Stackoverflow.com/users/657132",
"pm_score": 2,
"selected": false,
"text": "<p>I recently wrote a post about this very subject for implementations in <a href=\"http://cwestblog.com/2013/09/18/jscript-convert-image-to-base64/\" rel=\"nofollow\">JScript</a> and <a href=\"http://cwestblog.com/2013/09/23/vbscript-convert-image-to-base-64/\" rel=\"nofollow\">VBScript</a>. Here is the solution I have for VBScript:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Function convertImageToBase64(filePath)\n Dim inputStream\n Set inputStream = CreateObject(\"ADODB.Stream\")\n inputStream.Open\n inputStream.Type = 1 ' adTypeBinary\n inputStream.LoadFromFile filePath\n Dim bytes: bytes = inputStream.Read\n Dim dom: Set dom = CreateObject(\"Microsoft.XMLDOM\")\n Dim elem: Set elem = dom.createElement(\"tmp\")\n elem.dataType = \"bin.base64\"\n elem.nodeTypedValue = bytes\n convertImageToBase64 = \"data:image/png;base64,\" & Replace(elem.text, vbLf, \"\")\nEnd Function\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
What I'm trying to do is encode a gif file, to include in an XML document.
This is what I have now, but it doesn't seem to work.
```
Function gifToBase64(strGifFilename)
On Error Resume Next
Dim strBase64
Set inputStream = WScript.CreateObject("ADODB.Stream")
inputStream.LoadFromFile strGifFilename
strBase64 = inputStream.Text
Set inputStream = Nothing
gifToBase64 = strBase64
End Function
```
|
I recently wrote a post about this very subject for implementations in [JScript](http://cwestblog.com/2013/09/18/jscript-convert-image-to-base64/) and [VBScript](http://cwestblog.com/2013/09/23/vbscript-convert-image-to-base-64/). Here is the solution I have for VBScript:
```vb
Public Function convertImageToBase64(filePath)
Dim inputStream
Set inputStream = CreateObject("ADODB.Stream")
inputStream.Open
inputStream.Type = 1 ' adTypeBinary
inputStream.LoadFromFile filePath
Dim bytes: bytes = inputStream.Read
Dim dom: Set dom = CreateObject("Microsoft.XMLDOM")
Dim elem: Set elem = dom.createElement("tmp")
elem.dataType = "bin.base64"
elem.nodeTypedValue = bytes
convertImageToBase64 = "data:image/png;base64," & Replace(elem.text, vbLf, "")
End Function
```
|
188,808 |
<p>I have a Winform application built with C# and .Net 2.0. I have a textbox set with the MultiLine property.</p>
<p>The problem is when someone writes text with multiple lines (press few enters), presses the save button, and then closes and loads the form again, all the new lines disappear (the text is there at least).</p>
<p>For example, if the textbox had this in it:</p>
<pre><code>Line1
Line3
</code></pre>
<p>It will look like this after I save and load:</p>
<pre><code>Line1 Line3
</code></pre>
<p>Any idea why?</p>
<p><strong>Update</strong></p>
<p>The database is PostGres and when I use PGAdmin I can see all the line AND the "enters". So the persistence seem to have save all the line... the problem seem to be when I put back the string in the Textbox.</p>
|
[
{
"answer_id": 188838,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 3,
"selected": true,
"text": "<p>If I recall correctly, the textbox is really a string array.</p>\n\n<p>I think you can do this:</p>\n\n<pre><code>textBox1.Lines = foo.Split(new String[] {\"\\n\"},StringSplitOptions.RemoveEmptyEntries);\n</code></pre>\n\n<p>Edit again: If you want to keep the blank lines, the change to StringSplitOptions.None</p>\n"
},
{
"answer_id": 189053,
"author": "Wyatt",
"author_id": 26626,
"author_profile": "https://Stackoverflow.com/users/26626",
"pm_score": 0,
"selected": false,
"text": "<p>In Windows forms all carriage returns are preserved in a multiline text box, so the problem likely lies in the way data is retrieved from your database. I've never used PostGres, but I'm guessing that the way you're retrieving the text from the db is replacing all whitespace with single spaces.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
I have a Winform application built with C# and .Net 2.0. I have a textbox set with the MultiLine property.
The problem is when someone writes text with multiple lines (press few enters), presses the save button, and then closes and loads the form again, all the new lines disappear (the text is there at least).
For example, if the textbox had this in it:
```
Line1
Line3
```
It will look like this after I save and load:
```
Line1 Line3
```
Any idea why?
**Update**
The database is PostGres and when I use PGAdmin I can see all the line AND the "enters". So the persistence seem to have save all the line... the problem seem to be when I put back the string in the Textbox.
|
If I recall correctly, the textbox is really a string array.
I think you can do this:
```
textBox1.Lines = foo.Split(new String[] {"\n"},StringSplitOptions.RemoveEmptyEntries);
```
Edit again: If you want to keep the blank lines, the change to StringSplitOptions.None
|
188,828 |
<p>I've just learned ( yesterday ) to use "exists" instead of "in".</p>
<pre><code> BAD
select * from table where nameid in (
select nameid from othertable where otherdesc = 'SomeDesc' )
GOOD
select * from table t where exists (
select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeDesc' )
</code></pre>
<p>And I have some questions about this:</p>
<p>1) The explanation as I understood was: <em>"The reason why this is better is because only the matching values will be returned instead of building a massive list of possible results"</em>. Does that mean that while the first subquery might return 900 results the second will return only 1 ( yes or no )?</p>
<p>2) In the past I have had the RDBMS complainin: "only the first 1000 rows might be retrieved", this second approach would solve that problem?</p>
<p>3) What is the scope of the alias in the second subquery?... does the alias only lives in the parenthesis? </p>
<p>for example </p>
<pre><code> select * from table t where exists (
select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeDesc' )
AND
select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeOtherDesc' )
</code></pre>
<p>That is, if I use the same alias ( o for table othertable ) In the second "exist" will it present any problem with the first exists? or are they totally independent?</p>
<p>Is this something Oracle only related or it is valid for most RDBMS?</p>
<p>Thanks a lot</p>
|
[
{
"answer_id": 188849,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 3,
"selected": true,
"text": "<p>It's specific to each DBMS and depends on the query optimizer. Some optimizers detect IN clause and translate it. </p>\n\n<p>In all DBMSes I tested, alias is only valid inside the ( )</p>\n\n<p>BTW, you can rewrite the query as:</p>\n\n<pre><code>select t.* \nfrom table t \njoin othertable o on t.nameid = o.nameid \n and o.otherdesc in ('SomeDesc','SomeOtherDesc');\n</code></pre>\n\n<p>And, to answer your questions:</p>\n\n<ol>\n<li>Yes</li>\n<li>Yes</li>\n<li>Yes</li>\n</ol>\n"
},
{
"answer_id": 188851,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 1,
"selected": false,
"text": "<p>Personally I would use a join, rather than a subquery for this.</p>\n\n<pre><code>SELECT t.*\nFROM yourTable t\n INNER JOIN otherTable ot\n ON (t.nameid = ot.nameid AND ot.otherdesc = 'SomeDesc')\n</code></pre>\n"
},
{
"answer_id": 188899,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 2,
"selected": false,
"text": "<ol>\n<li>Oracle-specific: When you write a query using the IN clause, you're telling the rule-based optimizer that you want the inner query to drive the outer query. When you write EXISTS in a where clause, you're telling the optimizer that you want the outer query to be run first, using each value to fetch a value from the inner query. See <a href=\"https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5297080.html\" rel=\"nofollow noreferrer\">\"Difference between IN and EXISTS in subqueries\"</a>.</li>\n<li>Probably.</li>\n<li>Alias declared inside subquery lives inside subquery. By the way, I don't think your example with 2 ANDed subqueries is valid SQL. Did you mean UNION instead of AND?</li>\n</ol>\n"
},
{
"answer_id": 189259,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "<p>You are treading into complicated territory, known as 'correlated sub-queries'. Since we don't have detailed information about your tables and the key structures, some of the answers can only be 'maybe'.</p>\n\n<p>In your initial IN query, the notation would be valid whether or not OtherTable contains a column NameID (and, indeed, whether OtherDesc exists as a column in Table or OtherTable - which is not clear in any of your examples, but presumably is a column of OtherTable). This behaviour is what makes a correlated sub-query into a correlated sub-query. It is also a routine source of angst for people when they first run into it - invariably by accident. Since the SQL standard mandates the behaviour of interpreting a name in the sub-query as referring to a column in the outer query if there is no column with the relevant name in the tables mentioned in the sub-query but there is a column with the relevant name in the tables mentioned in the outer (main) query, no product that wants to claim conformance to (this bit of) the SQL standard will do anything different.</p>\n\n<p>The answer to your Q1 is \"it depends\", but given plausible assumptions (NameID exists as a column in both tables; OtherDesc only exists in OtherTable), the results should be the same in terms of the data set returned, but may not be equivalent in terms of performance.</p>\n\n<p>The answer to your Q2 is that in the past, you were using an inferior if not defective DBMS. If it supported EXISTS, then the DBMS might still complain about the cardinality of the result.</p>\n\n<p>The answer to your Q3 as applied to the first EXISTS query is \"t is available as an alias throughout the statement, but o is only available as an alias inside the parentheses\". As applied to your second example box - with AND connecting two sub-selects (the second of which is missing the open parenthesis when I'm looking at it), then \"t is available as an alias throughout the statement and refers to the same table, but there are two different aliases both labelled 'o', one for each sub-query\". Note that the query might return no data if OtherDesc is unique for a given NameID value in OtherTable; otherwise, it requires two rows in OtherTable with the same NameID and the two OtherDesc values for each row in Table with that NameID value.</p>\n"
},
{
"answer_id": 18349308,
"author": "user2607677",
"author_id": 2607677,
"author_profile": "https://Stackoverflow.com/users/2607677",
"pm_score": 1,
"selected": false,
"text": "<p>It is difficult to generalize that EXISTS is always better than IN. Logically if that is the case, then SQL community would have replaced IN with EXISTS... \nAlso, please note that IN and EXISTS are not same, the results may be different when you use the two...</p>\n\n<p>With IN, usually its a Full Table Scan of the inner table once without removing NULLs (so if you have NULLs in your inner table, IN will not remove NULLS by default)... While EXISTS removes NULL and in case of correlated subquery, it runs inner query for every row from outer query.</p>\n\n<p>Assuming there are no NULLS and its a simple query (with no correlation), EXIST might perform better if the row you are finding is not the last row. If it happens to be the last row, EXISTS may need to scan till the end like IN.. so similar performance...</p>\n\n<p>But IN and EXISTS are not interchangeable...</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20654/"
] |
I've just learned ( yesterday ) to use "exists" instead of "in".
```
BAD
select * from table where nameid in (
select nameid from othertable where otherdesc = 'SomeDesc' )
GOOD
select * from table t where exists (
select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeDesc' )
```
And I have some questions about this:
1) The explanation as I understood was: *"The reason why this is better is because only the matching values will be returned instead of building a massive list of possible results"*. Does that mean that while the first subquery might return 900 results the second will return only 1 ( yes or no )?
2) In the past I have had the RDBMS complainin: "only the first 1000 rows might be retrieved", this second approach would solve that problem?
3) What is the scope of the alias in the second subquery?... does the alias only lives in the parenthesis?
for example
```
select * from table t where exists (
select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeDesc' )
AND
select nameid from othertable o where t.nameid = o.nameid and otherdesc = 'SomeOtherDesc' )
```
That is, if I use the same alias ( o for table othertable ) In the second "exist" will it present any problem with the first exists? or are they totally independent?
Is this something Oracle only related or it is valid for most RDBMS?
Thanks a lot
|
It's specific to each DBMS and depends on the query optimizer. Some optimizers detect IN clause and translate it.
In all DBMSes I tested, alias is only valid inside the ( )
BTW, you can rewrite the query as:
```
select t.*
from table t
join othertable o on t.nameid = o.nameid
and o.otherdesc in ('SomeDesc','SomeOtherDesc');
```
And, to answer your questions:
1. Yes
2. Yes
3. Yes
|
188,833 |
<p>Why am I getting a textbox that returns undefined list of variables?</p>
<p>When I run this code:</p>
<pre><code>var query = (from tisa in db.TA_Info_Step_Archives
where tisa.ta_Serial.ToString().StartsWith(prefixText)
select tisa.TA_Serial.ToString()).Distinct().Take(Convert.ToInt32(count));
return query.ToList<string>().ToArray();
</code></pre>
<p>I get this XML file:</p>
<pre><code><string>200700160</string>
<string>200700161</string>
<string>200700162</string>
<string>200700163</string>
<string>200700164</string>
<string>200700170</string>
<string>200700171</string>
<string>200700172</string>
<string>200700173</string>
<string>200700174</string>
<string>200700175</string>
<string>200700176</string>
<string>200700177</string>
<string>200700178</string>
<string>200700179</string>
<string>200700180</string>
<string>200700181</string>
<string>200700182</string>
<string>200700183</string>
<string>200700184</string>
</code></pre>
<p>BUT, the textbox returns a list of <code>undefined</code>....</p>
<p>Help please?</p>
|
[
{
"answer_id": 188907,
"author": "ForCripeSake",
"author_id": 14833,
"author_profile": "https://Stackoverflow.com/users/14833",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds like the problem isn't with the method, but with the way you are hooking up the autocomplete to the method... Is your Extender similar to the following:</p>\n\n<pre><code><cc1:AutoCompleteExtender ID=\"Result\" runat=\"server\" TargetControlID=\"txtSearch\" ServiceMethod=\"YourMethodHere\"\n ServicePath=\"~/Service/YourWebServiceHere.asmx\" CompletionInterval=\"500\"\n EnableCaching=\"false\" CompletionListCssClass=\"AutoComplete_List\" CompletionSetCount=\"10\">\n</cc1:AutoCompleteExtender>\n</code></pre>\n"
},
{
"answer_id": 189089,
"author": "SpoiledTechie.com",
"author_id": 7644,
"author_profile": "https://Stackoverflow.com/users/7644",
"pm_score": 0,
"selected": false,
"text": "<p>The Problem that I am seeing is that the AJAX library is looking at the numbers as integers. It needs to be looking at them as strings.</p>\n\n<p>I have converted it to a string and still got nothing. I have to add some kind of character to the numbers to make their value now looked upon as a string. It is a horrible thing to do. But somewhere in the AJAX library for the autocomplete extender .js file, they don't look for integers. They only look for strings which needs to be looked at because their way of building is is flawed...</p>\n\n<p>Scott.</p>\n"
},
{
"answer_id": 255135,
"author": "Joel",
"author_id": 33235,
"author_profile": "https://Stackoverflow.com/users/33235",
"pm_score": 0,
"selected": false,
"text": "<p>I've run into the same issue. I agree the issue definitely seems to be stemming around that we're using numbers here. As soon as I append an alpha to the end of a array item it works.\nI believe we've found a bug.</p>\n\n<p>this kicks out the undefineds....</p>\n\n<pre><code>...\nda.Fill(dt);\n string[] items = new string[dt.Rows.Count];\n int i = 0;\n foreach (DataRow dr in dt.Rows)\n {\n items.SetValue(Convert.ToString(dr[\"somenumber\"]), i);\n i++;\n }\n...\n</code></pre>\n\n<p>where as this loads the list just fine </p>\n\n<pre><code>...\nda.Fill(dt);\n string[] items = new string[dt.Rows.Count];\n int i = 0;\n foreach (DataRow dr in dt.Rows)\n {\n items.SetValue(Convert.ToString(dr[\"somenumber\"]+\"foo\"), i);\n i++;\n }\n...\n</code></pre>\n\n<p>Seems like a bug to me.</p>\n"
},
{
"answer_id": 259268,
"author": "Joel",
"author_id": 33235,
"author_profile": "https://Stackoverflow.com/users/33235",
"pm_score": 3,
"selected": true,
"text": "<p>updated my ajax kit to version 1.0.10920 then changed my code to the following:</p>\n\n<pre><code> foreach (DataRow dr in dt.Rows)\n {\n items.SetValue(\"\\\"\" + dr[\"somenumber\"].ToString() + \"\\\"\", i);\n i++;\n }\n</code></pre>\n\n<p>Late friday nights with .net is not fun. I have no life. :-P</p>\n"
},
{
"answer_id": 771504,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I tried the code below and it worked for me:</p>\n\n<pre><code>items.SetValue(\"'\"+dr[\"somenumber\"]+\"'\", i);\n</code></pre>\n"
},
{
"answer_id": 5577186,
"author": "daniela_b",
"author_id": 696252,
"author_profile": "https://Stackoverflow.com/users/696252",
"pm_score": 0,
"selected": false,
"text": "<p>There is a difference between toolkit dll versions.</p>\n\n<p>In the updated version, one does not need to insert the \"'\"+ +\"'\", and it works fine. In version 1.0.10920, it is needed.</p>\n"
},
{
"answer_id": 17292171,
"author": "Santosh S Pawar",
"author_id": 2519122,
"author_profile": "https://Stackoverflow.com/users/2519122",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.asp.net/ajax\" rel=\"nofollow\">http://www.asp.net/ajax</a>\nIn this above link u will find AjaxControllToolkit just download it and add reference in ur application i am sure it will work fine. problem is u r working with very old AjaxControllToolkit so its not working ,work with AjaxControllToolkit 3.5 or 4.0.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7644/"
] |
Why am I getting a textbox that returns undefined list of variables?
When I run this code:
```
var query = (from tisa in db.TA_Info_Step_Archives
where tisa.ta_Serial.ToString().StartsWith(prefixText)
select tisa.TA_Serial.ToString()).Distinct().Take(Convert.ToInt32(count));
return query.ToList<string>().ToArray();
```
I get this XML file:
```
<string>200700160</string>
<string>200700161</string>
<string>200700162</string>
<string>200700163</string>
<string>200700164</string>
<string>200700170</string>
<string>200700171</string>
<string>200700172</string>
<string>200700173</string>
<string>200700174</string>
<string>200700175</string>
<string>200700176</string>
<string>200700177</string>
<string>200700178</string>
<string>200700179</string>
<string>200700180</string>
<string>200700181</string>
<string>200700182</string>
<string>200700183</string>
<string>200700184</string>
```
BUT, the textbox returns a list of `undefined`....
Help please?
|
updated my ajax kit to version 1.0.10920 then changed my code to the following:
```
foreach (DataRow dr in dt.Rows)
{
items.SetValue("\"" + dr["somenumber"].ToString() + "\"", i);
i++;
}
```
Late friday nights with .net is not fun. I have no life. :-P
|
188,834 |
<p>I need to dynamically construct an XPath query for an element attribute, where the attribute value is provided by the user. I'm unsure how to go about cleaning or sanitizing this value to prevent the XPath equivalent of a SQL injection attack. For example (in PHP):</p>
<pre><code><?php
function xPathQuery($attr) {
$xml = simplexml_load_file('example.xml');
return $xml->xpath("//myElement[@content='{$attr}']");
}
xPathQuery('This should work fine');
# //myElement[@content='This should work fine']
xPathQuery('As should "this"');
# //myElement[@content='As should "this"']
xPathQuery('This\'ll cause problems');
# //myElement[@content='This'll cause problems']
xPathQuery('\']/../privateElement[@content=\'private data');
# //myElement[@content='']/../privateElement[@content='private data']
</code></pre>
<p>The last one in particular is reminiscent to the SQL injection attacks of yore.</p>
<p>Now, I know for a fact there will be attributes containing single quotes and attributes containing double quotes. Since these are provided as an argument to a function, what would be the ideal way to sanitize the input for these?</p>
|
[
{
"answer_id": 188858,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": -1,
"selected": false,
"text": "<pre><code>function xPathQuery($attr) {\n $xml = simplexml_load_file('example.xml');\n $to_encode = array('&', '\"');\n $to_replace = array('&amp;','&quot;');\n $attr = replace($to_encode, $to_replace, $attr);\n return $xml->xpath(\"//myElement[@content=\\\"{$attr}\\\"]\");\n}\n</code></pre>\n\n<p>Ok, what does it do?</p>\n\n<p>It encodes all occurences of & and \" as &amp; and &quot; in the string, which should give you a safe selector for that particular use. Note that I also replaced the inner ' in the xpath with \". EDIT: It has since been pointed out that ' can be escaped as &apos;, so you could use whichever string quoting method you prefer.</p>\n"
},
{
"answer_id": 188989,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": -1,
"selected": false,
"text": "<p>I'd create a single-element XML document using a DOM, use the DOM to set the element's text to the provided value, and then grab the text out of the DOM's string representation of the XML. This will guarantee that all of the character escaping is done properly, and not just the character escaping that I'm happening to think about offhand.</p>\n\n<p>Edit: The reason I would use the DOM in situations like this is that the people who wrote the DOM have read the XML recommendation and I haven't (at least, not with the level of care they have). To pick a trivial example, the DOM will report a parse error if the text contains a character that XML doesn't allow (like #x8), because the DOM's authors have implemented section 2.2 of the XML recommendation.</p>\n\n<p>Now, I might say, \"well, I'll just get the list of invalid characters from the XML recommendation, and strip them out of the input.\" Sure. Let's just look the XML recommendation and...um, what the heck are the Unicode surrogate blocks? What kind of code do I have to write to get rid of them? Can they even get into my text in the first place?</p>\n\n<p>Let's suppose I figure that out. Are there other aspects of how the XML recommendation specifies character representations that I don't know about? Probably. Will these have an impact on what I'm trying to implement? Maybe.</p>\n\n<p>If I let the DOM do the character encoding for me, I don't have to worry about any of that stuff.</p>\n"
},
{
"answer_id": 194071,
"author": "gz.",
"author_id": 3665,
"author_profile": "https://Stackoverflow.com/users/3665",
"pm_score": 3,
"selected": false,
"text": "<p>XPath does actually include a method of doing this safely, in that it permits <a href=\"http://www.w3.org/TR/xpath#section-Expressions\" rel=\"noreferrer\">variable references</a> in the form <code>$varname</code> in expressions. The library on which PHP's SimpleXML is based <a href=\"http://xmlsoft.org/html/libxml-xpathInternals.html#xmlXPathRegisterVariable\" rel=\"noreferrer\">provides an interface to supply variables</a>, however this <a href=\"http://php.net/manual/en/function.simplexml-element-xpath.php\" rel=\"noreferrer\">is not exposed by the xpath function</a> in your example.</p>\n\n<p>As a demonstration of really how simple this can be:</p>\n\n<pre><code>>>> from lxml import etree\n>>> n = etree.fromstring('<n a=\\'He said \"I&apos;m here\"\\'/>')\n>>> n.xpath(\"@a=$maybeunsafe\", maybeunsafe='He said \"I\\'m here\"')\nTrue\n</code></pre>\n\n<p>That's using <a href=\"http://codespeak.net/lxml/\" rel=\"noreferrer\">lxml</a>, a python wrapper for the same underlying library as SimpleXML, with a similar <a href=\"http://codespeak.net/lxml/xpathxslt.html#the-xpath-method\" rel=\"noreferrer\">xpath function</a>. Booleans, numbers, and node-sets can also be passed directly.</p>\n\n<p>If switching to a more capable XPath interface is not an option, a workaround when given external string would be something (feel free to adapt to PHP) along the lines of:</p>\n\n<pre><code>def safe_xpath_string(strvar):\n if \"'\" in strvar:\n return \"',\\\"'\\\",'\".join(strvar.split(\"'\")).join((\"concat('\",\"')\"))\n return strvar.join(\"''\")\n</code></pre>\n\n<p>The return value can be directly inserted in your expression string. As that's not actually very readable, here is how it behaves:</p>\n\n<pre><code>>>> print safe_xpath_string(\"basic\")\n'basic'\n>>> print safe_xpath_string('He said \"I\\'m here\"')\nconcat('He said \"I',\"'\",'m here\"')\n</code></pre>\n\n<p>Note, you can't use escaping in the form <code>&apos;</code> outside of an XML document, nor are generic XML serialisation routines applicable. However, the XPath concat function can be used to create a string with both types of quotes in any context.</p>\n\n<p>PHP variant:</p>\n\n<pre><code>function safe_xpath_string($value)\n{\n $quote = \"'\";\n if (FALSE === strpos($value, $quote))\n return $quote.$value.$quote;\n else\n return sprintf(\"concat('%s')\", implode(\"', \\\"'\\\", '\", explode($quote, $value)));\n}\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I need to dynamically construct an XPath query for an element attribute, where the attribute value is provided by the user. I'm unsure how to go about cleaning or sanitizing this value to prevent the XPath equivalent of a SQL injection attack. For example (in PHP):
```
<?php
function xPathQuery($attr) {
$xml = simplexml_load_file('example.xml');
return $xml->xpath("//myElement[@content='{$attr}']");
}
xPathQuery('This should work fine');
# //myElement[@content='This should work fine']
xPathQuery('As should "this"');
# //myElement[@content='As should "this"']
xPathQuery('This\'ll cause problems');
# //myElement[@content='This'll cause problems']
xPathQuery('\']/../privateElement[@content=\'private data');
# //myElement[@content='']/../privateElement[@content='private data']
```
The last one in particular is reminiscent to the SQL injection attacks of yore.
Now, I know for a fact there will be attributes containing single quotes and attributes containing double quotes. Since these are provided as an argument to a function, what would be the ideal way to sanitize the input for these?
|
XPath does actually include a method of doing this safely, in that it permits [variable references](http://www.w3.org/TR/xpath#section-Expressions) in the form `$varname` in expressions. The library on which PHP's SimpleXML is based [provides an interface to supply variables](http://xmlsoft.org/html/libxml-xpathInternals.html#xmlXPathRegisterVariable), however this [is not exposed by the xpath function](http://php.net/manual/en/function.simplexml-element-xpath.php) in your example.
As a demonstration of really how simple this can be:
```
>>> from lxml import etree
>>> n = etree.fromstring('<n a=\'He said "I'm here"\'/>')
>>> n.xpath("@a=$maybeunsafe", maybeunsafe='He said "I\'m here"')
True
```
That's using [lxml](http://codespeak.net/lxml/), a python wrapper for the same underlying library as SimpleXML, with a similar [xpath function](http://codespeak.net/lxml/xpathxslt.html#the-xpath-method). Booleans, numbers, and node-sets can also be passed directly.
If switching to a more capable XPath interface is not an option, a workaround when given external string would be something (feel free to adapt to PHP) along the lines of:
```
def safe_xpath_string(strvar):
if "'" in strvar:
return "',\"'\",'".join(strvar.split("'")).join(("concat('","')"))
return strvar.join("''")
```
The return value can be directly inserted in your expression string. As that's not actually very readable, here is how it behaves:
```
>>> print safe_xpath_string("basic")
'basic'
>>> print safe_xpath_string('He said "I\'m here"')
concat('He said "I',"'",'m here"')
```
Note, you can't use escaping in the form `'` outside of an XML document, nor are generic XML serialisation routines applicable. However, the XPath concat function can be used to create a string with both types of quotes in any context.
PHP variant:
```
function safe_xpath_string($value)
{
$quote = "'";
if (FALSE === strpos($value, $quote))
return $quote.$value.$quote;
else
return sprintf("concat('%s')", implode("', \"'\", '", explode($quote, $value)));
}
```
|
188,839 |
<p>I use a structure of function pointers to implement an interface for different backends. The signatures are very different, but the return values are almost all void, void * or int.</p>
<pre><code>
struct my_interface {
void (*func_a)(int i);
void *(*func_b)(const char *bla);
...
int (*func_z)(char foo);
};
</code></pre>
<p>But it is not required that a backends supports functions for every interface function. So I have two possibilities, first option is to check before every call if the pointer is unequal NULL. I don't like that very much, because of the readability and because I fear the performance impacts (I haven't measured it, however). The other option is to have a dummy function, for the rare cases an interface function doesn't exist.</p>
<p>Therefore I'd need a dummy function for every signature, I wonder if it is possible to have only one for the different return values. And cast it to the given signature.</p>
<pre><code>
#include <stdio.h>
int nothing(void) {return 0;}
typedef int (*cb_t)(int);
int main(void)
{
cb_t func;
int i;
func = (cb_t) nothing;
i = func(1);
printf("%d\n", i);
return 0;
}
</code></pre>
<p>I tested this code with gcc and it works. But is it sane? Or can it corrupt the stack or can it cause other problems?</p>
<p>EDIT: Thanks to all the answers, I learned now much about calling conventions, after a bit of further reading. And have now a much better understanding of what happens under the hood.</p>
|
[
{
"answer_id": 188855,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 0,
"selected": false,
"text": "<p>It should be fine. Since the caller is responsible for cleaning up the stack after a call, it shouldn't leave anything extra on the stack. The callee (nothing() in this case) is ok since it wont try to use any parameters on the stack.</p>\n\n<p>EDIT: this does assume cdecl calling conventions, which is usually the default for C.</p>\n"
},
{
"answer_id": 188860,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "<p>You do run the risk of causing stack corruption. Having said that, if you declare the functions with <code>extern \"C\"</code> linkage (and/or <code>__cdecl</code> depending on your compiler), you <em>may</em> be able to get away with this. It would be similar then to the way a function such as <code>printf()</code> can take a variable number of arguments at the caller's discretion.</p>\n\n<p>Whether this works or not in your current situation may also depend on the exact compiler options you are using. If you're using MSVC, then debug vs. release compile options may make a big difference.</p>\n"
},
{
"answer_id": 188905,
"author": "Remo.D",
"author_id": 16827,
"author_profile": "https://Stackoverflow.com/users/16827",
"pm_score": 2,
"selected": false,
"text": "<p>I suspect you will get an undefined behaviour.</p>\n\n<p>You can assign (with the proper cast) a pointer to function to another pointer to function with a different signature, but when you call it weird things may happen.</p>\n\n<p>Your <code>nothing()</code> function takes no arguments, to the compiler this may mean that he can optimize the usage of the stack as there will be no arguments there. But here you call it with an argument, that is an unexpected situation and it may crash.</p>\n\n<p>I can't find the proper point in the standard but I remember it says that you can cast function pointers but when you call the resulting function you have to do with the right prototype otherwise the behaviour is undefined.</p>\n\n<p>As a side note, you should not compare a function pointer with a data pointer (like NULL) as thee pointers may belong to separate address spaces. There's an appendix in the C99 standard that allows this specific case but I don't think it's widely implemented. That said, on architecture where there is only one address space casting a function pointer to a data pointer or comparing it with NULL, will usually work.</p>\n"
},
{
"answer_id": 188909,
"author": "Jeff Mc",
"author_id": 25521,
"author_profile": "https://Stackoverflow.com/users/25521",
"pm_score": 0,
"selected": false,
"text": "<p>As long as you can guarantee that you're making a call using a method that has the caller balance the stack rather than the callee (__cdecl). If you don't have a calling convention specified the global convention could be set to something else. (__stdcall or __fastcall) Both of which could lead to stack corruption.</p>\n"
},
{
"answer_id": 189126,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 5,
"selected": true,
"text": "<p>By the C specification, casting a function pointer results in undefined behavior. In fact, for a while, GCC 4.3 prereleases would return NULL whenever you casted a function pointer, perfectly valid by the spec, but they backed out that change before release because it broke lots of programs.</p>\n\n<p>Assuming GCC continues doing what it does now, it will work fine with the default x86 calling convention (and most calling conventions on most architectures), but I wouldn't depend on it. Testing the function pointer against NULL at every callsite isn't much more expensive than a function call. If you really want, you may write a macro:</p>\n\n<pre>#define CALL_MAYBE(func, args...) do {if (func) (func)(## args);} while (0)</pre>\n\n<p>Or you could have a different dummy function for every signature, but I can understand that you'd like to avoid that.</p>\n\n<h2>Edit</h2>\n\n<p>Charles Bailey called me out on this, so I went and looked up the details (instead of relying on my holey memory). The <a href=\"http://c0x.coding-guidelines.com/6.3.2.3.html\" rel=\"noreferrer\">C specification</a> says</p>\n\n<blockquote>\n <p>766 A pointer to a function of one type may be converted to a pointer to a function of another type and back again;<br>\n 767 the result shall compare equal to the original pointer.<br>\n 768 If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.</p>\n</blockquote>\n\n<p>and GCC 4.2 prereleases (this was settled way before 4.3) was following these rules: the cast of a function pointer did not result in NULL, as I wrote, but attempting to call a function through a incompatible type, i.e.</p>\n\n<pre><code>func = (cb_t)nothing;\nfunc(1);\n</code></pre>\n\n<p>from your example, would result in an <code>abort</code>. They changed back to the 4.1 behavior (allow but warn), partly because this change broke OpenSSL, but OpenSSL has been fixed in the meantime, and this is undefined behavior which the compiler is free to change at any time.</p>\n\n<p>OpenSSL was only casting functions pointers to other function types taking and returning the same number of values of the same exact sizes, and this (assuming you're not dealing with floating-point) happens to be safe across all the platforms and calling conventions I know of. However, anything else is potentially unsafe.</p>\n"
},
{
"answer_id": 189196,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 0,
"selected": false,
"text": "<p>This won't work unless you use implementation-specific/platform-specific stuff to force the correct calling convention. For some calling conventions the called function is responsible for cleaning up the stack, so they must know what's been pushed on.</p>\n\n<p>I'd go for the check for NULL then call - I can't imagine it would have any impact on performance. </p>\n\n<p>Computers can check for NULL about as fast as anything they do.</p>\n"
},
{
"answer_id": 345689,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": -1,
"selected": false,
"text": "<p>Casting a function pointer to NULL is explicitly not supported by the C standard. You're at the mercy of the compiler writer. It works OK on a lot of compilers.</p>\n\n<p>It is one of the great annoyances of C that there is no equivalent of NULL or void* for function pointers.</p>\n\n<p>If you really want your code to be bulletproof, you can declare your own nulls, but you need one for each function type. For example, </p>\n\n<pre><code>void void_int_NULL(int n) { (void)n; abort(); }\n</code></pre>\n\n<p>and then you can test</p>\n\n<pre><code>if (my_thing->func_a != void_int_NULL) my_thing->func_a(99);\n</code></pre>\n\n<p>Ugly, innit?</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18687/"
] |
I use a structure of function pointers to implement an interface for different backends. The signatures are very different, but the return values are almost all void, void \* or int.
```
struct my_interface {
void (*func_a)(int i);
void *(*func_b)(const char *bla);
...
int (*func_z)(char foo);
};
```
But it is not required that a backends supports functions for every interface function. So I have two possibilities, first option is to check before every call if the pointer is unequal NULL. I don't like that very much, because of the readability and because I fear the performance impacts (I haven't measured it, however). The other option is to have a dummy function, for the rare cases an interface function doesn't exist.
Therefore I'd need a dummy function for every signature, I wonder if it is possible to have only one for the different return values. And cast it to the given signature.
```
#include <stdio.h>
int nothing(void) {return 0;}
typedef int (*cb_t)(int);
int main(void)
{
cb_t func;
int i;
func = (cb_t) nothing;
i = func(1);
printf("%d\n", i);
return 0;
}
```
I tested this code with gcc and it works. But is it sane? Or can it corrupt the stack or can it cause other problems?
EDIT: Thanks to all the answers, I learned now much about calling conventions, after a bit of further reading. And have now a much better understanding of what happens under the hood.
|
By the C specification, casting a function pointer results in undefined behavior. In fact, for a while, GCC 4.3 prereleases would return NULL whenever you casted a function pointer, perfectly valid by the spec, but they backed out that change before release because it broke lots of programs.
Assuming GCC continues doing what it does now, it will work fine with the default x86 calling convention (and most calling conventions on most architectures), but I wouldn't depend on it. Testing the function pointer against NULL at every callsite isn't much more expensive than a function call. If you really want, you may write a macro:
```
#define CALL_MAYBE(func, args...) do {if (func) (func)(## args);} while (0)
```
Or you could have a different dummy function for every signature, but I can understand that you'd like to avoid that.
Edit
----
Charles Bailey called me out on this, so I went and looked up the details (instead of relying on my holey memory). The [C specification](http://c0x.coding-guidelines.com/6.3.2.3.html) says
>
> 766 A pointer to a function of one type may be converted to a pointer to a function of another type and back again;
>
> 767 the result shall compare equal to the original pointer.
>
> 768 If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.
>
>
>
and GCC 4.2 prereleases (this was settled way before 4.3) was following these rules: the cast of a function pointer did not result in NULL, as I wrote, but attempting to call a function through a incompatible type, i.e.
```
func = (cb_t)nothing;
func(1);
```
from your example, would result in an `abort`. They changed back to the 4.1 behavior (allow but warn), partly because this change broke OpenSSL, but OpenSSL has been fixed in the meantime, and this is undefined behavior which the compiler is free to change at any time.
OpenSSL was only casting functions pointers to other function types taking and returning the same number of values of the same exact sizes, and this (assuming you're not dealing with floating-point) happens to be safe across all the platforms and calling conventions I know of. However, anything else is potentially unsafe.
|
188,850 |
<p>I would like a batch file to launch two separate programs then have the command line window close. Actually, to clarify, I am launching Internet Explorer with two different URLs.</p>
<p>So far I have something like this:</p>
<pre><code>start "~\iexplore.exe" "url1"
start "~\iexplore.exe" "url2"
</code></pre>
<p>What I get is one instance of Internet Explorer with only the second URL loaded. Seems the second is replacing the second. I seem to remember a syntax where I would load a new command line window and pass the command to execute on load, but can't find the reference.</p>
<p>As a second part of the question: what is a good reference URL to keep for the times you need to write a quick batch file?</p>
<p>Edit: I have marked an answer, because it does work. I now have two windows open, one for each URL. (thanks!) The funny thing is that without the /d approach using my original syntax I get different results based on whether I have a pre-existing Internet Explorer instance open. </p>
<ul>
<li>If I do I get two new tabs added for
my two URLs (sweet!) </li>
<li>If not I get only one final tab for the second URL I passed in.</li>
</ul>
|
[
{
"answer_id": 188914,
"author": "Daniel Plaisted",
"author_id": 1509,
"author_profile": "https://Stackoverflow.com/users/1509",
"pm_score": 0,
"selected": false,
"text": "<p>There is a setting in the IE options that controls whether it should open new links in an existing window or in a new window. I'm not sure if you can control it from the command line but maybe changing this option would be enough for you.</p>\n\n<p>In IE7 it looks like the option is \"Reuse windows for launching shortcuts (when tabbed browsing is disabled)\".</p>\n"
},
{
"answer_id": 188930,
"author": "Rodger Cooley",
"author_id": 5667,
"author_profile": "https://Stackoverflow.com/users/5667",
"pm_score": 6,
"selected": true,
"text": "<p>Try this in your batch file:</p>\n\n<pre><code>@echo off\nstart /d \"C:\\Program Files\\Internet Explorer\" IEXPLORE.EXE www.google.com\nstart /d \"C:\\Program Files\\Internet Explorer\" IEXPLORE.EXE www.yahoo.com\n</code></pre>\n"
},
{
"answer_id": 1314704,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks for the tip Rodger.</p>\n\n<p>For me it worked as below:</p>\n\n<pre><code>@echo off\n\nstart /d \"\" IEXPLORE.EXE www.google.com\n\nstart /d \"\" IEXPLORE.EXE www.yahoo.com\n</code></pre>\n\n<p>With the settings in Internet Explorer 8:</p>\n\n<ul>\n<li>always open popups in a new tab</li>\n<li>a new tab in the current window</li>\n</ul>\n\n<p>[email protected]</p>\n"
},
{
"answer_id": 2683332,
"author": "Sam M",
"author_id": 322330,
"author_profile": "https://Stackoverflow.com/users/322330",
"pm_score": 1,
"selected": false,
"text": "<p>This worked for me:</p>\n\n<pre><code>start /d IEXPLORE.EXE www.google.com\nstart /d IEXPLORE.EXE www.yahoo.com\n</code></pre>\n\n<p>But for some reason opened them up in Firefox instead?!?</p>\n\n<p>I tried this but it merely opened up sites in two different windows:</p>\n\n<pre><code>start /d \"C:\\Program Files\\Internet Explorer\" IEXPLORE.EXE www.google.com\nstart /d \"C:\\Program Files\\Internet Explorer\" IEXPLORE.EXE www.yahoo.com\n</code></pre>\n"
},
{
"answer_id": 3689762,
"author": "Marcelo",
"author_id": 444926,
"author_profile": "https://Stackoverflow.com/users/444926",
"pm_score": 0,
"selected": false,
"text": "<p>Try this so you allow enough time for the first process to start.. else it will spawn 2 processes because the first one is not still running when you run the second one...\nThis can happen if your computer is too fast..</p>\n\n<pre><code>@echo off\nstart /d iexplore.exe http://google.com\nPING 1.1.1.1 -n 1 -w 2000 >NUL\nSTART /d iexplore.exe blablabla\n</code></pre>\n\n<p>replace blablabla with another address</p>\n"
},
{
"answer_id": 3990606,
"author": "Emi",
"author_id": 483380,
"author_profile": "https://Stackoverflow.com/users/483380",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks Marcelo. This worked for me. I wanted to open a new IE Window and open two tabs in that so I modified the code:</p>\n\n<pre><code>start iexplore.exe website\nPING 1.1.1.1 -n 1 -w 2000 >NUL \nSTART /d iexplore.exe website\n</code></pre>\n"
},
{
"answer_id": 25169091,
"author": "Kevin Fegan",
"author_id": 606539,
"author_profile": "https://Stackoverflow.com/users/606539",
"pm_score": 3,
"selected": false,
"text": "<p>You can use either of these two scripts to open the URLs in separate tabs in a (single) new IE window. You can call either of these scripts from within your batch script (or at the command prompt):</p>\n\n<p><strong>JavaScript</strong><br>\nCreate a file with a name like: <strong>\"urls.js\"</strong>: </p>\n\n<pre><code>var navOpenInNewWindow = 0x1;\nvar navOpenInNewTab = 0x800;\nvar navOpenInBackgroundTab = 0x1000;\n\nvar intLoop = 0;\nvar intArrUBound = 0;\nvar navFlags = navOpenInBackgroundTab;\nvar arrstrUrl = new Array(3);\nvar objIE;\n\n intArrUBound = arrstrUrl.length;\n\n arrstrUrl[0] = \"http://bing.com/\";\n arrstrUrl[1] = \"http://google.com/\";\n arrstrUrl[2] = \"http://msn.com/\";\n arrstrUrl[3] = \"http://yahoo.com/\";\n\n objIE = new ActiveXObject(\"InternetExplorer.Application\");\n objIE.Navigate2(arrstrUrl[0]);\n\n for (intLoop=1;intLoop<=intArrUBound;intLoop++) {\n\n objIE.Navigate2(arrstrUrl[intLoop], navFlags);\n\n }\n\n objIE.Visible = true;\n objIE = null;\n</code></pre>\n\n<p><br />\n<strong>VB Script</strong><br>\nCreate a file with a name like: <strong>\"urls.vbs\"</strong>: </p>\n\n<pre><code>Option Explicit\n\nConst navOpenInNewWindow = &h1\nConst navOpenInNewTab = &h800\nConst navOpenInBackgroundTab = &h1000\n\nDim intLoop : intLoop = 0\nDim intArrUBound : intArrUBound = 0\nDim navFlags : navFlags = navOpenInBackgroundTab\n\nDim arrstrUrl(3)\nDim objIE\n\n intArrUBound = UBound(arrstrUrl)\n\n arrstrUrl(0) = \"http://bing.com/\"\n arrstrUrl(1) = \"http://google.com/\"\n arrstrUrl(2) = \"http://msn.com/\"\n arrstrUrl(3) = \"http://yahoo.com/\"\n\n set objIE = CreateObject(\"InternetExplorer.Application\")\n objIE.Navigate2 arrstrUrl(0)\n\n For intLoop = 1 to intArrUBound\n\n objIE.Navigate2 arrstrUrl(intLoop), navFlags\n\n Next\n\n objIE.Visible = True\n set objIE = Nothing\n</code></pre>\n\n<p><br />\nOnce you decide on <strong>\"JavaScript\"</strong> or <strong>\"VB Script\"</strong>, you have a few choices:</p>\n\n<p>If your URLs are static: </p>\n\n<p>1) You could write the <strong>\"JS/VBS\"</strong> script file (above) and then just call it from a batch script. </p>\n\n<p>From within the batch script (or command prompt), call the <strong>\"JS/VBS\"</strong> script like this:</p>\n\n<pre><code>cscript //nologo urls.vbs\ncscript //nologo urls.js\n</code></pre>\n\n<p><br />\nIf the URLs change infrequently:</p>\n\n<p>2) You could have the batch script write the <strong>\"JS/VBS\"</strong> script on the fly and then call it. </p>\n\n<p><br />\nIf the URLs could be different each time:</p>\n\n<p>3) Use the <strong>\"JS/VBS\"</strong> scripts (below) and pass the URLs of the pages to open as command line arguments: </p>\n\n<p><strong>JavaScript</strong><br>\nCreate a file with a name like: <strong>\"urls.js\"</strong>: </p>\n\n<pre><code>var navOpenInNewWindow = 0x1;\nvar navOpenInNewTab = 0x800;\nvar navOpenInBackgroundTab = 0x1000;\n\nvar intLoop = 0;\nvar navFlags = navOpenInBackgroundTab;\nvar objIE;\nvar intArgsLength = WScript.Arguments.Length;\n\n if (intArgsLength == 0) {\n\n WScript.Echo(\"Missing parameters\");\n WScript.Quit(1);\n\n }\n\n objIE = new ActiveXObject(\"InternetExplorer.Application\");\n objIE.Navigate2(WScript.Arguments(0));\n\n for (intLoop=1;intLoop<intArgsLength;intLoop++) {\n\n objIE.Navigate2(WScript.Arguments(intLoop), navFlags);\n\n }\n\n objIE.Visible = true;\n objIE = null;\n</code></pre>\n\n<p><br />\n<strong>VB Script</strong><br>\nCreate a file with a name like: <strong>\"urls.vbs\"</strong>:</p>\n\n<pre><code>Option Explicit\n\nConst navOpenInNewWindow = &h1\nConst navOpenInNewTab = &h800\nConst navOpenInBackgroundTab = &h1000\n\nDim intLoop\nDim navFlags : navFlags = navOpenInBackgroundTab\nDim objIE\n\n If WScript.Arguments.Count = 0 Then\n\n WScript.Echo \"Missing parameters\"\n WScript.Quit(1)\n\n End If\n\n set objIE = CreateObject(\"InternetExplorer.Application\")\n objIE.Navigate2 WScript.Arguments(0)\n\n For intLoop = 1 to (WScript.Arguments.Count-1)\n\n objIE.Navigate2 WScript.Arguments(intLoop), navFlags\n\n Next\n\n objIE.Visible = True\n set objIE = Nothing\n</code></pre>\n\n<p><br />\nIf the script is called without any parameters, these will return <strong><code>%errorlevel%=1</code></strong>, otherwise they will return <strong><code>%errorlevel%=0</code></strong>. No checking is done regarding the \"validity\" or \"availability\" of any of the URLs.</p>\n\n<p><br />\nFrom within the batch script (or command prompt), call the <strong>\"JS/VBS\"</strong> script like this:</p>\n\n<pre><code>cscript //nologo urls.js \"http://bing.com/\" \"http://google.com/\" \"http://msn.com/\" \"http://yahoo.com/\"\ncscript //nologo urls.vbs \"http://bing.com/\" \"http://google.com/\" \"http://msn.com/\" \"http://yahoo.com/\"\n</code></pre>\n\n<p>OR even:</p>\n\n<pre><code>cscript //nologo urls.js \"bing.com\" \"google.com\" \"msn.com\" \"yahoo.com\"\ncscript //nologo urls.vbs \"bing.com\" \"google.com\" \"msn.com\" \"yahoo.com\"\n</code></pre>\n\n<p><br />\nIf for some reason, you wanted to run these with \"wscript\" instead, remember to use \"start /w\" so the exit codes (%errorlevel%) will be returned to your batch script:</p>\n\n<pre><code>start /w \"\" wscript //nologo urls.js \"url1\" \"url2\" ...\nstart /w \"\" wscript //nologo urls.vbs \"url1\" \"url2\" ...\n</code></pre>\n\n<p><hr>\n<strong>Edit:</strong> 21-Sep-2016</p>\n\n<p>There has been a comment that my solution is too complicated. I disagree. You pick the <code>JavaScript</code> solution, <strong><em>or</em></strong> the <code>VB Script</code> solution (not both), and each is only about 10 lines of actual code (less if you eliminate the error checking/reporting), plus a few lines to initialize constants and variables. </p>\n\n<p>Once you have decided (JS or VB), you write that script <strong>one time</strong>, and then you call that script from <code>batch</code>, passing the <code>URLs</code>, anytime you want to use it, like: </p>\n\n<pre><code>cscript //nologo urls.vbs \"bing.com\" \"google.com\" \"msn.com\" \"yahoo.com\"\n</code></pre>\n\n<p>The reason I wrote this answer, is because all the other answers, which work for some people, will fail to work for others, depending on: </p>\n\n<ol>\n<li>The current Internet Explorer settings for \"open popups in a new tab\", \"open in current/new window/tab\", etc... Assuming you already have those setting set how you like them for general browsing, most people would find it undesirable to have change those settings back and forth in order to make the script work.</li>\n<li>Their behavior is (can be) inconsistent depending on whether or not there was an IE window already open before the \"new\" links were opened. If there was an IE window (perhaps with many open tabs) already open, then all the new tabs would be added there as well. This might not be desired. </li>\n</ol>\n\n<p>The solution I provided doesn't have these issues and should behave the same, regardless of any IE Settings or any existing IE Windows. (Please let me know if I'm wrong about this and I'll try to address it.)</p>\n"
},
{
"answer_id": 28475477,
"author": "Zlelik",
"author_id": 2940920,
"author_profile": "https://Stackoverflow.com/users/2940920",
"pm_score": 2,
"selected": false,
"text": "<p>Of course it is an old post but just for people who will find it through a search engine.</p>\n<p>Another solution is to run it like this for IE9 and later</p>\n<pre><code>iexplore.exe" -noframemerging http://google.com\niexplore.exe" -noframemerging http://gmail.com\n</code></pre>\n<p><code>-noframemerging</code> means run IE independently. For example if you want to run 2 browsers and login as different usernames it will not work if you just run 2 IE. But with <code>-noframemerging</code> it will work.</p>\n<p><code>-noframemerging</code> works for IE9 and later, for early versions like IE8 it is <code>-nomerge</code></p>\n<p>Usually I create 1 bat file like this run_ie.bat</p>\n<pre><code>"c:\\Program Files (x86)\\Internet Explorer\\iexplore.exe" -noframemerging %1\n</code></pre>\n<p>and I create another bat file like this run_2_ie.bat</p>\n<pre><code>start run_ie.bat http://google.com\nstart run_ie.bat http://yahoo.com\n</code></pre>\n"
},
{
"answer_id": 62289934,
"author": "Daniel Hudsky",
"author_id": 7952824,
"author_profile": "https://Stackoverflow.com/users/7952824",
"pm_score": 0,
"selected": false,
"text": "<p>The top answer is almost correct, but you also need to add an ampersand at the end of each line. For example write the batch file: </p>\n\n<pre><code>start /d \"~\\iexplore.exe\" \"www.google.com\" & \nstart /d \"~\\iexplore.exe\" \"www.yahoo.com\" &\nstart /d \"~\\iexplore.exe\" \"www.blackholesurfer.com\" &\n</code></pre>\n\n<p>The ampersand allows the prompt to return to the shell and launch another tab. \nThis is a windows solution only, but the ampersand has the same effect in linux shell. </p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10552/"
] |
I would like a batch file to launch two separate programs then have the command line window close. Actually, to clarify, I am launching Internet Explorer with two different URLs.
So far I have something like this:
```
start "~\iexplore.exe" "url1"
start "~\iexplore.exe" "url2"
```
What I get is one instance of Internet Explorer with only the second URL loaded. Seems the second is replacing the second. I seem to remember a syntax where I would load a new command line window and pass the command to execute on load, but can't find the reference.
As a second part of the question: what is a good reference URL to keep for the times you need to write a quick batch file?
Edit: I have marked an answer, because it does work. I now have two windows open, one for each URL. (thanks!) The funny thing is that without the /d approach using my original syntax I get different results based on whether I have a pre-existing Internet Explorer instance open.
* If I do I get two new tabs added for
my two URLs (sweet!)
* If not I get only one final tab for the second URL I passed in.
|
Try this in your batch file:
```
@echo off
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.google.com
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.yahoo.com
```
|
188,886 |
<p>After my <code>form.Form</code> validates the user input values I pass them to a separate (external) process for further processing. This external process can potentially find further errors in the values.</p>
<p>Is there a way to inject these errors into the already validated form so they can be displayed via the usual form error display methods (or are there better alternative approaches)?</p>
<p>One suggestions was to include the external processing in the form validation, which is not ideal because the external process does a lot more than merely validate.</p>
|
[
{
"answer_id": 188904,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 4,
"selected": false,
"text": "<p>You can add additional error details to the form's <code>_errors</code> attribute directly:</p>\n\n<p><a href=\"https://docs.djangoproject.com/en/1.5/ref/forms/validation/#described-later\" rel=\"nofollow noreferrer\">https://docs.djangoproject.com/en/1.5/ref/forms/validation/#described-later</a>\n<a href=\"https://docs.djangoproject.com/en/1.6/ref/forms/validation/#modifying-field-errors\" rel=\"nofollow noreferrer\">https://docs.djangoproject.com/en/1.6/ref/forms/validation/#modifying-field-errors</a></p>\n"
},
{
"answer_id": 188906,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 8,
"selected": true,
"text": "<p><code>Form._errors</code> can be treated like a standard dictionary. It's considered good form to use the <code>ErrorList</code> class, and to append errors to the existing list:</p>\n\n<pre><code>from django.forms.utils import ErrorList\nerrors = form._errors.setdefault(\"myfield\", ErrorList())\nerrors.append(u\"My error here\")\n</code></pre>\n\n<p>And if you want to add non-field errors, use <code>django.forms.forms.NON_FIELD_ERRORS</code> (defaults to <code>\"__all__\"</code>) instead of <code>\"myfield\"</code>.</p>\n"
},
{
"answer_id": 28058268,
"author": "rstuart85",
"author_id": 1713202,
"author_profile": "https://Stackoverflow.com/users/1713202",
"pm_score": 7,
"selected": false,
"text": "<p>For Django 1.7+, you should use <code>form.add_error()</code> instead of accessing <code>form._errors</code> directly.</p>\n\n<p>Documentation: <a href=\"https://docs.djangoproject.com/en/stable/ref/forms/api/#django.forms.Form.add_error\">https://docs.djangoproject.com/en/stable/ref/forms/api/#django.forms.Form.add_error</a></p>\n"
},
{
"answer_id": 60258267,
"author": "Muhammad Faizan Fareed",
"author_id": 7300865,
"author_profile": "https://Stackoverflow.com/users/7300865",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Add error to specific field :</strong></p>\n\n<pre><code>form.add_error('fieldName', 'error description')\n</code></pre>\n\n<p>**Add error to non fields **</p>\n\n<pre><code>form.add_error(None, 'error description')\n#Only pass None instead of field name\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13055/"
] |
After my `form.Form` validates the user input values I pass them to a separate (external) process for further processing. This external process can potentially find further errors in the values.
Is there a way to inject these errors into the already validated form so they can be displayed via the usual form error display methods (or are there better alternative approaches)?
One suggestions was to include the external processing in the form validation, which is not ideal because the external process does a lot more than merely validate.
|
`Form._errors` can be treated like a standard dictionary. It's considered good form to use the `ErrorList` class, and to append errors to the existing list:
```
from django.forms.utils import ErrorList
errors = form._errors.setdefault("myfield", ErrorList())
errors.append(u"My error here")
```
And if you want to add non-field errors, use `django.forms.forms.NON_FIELD_ERRORS` (defaults to `"__all__"`) instead of `"myfield"`.
|
188,889 |
<p>how do I pass additional information to the service method returning the collection of items? I'll attempt to explain what I mean, I have 2 text boxes on a form, I need to fill out names, based of a specific account id in a database. so, I need to pass an integer to the getNamesForDropDown method. I couldn't figure out what to do, so I did the wrong thing, and used the CompletionSetCount to actually pass the information I needed:</p>
<pre><code>[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] getNamesForDropDown(string prefixText, int count)
{
String sql = "Select fldName From idAccountReps Where idAccount = " + count.ToString();
//... rest of the method removed, this should be enough code to understand
//... the evil wrongness I did.
}
</code></pre>
<p>in my front side aspx file, i set the CompletionSetCount based off the Account id the user is currently viewing on that page. </p>
<pre><code><ajaxtk:AutoCompleteExtender
runat="server"
ID="AC1"
TargetControlID="txtAccName"
ServiceMethod="getNamesForDropDown"
ServicePath="AccountInfo.asmx"
MinimumPrefixLength="1"
EnableCaching="true"
CompletionSetCount='<%# Eval("idAccount") %>'
/>
</code></pre>
<p>So, that's definitely a wrong way... what would be the right way?</p>
|
[
{
"answer_id": 188903,
"author": "azamsharp",
"author_id": 3797,
"author_profile": "https://Stackoverflow.com/users/3797",
"pm_score": 2,
"selected": false,
"text": "<p>If you like you can use a separator with the prefixText. So, you can pass \"1:bcd\" and on the service end you can split the two items: </p>\n\n<pre><code>string[] arguments = prefixText.Split(':'); \nint id = Int32.Parse(arguments[0]);\nstring text = arguments[1]; \n</code></pre>\n"
},
{
"answer_id": 188923,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 2,
"selected": false,
"text": "<p>Holy smoke, I think this is what I need, I swear I never saw this option before I started programming this. Is this a new property to the autocompleteextender?</p>\n\n<p><a href=\"http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx\" rel=\"nofollow noreferrer\">Excerpt from Documentation</a>:</p>\n\n<p>ContextKey - User/page specific context provided to an optional overload of the web method described by ServiceMethod/ServicePath. If the context key is used, it should have the same signature with an additional parameter named contextKey of type string:</p>\n\n<p>[System.Web.Services.WebMethod]\n[System.Web.Script.Services.ScriptMethod]\npublic string[] GetCompletionList(\n string prefixText, int count, string contextKey) { ... }</p>\n\n<p>Note that you can replace \"GetCompletionList\" with a name of your choice, but the return type and parameter name and type must exactly match, including case.</p>\n\n<p>Edit: It doesn't matter if it is new or not, or whether i just completely overlooked it. It works, and I'm happy. It took me about 10 minutes from being confused to figuring out my own answer. </p>\n"
},
{
"answer_id": 188926,
"author": "ForCripeSake",
"author_id": 14833,
"author_profile": "https://Stackoverflow.com/users/14833",
"pm_score": 4,
"selected": true,
"text": "<p>azam has the right idea- but the signature of the autocomplete method can also have a third parameter:</p>\n\n<p>public string[] yourmethod(string prefixText, int count, string <strong>contextKey</strong>)</p>\n\n<p>you can Split up the results of the contextKey string using Azam's method- but this way you do not have to worry about sanatizing the user's input of the .Split()'s delimiter (:)</p>\n"
},
{
"answer_id": 7571125,
"author": "Mudassar Khan",
"author_id": 967312,
"author_profile": "https://Stackoverflow.com/users/967312",
"pm_score": 1,
"selected": false,
"text": "<p>Refer here\n<a href=\"http://www.aspsnippets.com/Articles/ASPNet-AJAX-AutoCompleteExtender-Pass-Additional-Parameter-to-WebMethod-using-ContextKey.aspx\" rel=\"nofollow\">http://www.aspsnippets.com/Articles/ASPNet-AJAX-AutoCompleteExtender-Pass-Additional-Parameter-to-WebMethod-using-ContextKey.aspx</a></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18893/"
] |
how do I pass additional information to the service method returning the collection of items? I'll attempt to explain what I mean, I have 2 text boxes on a form, I need to fill out names, based of a specific account id in a database. so, I need to pass an integer to the getNamesForDropDown method. I couldn't figure out what to do, so I did the wrong thing, and used the CompletionSetCount to actually pass the information I needed:
```
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] getNamesForDropDown(string prefixText, int count)
{
String sql = "Select fldName From idAccountReps Where idAccount = " + count.ToString();
//... rest of the method removed, this should be enough code to understand
//... the evil wrongness I did.
}
```
in my front side aspx file, i set the CompletionSetCount based off the Account id the user is currently viewing on that page.
```
<ajaxtk:AutoCompleteExtender
runat="server"
ID="AC1"
TargetControlID="txtAccName"
ServiceMethod="getNamesForDropDown"
ServicePath="AccountInfo.asmx"
MinimumPrefixLength="1"
EnableCaching="true"
CompletionSetCount='<%# Eval("idAccount") %>'
/>
```
So, that's definitely a wrong way... what would be the right way?
|
azam has the right idea- but the signature of the autocomplete method can also have a third parameter:
public string[] yourmethod(string prefixText, int count, string **contextKey**)
you can Split up the results of the contextKey string using Azam's method- but this way you do not have to worry about sanatizing the user's input of the .Split()'s delimiter (:)
|
188,892 |
<p>Is there a built-in mechanism in .NET to match patterns other than Regular Expressions? I'd like to match using UNIX style (glob) wildcards (* = any number of any character). </p>
<p>I'd like to use this for a end-user facing control. I fear that permitting all RegEx capabilities will be very confusing.</p>
|
[
{
"answer_id": 188924,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know if the .NET framework has glob matching, but couldn't you replace the * with .*? and use regexes?</p>\n"
},
{
"answer_id": 188929,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 3,
"selected": false,
"text": "<p>If you use VB.Net, you can use the Like statement, which has Glob like syntax.</p>\n\n<p><a href=\"http://www.getdotnetcode.com/gdncstore/free/Articles/Intoduction%20to%20the%20VB%20NET%20Like%20Operator.htm\" rel=\"nofollow noreferrer\">http://www.getdotnetcode.com/gdncstore/free/Articles/Intoduction%20to%20the%20VB%20NET%20Like%20Operator.htm</a></p>\n"
},
{
"answer_id": 190297,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 6,
"selected": true,
"text": "<p>I found the actual code for you:</p>\n\n<pre><code>Regex.Escape( wildcardExpression ).Replace( @\"\\*\", \".*\" ).Replace( @\"\\?\", \".\" );\n</code></pre>\n"
},
{
"answer_id": 613814,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote a <a href=\"https://github.com/DinoChiesa/DotNetZip/blob/master/Zip/FileSelector.cs\" rel=\"nofollow noreferrer\">FileSelector</a> class that does selection of files based on filenames. It also selects files based on time, size, and attributes. If you just want filename globbing then you express the name in forms like "*.txt" and similar. If you want the other parameters then you specify a boolean logic statement like "name = *.xls and ctime < 2009-01-01" - implying an .xls file created before January 1st 2009. You can also select based on the negative: "name != *.xls" means all files that are not xls.</p>\n<p>Check it out.\nOpen source. Liberal license.\nFree to use elsewhere.</p>\n"
},
{
"answer_id": 3408256,
"author": "Doug Clutter",
"author_id": 340568,
"author_profile": "https://Stackoverflow.com/users/340568",
"pm_score": 2,
"selected": false,
"text": "<p>Based on previous posts, I threw together a C# class:</p>\n\n<pre><code>using System;\nusing System.Text.RegularExpressions;\n\npublic class FileWildcard\n{\n Regex mRegex;\n\n public FileWildcard(string wildcard)\n {\n string pattern = string.Format(\"^{0}$\", Regex.Escape(wildcard)\n .Replace(@\"\\*\", \".*\").Replace(@\"\\?\", \".\"));\n mRegex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);\n }\n public bool IsMatch(string filenameToCompare)\n {\n return mRegex.IsMatch(filenameToCompare);\n }\n}\n</code></pre>\n\n<p>Using it would go something like this:</p>\n\n<pre><code>FileWildcard w = new FileWildcard(\"*.txt\");\nif (w.IsMatch(\"Doug.Txt\"))\n Console.WriteLine(\"We have a match\");\n</code></pre>\n\n<p>The matching is NOT the same as the System.IO.Directory.GetFiles() method, so don't use them together.</p>\n"
},
{
"answer_id": 3562062,
"author": "Dan Mangiarelli",
"author_id": 91993,
"author_profile": "https://Stackoverflow.com/users/91993",
"pm_score": 4,
"selected": false,
"text": "<p>The 2- and 3-argument variants of the listing methods like <code>GetFiles()</code> and <code>EnumerateDirectories()</code> take a search string as their second argument that supports filename globbing, with both <code>*</code> and <code>?</code>.</p>\n\n<pre><code>class GlobTestMain\n{\n static void Main(string[] args)\n {\n string[] exes = Directory.GetFiles(Environment.CurrentDirectory, \"*.exe\");\n foreach (string file in exes)\n {\n Console.WriteLine(Path.GetFileName(file));\n }\n }\n}\n</code></pre>\n\n<p>would yield</p>\n\n<pre><code>GlobTest.exe\nGlobTest.vshost.exe\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/wz42302f.aspx\" rel=\"noreferrer\">The docs</a> state that there are some caveats with matching extensions. It also states that 8.3 file names are matched (which may be generated automatically behind the scenes), which can result in \"duplicate\" matches in given some patterns.</p>\n\n<p>The methods that support this are <code>GetFiles()</code>, <code>GetDirectories()</code>, and <code>GetFileSystemEntries()</code>. The <code>Enumerate</code> variants also support this.</p>\n"
},
{
"answer_id": 4146349,
"author": "mindplay.dk",
"author_id": 283851,
"author_profile": "https://Stackoverflow.com/users/283851",
"pm_score": 6,
"selected": false,
"text": "<p>I like my code a little more semantic, so I wrote this extension method:</p>\n\n<pre><code>using System.Text.RegularExpressions;\n\nnamespace Whatever\n{\n public static class StringExtensions\n {\n /// <summary>\n /// Compares the string against a given pattern.\n /// </summary>\n /// <param name=\"str\">The string.</param>\n /// <param name=\"pattern\">The pattern to match, where \"*\" means any sequence of characters, and \"?\" means any single character.</param>\n /// <returns><c>true</c> if the string matches the given pattern; otherwise <c>false</c>.</returns>\n public static bool Like(this string str, string pattern)\n {\n return new Regex(\n \"^\" + Regex.Escape(pattern).Replace(@\"\\*\", \".*\").Replace(@\"\\?\", \".\") + \"$\",\n RegexOptions.IgnoreCase | RegexOptions.Singleline\n ).IsMatch(str);\n }\n }\n}\n</code></pre>\n\n<p>(change the namespace and/or copy the extension method to your own string extensions class)</p>\n\n<p>Using this extension, you can write statements like this:</p>\n\n<pre><code>if (File.Name.Like(\"*.jpg\"))\n{\n ....\n}\n</code></pre>\n\n<p>Just sugar to make your code a little more legible :-)</p>\n"
},
{
"answer_id": 8094334,
"author": "Tony Edgecombe",
"author_id": 57094,
"author_profile": "https://Stackoverflow.com/users/57094",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to avoid regular expressions this is a basic glob implementation:</p>\n\n<pre><code>public static class Globber\n{\n public static bool Glob(this string value, string pattern)\n {\n int pos = 0;\n\n while (pattern.Length != pos)\n {\n switch (pattern[pos])\n {\n case '?':\n break;\n\n case '*':\n for (int i = value.Length; i >= pos; i--)\n {\n if (Glob(value.Substring(i), pattern.Substring(pos + 1)))\n {\n return true;\n }\n }\n return false;\n\n default:\n if (value.Length == pos || char.ToUpper(pattern[pos]) != char.ToUpper(value[pos]))\n {\n return false;\n }\n break;\n }\n\n pos++;\n }\n\n return value.Length == pos;\n }\n}\n</code></pre>\n\n<p>Use it like this:</p>\n\n<pre><code>Assert.IsTrue(\"text.txt\".Glob(\"*.txt\"));\n</code></pre>\n"
},
{
"answer_id": 37611277,
"author": "cleftheris",
"author_id": 61577,
"author_profile": "https://Stackoverflow.com/users/61577",
"pm_score": 5,
"selected": false,
"text": "<p>Just for the sake of completeness. Since 2016 in <code>dotnet core</code> there is a new nuget package called <code>Microsoft.Extensions.FileSystemGlobbing</code> that supports advanced globing paths. (<a href=\"https://www.nuget.org/packages/Microsoft.Extensions.FileSystemGlobbing\" rel=\"noreferrer\">Nuget Package</a>)</p>\n\n<p>some examples might be, searching for wildcard nested folder structures and files which is very common in web development scenarios.</p>\n\n<ul>\n<li><code>wwwroot/app/**/*.module.js</code></li>\n<li><code>wwwroot/app/**/*.js</code></li>\n</ul>\n\n<p>This works somewhat similar with what <code>.gitignore</code> files use to determine which files to exclude from source control.</p>\n"
},
{
"answer_id": 39024810,
"author": "Bill Menees",
"author_id": 1882616,
"author_profile": "https://Stackoverflow.com/users/1882616",
"pm_score": 2,
"selected": false,
"text": "<p>From C# you can use .NET's <a href=\"https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.compilerservices.likeoperator.likestring.aspx\" rel=\"nofollow\">LikeOperator.LikeString</a> method. That's the backing implementation for VB's <a href=\"https://msdn.microsoft.com/en-us/library/swf8kaxw.aspx\" rel=\"nofollow\">LIKE operator</a>. It supports patterns using *, ?, #, [charlist], and [!charlist].</p>\n\n<p>You can use the LikeString method from C# by adding a reference to the Microsoft.VisualBasic.dll assembly, which is included with every version of the .NET Framework. Then you invoke the LikeString method just like any other static .NET method:</p>\n\n<pre><code>using Microsoft.VisualBasic;\nusing Microsoft.VisualBasic.CompilerServices;\n...\nbool isMatch = LikeOperator.LikeString(\"I love .NET!\", \"I love *\", CompareMethod.Text);\n// isMatch should be true.\n</code></pre>\n"
},
{
"answer_id": 42609077,
"author": "TarmoPikaro",
"author_id": 2338477,
"author_profile": "https://Stackoverflow.com/users/2338477",
"pm_score": 0,
"selected": false,
"text": "<p>Just out of curiosity I've glanced into Microsoft.Extensions.FileSystemGlobbing - and it was dragging quite huge dependencies on quite many libraries - I've decided why I cannot try to write something similar?</p>\n\n<p>Well - easy to say than done, I've quickly noticed that it was not so trivial function after all - for example \"*.txt\" should match for files only in current directly, while \"**.txt\" should also harvest sub folders. </p>\n\n<p>Microsoft also tests some odd matching pattern sequences like \"./*.txt\" - I'm not sure who actually needs \"./\" kind of string - since they are removed anyway while processing.\n(<a href=\"https://github.com/aspnet/FileSystem/blob/dev/test/Microsoft.Extensions.FileSystemGlobbing.Tests/PatternMatchingTests.cs\" rel=\"nofollow noreferrer\">https://github.com/aspnet/FileSystem/blob/dev/test/Microsoft.Extensions.FileSystemGlobbing.Tests/PatternMatchingTests.cs</a>)</p>\n\n<p>Anyway, I've coded my own function - and there will be two copies of it - one in svn (I might bugfix it later on) - and I'll copy one sample here as well for demo purposes. I recommend to copy paste from svn link.</p>\n\n<p>SVN Link:</p>\n\n<p><a href=\"https://sourceforge.net/p/syncproj/code/HEAD/tree/SolutionProjectBuilder.cs#l800\" rel=\"nofollow noreferrer\">https://sourceforge.net/p/syncproj/code/HEAD/tree/SolutionProjectBuilder.cs#l800</a>\n(Search for matchFiles function if not jumped correctly).</p>\n\n<p>And here is also local function copy:</p>\n\n<pre><code>/// <summary>\n/// Matches files from folder _dir using glob file pattern.\n/// In glob file pattern matching * reflects to any file or folder name, ** refers to any path (including sub-folders).\n/// ? refers to any character.\n/// \n/// There exists also 3-rd party library for performing similar matching - 'Microsoft.Extensions.FileSystemGlobbing'\n/// but it was dragging a lot of dependencies, I've decided to survive without it.\n/// </summary>\n/// <returns>List of files matches your selection</returns>\nstatic public String[] matchFiles( String _dir, String filePattern )\n{\n if (filePattern.IndexOfAny(new char[] { '*', '?' }) == -1) // Speed up matching, if no asterisk / widlcard, then it can be simply file path.\n {\n String path = Path.Combine(_dir, filePattern);\n if (File.Exists(path))\n return new String[] { filePattern };\n return new String[] { };\n }\n\n String dir = Path.GetFullPath(_dir); // Make it absolute, just so we can extract relative path'es later on.\n String[] pattParts = filePattern.Replace(\"/\", \"\\\\\").Split('\\\\');\n List<String> scanDirs = new List<string>();\n scanDirs.Add(dir);\n\n //\n // By default glob pattern matching specifies \"*\" to any file / folder name, \n // which corresponds to any character except folder separator - in regex that's \"[^\\\\]*\"\n // glob matching also allow double astrisk \"**\" which also recurses into subfolders. \n // We split here each part of match pattern and match it separately.\n //\n for (int iPatt = 0; iPatt < pattParts.Length; iPatt++)\n {\n bool bIsLast = iPatt == (pattParts.Length - 1);\n bool bRecurse = false;\n\n String regex1 = Regex.Escape(pattParts[iPatt]); // Escape special regex control characters (\"*\" => \"\\*\", \".\" => \"\\.\")\n String pattern = Regex.Replace(regex1, @\"\\\\\\*(\\\\\\*)?\", delegate (Match m)\n {\n if (m.ToString().Length == 4) // \"**\" => \"\\*\\*\" (escaped) - we need to recurse into sub-folders.\n {\n bRecurse = true;\n return \".*\";\n }\n else\n return @\"[^\\\\]*\";\n }).Replace(@\"\\?\", \".\");\n\n if (pattParts[iPatt] == \"..\") // Special kind of control, just to scan upper folder.\n {\n for (int i = 0; i < scanDirs.Count; i++)\n scanDirs[i] = scanDirs[i] + \"\\\\..\";\n\n continue;\n }\n\n Regex re = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);\n int nScanItems = scanDirs.Count;\n for (int i = 0; i < nScanItems; i++)\n {\n String[] items;\n if (!bIsLast)\n items = Directory.GetDirectories(scanDirs[i], \"*\", (bRecurse) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);\n else\n items = Directory.GetFiles(scanDirs[i], \"*\", (bRecurse) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);\n\n foreach (String path in items)\n {\n String matchSubPath = path.Substring(scanDirs[i].Length + 1);\n if (re.Match(matchSubPath).Success)\n scanDirs.Add(path);\n }\n }\n scanDirs.RemoveRange(0, nScanItems); // Remove items what we have just scanned.\n } //for\n\n // Make relative and return.\n return scanDirs.Select( x => x.Substring(dir.Length + 1) ).ToArray();\n} //matchFiles\n</code></pre>\n\n<p>If you find any bugs, I'll be grad to fix them.</p>\n"
},
{
"answer_id": 43209839,
"author": "Jon",
"author_id": 7319955,
"author_profile": "https://Stackoverflow.com/users/7319955",
"pm_score": 0,
"selected": false,
"text": "<p>I wrote a solution that does it. It does not depend on any library and it does not support \"!\" or \"[]\" operators. It supports the following search patterns:</p>\n\n<p>C:\\Logs\\*.txt </p>\n\n<p>C:\\Logs\\**\\*P1?\\**\\asd*.pdf </p>\n\n<pre><code> /// <summary>\n /// Finds files for the given glob path. It supports ** * and ? operators. It does not support !, [] or ![] operators\n /// </summary>\n /// <param name=\"path\">the path</param>\n /// <returns>The files that match de glob</returns>\n private ICollection<FileInfo> FindFiles(string path)\n {\n List<FileInfo> result = new List<FileInfo>();\n //The name of the file can be any but the following chars '<','>',':','/','\\','|','?','*','\"'\n const string folderNameCharRegExp = @\"[^\\<\\>:/\\\\\\|\\?\\*\" + \"\\\"]\";\n const string folderNameRegExp = folderNameCharRegExp + \"+\";\n //We obtain the file pattern\n string filePattern = Path.GetFileName(path);\n List<string> pathTokens = new List<string>(Path.GetDirectoryName(path).Split('\\\\', '/'));\n //We obtain the root path from where the rest of files will obtained \n string rootPath = null;\n bool containsWildcardsInDirectories = false;\n for (int i = 0; i < pathTokens.Count; i++)\n {\n if (!pathTokens[i].Contains(\"*\")\n && !pathTokens[i].Contains(\"?\"))\n {\n if (rootPath != null)\n rootPath += \"\\\\\" + pathTokens[i];\n else\n rootPath = pathTokens[i];\n pathTokens.RemoveAt(0);\n i--;\n }\n else\n {\n containsWildcardsInDirectories = true;\n break;\n }\n }\n if (Directory.Exists(rootPath))\n {\n //We build the regular expression that the folders should match\n string regularExpression = rootPath.Replace(\"\\\\\", \"\\\\\\\\\").Replace(\":\", \"\\\\:\").Replace(\" \", \"\\\\s\");\n foreach (string pathToken in pathTokens)\n {\n if (pathToken == \"**\")\n {\n regularExpression += string.Format(CultureInfo.InvariantCulture, @\"(\\\\{0})*\", folderNameRegExp);\n }\n else\n {\n regularExpression += @\"\\\\\" + pathToken.Replace(\"*\", folderNameCharRegExp + \"*\").Replace(\" \", \"\\\\s\").Replace(\"?\", folderNameCharRegExp);\n }\n }\n Regex globRegEx = new Regex(regularExpression, RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);\n string[] directories = Directory.GetDirectories(rootPath, \"*\", containsWildcardsInDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);\n foreach (string directory in directories)\n {\n if (globRegEx.Matches(directory).Count > 0)\n {\n DirectoryInfo directoryInfo = new DirectoryInfo(directory);\n result.AddRange(directoryInfo.GetFiles(filePattern));\n }\n }\n\n }\n return result;\n }\n</code></pre>\n"
},
{
"answer_id": 45532419,
"author": "Matthew Sheeran",
"author_id": 8424680,
"author_profile": "https://Stackoverflow.com/users/8424680",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://www.nuget.org/packages/Glob.cs\" rel=\"nofollow noreferrer\">https://www.nuget.org/packages/Glob.cs</a></p>\n\n<p><a href=\"https://github.com/mganss/Glob.cs\" rel=\"nofollow noreferrer\">https://github.com/mganss/Glob.cs</a></p>\n\n<p>A GNU Glob for .NET.</p>\n\n<p>You can get rid of the package reference after installing and just compile the single Glob.cs source file.</p>\n\n<p>And as it's an implementation of GNU Glob it's cross platform and cross language once you find another similar implementation enjoy!</p>\n"
},
{
"answer_id": 52281887,
"author": "Darrell",
"author_id": 1008012,
"author_profile": "https://Stackoverflow.com/users/1008012",
"pm_score": 3,
"selected": false,
"text": "<p>I have written a globbing library for .NETStandard, with tests and benchmarks. My goal was to produce a library for .NET, with minimal dependencies, that doesn't use Regex, and outperforms Regex. </p>\n\n<p>You can find it here: </p>\n\n<ul>\n<li><a href=\"http://github.com/dazinator/DotNet.Glob\" rel=\"nofollow noreferrer\">github.com/dazinator/DotNet.Glob</a></li>\n<li><a href=\"https://www.nuget.org/packages/DotNet.Glob/\" rel=\"nofollow noreferrer\">https://www.nuget.org/packages/DotNet.Glob/</a></li>\n</ul>\n"
},
{
"answer_id": 68931309,
"author": "Ryan",
"author_id": 2266345,
"author_profile": "https://Stackoverflow.com/users/2266345",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately the accepted answer will not handle escaped input correctly, because string <code>.Replace("\\*", ".*")</code> fails to distinguish between "*" and "\\*" - it will happily replace "*" in both of these strings, leading to incorrect results.</p>\n<p>Instead, a basic tokenizer can be used to convert the glob path into a regex pattern, which can then be matched against a filename using <code>Regex.Match</code>. This is a more robust and flexible solution.</p>\n<p>Here is a method to do this. It handles <code>?</code>, <code>*</code>, and <code>**</code>, and surrounds each of these globs with a capture group, so the values of each glob can be inspected after the Regex has been matched.</p>\n<pre><code>static string GlobbedPathToRegex(ReadOnlySpan<char> pattern, ReadOnlySpan<char> dirSeparatorChars)\n{\n StringBuilder builder = new StringBuilder();\n builder.Append('^');\n\n ReadOnlySpan<char> remainder = pattern;\n\n while (remainder.Length > 0)\n {\n int specialCharIndex = remainder.IndexOfAny('*', '?');\n\n if (specialCharIndex >= 0)\n {\n ReadOnlySpan<char> segment = remainder.Slice(0, specialCharIndex);\n\n if (segment.Length > 0)\n {\n string escapedSegment = Regex.Escape(segment.ToString());\n builder.Append(escapedSegment);\n }\n\n char currentCharacter = remainder[specialCharIndex];\n char nextCharacter = specialCharIndex < remainder.Length - 1 ? remainder[specialCharIndex + 1] : '\\0';\n\n switch (currentCharacter)\n {\n case '*':\n if (nextCharacter == '*')\n {\n // We have a ** glob expression\n // Match any character, 0 or more times.\n builder.Append("(.*)");\n\n // Skip over **\n remainder = remainder.Slice(specialCharIndex + 2);\n }\n else\n {\n // We have a * glob expression\n // Match any character that isn't a dirSeparatorChar, 0 or more times.\n if(dirSeparatorChars.Length > 0) {\n builder.Append($"([^{Regex.Escape(dirSeparatorChars.ToString())}]*)");\n }\n else {\n builder.Append("(.*)");\n }\n\n // Skip over *\n remainder = remainder.Slice(specialCharIndex + 1);\n }\n break;\n case '?':\n builder.Append("(.)"); // Regex equivalent of ?\n\n // Skip over ?\n remainder = remainder.Slice(specialCharIndex + 1);\n break;\n }\n }\n else\n {\n // No more special characters, append the rest of the string\n string escapedSegment = Regex.Escape(remainder.ToString());\n builder.Append(escapedSegment);\n remainder = ReadOnlySpan<char>.Empty;\n }\n }\n\n builder.Append('$');\n\n return builder.ToString();\n}\n</code></pre>\n<p>The to use it:</p>\n<pre><code>string testGlobPathInput = "/Hello/Test/Blah/**/test*123.fil?";\nstring globPathRegex = GlobbedPathToRegex(testGlobPathInput, "/"); // Could use "\\\\/" directory separator chars on Windows\n\nConsole.WriteLine($"Globbed path: {testGlobPathInput}");\nConsole.WriteLine($"Regex conversion: {globPathRegex}");\n\nstring testPath = "/Hello/Test/Blah/All/Hail/The/Hypnotoad/test_somestuff_123.file";\nConsole.WriteLine($"Test Path: {testPath}");\nvar regexGlobPathMatch = Regex.Match(testPath, globPathRegex);\n\nConsole.WriteLine($"Match: {regexGlobPathMatch.Success}");\n\nfor(int i = 0; i < regexGlobPathMatch.Groups.Count; i++) {\n Console.WriteLine($"Group [{i}]: {regexGlobPathMatch.Groups[i]}");\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>Globbed path: /Hello/Test/Blah/**/test*123.fil?\nRegex conversion: ^/Hello/Test/Blah/(.*)/test([^/]*)123\\.fil(.)$\nTest Path: /Hello/Test/Blah/All/Hail/The/Hypnotoad/test_somestuff_123.file\nMatch: True\nGroup [0]: /Hello/Test/Blah/All/Hail/The/Hypnotoad/test_somestuff_123.file\nGroup [1]: All/Hail/The/Hypnotoad\nGroup [2]: _somestuff_\nGroup [3]: e\n</code></pre>\n<p>I have created a gist here as a canonical version of this method:</p>\n<p><a href=\"https://gist.github.com/crozone/9a10156a37c978e098e43d800c6141ad\" rel=\"nofollow noreferrer\">https://gist.github.com/crozone/9a10156a37c978e098e43d800c6141ad</a></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1807/"
] |
Is there a built-in mechanism in .NET to match patterns other than Regular Expressions? I'd like to match using UNIX style (glob) wildcards (\* = any number of any character).
I'd like to use this for a end-user facing control. I fear that permitting all RegEx capabilities will be very confusing.
|
I found the actual code for you:
```
Regex.Escape( wildcardExpression ).Replace( @"\*", ".*" ).Replace( @"\?", "." );
```
|
188,894 |
<p>I have a .NET WinForms textbox for a phone number field. After allowing free-form text, I'd like to format the text as a "more readable" phone number after the user leaves the textbox. (Outlook has this feature for phone fields when you create/edit a contact)</p>
<ul>
<li>1234567 becomes 123-4567</li>
<li>1234567890 becomes (123) 456-7890</li>
<li>(123)456.7890 becomes (123) 456-7890</li>
<li>123.4567x123 becomes 123-4567 x123</li>
<li>etc</li>
</ul>
|
[
{
"answer_id": 188935,
"author": "Davy8",
"author_id": 23822,
"author_profile": "https://Stackoverflow.com/users/23822",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know of any way other than doing it yourself by possibly making some masks and checking which one it matches and doing each mask on a case by case basis. Don't think it'd be too hard, just time consuming.</p>\n"
},
{
"answer_id": 188936,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<p>My guess is that you could accomplish this with a conditional statement to look at the input and then parse it into a specific format. But I'm guessing there is going to be a good amount of logic to investigate the input and format the output.</p>\n"
},
{
"answer_id": 188962,
"author": "brock.holum",
"author_id": 15860,
"author_profile": "https://Stackoverflow.com/users/15860",
"pm_score": 2,
"selected": false,
"text": "<p>A fairly simple-minded approach would be to use a regular expression. Depending on which type of phone numbers you're accepting, you could write a regular expression that looks for the digits (for US-only, you know there can be 7 or 10 total - maybe with a leading '1') and potential separators between them (period, dash, parens, spaces, etc.).</p>\n\n<p>Once you run the match against the regex, you'll need to write the logic to determine what you actually got and format it from there.</p>\n\n<p>EDIT: Just wanted to add a very basic example (by no means is this going to work for all of the examples you posted above). Geoff's suggestion of stripping non-numeric characters might help out a bit depending on how you write your regex.</p>\n\n<pre><code>Regex regex = new Regex(@\"(?<areaCode>([\\d]{3}))?[\\s.-]?(?<leadingThree>([\\d]{3}))[\\s.-]?(?<lastFour>([\\d]{4}))[x]?(?<extension>[\\d]{1,})?\");\nstring phoneNumber = \"701 123-4567x324\";\n\nMatch phoneNumberMatch = regex.Match(phoneNumber);\nif(phoneNumberMatch.Success)\n{\n if (phoneNumberMatch.Groups[\"areaCode\"].Success)\n {\n Console.WriteLine(phoneNumberMatch.Groups[\"areaCode\"].Value);\n }\n if (phoneNumberMatch.Groups[\"leadingThree\"].Success)\n {\n Console.WriteLine(phoneNumberMatch.Groups[\"leadingThree\"].Value);\n }\n if (phoneNumberMatch.Groups[\"lastFour\"].Success)\n {\n Console.WriteLine(phoneNumberMatch.Groups[\"lastFour\"].Value);\n }\n if (phoneNumberMatch.Groups[\"extension\"].Success)\n {\n Console.WriteLine(phoneNumberMatch.Groups[\"extension\"].Value);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 188974,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 1,
"selected": false,
"text": "<p>I think the easiest thing to do is to first strip any non-numeric characters from the string so that you just have a number then format as mentioned in this <a href=\"https://stackoverflow.com/questions/188510/how-to-format-a-string-as-a-telephone-number-in-c\">question</a></p>\n"
},
{
"answer_id": 189342,
"author": "Shawn Miller",
"author_id": 247,
"author_profile": "https://Stackoverflow.com/users/247",
"pm_score": 1,
"selected": false,
"text": "<p>I thought about stripping any non-numeric characters and then formatting, but I don't think that works so well for the extension case (123.4567x123)</p>\n"
},
{
"answer_id": 190180,
"author": "Dennis Williamson",
"author_id": 26428,
"author_profile": "https://Stackoverflow.com/users/26428",
"pm_score": 1,
"selected": false,
"text": "<p>Lop off the extension then strip the non-numeric character from the remainder. Format it then add the extension back on.</p>\n\n<pre><code>Start: 123.4567x123\nLop: 123.4567\nStrip: 1234567\nFormat: 123-4567\nAdd: 123-4567 x123\n</code></pre>\n"
},
{
"answer_id": 1117478,
"author": "dividius",
"author_id": 133013,
"author_profile": "https://Stackoverflow.com/users/133013",
"pm_score": 0,
"selected": false,
"text": "<p>This works for me. Worth checking performance if you are doing this in a tight loop...</p>\n\n<pre><code>public static string FormatPhoneNumber(string phone)\n{\n phone = Regex.Replace(phone, @\"[^\\d]\", \"\");\n if (phone.Length == 10)\n return Regex.Replace(phone,\n \"(?<ac>\\\\d{3})(?<pref>\\\\d{3})(?<num>\\\\d{4})\",\n \"(${ac}) ${pref}-${num}\");\n else if ((phone.Length < 16) && (phone.Length > 10))\n return Regex.Replace(phone,\n \"(?<ac>\\\\d{3})(?<pref>\\\\d{3})(?<num>\\\\d{4})(?<ext>\\\\d{1,5})\", \n \"(${ac}) ${pref}-${num} x${ext}\");\n else\n return string.Empty;\n</code></pre>\n\n<p>}</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247/"
] |
I have a .NET WinForms textbox for a phone number field. After allowing free-form text, I'd like to format the text as a "more readable" phone number after the user leaves the textbox. (Outlook has this feature for phone fields when you create/edit a contact)
* 1234567 becomes 123-4567
* 1234567890 becomes (123) 456-7890
* (123)456.7890 becomes (123) 456-7890
* 123.4567x123 becomes 123-4567 x123
* etc
|
A fairly simple-minded approach would be to use a regular expression. Depending on which type of phone numbers you're accepting, you could write a regular expression that looks for the digits (for US-only, you know there can be 7 or 10 total - maybe with a leading '1') and potential separators between them (period, dash, parens, spaces, etc.).
Once you run the match against the regex, you'll need to write the logic to determine what you actually got and format it from there.
EDIT: Just wanted to add a very basic example (by no means is this going to work for all of the examples you posted above). Geoff's suggestion of stripping non-numeric characters might help out a bit depending on how you write your regex.
```
Regex regex = new Regex(@"(?<areaCode>([\d]{3}))?[\s.-]?(?<leadingThree>([\d]{3}))[\s.-]?(?<lastFour>([\d]{4}))[x]?(?<extension>[\d]{1,})?");
string phoneNumber = "701 123-4567x324";
Match phoneNumberMatch = regex.Match(phoneNumber);
if(phoneNumberMatch.Success)
{
if (phoneNumberMatch.Groups["areaCode"].Success)
{
Console.WriteLine(phoneNumberMatch.Groups["areaCode"].Value);
}
if (phoneNumberMatch.Groups["leadingThree"].Success)
{
Console.WriteLine(phoneNumberMatch.Groups["leadingThree"].Value);
}
if (phoneNumberMatch.Groups["lastFour"].Success)
{
Console.WriteLine(phoneNumberMatch.Groups["lastFour"].Value);
}
if (phoneNumberMatch.Groups["extension"].Success)
{
Console.WriteLine(phoneNumberMatch.Groups["extension"].Value);
}
}
```
|
188,942 |
<p>I'm writing some cross-platform code between Windows and Mac.</p>
<p>If list::end() "returns an iterator that addresses the location succeeding the last element in a list" and can be checked when traversing a list forward, what is the best way to traverse backwards?</p>
<p>This code workson the Mac but not on Windows (can't decrement beyond first element):</p>
<pre><code>list<DVFGfxObj*>::iterator iter = m_Objs.end();
for (iter--; iter!=m_Objs.end(); iter--)// By accident discovered that the iterator is circular ?
{
}
</code></pre>
<p>this works on Windows:</p>
<pre><code>list<DVFGfxObj*>::iterator iter = m_Objs.end();
do{
iter--;
} while (*iter != *m_Objs.begin());
</code></pre>
<p>Is there another way to traverse backward that could be implemented in a for loop?</p>
|
[
{
"answer_id": 188948,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 7,
"selected": true,
"text": "<p>Use <code>reverse_iterator</code> instead of <code>iterator</code>.\nUse <code>rbegin()</code> & <code>rend()</code> instead of <code>begin()</code> & <code>end()</code>.</p>\n<p>Another possibility, if you like using the <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/foreach.html\" rel=\"nofollow noreferrer\"><code>BOOST_FOREACH</code></a> macro is to use the <code>BOOST_REVERSE_FOREACH</code> macro introduced in Boost 1.36.0.</p>\n"
},
{
"answer_id": 188959,
"author": "Anthony Cramp",
"author_id": 488,
"author_profile": "https://Stackoverflow.com/users/488",
"pm_score": 4,
"selected": false,
"text": "<p>You probably want the reverse iterators. From memory:</p>\n\n<pre><code>list<DVFGfxObj*>::reverse_iterator iter = m_Objs.rbegin();\nfor( ; iter != m_Objs.rend(); ++iter)\n{\n}\n</code></pre>\n"
},
{
"answer_id": 188983,
"author": "ejgottl",
"author_id": 9808,
"author_profile": "https://Stackoverflow.com/users/9808",
"pm_score": 3,
"selected": false,
"text": "<p>As already mentioned by Ferruccio, use reverse_iterator:</p>\n\n<pre><code>for (std::list<int>::reverse_iterator i = s.rbegin(); i != s.rend(); ++i)\n</code></pre>\n"
},
{
"answer_id": 188985,
"author": "steffenj",
"author_id": 15328,
"author_profile": "https://Stackoverflow.com/users/15328",
"pm_score": 3,
"selected": false,
"text": "<p>This should work:</p>\n\n<pre><code>list<DVFGfxObj*>::reverse_iterator iter = m_Objs.rbegin();\nfor (; iter!= m_Objs.rend(); iter++)\n{\n}\n</code></pre>\n"
},
{
"answer_id": 223405,
"author": "mmocny",
"author_id": 29701,
"author_profile": "https://Stackoverflow.com/users/29701",
"pm_score": 4,
"selected": false,
"text": "<p>The best/easiest way to reverse iterate a list is (as already stated) to use reverse iterators rbegin/rend.</p>\n\n<p>However, I did want to mention that reverse iterators are implemented storing the \"current\" iterator position off-by-one (at least on the GNU implementation of the standard library).</p>\n\n<p>This is done to simplify the implementation, in order for the range in reverse to have the same semantics as a range forward [begin, end) and [rbegin, rend)</p>\n\n<p>What this means is that dereferencing an iterator involves creating a new temporary, and then decrementing it, <em>each and every time</em>:</p>\n\n<pre><code> reference\n operator*() const\n {\n_Iterator __tmp = current;\nreturn *--__tmp;\n }\n</code></pre>\n\n<p>Thus, <em>dereferencing a reverse_iterator is slower than an normal iterator.</em></p>\n\n<p>However, You can instead use the regular bidirectional iterators to simulate reverse iteration yourself, avoiding this overhead:</p>\n\n<pre><code>for ( iterator current = end() ; current != begin() ; /* Do nothing */ )\n{\n --current; // Unfortunately, you now need this here\n /* Do work */\n cout << *current << endl;\n}\n</code></pre>\n\n<p>Testing showed this solution to be ~5 times faster <em>for each dereference</em> used in the body of the loop.</p>\n\n<p>Note: Testing was not done with the code above, as that std::cout would have been the bottleneck.</p>\n\n<p>Also Note: the 'wall clock time' difference was ~5 seconds with a std::list size of 10 million elements. So, realistically, unless the size of your data is that large, just stick to rbegin() rend()!</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8761/"
] |
I'm writing some cross-platform code between Windows and Mac.
If list::end() "returns an iterator that addresses the location succeeding the last element in a list" and can be checked when traversing a list forward, what is the best way to traverse backwards?
This code workson the Mac but not on Windows (can't decrement beyond first element):
```
list<DVFGfxObj*>::iterator iter = m_Objs.end();
for (iter--; iter!=m_Objs.end(); iter--)// By accident discovered that the iterator is circular ?
{
}
```
this works on Windows:
```
list<DVFGfxObj*>::iterator iter = m_Objs.end();
do{
iter--;
} while (*iter != *m_Objs.begin());
```
Is there another way to traverse backward that could be implemented in a for loop?
|
Use `reverse_iterator` instead of `iterator`.
Use `rbegin()` & `rend()` instead of `begin()` & `end()`.
Another possibility, if you like using the [`BOOST_FOREACH`](http://www.boost.org/doc/libs/1_36_0/doc/html/foreach.html) macro is to use the `BOOST_REVERSE_FOREACH` macro introduced in Boost 1.36.0.
|
188,967 |
<p>I want to do this in code, not with ALT+F1.</p>
|
[
{
"answer_id": 188981,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 5,
"selected": false,
"text": "<pre><code>sp_help tablename \n</code></pre>\n\n<p>In the output look for something like this:</p>\n\n<pre><code> Identity Seed Increment Not For Replication \n ----------- ------- ------------ ---------------------- \n userid 15500 1 0 \n</code></pre>\n"
},
{
"answer_id": 189025,
"author": "Luke Bennett",
"author_id": 17602,
"author_profile": "https://Stackoverflow.com/users/17602",
"pm_score": 3,
"selected": false,
"text": "<p>Adjust the <code>WHERE</code> clause to suit:</p>\n\n<pre><code>select\n a.name as TableName,\n b.name as IdentityColumn\nfrom\n sysobjects a inner join syscolumns b on a.id = b.id\nwhere\n columnproperty(a.id, b.name, 'isIdentity') = 1\n and objectproperty(a.id, 'isTable') = 1\n</code></pre>\n"
},
{
"answer_id": 189032,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 7,
"selected": true,
"text": "<p>You can also do it this way:</p>\n\n<pre><code>select columnproperty(object_id('mytable'),'mycolumn','IsIdentity')\n</code></pre>\n\n<p>Returns 1 if it's an identity, 0 if not.</p>\n"
},
{
"answer_id": 38591783,
"author": "Tschallacka",
"author_id": 1356107,
"author_profile": "https://Stackoverflow.com/users/1356107",
"pm_score": 1,
"selected": false,
"text": "<p>As expansion on @Blogbeard's answer</p>\n\n<p>If you like pure query and not inbuilt functions</p>\n\n<pre><code>select col_name(sys.all_objects.object_id, column_id) as id from sys.identity_columns \njoin sys.all_objects on sys.identity_columns.object_id = sys.all_objects.object_id\nwhere sys.all_objects.name = 'system_files'\n</code></pre>\n"
},
{
"answer_id": 53135123,
"author": "KamalDeep",
"author_id": 7007438,
"author_profile": "https://Stackoverflow.com/users/7007438",
"pm_score": 1,
"selected": false,
"text": "<p>Identity is the value that is used for the very first row loaded into the table.</p>\n\n<p>There is a microsoft article which can provide good knowledge about Identity:</p>\n\n<blockquote>\n <p><a href=\"https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property?view=sql-server-2017\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property?view=sql-server-2017</a></p>\n</blockquote>\n\n<p>Now, there are couple of ways for identifying which column is an identity column in a table:</p>\n\n<ul>\n<li>We can use sql query: select\n<em>columnproperty(object_id('mytable'),'mycolumn','IsIdentity')</em> </li>\n<li>sp_help <em>tablename</em></li>\n</ul>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2484/"
] |
I want to do this in code, not with ALT+F1.
|
You can also do it this way:
```
select columnproperty(object_id('mytable'),'mycolumn','IsIdentity')
```
Returns 1 if it's an identity, 0 if not.
|
188,968 |
<p>I would like a constraint on a SQL Server 2000 table column that is sort of a combination of a foreign key and a check constraint. The value of my column must exist in the other table, but I am only concerned with values in the other table where one of its columns equal a specified value. The simplified tables are:</p>
<pre>
import_table:
part_number varchar(30)
quantity int
inventory_master:
part_number varchar(30)
type char(1)
</pre>
<p>So I want to ensure the <code>part_number</code> exists in <code>inventory_master</code>, but only if the type is 'C'. Is this possible? Thanks.</p>
|
[
{
"answer_id": 188981,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 5,
"selected": false,
"text": "<pre><code>sp_help tablename \n</code></pre>\n\n<p>In the output look for something like this:</p>\n\n<pre><code> Identity Seed Increment Not For Replication \n ----------- ------- ------------ ---------------------- \n userid 15500 1 0 \n</code></pre>\n"
},
{
"answer_id": 189025,
"author": "Luke Bennett",
"author_id": 17602,
"author_profile": "https://Stackoverflow.com/users/17602",
"pm_score": 3,
"selected": false,
"text": "<p>Adjust the <code>WHERE</code> clause to suit:</p>\n\n<pre><code>select\n a.name as TableName,\n b.name as IdentityColumn\nfrom\n sysobjects a inner join syscolumns b on a.id = b.id\nwhere\n columnproperty(a.id, b.name, 'isIdentity') = 1\n and objectproperty(a.id, 'isTable') = 1\n</code></pre>\n"
},
{
"answer_id": 189032,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 7,
"selected": true,
"text": "<p>You can also do it this way:</p>\n\n<pre><code>select columnproperty(object_id('mytable'),'mycolumn','IsIdentity')\n</code></pre>\n\n<p>Returns 1 if it's an identity, 0 if not.</p>\n"
},
{
"answer_id": 38591783,
"author": "Tschallacka",
"author_id": 1356107,
"author_profile": "https://Stackoverflow.com/users/1356107",
"pm_score": 1,
"selected": false,
"text": "<p>As expansion on @Blogbeard's answer</p>\n\n<p>If you like pure query and not inbuilt functions</p>\n\n<pre><code>select col_name(sys.all_objects.object_id, column_id) as id from sys.identity_columns \njoin sys.all_objects on sys.identity_columns.object_id = sys.all_objects.object_id\nwhere sys.all_objects.name = 'system_files'\n</code></pre>\n"
},
{
"answer_id": 53135123,
"author": "KamalDeep",
"author_id": 7007438,
"author_profile": "https://Stackoverflow.com/users/7007438",
"pm_score": 1,
"selected": false,
"text": "<p>Identity is the value that is used for the very first row loaded into the table.</p>\n\n<p>There is a microsoft article which can provide good knowledge about Identity:</p>\n\n<blockquote>\n <p><a href=\"https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property?view=sql-server-2017\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql-identity-property?view=sql-server-2017</a></p>\n</blockquote>\n\n<p>Now, there are couple of ways for identifying which column is an identity column in a table:</p>\n\n<ul>\n<li>We can use sql query: select\n<em>columnproperty(object_id('mytable'),'mycolumn','IsIdentity')</em> </li>\n<li>sp_help <em>tablename</em></li>\n</ul>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23976/"
] |
I would like a constraint on a SQL Server 2000 table column that is sort of a combination of a foreign key and a check constraint. The value of my column must exist in the other table, but I am only concerned with values in the other table where one of its columns equal a specified value. The simplified tables are:
```
import_table:
part_number varchar(30)
quantity int
inventory_master:
part_number varchar(30)
type char(1)
```
So I want to ensure the `part_number` exists in `inventory_master`, but only if the type is 'C'. Is this possible? Thanks.
|
You can also do it this way:
```
select columnproperty(object_id('mytable'),'mycolumn','IsIdentity')
```
Returns 1 if it's an identity, 0 if not.
|
188,977 |
<p>I have a method running in a seperate thread. The thread is created and started from a form in a windows application. If an exception is thrown from inside the thread, what is the best way to pass it back to the main application. Right now, I'm passing a reference to the main form into the thread, then invoking the method from the thread, and causing the method to be called by the main application thread. Is there a best practice way to do this because I'm not comfortable with how I'm doing it now.</p>
<p>Example of my form:</p>
<pre><code>public class frmMyForm : System.Windows.Forms.Form
{
/// <summary>
/// Create a thread
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnTest_Click(object sender, EventArgs e)
{
try
{
//Create and start the thread
ThreadExample pThreadExample = new ThreadExample(this);
pThreadExample.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName);
}
}
/// <summary>
/// Called from inside the thread
/// </summary>
/// <param name="ex"></param>
public void HandleError(Exception ex)
{
//Invoke a method in the GUI's main thread
this.Invoke(new ThreadExample.delThreadSafeTriggerScript(HandleError), new Object[] { ex });
}
private void __HandleError(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
</code></pre>
<p>Example of my thread class:</p>
<pre><code>public class ThreadExample
{
public delegate void delThreadSafeHandleException(System.Exception ex);
private Thread thExample_m;
frmMyForm pForm_m;
private frmMyForm Form
{
get
{
return pForm_m;
}
}
public ThreadExample(frmMyForm pForm)
{
pForm_m = pForm;
thExample_m = new Thread(new ThreadStart(Main));
thExample_m.Name = "Example Thread";
}
public void Start()
{
thExample_m.Start();
}
private void Main()
{
try
{
throw new Exception("Test");
}
catch (Exception ex)
{
Form.HandleException(ex);
}
}
}
</code></pre>
|
[
{
"answer_id": 188992,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 1,
"selected": false,
"text": "<p>Throwing exceptions between threads is not easy and probably not desired. instead you can pass the exception using a shared data structure or variable and use waitHandle to wait on the 1st thread.</p>\n"
},
{
"answer_id": 188993,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "<p>So you're using Invoke to marshall back to the UI thread, by the looks of it - which is exactly what you need to do. I'd personally use an Action<Exception> for simplicity's sake, and possibly BeginInvoke instead of Invoke, but basically you're doing the right thing.</p>\n"
},
{
"answer_id": 188998,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Probably a better way would be to pass a delegate into the thread instead of a reference to the form itself.</p>\n"
},
{
"answer_id": 219976,
"author": "jezell",
"author_id": 27453,
"author_profile": "https://Stackoverflow.com/users/27453",
"pm_score": 3,
"selected": false,
"text": "<p>Use the BackgroundWorker class in the .NET framework instead. It is the best practice for performing UI work on a different thread.</p>\n"
},
{
"answer_id": 11985904,
"author": "Mrinmoy Das",
"author_id": 1589647,
"author_profile": "https://Stackoverflow.com/users/1589647",
"pm_score": 0,
"selected": false,
"text": "<p>I totally agree with Dror. In a formal way we can call this structure as FaultContract. Fundamentally when an exception has happened in another thread, the client thread can hardly do any thing at that moment except that to collect that information and act accordingly in it's own theread. If the thereads are in different AppPool then there is an extra complexity of Serialization (that can be a seperate topic altogether). </p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/188977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9266/"
] |
I have a method running in a seperate thread. The thread is created and started from a form in a windows application. If an exception is thrown from inside the thread, what is the best way to pass it back to the main application. Right now, I'm passing a reference to the main form into the thread, then invoking the method from the thread, and causing the method to be called by the main application thread. Is there a best practice way to do this because I'm not comfortable with how I'm doing it now.
Example of my form:
```
public class frmMyForm : System.Windows.Forms.Form
{
/// <summary>
/// Create a thread
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnTest_Click(object sender, EventArgs e)
{
try
{
//Create and start the thread
ThreadExample pThreadExample = new ThreadExample(this);
pThreadExample.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName);
}
}
/// <summary>
/// Called from inside the thread
/// </summary>
/// <param name="ex"></param>
public void HandleError(Exception ex)
{
//Invoke a method in the GUI's main thread
this.Invoke(new ThreadExample.delThreadSafeTriggerScript(HandleError), new Object[] { ex });
}
private void __HandleError(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
```
Example of my thread class:
```
public class ThreadExample
{
public delegate void delThreadSafeHandleException(System.Exception ex);
private Thread thExample_m;
frmMyForm pForm_m;
private frmMyForm Form
{
get
{
return pForm_m;
}
}
public ThreadExample(frmMyForm pForm)
{
pForm_m = pForm;
thExample_m = new Thread(new ThreadStart(Main));
thExample_m.Name = "Example Thread";
}
public void Start()
{
thExample_m.Start();
}
private void Main()
{
try
{
throw new Exception("Test");
}
catch (Exception ex)
{
Form.HandleException(ex);
}
}
}
```
|
So you're using Invoke to marshall back to the UI thread, by the looks of it - which is exactly what you need to do. I'd personally use an Action<Exception> for simplicity's sake, and possibly BeginInvoke instead of Invoke, but basically you're doing the right thing.
|
189,019 |
<p>I found an example of implementing the repository pattern in NHibernate on the web, and one of the methods uses this code to get the first result of a query:</p>
<pre><code>public IEnumerable<T> FindAll(DetachedCriteria criteria, int firstResult, int numberOfResults, params Order[] orders)
{
criteria.SetFirstResult(firstResult).SetMaxResults(numberOfResults);
return FindAll(criteria, orders);
}
</code></pre>
<p>But VS intellisense isn't picking up this method from DetachedCriteria. Does anyone know if this is possible with DetachedCriteria? I'm using NHibernate version 1.2.1.</p>
|
[
{
"answer_id": 188992,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 1,
"selected": false,
"text": "<p>Throwing exceptions between threads is not easy and probably not desired. instead you can pass the exception using a shared data structure or variable and use waitHandle to wait on the 1st thread.</p>\n"
},
{
"answer_id": 188993,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "<p>So you're using Invoke to marshall back to the UI thread, by the looks of it - which is exactly what you need to do. I'd personally use an Action<Exception> for simplicity's sake, and possibly BeginInvoke instead of Invoke, but basically you're doing the right thing.</p>\n"
},
{
"answer_id": 188998,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Probably a better way would be to pass a delegate into the thread instead of a reference to the form itself.</p>\n"
},
{
"answer_id": 219976,
"author": "jezell",
"author_id": 27453,
"author_profile": "https://Stackoverflow.com/users/27453",
"pm_score": 3,
"selected": false,
"text": "<p>Use the BackgroundWorker class in the .NET framework instead. It is the best practice for performing UI work on a different thread.</p>\n"
},
{
"answer_id": 11985904,
"author": "Mrinmoy Das",
"author_id": 1589647,
"author_profile": "https://Stackoverflow.com/users/1589647",
"pm_score": 0,
"selected": false,
"text": "<p>I totally agree with Dror. In a formal way we can call this structure as FaultContract. Fundamentally when an exception has happened in another thread, the client thread can hardly do any thing at that moment except that to collect that information and act accordingly in it's own theread. If the thereads are in different AppPool then there is an extra complexity of Serialization (that can be a seperate topic altogether). </p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] |
I found an example of implementing the repository pattern in NHibernate on the web, and one of the methods uses this code to get the first result of a query:
```
public IEnumerable<T> FindAll(DetachedCriteria criteria, int firstResult, int numberOfResults, params Order[] orders)
{
criteria.SetFirstResult(firstResult).SetMaxResults(numberOfResults);
return FindAll(criteria, orders);
}
```
But VS intellisense isn't picking up this method from DetachedCriteria. Does anyone know if this is possible with DetachedCriteria? I'm using NHibernate version 1.2.1.
|
So you're using Invoke to marshall back to the UI thread, by the looks of it - which is exactly what you need to do. I'd personally use an Action<Exception> for simplicity's sake, and possibly BeginInvoke instead of Invoke, but basically you're doing the right thing.
|
189,055 |
<p>Typically you will find STL code like this:</p>
<pre><code>for (SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(); Iter != m_SomeMemberContainerVar.end(); ++Iter)
{
}
</code></pre>
<p>But we actually have the recommendation to write it like this:</p>
<pre><code>SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin();
SomeClass::SomeContainer::iterator IterEnd = m_SomeMemberContainerVar.end();
for (; Iter != IterEnd; ++Iter)
{
}
</code></pre>
<p>If you're worried about scoping, add enclosing braces:</p>
<pre><code>{
SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin();
SomeClass::SomeContainer::iterator IterEnd = m_SomeMemberContainerVar.end();
for (; Iter != IterEnd; ++Iter)
{
}
}
</code></pre>
<p>This is supposed to give a speed and efficiency gain, especially if you are programming consoles, because the .end() function is not called on each iteration of the loop. I just take the performance improvement for granted, it sounds reasonable but i don't know how much and it certainly depends on the type of container and actual STL implementation in use. But having used this style for a couple months now i actually prefer it over the first anyway.</p>
<p>The reason being readability: the for line is neat and tidy. With qualifiers and member variables in real production code it is quite easy to have <strong>really</strong> long for lines if you use the style in the first example. That's why i intentionally made it to have a horizontal scrollbar in this example, just so you see what i'm talking about. ;)</p>
<p>On the other hand, you suddenly introduce the Iter variables to the outer scope of the for loop. But then, at least in the environment i work in, the Iter would have been accessible in the outer scope even in the first example.</p>
<p>What is your take on this? Are there any pro's to the first style other than possibly limiting the scope of Iter?</p>
|
[
{
"answer_id": 189060,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 3,
"selected": false,
"text": "<p>The first form (inside the for loop) is better if the iterator is not needed after the for loop. It limits its scope to the for loop.</p>\n\n<p>I seriously doubt that there is any efficiency gain either way. It can also be made more readable with a typedef.</p>\n\n<pre><code>typedef SomeClass::SomeContainer::iterator MyIter;\n\nfor (MyIter Iter = m_SomeMemberContainerVar.begin(); Iter != m_SomeMemberContainerVar.end(); ++Iter)\n{\n}\n</code></pre>\n\n<p>I would recommend shorter names ;-)</p>\n"
},
{
"answer_id": 189066,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": 0,
"selected": false,
"text": "<p>You can throw braces around the initialization and loop if you are concerned about scope. Often what I'll do is declare iterators at the start of the function and reuse them throughout the program.</p>\n"
},
{
"answer_id": 189067,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 0,
"selected": false,
"text": "<p>I find the second option more readable, as you don't end up with one giant line. However, Ferruccio brings up a good point about the scope.</p>\n"
},
{
"answer_id": 189068,
"author": "Fred Larson",
"author_id": 10077,
"author_profile": "https://Stackoverflow.com/users/10077",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with Ferruccio. The first style might be preferred by some in order to pull the end() call out of the loop.</p>\n\n<p>I might also add that C++0x will actually make both versions much cleaner:</p>\n\n<pre><code>for (auto iter = container.begin(); iter != container.end(); ++iter)\n{\n ...\n}\n\nauto iter = container.begin();\nauto endIter = container.end();\nfor (; iter != endIter; ++iter)\n{\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 189074,
"author": "Nemanja Trifunovic",
"author_id": 8899,
"author_profile": "https://Stackoverflow.com/users/8899",
"pm_score": 0,
"selected": false,
"text": "<p>I would usually write:</p>\n\n<pre><code>SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(),\n IterEnd = m_SomeMemberContainerVar.end();\n\nfor(...)\n</code></pre>\n"
},
{
"answer_id": 189077,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 5,
"selected": true,
"text": "<p>If you wrap your code into lines properly, the inline form would be equally readable. Besides, you should always do the <code>iterEnd = container.end()</code> as an optimization:</p>\n\n<pre><code>for (SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(),\n IterEnd = m_SomeMemberContainerVar.end();\n Iter != IterEnd;\n ++Iter)\n{\n}\n</code></pre>\n\n<p><em>Update: fixed the code per paercebal's advice.</em></p>\n"
},
{
"answer_id": 189081,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 1,
"selected": false,
"text": "<p>I don't have a particularly strong opinion one way or the other, though iterator lifetime would lean me toward the for-scoped version.</p>\n\n<p>However, readability may be an issue; that can be helped by using a typedef so the iterator type is a bit more manageable:</p>\n\n<pre><code>typedef SomeClass::SomeContainer::iterator sc_iter_t;\n\nfor (sc_iter_t Iter = m_SomeMemberContainerVar.begin(); Iter != m_SomeMemberContainerVar.end(); ++Iter)\n{\n}\n</code></pre>\n\n<p>Not a huge improvement, but a bit.</p>\n"
},
{
"answer_id": 189129,
"author": "user25601",
"author_id": 25601,
"author_profile": "https://Stackoverflow.com/users/25601",
"pm_score": 1,
"selected": false,
"text": "<p>I don't have any console experience, but in most modern C++ compiliers either option ends up being equivilent except for the question of scope. The visual studio compilier will virtually always even in debug code put the condition comparison in an implicit temporary variable (usually a register). So while logically it looks like the end() call is being made through each iteration, the optimized compiled code actually only makes the call once and the comparison is the only thing that is done each subsiquent time through the loop.</p>\n\n<p>This may not be the case on consoles, but you could unassemble the loop to check to see if the optimization is taking place. If it is, then you can you whatever style you prefer or is standard in your organization.</p>\n"
},
{
"answer_id": 189134,
"author": "joeld",
"author_id": 19104,
"author_profile": "https://Stackoverflow.com/users/19104",
"pm_score": 3,
"selected": false,
"text": "<p>Another alternative is to use a foreach macro, for example <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/foreach.html\" rel=\"noreferrer\">boost foreach</a>:</p>\n\n<pre><code>BOOST_FOREACH( ContainedType item, m_SomeMemberContainerVar )\n{\n mangle( item );\n}\n</code></pre>\n\n<p>I know macros are discouraged in modern c++, but until the auto keyword is widely available this is the best way I've found to get something that is concise and readable, and still completely typesafe and fast. You can implement your macro using whichever initialization style gets you better performance.</p>\n\n<p>There's also a note on the linked page about redefining BOOST_FOREACH as foreach to avoid the annoying all caps.</p>\n"
},
{
"answer_id": 189257,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 1,
"selected": false,
"text": "<p>It may make for disjointed code, but I also like to pull it out to a separate function, and pass both iterators to it.</p>\n\n<pre><code>doStuff(coll.begin(), coll.end())\n</code></pre>\n\n<p>and have..</p>\n\n<pre><code>template<typename InIt>\nvoid doStuff(InIt first, InIt last)\n{\n for (InIt curr = first; curr!= last; ++curr)\n {\n // Do stuff\n }\n }\n</code></pre>\n\n<p>Things to like:</p>\n\n<ul>\n<li>Never have to mention the ugly iterator type (or think about whether it's const or not-const)</li>\n<li>If there is gain from not calling end() on each iteration, I'm getting it</li>\n</ul>\n\n<p>Things to not like:</p>\n\n<ul>\n<li>Breaks up the code </li>\n<li>Overhead of additional function call.</li>\n</ul>\n\n<p>But one day, we'll have lambdas!</p>\n"
},
{
"answer_id": 194245,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 2,
"selected": false,
"text": "<p>No, it's a bad idea to get a hold on <code>iter.end()</code> before the loop starts. If your loop changes the container then the end iterator may be invalidated. Also, the <code>end()</code> method is guaranteed to be O(1).</p>\n\n<p>Premature optimization is the root of all evil.</p>\n\n<p>Also, the compiler may be smarter than you think.</p>\n"
},
{
"answer_id": 194256,
"author": "Chris Jefferson",
"author_id": 27074,
"author_profile": "https://Stackoverflow.com/users/27074",
"pm_score": 2,
"selected": false,
"text": "<p>Having looked at this in g++ at -O2 optimisation (just to be specific)</p>\n\n<p>There is no difference in the generated code for std::vector, std::list and std::map (and friends). There is a tiny overhead with std::deque.</p>\n\n<p>So in general, from a performance viewpoint it makes little difference.</p>\n"
},
{
"answer_id": 195090,
"author": "An̲̳̳drew",
"author_id": 17035,
"author_profile": "https://Stackoverflow.com/users/17035",
"pm_score": 1,
"selected": false,
"text": "<p>I don't think it's bad style at all. Just use typedefs to avoid the STL verbosity and long lines.</p>\n\n<pre><code>typedef set<Apple> AppleSet;\ntypedef AppleSet::iterator AppleIter;\nAppleSet apples;\n\nfor (AppleIter it = apples.begin (); it != apples.end (); ++it)\n{\n ...\n}\n</code></pre>\n\n<p><a href=\"http://www.codinghorror.com/blog/archives/001148.html\" rel=\"nofollow noreferrer\">Spartan Programming</a> is one way to mitigate your style concerns.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15328/"
] |
Typically you will find STL code like this:
```
for (SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(); Iter != m_SomeMemberContainerVar.end(); ++Iter)
{
}
```
But we actually have the recommendation to write it like this:
```
SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin();
SomeClass::SomeContainer::iterator IterEnd = m_SomeMemberContainerVar.end();
for (; Iter != IterEnd; ++Iter)
{
}
```
If you're worried about scoping, add enclosing braces:
```
{
SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin();
SomeClass::SomeContainer::iterator IterEnd = m_SomeMemberContainerVar.end();
for (; Iter != IterEnd; ++Iter)
{
}
}
```
This is supposed to give a speed and efficiency gain, especially if you are programming consoles, because the .end() function is not called on each iteration of the loop. I just take the performance improvement for granted, it sounds reasonable but i don't know how much and it certainly depends on the type of container and actual STL implementation in use. But having used this style for a couple months now i actually prefer it over the first anyway.
The reason being readability: the for line is neat and tidy. With qualifiers and member variables in real production code it is quite easy to have **really** long for lines if you use the style in the first example. That's why i intentionally made it to have a horizontal scrollbar in this example, just so you see what i'm talking about. ;)
On the other hand, you suddenly introduce the Iter variables to the outer scope of the for loop. But then, at least in the environment i work in, the Iter would have been accessible in the outer scope even in the first example.
What is your take on this? Are there any pro's to the first style other than possibly limiting the scope of Iter?
|
If you wrap your code into lines properly, the inline form would be equally readable. Besides, you should always do the `iterEnd = container.end()` as an optimization:
```
for (SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(),
IterEnd = m_SomeMemberContainerVar.end();
Iter != IterEnd;
++Iter)
{
}
```
*Update: fixed the code per paercebal's advice.*
|
189,062 |
<p>When I navigate on a website utilizing MasterPages, does the application know what page I am on? If so, does it store it in an object I can access?</p>
<p>The reason I am asking is so I can replace this:</p>
<pre><code>//masterpage
<div id="nav_main">
<ul><asp:ContentPlaceHolder ID="navigation" runat="server">
</asp:ContentPlaceHolder></ul>
</div>
//content page(s)
<asp:Content ContentPlaceHolderID="navigation" ID="theNav" runat="server">
<li><a href="default.aspx">Home</a></li>
<li id="current"><a href="faq.aspx">FAQ</a></li>
<li><a href="videos.aspx">Videos</a></li>
<li><a href="#">Button 4</a></li>
<li><a href="#">Button 5</a></li>
</asp:Content>
</code></pre>
<p>With a more elegant solution for the navigation, which highlights the link to the page by having the list item's ID set to "current". Currently each page recreates the navigation with its respective link's ID set to current.</p>
|
[
{
"answer_id": 189085,
"author": "Jared",
"author_id": 1980,
"author_profile": "https://Stackoverflow.com/users/1980",
"pm_score": 0,
"selected": false,
"text": "<p>You should be able to get the page by accessing the Page property. IE:</p>\n\n<pre><code>string type = this.Page.GetType().Name.ToString();\n</code></pre>\n"
},
{
"answer_id": 189166,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": -1,
"selected": false,
"text": "<p>There's also the Request.RawURL</p>\n"
},
{
"answer_id": 189179,
"author": "Jared",
"author_id": 1980,
"author_profile": "https://Stackoverflow.com/users/1980",
"pm_score": 3,
"selected": false,
"text": "<p>To get the current request URL from within the master page you would do:</p>\n\n<pre><code>string s = this.Page.Request.FilePath; // \"/Default.aspx\"\n</code></pre>\n\n<p>I also recommend moving your navigation into the master page instead of the content page. This will make it easier to maintain / access.</p>\n"
},
{
"answer_id": 189183,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": -1,
"selected": false,
"text": "<p>The navigation control, not the master page, should be in charge of what page is currently highlighted.</p>\n\n<p>Either the page that is loaded should notify the navigation item who it is, or the nav control itself should keep track of it.</p>\n\n<p>The point is that master pages are supposed to simply be a holder that content is displayed in. They aren't supposed to control anything.</p>\n"
},
{
"answer_id": 189220,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "<p>You'd probably just use one of the <a href=\"http://www.west-wind.com/weblog/posts/269.aspx\" rel=\"nofollow noreferrer\">Request path</a> from within the master page to set the current. I'd probably also have a property on the master page to override it, so that pages without links or something could set it to something reasonable.</p>\n"
},
{
"answer_id": 189258,
"author": "Blumer",
"author_id": 8117,
"author_profile": "https://Stackoverflow.com/users/8117",
"pm_score": 5,
"selected": true,
"text": "<p>I'd concur with Chris: use a control to handle display of this menu and make it aware of what link should be highlighted. Here's a method I use regularly. It may become more complex if you've got multiple pages that would need the same link styled differently, but you get the idea.</p>\n\n<pre><code>Dim thisURL As String = Request.Url.Segments(Request.Url.Segments.Count - 1)\nSelect Cast thisUrl\n Case \"MenuItem1.aspx\"\n lnkMenu1.CssClass = \"Current\"\n Case \"MenuItem2.aspx\"\n lnkMenu2.CssClass = \"Current\"\nEnd Select\n</code></pre>\n"
},
{
"answer_id": 16061777,
"author": "Kush",
"author_id": 1324789,
"author_profile": "https://Stackoverflow.com/users/1324789",
"pm_score": -1,
"selected": false,
"text": "<p>try </p>\n\n<pre><code>this.Page.Master\n</code></pre>\n\n<p>It will get you the master page of the current page.</p>\n"
},
{
"answer_id": 17526003,
"author": "Sarim Shekhani",
"author_id": 1178073,
"author_profile": "https://Stackoverflow.com/users/1178073",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, Use the below code in your master file. It will give you the content page name. </p>\n\n<pre><code>Page.ToString().Replace(\"ASP.\",\"\").Replace(\"_\",\".\")\n</code></pre>\n"
},
{
"answer_id": 23493551,
"author": "Wazi",
"author_id": 3443090,
"author_profile": "https://Stackoverflow.com/users/3443090",
"pm_score": 0,
"selected": false,
"text": "<p>It worked for me this way - Thanks Jared</p>\n\n<p>This is what I did to get our nav menu to highlight the current menu item for the page that we are viewing. The code is in the master page.\nYou basically get the filepath (Jared's way)\nWe use the \"~\" in our links so I had to strip that out.\nIterate the menuItems collection of the Menu control.\nCompare the navigateUrl property.</p>\n\n<p>(I'm not the best coder and even worse at explaining - but it works and I was quite chuffed with it!)</p>\n\n<pre><code>protected void HighlightSelectedMenuItem()\n {\n string s = this.Page.Request.FilePath; // \"/Default.aspx\"\n string nav;\n if (s.Contains(\"~\"))\n {\n s = s.Remove(s.IndexOf(\"~\"), 1);\n }\n\n foreach (MenuItem item in navMenu.Items)\n {\n if (item.NavigateUrl.Contains(\"~\"))\n {\n nav = item.NavigateUrl.Remove(item.NavigateUrl.IndexOf(\"~\"), 1);\n if (s == nav)\n {\n item.Selected = true;\n }\n }\n\n }\n }\n</code></pre>\n"
},
{
"answer_id": 26190128,
"author": "Meysam Ghorbani",
"author_id": 3988122,
"author_profile": "https://Stackoverflow.com/users/3988122",
"pm_score": 0,
"selected": false,
"text": "<pre><code>string s = this.Page.GetType().FullName;\nstring[] array = s.Split('_');\nint count = array.Count<String>();\nstring currentPage = array[count - 2];\n</code></pre>\n"
},
{
"answer_id": 50665209,
"author": "eblancode",
"author_id": 8963333,
"author_profile": "https://Stackoverflow.com/users/8963333",
"pm_score": 1,
"selected": false,
"text": "<p>Alternatively you can search for page title if you have set an specific title to the child page instead of masterpage try:</p>\n\n<pre><code>this.Page.Title\n</code></pre>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 50741897,
"author": "masoud Cheragee",
"author_id": 720242,
"author_profile": "https://Stackoverflow.com/users/720242",
"pm_score": 1,
"selected": false,
"text": "<p>this is in C#</p>\n\n<pre><code>string thisURL = Request.Url.Segments[Request.Url.Segments.Length - 1];\n if (thisURL.ToLower()== \"default.aspx\") li1.Attributes.Add(\"class\",\"yekan active\");\n if (thisURL.ToLower() == \"experts.aspx\") li2.Attributes.Add(\"class\", \"yekan active\");\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
When I navigate on a website utilizing MasterPages, does the application know what page I am on? If so, does it store it in an object I can access?
The reason I am asking is so I can replace this:
```
//masterpage
<div id="nav_main">
<ul><asp:ContentPlaceHolder ID="navigation" runat="server">
</asp:ContentPlaceHolder></ul>
</div>
//content page(s)
<asp:Content ContentPlaceHolderID="navigation" ID="theNav" runat="server">
<li><a href="default.aspx">Home</a></li>
<li id="current"><a href="faq.aspx">FAQ</a></li>
<li><a href="videos.aspx">Videos</a></li>
<li><a href="#">Button 4</a></li>
<li><a href="#">Button 5</a></li>
</asp:Content>
```
With a more elegant solution for the navigation, which highlights the link to the page by having the list item's ID set to "current". Currently each page recreates the navigation with its respective link's ID set to current.
|
I'd concur with Chris: use a control to handle display of this menu and make it aware of what link should be highlighted. Here's a method I use regularly. It may become more complex if you've got multiple pages that would need the same link styled differently, but you get the idea.
```
Dim thisURL As String = Request.Url.Segments(Request.Url.Segments.Count - 1)
Select Cast thisUrl
Case "MenuItem1.aspx"
lnkMenu1.CssClass = "Current"
Case "MenuItem2.aspx"
lnkMenu2.CssClass = "Current"
End Select
```
|
189,079 |
<p>I'm having some minor problems with some animations I'm trying to set up. I have a couple divs stacked on top of each other kind of like this.</p>
<pre><code><div id="div1">
Stuff...
</div>
<div id="div2">
More Stuff...
</div>
</code></pre>
<p>Each of these divs has a drop shadow applied to it via jQuery plugin (jquery.dropshadow.js).</p>
<p>The problem occurs when I expand one of the divs using some kind of animation. The shadow does not update with the size of the div. I can redraw the shadow in the callback of the animation but still looks pretty joggy.</p>
<p>Is there a way that I can update the status of my shadows periodically throughout the course of the animation or can anyone recommend a better drop shadow library that would fix the problem? It doesn't have to be jQuery plugin.</p>
|
[
{
"answer_id": 189438,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, I still don't know how you animate, but I give you another example:</p>\n\n<pre><code>$('#foo').slideToggle().ready(function(){\n $('#foo').dropShadow(options); \n});\n</code></pre>\n\n<p>So, instead of <code>slideToggle</code>, just use whatever animation <em>thingy</em> you got.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 189535,
"author": "Marko Dumic",
"author_id": 5817,
"author_profile": "https://Stackoverflow.com/users/5817",
"pm_score": 1,
"selected": false,
"text": "<p>Try to apply the same animation effects to the shadow element(s). \nI don't know the exact technique used in jquery.dropshadow.js, but I suspect it creates copies of your shadow casting elements and styles them to achieve shadow like appearance. It is possible that these copies are siblings of their source elements, thus don't \"follow\" animation (as child elements would).</p>\n"
},
{
"answer_id": 190158,
"author": "Rudi",
"author_id": 22830,
"author_profile": "https://Stackoverflow.com/users/22830",
"pm_score": 2,
"selected": false,
"text": "<p>I think the only way to do this (at least with that particular drop shadow plugin) would be targeting both the element you want <strong>and</strong> all the drop-shadow \"phantom\" elements, in your animation. So, for example:</p>\n\n<pre><code> <style type=\"text/css\">\n #div1 { width: 50px; }\n </style>\n\n <div id=\"div1\">\n <p>Here is a lot of stuff. Stuff stuff stuff.</p>\n</div>\n\n<script type=\"text/javascript\">\n $(document).ready(function() {\n $(\"#div1\").dropShadow();\n $(\"#div1\").click(function() {\n $(\"#div1, #div1 + .dropShadow .dropShadow\").animate({ width: \"400px\" }, 1500);\n });\n });\n </script>\n</code></pre>\n\n<p>This is based on the structure of the rendered code that the drop-shadow plugin produces... all the fuzzy copies of your original element get a class of <em>.dropShadow</em> and get grouped into a container element which also has a class of <em>.dropShadow</em> and gets stuck into the document right after the original element (thus the <em>+</em> selector). </p>\n\n<p>As long as you apply whatever animation you're doing to all of these shadow elements, they all get animated (however, it <em>is</em> a bit jerky from all that processing... uffda).</p>\n"
},
{
"answer_id": 191268,
"author": "Dr. Bob",
"author_id": 12182,
"author_profile": "https://Stackoverflow.com/users/12182",
"pm_score": 3,
"selected": true,
"text": "<p>I would suggest using <strong>CSS</strong> for your drop shadows, and <strong>not JS</strong>.</p>\n\n<p>I have dealt with this exact problem in the past and I have completely stopped using JS for drop shadows. I have never seen animations with JS shadows look as smooth as pure CSS. Also, using too much JS to alter the page elements can cause performance issues.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17881/"
] |
I'm having some minor problems with some animations I'm trying to set up. I have a couple divs stacked on top of each other kind of like this.
```
<div id="div1">
Stuff...
</div>
<div id="div2">
More Stuff...
</div>
```
Each of these divs has a drop shadow applied to it via jQuery plugin (jquery.dropshadow.js).
The problem occurs when I expand one of the divs using some kind of animation. The shadow does not update with the size of the div. I can redraw the shadow in the callback of the animation but still looks pretty joggy.
Is there a way that I can update the status of my shadows periodically throughout the course of the animation or can anyone recommend a better drop shadow library that would fix the problem? It doesn't have to be jQuery plugin.
|
I would suggest using **CSS** for your drop shadows, and **not JS**.
I have dealt with this exact problem in the past and I have completely stopped using JS for drop shadows. I have never seen animations with JS shadows look as smooth as pure CSS. Also, using too much JS to alter the page elements can cause performance issues.
|
189,087 |
<p>If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this.</p>
<pre><code>for i in range(len(alist)):
for j in range(len(alist[i])):
if alist[i][j].isWhatever:
blist[i][j].doSomething()
</code></pre>
<p>Is there a nicer way to do something like this?</p>
|
[
{
"answer_id": 189096,
"author": "Haoest",
"author_id": 10088,
"author_profile": "https://Stackoverflow.com/users/10088",
"pm_score": -1,
"selected": false,
"text": "<pre><code>for d1 in alist\n for d2 in d1\n if d2 = \"whatever\"\n do_my_thing()\n</code></pre>\n"
},
{
"answer_id": 189111,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 3,
"selected": false,
"text": "<p>You could zip them. ie:</p>\n\n<pre><code>for a_row,b_row in zip(alist, blist):\n for a_item, b_item in zip(a_row,b_row):\n if a_item.isWhatever:\n b_item.doSomething()\n</code></pre>\n\n<p>However the overhead of zipping and iterating over the items may be higher than your original method if you rarely actually use the b_item (ie a_item.isWhatever is usually False). You could use itertools.izip instead of zip to reduce the memory impact of this, but its still probably going to be slightly slower unless you always need the b_item.</p>\n\n<p>Alternatively, consider using a 3D list instead, so terrain for cell i,j is at l[i][j][0], objects at l[i][j][1] etc, or even combine the objects so you can do a[i][j].terrain, a[i][j].object etc.</p>\n\n<p>[Edit] <a href=\"https://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189497\">DzinX's timings</a> actually show that the impact of the extra check for b_item isn't really significant, next to the performance penalty of re-looking up by index, so the above (using izip) seems to be fastest. </p>\n\n<p>I've now given a quick test for the 3d approach as well, and it seems faster still, so if you can store your data in that form, it could be both simpler and faster to access. Here's an example of using it:</p>\n\n<pre><code># Initialise 3d list:\nalist = [ [[A(a_args), B(b_args)] for i in xrange(WIDTH)] for j in xrange(HEIGHT)]\n\n# Process it:\nfor row in xlist:\n for a,b in row:\n if a.isWhatever(): \n b.doSomething()\n</code></pre>\n\n<p>Here are my timings for 10 loops using a 1000x1000 array, with various proportions of isWhatever being true are:</p>\n\n<pre><code> ( Chance isWhatever is True )\nMethod 100% 50% 10% 1%\n\n3d 3.422 2.151 1.067 0.824\nizip 3.647 2.383 1.282 0.985\noriginal 5.422 3.426 1.891 1.534\n</code></pre>\n"
},
{
"answer_id": 189112,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 2,
"selected": false,
"text": "<p>Are you sure that the objects in the two matrices you are iterating in parallel are instances of conceptually distinct classes? What about merging the two classes ending up with a matrix of objects that contain <em>both</em> isWhatever() and doSomething()?</p>\n"
},
{
"answer_id": 189165,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 5,
"selected": true,
"text": "<p>I'd start by writing a generator method:</p>\n\n<pre><code>def grid_objects(alist, blist):\n for i in range(len(alist)):\n for j in range(len(alist[i])):\n yield(alist[i][j], blist[i][j])\n</code></pre>\n\n<p>Then whenever you need to iterate over the lists your code looks like this:</p>\n\n<pre><code>for (a, b) in grid_objects(alist, blist):\n if a.is_whatever():\n b.do_something()\n</code></pre>\n"
},
{
"answer_id": 189234,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.python.org/doc/2.5.2/ref/genexpr.html\" rel=\"nofollow noreferrer\">Generator expressions</a> and <code>izip</code> from <a href=\"http://www.python.org/doc/2.5.2/lib/itertools-functions.html\" rel=\"nofollow noreferrer\">itertools module</a> will do very nicely here:</p>\n\n<pre><code>from itertools import izip\nfor a, b in (pair for (aline, bline) in izip(alist, blist) \n for pair in izip(aline, bline)):\n if a.isWhatever:\n b.doSomething()\n</code></pre>\n\n<p>The line in <code>for</code> statement above means:</p>\n\n<ul>\n<li>take each line from combined grids <code>alist</code> and <code>blist</code> and make a tuple from them <code>(aline, bline)</code></li>\n<li>now combine these lists with <code>izip</code> again and take each element from them (<code>pair</code>).</li>\n</ul>\n\n<p>This method has two advantages:</p>\n\n<ul>\n<li>there are no indices used anywhere</li>\n<li>you don't have to create lists with <code>zip</code> and use more efficient generators with <code>izip</code> instead.</li>\n</ul>\n"
},
{
"answer_id": 189270,
"author": "John Fouhy",
"author_id": 15154,
"author_profile": "https://Stackoverflow.com/users/15154",
"pm_score": 2,
"selected": false,
"text": "<p>As a slight style change, you could use enumerate:</p>\n\n<pre><code>for i, arow in enumerate(alist):\n for j, aval in enumerate(arow):\n if aval.isWhatever():\n blist[i][j].doSomething()\n</code></pre>\n\n<p>I don't think you'll get anything significantly simpler unless you rearrange your data structures as Federico suggests. So that you could turn the last line into something like \"aval.b.doSomething()\".</p>\n"
},
{
"answer_id": 189348,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 1,
"selected": false,
"text": "<p>If the two 2D-lists remain constant during the lifetime of your game <em>and</em> you can't enjoy Python's multiple inheritance to join the alist[i][j] and blist[i][j] object classes (as others have suggested), you could add a pointer to the corresponding <em>b</em> item in each <em>a</em> item after the lists are created, like this:</p>\n\n<pre><code>for a_row, b_row in itertools.izip(alist, blist):\n for a_item, b_item in itertools.izip(a_row, b_row):\n a_item.b_item= b_item\n</code></pre>\n\n<p>Various optimisations can apply here, like your classes having <code>__slots__</code> defined, or the initialization code above could be merged with your own initialization code e.t.c. After that, your loop will become:</p>\n\n<pre><code>for a_row in alist:\n for a_item in a_row:\n if a_item.isWhatever():\n a_item.b_item.doSomething()\n</code></pre>\n\n<p>That should be more efficient.</p>\n"
},
{
"answer_id": 189497,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 5,
"selected": false,
"text": "<p>If anyone is interested in performance of the above solutions, here they are for 4000x4000 grids, from fastest to slowest:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189111\">Brian</a>: 1.08s (modified, with <code>izip</code> instead of <code>zip</code>)</li>\n<li><a href=\"https://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189270\">John</a>: 2.33s</li>\n<li><a href=\"https://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189234\">DzinX</a>: 2.36s</li>\n<li><a href=\"https://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189348\">ΤΖΩΤΖΙΟΥ</a>: 2.41s (but object initialization took 62s)</li>\n<li><a href=\"https://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly\">Eugene</a>: 3.17s</li>\n<li><a href=\"https://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189165\">Robert</a>: 4.56s</li>\n<li><a href=\"https://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189111\">Brian</a>: 27.24s (original, with <code>zip</code>)</li>\n</ul>\n\n<p><strong>EDIT</strong>: Added Brian's scores with <code>izip</code> modification and it won by a large amount!</p>\n\n<p>John's solution is also very fast, although it uses indices (I was really surprised to see this!), whereas Robert's and Brian's (with <code>zip</code>) are slower than the question creator's initial solution.</p>\n\n<p>So let's present <a href=\"https://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189111\">Brian</a>'s winning function, as it is not shown in proper form anywhere in this thread:</p>\n\n<pre><code>from itertools import izip\nfor a_row,b_row in izip(alist, blist):\n for a_item, b_item in izip(a_row,b_row):\n if a_item.isWhatever:\n b_item.doSomething()\n</code></pre>\n"
},
{
"answer_id": 190904,
"author": "Ants Aasma",
"author_id": 107366,
"author_profile": "https://Stackoverflow.com/users/107366",
"pm_score": 2,
"selected": false,
"text": "<p>When you are operating with grids of numbers and want really good performance, you should consider using <a href=\"http://numpy.scipy.org\" rel=\"nofollow noreferrer\">Numpy</a>. It's surprisingly easy to use and lets you think in terms of operations with grids instead of loops over grids. The performance comes from the fact that the operations are then run over whole grids with optimised SSE code.</p>\n\n<p>For example here is some numpy using code that I wrote that does brute force numerical simulation of charged particles connected by springs. This code calculates a timestep for a 3d system with 100 nodes and 99 edges in 31ms. That is over 10x faster than the best pure python code I could come up with.</p>\n\n<pre><code>from numpy import array, sqrt, float32, newaxis\ndef evolve(points, velocities, edges, timestep=0.01, charge=0.1, mass=1., edgelen=0.5, dampen=0.95):\n \"\"\"Evolve a n body system of electrostatically repulsive nodes connected by\n springs by one timestep.\"\"\"\n velocities *= dampen\n\n # calculate matrix of distance vectors between all points and their lengths squared\n dists = array([[p2 - p1 for p2 in points] for p1 in points])\n l_2 = (dists*dists).sum(axis=2)\n\n # make the diagonal 1's to avoid division by zero\n for i in xrange(points.shape[0]):\n l_2[i,i] = 1\n\n l_2_inv = 1/l_2\n l_3_inv = l_2_inv*sqrt(l_2_inv)\n\n # repulsive force: distance vectors divided by length cubed, summed and multiplied by scale\n scale = timestep*charge*charge/mass\n velocities -= scale*(l_3_inv[:,:,newaxis].repeat(points.shape[1], axis=2)*dists).sum(axis=1)\n\n # calculate spring contributions for each point\n for idx, (point, outedges) in enumerate(izip(points, edges)):\n edgevecs = point - points.take(outedges, axis=0)\n edgevec_lens = sqrt((edgevecs*edgevecs).sum(axis=1))\n scale = timestep/mass\n velocities[idx] += (edgevecs*((((edgelen*scale)/edgevec_lens - scale))[:,newaxis].repeat(points.shape[1],axis=1))).sum(axis=0)\n\n # move points to new positions\n points += velocities*timestep\n</code></pre>\n"
},
{
"answer_id": 193825,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If <code>a.isWhatever</code> is rarely true you could build an \"index\" once:</p>\n\n<pre><code>a_index = set((i,j) \n for i,arow in enumerate(a) \n for j,a in enumerate(arow) \n if a.IsWhatever())\n</code></pre>\n\n<p>and each time you want something to be done:</p>\n\n<pre><code>for (i,j) in a_index:\n b[i][j].doSomething()\n</code></pre>\n\n<p>If a changes over time, then you will need to\nkeep the index up-to-date. That's why I used\na set, so items can be added and removed fast.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25680/"
] |
If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this.
```
for i in range(len(alist)):
for j in range(len(alist[i])):
if alist[i][j].isWhatever:
blist[i][j].doSomething()
```
Is there a nicer way to do something like this?
|
I'd start by writing a generator method:
```
def grid_objects(alist, blist):
for i in range(len(alist)):
for j in range(len(alist[i])):
yield(alist[i][j], blist[i][j])
```
Then whenever you need to iterate over the lists your code looks like this:
```
for (a, b) in grid_objects(alist, blist):
if a.is_whatever():
b.do_something()
```
|
189,094 |
<p>How can I get list all the files within a folder recursively in Java? </p>
|
[
{
"answer_id": 189108,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 5,
"selected": false,
"text": "<pre><code>import java.io.File;\npublic class Test {\n public static void main( String [] args ) {\n File actual = new File(\".\");\n for( File f : actual.listFiles()){\n System.out.println( f.getName() );\n }\n }\n}\n</code></pre>\n\n<p>It displays indistinctly files and folders.</p>\n\n<p>See the methods in File class to order them or avoid directory print etc.</p>\n\n<p><a href=\"http://java.sun.com/javase/6/docs/api/java/io/File.html\" rel=\"noreferrer\">http://java.sun.com/javase/6/docs/api/java/io/File.html</a></p>\n"
},
{
"answer_id": 189739,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 7,
"selected": true,
"text": "<p>Not sure how you want to represent the tree? Anyway here's an example which scans the entire subtree using recursion. Files and directories are treated alike. Note that <a href=\"http://docs.oracle.com/javase/6/docs/api/java/io/File.html#listFiles%28%29\" rel=\"noreferrer\">File.listFiles()</a> returns null for non-directories.</p>\n\n<pre><code>public static void main(String[] args) {\n Collection<File> all = new ArrayList<File>();\n addTree(new File(\".\"), all);\n System.out.println(all);\n}\n\nstatic void addTree(File file, Collection<File> all) {\n File[] children = file.listFiles();\n if (children != null) {\n for (File child : children) {\n all.add(child);\n addTree(child, all);\n }\n }\n}\n</code></pre>\n\n<p>Java 7 offers a couple of improvements. For example, <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newDirectoryStream%28java.nio.file.Path%29\" rel=\"noreferrer\">DirectoryStream</a> provides one result at a time - the caller no longer has to wait for all I/O operations to complete before acting. This allows incremental GUI updates, early cancellation, etc.</p>\n\n<pre><code>static void addTree(Path directory, Collection<Path> all)\n throws IOException {\n try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {\n for (Path child : ds) {\n all.add(child);\n if (Files.isDirectory(child)) {\n addTree(child, all);\n }\n }\n }\n}\n</code></pre>\n\n<p>Note that the dreaded null return value has been replaced by IOException.</p>\n\n<p>Java 7 also offers a <a href=\"http://docs.oracle.com/javase/tutorial/essential/io/walk.html\" rel=\"noreferrer\">tree walker</a>:</p>\n\n<pre><code>static void addTree(Path directory, final Collection<Path> all)\n throws IOException {\n Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)\n throws IOException {\n all.add(file);\n return FileVisitResult.CONTINUE;\n }\n });\n}\n</code></pre>\n"
},
{
"answer_id": 190492,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 0,
"selected": false,
"text": "<p>In JDK7, \"more NIO features\" should have methods to apply the visitor pattern over a file tree or just the immediate contents of a directory - no need to find all the files in a potentially huge directory before iterating over them. </p>\n"
},
{
"answer_id": 192001,
"author": "Leonel",
"author_id": 15649,
"author_profile": "https://Stackoverflow.com/users/15649",
"pm_score": 3,
"selected": false,
"text": "<p>You can also use the <a href=\"http://java.sun.com/javase/6/docs/api/java/io/FileFilter.html\" rel=\"noreferrer\" title=\"http://java.sun.com/javase/6/docs/api/java/io/FileFilter.html\"><code>FileFilter</code></a> interface to filter out what you want. It is best used when you create an anonymous class that implements it:</p>\n\n<pre><code>import java.io.File;\nimport java.io.FileFilter;\n\npublic class ListFiles {\n public File[] findDirectories(File root) { \n return root.listFiles(new FileFilter() {\n public boolean accept(File f) {\n return f.isDirectory();\n }});\n }\n\n public File[] findFiles(File root) {\n return root.listFiles(new FileFilter() {\n public boolean accept(File f) {\n return f.isFile();\n }});\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10496532,
"author": "Ohad Dan",
"author_id": 1381751,
"author_profile": "https://Stackoverflow.com/users/1381751",
"pm_score": 1,
"selected": false,
"text": "<p>Visualizing the tree structure was the most convenient way for me :</p>\n\n<pre><code>public static void main(String[] args) throws IOException {\n printTree(0, new File(\"START/FROM/DIR\"));\n}\n\nstatic void printTree(int depth, File file) throws IOException { \n StringBuilder indent = new StringBuilder();\n String name = file.getName();\n\n for (int i = 0; i < depth; i++) {\n indent.append(\".\");\n }\n\n //Pretty print for directories\n if (file.isDirectory()) { \n System.out.println(indent.toString() + \"|\");\n if(isPrintName(name)){\n System.out.println(indent.toString() + \"*\" + file.getName() + \"*\");\n }\n }\n //Print file name\n else if(isPrintName(name)) {\n System.out.println(indent.toString() + file.getName()); \n }\n //Recurse children\n if (file.isDirectory()) { \n File[] files = file.listFiles(); \n for (int i = 0; i < files.length; i++){\n printTree(depth + 4, files[i]);\n } \n }\n}\n\n//Exclude some file names\nstatic boolean isPrintName(String name){\n if (name.charAt(0) == '.') {\n return false;\n }\n if (name.contains(\"svn\")) {\n return false;\n }\n //.\n //. Some more exclusions\n //.\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 15110811,
"author": "Rohit sharma",
"author_id": 2115098,
"author_profile": "https://Stackoverflow.com/users/2115098",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public static void directory(File dir) {\n File[] files = dir.listFiles();\n for (File file : files) {\n System.out.println(file.getAbsolutePath());\n if (file.listFiles() != null)\n directory(file); \n }\n} \n</code></pre>\n\n<p>Here <code>dir</code> is Directory to be scanned. e.g. <code>c:\\</code></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8418/"
] |
How can I get list all the files within a folder recursively in Java?
|
Not sure how you want to represent the tree? Anyway here's an example which scans the entire subtree using recursion. Files and directories are treated alike. Note that [File.listFiles()](http://docs.oracle.com/javase/6/docs/api/java/io/File.html#listFiles%28%29) returns null for non-directories.
```
public static void main(String[] args) {
Collection<File> all = new ArrayList<File>();
addTree(new File("."), all);
System.out.println(all);
}
static void addTree(File file, Collection<File> all) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
all.add(child);
addTree(child, all);
}
}
}
```
Java 7 offers a couple of improvements. For example, [DirectoryStream](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#newDirectoryStream%28java.nio.file.Path%29) provides one result at a time - the caller no longer has to wait for all I/O operations to complete before acting. This allows incremental GUI updates, early cancellation, etc.
```
static void addTree(Path directory, Collection<Path> all)
throws IOException {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {
for (Path child : ds) {
all.add(child);
if (Files.isDirectory(child)) {
addTree(child, all);
}
}
}
}
```
Note that the dreaded null return value has been replaced by IOException.
Java 7 also offers a [tree walker](http://docs.oracle.com/javase/tutorial/essential/io/walk.html):
```
static void addTree(Path directory, final Collection<Path> all)
throws IOException {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
all.add(file);
return FileVisitResult.CONTINUE;
}
});
}
```
|
189,113 |
<p>I moved a <a href="http://en.wikipedia.org/wiki/WordPress" rel="noreferrer">WordPress</a> installation to a new folder on a Windows/<a href="http://en.wikipedia.org/wiki/Internet_Information_Services" rel="noreferrer">IIS</a> server. I'm setting up 301 redirects in PHP, but it doesn't seem to be working. My post URLs have the following format:</p>
<pre class="lang-none prettyprint-override"><code>http:://www.example.com/OLD_FOLDER/index.php/post-title/
</code></pre>
<p>I can't figure out how to grab the <code>/post-title/</code> part of the URL.</p>
<p><code>$_SERVER["REQUEST_URI"]</code> - which everyone seems to recommend - is returning an empty string. <code>$_SERVER["PHP_SELF"]</code> is just returning <code>index.php</code>. Why is this, and how can I fix it?</p>
|
[
{
"answer_id": 189123,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": false,
"text": "<p><code>$_SERVER['REQUEST_URI']</code> doesn't work on IIS, but I did find this: <a href=\"http://neosmart.net/blog/2006/100-apache-compliant-request_uri-for-iis-and-windows/\" rel=\"noreferrer\"><a href=\"http://neosmart.net/blog/2006/100-apache-compliant-request_uri-for-iis-and-windows/\" rel=\"noreferrer\">http://neosmart.net/blog/2006/100-apache-compliant-request_uri-for-iis-and-windows/</a></a> which sounds promising.</p>\n"
},
{
"answer_id": 189125,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 8,
"selected": true,
"text": "<p>Maybe, because you are under IIS, </p>\n\n<pre><code>$_SERVER['PATH_INFO']\n</code></pre>\n\n<p>is what you want, based on the URLs you used to explain.</p>\n\n<p>For Apache, you'd use <code>$_SERVER['REQUEST_URI']</code>.</p>\n"
},
{
"answer_id": 189150,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 2,
"selected": false,
"text": "<p>REQUEST_URI is set by Apache, so you won't get it with IIS. Try doing a var_dump or print_r on $_SERVER and see what values exist there that you can use.</p>\n"
},
{
"answer_id": 190770,
"author": "Adam Hopkinson",
"author_id": 12280,
"author_profile": "https://Stackoverflow.com/users/12280",
"pm_score": 2,
"selected": false,
"text": "<p>The posttitle part of the <a href=\"http://en.wikipedia.org/wiki/Uniform_Resource_Locator\" rel=\"nofollow noreferrer\">URL</a> is after your <code>index.php</code> file, which is a common way of providing friendly URLs without using mod_rewrite. The posttitle is actually therefore part of the query string, so you should be able to get it using $_SERVER['QUERY_STRING']</p>\n"
},
{
"answer_id": 1229827,
"author": "Jrgns",
"author_id": 6681,
"author_profile": "https://Stackoverflow.com/users/6681",
"pm_score": 3,
"selected": false,
"text": "<p>I use the following function to get the current, full URL. This should work on IIS and Apache.</p>\n\n<pre><code>function get_current_url() {\n\n $protocol = 'http';\n if ($_SERVER['SERVER_PORT'] == 443 || (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')) {\n $protocol .= 's';\n $protocol_port = $_SERVER['SERVER_PORT'];\n } else {\n $protocol_port = 80;\n }\n\n $host = $_SERVER['HTTP_HOST'];\n $port = $_SERVER['SERVER_PORT'];\n $request = $_SERVER['PHP_SELF'];\n $query = isset($_SERVER['argv']) ? substr($_SERVER['argv'][0], strpos($_SERVER['argv'][0], ';') + 1) : '';\n\n $toret = $protocol . '://' . $host . ($port == $protocol_port ? '' : ':' . $port) . $request . (empty($query) ? '' : '?' . $query);\n\n return $toret;\n}\n</code></pre>\n"
},
{
"answer_id": 1229924,
"author": "Tyler Carter",
"author_id": 58088,
"author_profile": "https://Stackoverflow.com/users/58088",
"pm_score": 6,
"selected": false,
"text": "<pre><code>$pageURL = (@$_SERVER[\"HTTPS\"] == \"on\") ? \"https://\" : \"http://\";\nif ($_SERVER[\"SERVER_PORT\"] != \"80\")\n{\n $pageURL .= $_SERVER[\"SERVER_NAME\"].\":\".$_SERVER[\"SERVER_PORT\"].$_SERVER[\"REQUEST_URI\"];\n} \nelse \n{\n $pageURL .= $_SERVER[\"SERVER_NAME\"].$_SERVER[\"REQUEST_URI\"];\n}\nreturn $pageURL;\n</code></pre>\n"
},
{
"answer_id": 2084669,
"author": "Joomla Developers",
"author_id": 253024,
"author_profile": "https://Stackoverflow.com/users/253024",
"pm_score": 0,
"selected": false,
"text": "<p>I have used the following code, and I am getting the right result...</p>\n\n<pre><code><?php\n function currentPageURL() {\n $curpageURL = 'http';\n if ($_SERVER[\"HTTPS\"] == \"on\") {\n $curpageURL.= \"s\";\n }\n $curpageURL.= \"://\";\n if ($_SERVER[\"SERVER_PORT\"] != \"80\") {\n $curpageURL.= $_SERVER[\"SERVER_NAME\"].\":\".$_SERVER[\"SERVER_PORT\"].$_SERVER[\"REQUEST_URI\"];\n } \n else {\n $curpageURL.= $_SERVER[\"SERVER_NAME\"].$_SERVER[\"REQUEST_URI\"];\n }\n return $curpageURL;\n }\n echo currentPageURL();\n?>\n</code></pre>\n"
},
{
"answer_id": 3900684,
"author": "Avery",
"author_id": 471563,
"author_profile": "https://Stackoverflow.com/users/471563",
"pm_score": 3,
"selected": false,
"text": "<p>Add:</p>\n\n<pre><code>function my_url(){\n $url = (!empty($_SERVER['HTTPS'])) ?\n \"https://\".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] :\n \"http://\".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];\n echo $url;\n}\n</code></pre>\n\n<p>Then just call the <code>my_url</code> function.</p>\n"
},
{
"answer_id": 4484061,
"author": "Sureshkumar",
"author_id": 547822,
"author_profile": "https://Stackoverflow.com/users/547822",
"pm_score": 3,
"selected": false,
"text": "<p>Use this class to get the URL works.</p>\n\n<pre><code>class VirtualDirectory\n{\n var $protocol;\n var $site;\n var $thisfile;\n var $real_directories;\n var $num_of_real_directories;\n var $virtual_directories = array();\n var $num_of_virtual_directories = array();\n var $baseURL;\n var $thisURL;\n\n function VirtualDirectory()\n {\n $this->protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';\n $this->site = $this->protocol . '://' . $_SERVER['HTTP_HOST'];\n $this->thisfile = basename($_SERVER['SCRIPT_FILENAME']);\n $this->real_directories = $this->cleanUp(explode(\"/\", str_replace($this->thisfile, \"\", $_SERVER['PHP_SELF'])));\n $this->num_of_real_directories = count($this->real_directories);\n $this->virtual_directories = array_diff($this->cleanUp(explode(\"/\", str_replace($this->thisfile, \"\", $_SERVER['REQUEST_URI']))),$this->real_directories);\n $this->num_of_virtual_directories = count($this->virtual_directories);\n $this->baseURL = $this->site . \"/\" . implode(\"/\", $this->real_directories) . \"/\";\n $this->thisURL = $this->baseURL . implode(\"/\", $this->virtual_directories) . \"/\";\n }\n\n function cleanUp($array)\n {\n $cleaned_array = array();\n foreach($array as $key => $value)\n {\n $qpos = strpos($value, \"?\");\n if($qpos !== false)\n {\n break;\n }\n if($key != \"\" && $value != \"\")\n {\n $cleaned_array[] = $value;\n }\n }\n return $cleaned_array;\n }\n}\n\n$virdir = new VirtualDirectory();\necho $virdir->thisURL;\n</code></pre>\n"
},
{
"answer_id": 6000346,
"author": "beniwal",
"author_id": 753387,
"author_profile": "https://Stackoverflow.com/users/753387",
"pm_score": 2,
"selected": false,
"text": "<p>Use the following line on the top of the PHP page where you're using <code>$_SERVER['REQUEST_URI']</code>. This will resolve your issue.</p>\n\n<pre><code>$_SERVER['REQUEST_URI'] = $_SERVER['PHP_SELF'] . '?' . $_SERVER['argv'][0];\n</code></pre>\n"
},
{
"answer_id": 10133524,
"author": "cwd",
"author_id": 288032,
"author_profile": "https://Stackoverflow.com/users/288032",
"pm_score": 5,
"selected": false,
"text": "<h2>For Apache:</h2>\n\n<pre><code>'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']\n</code></pre>\n\n<p><br />\nYou can also use <code>HTTP_HOST</code> instead of <code>SERVER_NAME</code> as Herman commented. See <a href=\"https://stackoverflow.com/questions/1459739/php-serverhttp-host-vs-serverserver-name-am-i-understanding-the-ma\">this related question</a> for a full discussion. In short, you are probably OK with using either. Here is the 'host' version:</p>\n\n<pre><code>'http'.(empty($_SERVER['HTTPS'])?'':'s').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']\n</code></pre>\n\n<p><br /></p>\n\n<h3>For the Paranoid / Why it Matters</h3>\n\n<p>Typically, I set <code>ServerName</code> in the <code>VirtualHost</code> because I want <em>that</em> to be the <a href=\"http://en.wikipedia.org/wiki/Canonical_link_element\" rel=\"nofollow noreferrer\">canonical</a> form of the website. The <code>$_SERVER['HTTP_HOST']</code> is set based on the request headers. If the server responds to any/all domain names at that IP address, a user could spoof the header, or worse, someone could point a DNS record to your IP address, and then your server / website would be serving out a website with dynamic links built on an incorrect URL. If you use the latter method you should also configure your <code>vhost</code> or set up an <code>.htaccess</code> rule to enforce the domain you want to serve out, something like:</p>\n\n<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} !(^stackoverflow.com*)$\nRewriteRule (.*) https://stackoverflow.com/$1 [R=301,L]\n#sometimes u may need to omit this slash ^ depending on your server\n</code></pre>\n\n<p>Hope that helps. The real point of this answer was just to provide the first line of code for those people who ended up here when searching for a way to get the complete URL with apache :)</p>\n"
},
{
"answer_id": 19483052,
"author": "Gajus",
"author_id": 368691,
"author_profile": "https://Stackoverflow.com/users/368691",
"pm_score": 0,
"selected": false,
"text": "<p>Everyone forgot <a href=\"http://uk3.php.net/manual/en/function.http-build-url.php\" rel=\"nofollow\">http_build_url</a>?</p>\n\n<pre><code>http_build_url($_SERVER['REQUEST_URI']);\n</code></pre>\n\n<p>When no parameters are passed to <code>http_build_url</code> it will automatically assume the current URL. I would expect <code>REQUEST_URI</code> to be included as well, though it seems to be required in order to include the GET parameters.</p>\n\n<p>The above example will return full URL.</p>\n"
},
{
"answer_id": 20123709,
"author": "SpYk3HH",
"author_id": 900807,
"author_profile": "https://Stackoverflow.com/users/900807",
"pm_score": 1,
"selected": false,
"text": "<p>Oh, the fun of a snippet!</p>\n\n<pre><code>if (!function_exists('base_url')) {\n function base_url($atRoot=FALSE, $atCore=FALSE, $parse=FALSE){\n if (isset($_SERVER['HTTP_HOST'])) {\n $http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';\n $hostname = $_SERVER['HTTP_HOST'];\n $dir = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);\n\n $core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);\n $core = $core[0];\n\n $tmplt = $atRoot ? ($atCore ? \"%s://%s/%s/\" : \"%s://%s/\") : ($atCore ? \"%s://%s/%s/\" : \"%s://%s%s\");\n $end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);\n $base_url = sprintf( $tmplt, $http, $hostname, $end );\n }\n else $base_url = 'http://localhost/';\n\n if ($parse) {\n $base_url = parse_url($base_url);\n if (isset($base_url['path'])) if ($base_url['path'] == '/') $base_url['path'] = '';\n }\n\n return $base_url;\n }\n}\n</code></pre>\n\n<p>It has beautiful returns like:</p>\n\n<pre><code>// A URL like http://stackoverflow.com/questions/189113/how-do-i-get-current-page-full-url-in-php-on-a-windows-iis-server:\n\necho base_url(); // Will produce something like: http://stackoverflow.com/questions/189113/\necho base_url(TRUE); // Will produce something like: http://stackoverflow.com/\necho base_url(TRUE, TRUE); || echo base_url(NULL, TRUE); //Will produce something like: http://stackoverflow.com/questions/\n\n// And finally:\necho base_url(NULL, NULL, TRUE);\n// Will produce something like:\n// array(3) {\n// [\"scheme\"]=>\n// string(4) \"http\"\n// [\"host\"]=>\n// string(12) \"stackoverflow.com\"\n// [\"path\"]=>\n// string(35) \"/questions/189113/\"\n// }\n</code></pre>\n"
},
{
"answer_id": 27585905,
"author": "Hüseyin Yağlı",
"author_id": 531524,
"author_profile": "https://Stackoverflow.com/users/531524",
"pm_score": 0,
"selected": false,
"text": "<p>In my apache server, this gives me the full URL in the exact format you are looking for:</p>\n\n<pre><code>$_SERVER[\"SCRIPT_URI\"]\n</code></pre>\n"
},
{
"answer_id": 39231892,
"author": "user1949536",
"author_id": 1949536,
"author_profile": "https://Stackoverflow.com/users/1949536",
"pm_score": 0,
"selected": false,
"text": "<h1>Reverse Proxy Support!</h1>\n\n<p>Something a little more robust. <strong>Note</strong> It'll only work on <code>5.3</code> or greater.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>/*\n * Compatibility with multiple host headers.\n * Support of \"Reverse Proxy\" configurations.\n *\n * Michael Jett <[email protected]>\n */\n\nfunction base_url() {\n\n $protocol = @$_SERVER['HTTP_X_FORWARDED_PROTO'] \n ?: @$_SERVER['REQUEST_SCHEME']\n ?: ((isset($_SERVER[\"HTTPS\"]) && $_SERVER[\"HTTPS\"] == \"on\") ? \"https\" : \"http\");\n\n $port = @intval($_SERVER['HTTP_X_FORWARDED_PORT'])\n ?: @intval($_SERVER[\"SERVER_PORT\"])\n ?: (($protocol === 'https') ? 443 : 80);\n\n $host = @explode(\":\", $_SERVER['HTTP_HOST'])[0]\n ?: @$_SERVER['SERVER_NAME']\n ?: @$_SERVER['SERVER_ADDR'];\n\n // Don't include port if it's 80 or 443 and the protocol matches\n $port = ($protocol === 'https' && $port === 443) || ($protocol === 'http' && $port === 80) ? '' : ':' . $port;\n\n return sprintf('%s://%s%s/%s', $protocol, $host, $port, @trim(reset(explode(\"?\", $_SERVER['REQUEST_URI'])), '/'));\n}\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19487/"
] |
I moved a [WordPress](http://en.wikipedia.org/wiki/WordPress) installation to a new folder on a Windows/[IIS](http://en.wikipedia.org/wiki/Internet_Information_Services) server. I'm setting up 301 redirects in PHP, but it doesn't seem to be working. My post URLs have the following format:
```none
http:://www.example.com/OLD_FOLDER/index.php/post-title/
```
I can't figure out how to grab the `/post-title/` part of the URL.
`$_SERVER["REQUEST_URI"]` - which everyone seems to recommend - is returning an empty string. `$_SERVER["PHP_SELF"]` is just returning `index.php`. Why is this, and how can I fix it?
|
Maybe, because you are under IIS,
```
$_SERVER['PATH_INFO']
```
is what you want, based on the URLs you used to explain.
For Apache, you'd use `$_SERVER['REQUEST_URI']`.
|
189,121 |
<p>using MVP, what is the normal order of construction and dependency injection.</p>
<p>normally you create a presenter for each view and pass the view into the presenter on constructor. But what if you have:</p>
<ol>
<li>A Service that multiple views need to listen to events on.</li>
<li>Multiple views all pointing to the same data model cache.</li>
</ol>
<p>can someone display a normal flow of info from a user click to data coming back in a service from a server.</p>
|
[
{
"answer_id": 191182,
"author": "Romain Verdier",
"author_id": 4687,
"author_profile": "https://Stackoverflow.com/users/4687",
"pm_score": 5,
"selected": true,
"text": "<p>Here is what I do:</p>\n\n<p>First, I define theses interfaces:</p>\n\n<pre><code>public interface IView<TPresenter>\n{\n TPresenter Presenter { get; set; }\n}\n\npublic interface IPresenter<TView, TPresenter>\n where TView : IView<TPresenter>\n where TPresenter : IPresenter<TView, TPresenter>\n{\n TView View { get; set; }\n}\n</code></pre>\n\n<p>Then this abstract presenter class: </p>\n\n<pre><code>public abstract class AbstractPresenter<TView, TPresenter> : IPresenter<TView, TPresenter>\n where TView : IView<TPresenter>\n where TPresenter : class, IPresenter<TView, TPresenter>\n{\n protected TView view;\n\n public TView View\n {\n get { return this.view; }\n set\n {\n this.view = value;\n this.view.Presenter = this as TPresenter;\n }\n }\n}\n</code></pre>\n\n<p>The view is injected via a property, instead of the constructor, to allow the bi-directional affection in the setter. Notice that a safe cast is needed...</p>\n\n<p>Then, my concrete presenter is something like :</p>\n\n<pre><code>public class MyPresenter : AbstractPresenter<IMyView, MyPresenter>\n{\n //...\n}\n</code></pre>\n\n<p>Where <code>IMyView</code> implements <code>IView</code>. A concrete view type must exists (e.g. <code>MyView</code>), but it's the container that resolves it:</p>\n\n<ol>\n<li>I register <code>MyPresenter</code> type as itself in the container, with a transient behavior.</li>\n<li>I register <code>MyView</code> as an <code>IMyView</code> in the container with a transient behavior.</li>\n<li>I then asks for a <code>MyPresenter</code> to the container.</li>\n<li>Container instanciate a MyView</li>\n<li>It instanciates a <code>MyPresenter</code></li>\n<li>It inject the view into the presenter through the <code>AbstractPresenter.View</code> property.</li>\n<li>The setter code completes the bi-directional association</li>\n<li>The container returns the couple Presenter/View</li>\n</ol>\n\n<p><strong>It allows you to inject other dependencies (services, repos) into both your view and your presenter.</strong> But in the scenario you described, I recommend you to inject services and caches into the <strong>presenter</strong>, instead of the view.</p>\n"
},
{
"answer_id": 845750,
"author": "Mike Post",
"author_id": 20788,
"author_profile": "https://Stackoverflow.com/users/20788",
"pm_score": 3,
"selected": false,
"text": "<p>In WinForms, I prefer a simple approach. Usually you're dealing with a few UserControls on a design surface -- make these your view classes. .NET creates the control hierarchy for you (via InitializeComponent). If you use the <a href=\"http://martinfowler.com/eaaDev/PassiveScreen.html\" rel=\"noreferrer\">Passive View</a> pattern, each view then instantiates it's presenter. (You can do this either directly or by asking an IOC container.) Use constructor injection to pass a reference to the view's interface to the presenter's constructor. The presenter can then wire itself up to view events. Repeat the process for the model: the presenter instantiates a model and wires up to its events. (In this case you don't need the constructor injection since Passive View says the presenter keeps a reference to the model, not vice versa.)</p>\n\n<p>The only nit I've found with this approach is properly managing lifetimes of the model and presenter. You want to keep the view as simple as possible, so you probably don't want it maintaining a reference to the presenter. However, that means you've got this presenter object hanging around with event handlers tied to your view. This setup prevents your view from being garbage collected. One solution is to have your view publish an event that indicates it's closing. The presenter would receive the event and remove both its model and view subscriptions. The objects in your web are now properly dereferenced and the garbage collector can go about its work.</p>\n\n<p>You wind up with something like the following:</p>\n\n<pre><code>public interface IView\n{\n ...\n event Action SomeEvent;\n event EventHandler Disposed;\n ...\n}\n\n// Note that the IView.Disposed event is implemented by the \n// UserControl.Disposed event. \npublic class View : UserControl, IView\n{\n public event Action SomeEvent;\n\n public View()\n {\n var presenter = new Presenter(this);\n }\n}\n\npublic interface IModel\n{\n ...\n event Action ModelChanged;\n ...\n}\n\npublic class Model : IModel\n{\n ...\n public event Action ModelChanged;\n ...\n}\n\npublic class Presenter\n{\n private IView MyView;\n private IModel MyModel;\n\n public Presenter(View view)\n {\n MyView = view;\n MyView.SomeEvent += RespondToSomeEvent;\n MyView.Disposed += ViewDisposed;\n\n MyModel = new Model();\n MyModel.ModelChanged += RespondToModelChanged;\n }\n\n // You could take this a step further by implementing IDisposable on the\n // presenter and having View.Dispose() trigger Presenter.Dispose().\n private void ViewDisposed(object sender, EventArgs e)\n {\n MyView.SomeEvent -= RespondToSomeEvent;\n MyView.Disposed -= ViewDisposed;\n MyView = null;\n\n MyModel.Modelchanged -= RespondToModelChanged;\n MyModel = null;\n }\n}\n</code></pre>\n\n<p>You can decouple this example a step further by using IOC and asking your IOC container for implementations of IModel (in the Presenter class) and IPresenter (in the View class).</p>\n"
},
{
"answer_id": 9917053,
"author": "Pradeep",
"author_id": 1299458,
"author_profile": "https://Stackoverflow.com/users/1299458",
"pm_score": 0,
"selected": false,
"text": "<pre><code>interface IEmployee\n{\n int EmployeeId {get;}\n string FirstName {get;}\n string LastName {get;}\n}\ninterface IEmployeeRepository\n{\n void SaveEmployee(IEmployee employee);\n IEmployee GetEmployeeById(int employeeId);\n IEmployee[] Employees { get; }\n}\ninterface IEmployeeView\n{\n event Action<IEmployee> OnEmployeeSaved;\n}\n\ninterface IEmployeeController\n{\n IEmployeeView View {get;}\n IEmployeeRepository Repository {get;}\n IEmployee[] Employees {get;} \n}\n\npartial class EmployeeView: UserControl, IEmployeeView\n{\n public EmployeeView()\n {\n InitComponent();\n }\n}\nclass EmployeeController:IEmployeeController\n{\n private IEmployeeView view;\n private IEmployeeRepository repository;\n public EmployeeController(IEmployeeView view, IEmployeeRepository repository)\n {\n this.repository = repository;\n this.view = view;\n this.view.OnEmployeeSaved+=new Action<IEmployee>(view_OnEmployeeSaved);\n }\n\n void view_OnEmployeeSaved(IEmployee employee)\n {\n repository.SaveEmployee(employee);\n }\n public IEmployeeView View \n {\n get\n { \n return view;\n }\n }\n public IEmployeeRepository Repository\n {\n get\n {\n return repository;\n }\n }\n\n public IEmployee[] Employees\n {\n get \n {\n return repository.Employees;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 51503771,
"author": "Nishara MJ",
"author_id": 1633297,
"author_profile": "https://Stackoverflow.com/users/1633297",
"pm_score": 0,
"selected": false,
"text": "<p>WinformsMVP is a very good MVP framework for Windows forms. You can easily inject an service across multiple views easily using this framework. <a href=\"https://www.codeproject.com/Articles/522809/WinForms-MVP-An-MVP-Framework-for-WinForms\" rel=\"nofollow noreferrer\">This</a> is a good article with a sample source code explains how to use the framework.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
using MVP, what is the normal order of construction and dependency injection.
normally you create a presenter for each view and pass the view into the presenter on constructor. But what if you have:
1. A Service that multiple views need to listen to events on.
2. Multiple views all pointing to the same data model cache.
can someone display a normal flow of info from a user click to data coming back in a service from a server.
|
Here is what I do:
First, I define theses interfaces:
```
public interface IView<TPresenter>
{
TPresenter Presenter { get; set; }
}
public interface IPresenter<TView, TPresenter>
where TView : IView<TPresenter>
where TPresenter : IPresenter<TView, TPresenter>
{
TView View { get; set; }
}
```
Then this abstract presenter class:
```
public abstract class AbstractPresenter<TView, TPresenter> : IPresenter<TView, TPresenter>
where TView : IView<TPresenter>
where TPresenter : class, IPresenter<TView, TPresenter>
{
protected TView view;
public TView View
{
get { return this.view; }
set
{
this.view = value;
this.view.Presenter = this as TPresenter;
}
}
}
```
The view is injected via a property, instead of the constructor, to allow the bi-directional affection in the setter. Notice that a safe cast is needed...
Then, my concrete presenter is something like :
```
public class MyPresenter : AbstractPresenter<IMyView, MyPresenter>
{
//...
}
```
Where `IMyView` implements `IView`. A concrete view type must exists (e.g. `MyView`), but it's the container that resolves it:
1. I register `MyPresenter` type as itself in the container, with a transient behavior.
2. I register `MyView` as an `IMyView` in the container with a transient behavior.
3. I then asks for a `MyPresenter` to the container.
4. Container instanciate a MyView
5. It instanciates a `MyPresenter`
6. It inject the view into the presenter through the `AbstractPresenter.View` property.
7. The setter code completes the bi-directional association
8. The container returns the couple Presenter/View
**It allows you to inject other dependencies (services, repos) into both your view and your presenter.** But in the scenario you described, I recommend you to inject services and caches into the **presenter**, instead of the view.
|
189,148 |
<p>(See related question: <a href="https://stackoverflow.com/questions/162917/how-do-i-report-an-error-midway-through-a-chunked-http-repsonse-without-closing">How do I report an error midway through a chunked http repsonse without closing the connection?</a>)</p>
<p>In my case, the #1 desire is for the browser to display an error message. No matter how uninformative.</p>
<p>Closing the ServletResponse outputStream obviously doesn't work. Neither does throwing an exception, even if I don't close first (tested on Tomcat 6.0.16). I think that what I want is either a RST packet, FIN in the middle of a chunk, or badly formed chunk headers.</p>
<p>After that I can worry about how various browsers respond.</p>
<p>Edited for clarification: This is for a file download, perhaps several gigabytes of binary data. I can't make certain that all of the data can be successfully read or decrypted before I have to start sending some of it.</p>
|
[
{
"answer_id": 189285,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 0,
"selected": false,
"text": "<p>I think you're going about it the wrong way. It seems like it would be simpler to not actually start sending the data until you're sure if will be a success or a failure. That way you can send an error message at the start if needed, instead of sending partial data that's not valid.</p>\n\n<p>If you really must, you might be able to wrangle something up with JavaScript. When you get to the error, output something like this before closing the connection:</p>\n\n<pre><code><script type=\"text/javascript\"> alert(\"Processing failed!\"); </script>\n</code></pre>\n\n<p>You might want to expand on the script, but you get the general idea. This is assuming that what's being sent back to the browser is a HTML page, you didn't specify that in the question.</p>\n"
},
{
"answer_id": 206207,
"author": "Darron",
"author_id": 22704,
"author_profile": "https://Stackoverflow.com/users/22704",
"pm_score": 2,
"selected": true,
"text": "<p>My own answer, after research.</p>\n\n<p>Part one: There seems to be no way to convince the application servers that I tested to put an error onto the wire past the \"committed\" phase. The following Servlet code results in legal HTTP Chunked Transfer headers on the socket. Interestingly, in the case of WebSphere an error message is appended to the end of the stream before the end mark.</p>\n\n<pre><code>public class Servlet extends HttpServlet {\n public static final int ARRAY_SIZE = 65536;\n private static final int SEND_COUNT = 100000;\n\n protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {\n\n String testData = \"This is a fairly long piece of test text, running on and on and on, over and over.\";\n\n final ServletOutputStream outputStream = response.getOutputStream();\n for (int i = 0; i < SEND_COUNT; ++i) {\n outputStream.println(testData);\n }\n throw new ServletException(\"Break it now\");\n }\n}\n</code></pre>\n\n<p>Part two: Even if the application server was willing to either write bogus data to the wire or close the socket without a closing zero length chunk, common clients do not report an error. IE7, FF3 and cURL do not report errors in chunk encoding. This makes HTTP downloads inherently unreliable, and is contrary to the spirit if not the letter of the HTTP 1.1 RFC.</p>\n"
},
{
"answer_id": 206250,
"author": "johnstok",
"author_id": 27929,
"author_profile": "https://Stackoverflow.com/users/27929",
"pm_score": 0,
"selected": false,
"text": "<p>The servlet API doesn't allow it. Once the response is committed the response code has been sent. The best you can do is close the connection and log the error.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22704/"
] |
(See related question: [How do I report an error midway through a chunked http repsonse without closing the connection?](https://stackoverflow.com/questions/162917/how-do-i-report-an-error-midway-through-a-chunked-http-repsonse-without-closing))
In my case, the #1 desire is for the browser to display an error message. No matter how uninformative.
Closing the ServletResponse outputStream obviously doesn't work. Neither does throwing an exception, even if I don't close first (tested on Tomcat 6.0.16). I think that what I want is either a RST packet, FIN in the middle of a chunk, or badly formed chunk headers.
After that I can worry about how various browsers respond.
Edited for clarification: This is for a file download, perhaps several gigabytes of binary data. I can't make certain that all of the data can be successfully read or decrypted before I have to start sending some of it.
|
My own answer, after research.
Part one: There seems to be no way to convince the application servers that I tested to put an error onto the wire past the "committed" phase. The following Servlet code results in legal HTTP Chunked Transfer headers on the socket. Interestingly, in the case of WebSphere an error message is appended to the end of the stream before the end mark.
```
public class Servlet extends HttpServlet {
public static final int ARRAY_SIZE = 65536;
private static final int SEND_COUNT = 100000;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
String testData = "This is a fairly long piece of test text, running on and on and on, over and over.";
final ServletOutputStream outputStream = response.getOutputStream();
for (int i = 0; i < SEND_COUNT; ++i) {
outputStream.println(testData);
}
throw new ServletException("Break it now");
}
}
```
Part two: Even if the application server was willing to either write bogus data to the wire or close the socket without a closing zero length chunk, common clients do not report an error. IE7, FF3 and cURL do not report errors in chunk encoding. This makes HTTP downloads inherently unreliable, and is contrary to the spirit if not the letter of the HTTP 1.1 RFC.
|
189,156 |
<p>Running FxCop on my code, I get this warning:</p>
<blockquote>
<p>Microsoft.Maintainability :
'FooBar.ctor is coupled with 99
different types from 9 different
namespaces. Rewrite or refactor the
method to decrease its class coupling,
or consider moving the method to one
of the other types it is tightly
coupled with. A class coupling above
40 indicates poor maintainability, a
class coupling between 40 and 30
indicates moderate maintainability,
and a class coupling below 30
indicates good maintainability.</p>
</blockquote>
<p>My class is a landing zone for all messages from the server. The server can send us messages of different EventArgs types:</p>
<pre><code>public FooBar()
{
var messageHandlers = new Dictionary<Type, Action<EventArgs>>();
messageHandlers.Add(typeof(YouHaveBeenLoggedOutEventArgs), HandleSignOut);
messageHandlers.Add(typeof(TestConnectionEventArgs), HandleConnectionTest);
// ... etc for 90 other types
}
</code></pre>
<p>The "HandleSignOut" and "HandleConnectionTest" methods have little code in them; they usually pass the work off to a function in another class.</p>
<p>How can I make this class better with lower coupling?</p>
|
[
{
"answer_id": 189164,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps instead of having a different class for each message, use a flag that identifies the message.</p>\n\n<p>That would drastically reduce the number of messages you have and increase maintainability. My guess is that most of the message classes have about zero difference.</p>\n\n<p>It's hard to pick an additional way of attacking this because the rest of the architecture is unknown (to me). </p>\n\n<p>If you look at Windows, for example, it doesn't natively know how to handle each message that might be thrown about. Instead, the underlying message handlers register callback functions with the main thread. </p>\n\n<p>You might take a similiar approach. Each message class would need to know how to handle itself and could register itself with the larger application. This should greatly simplify the code and get rid of the tight coupling.</p>\n"
},
{
"answer_id": 189199,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": false,
"text": "<p>You could also use some sort of IoC framework, like Spring.NET, to inject the dictionary. This way, if you get a new message type, you don't have to recompile this central hub - just change a config file.\n<hr/>\nThe long awaited example:</p>\n\n<p>Create a new console app, named Example, and add this:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing Spring.Context.Support;\n\nnamespace Example\n{\n internal class Program\n {\n private static void Main(string[] args)\n {\n MessageBroker broker = (MessageBroker) ContextRegistry.GetContext()[\"messageBroker\"];\n broker.Dispatch(null, new Type1EventArgs());\n broker.Dispatch(null, new Type2EventArgs());\n broker.Dispatch(null, new EventArgs());\n }\n }\n\n public class MessageBroker\n {\n private Dictionary<Type, object> handlers;\n\n public Dictionary<Type, object> Handlers\n {\n get { return handlers; }\n set { handlers = value; }\n }\n\n public void Dispatch<T>(object sender, T e) where T : EventArgs\n {\n object entry;\n if (Handlers.TryGetValue(e.GetType(), out entry))\n {\n MessageHandler<T> handler = entry as MessageHandler<T>;\n if (handler != null)\n {\n handler.HandleMessage(sender, e);\n }\n else\n {\n //I'd log an error here\n Console.WriteLine(\"The handler defined for event type '\" + e.GetType().Name + \"' doesn't implement the correct interface!\");\n }\n }\n else\n {\n //I'd log a warning here\n Console.WriteLine(\"No handler defined for event type: \" + e.GetType().Name);\n }\n }\n }\n\n public interface MessageHandler<T> where T : EventArgs\n {\n void HandleMessage(object sender, T message);\n }\n\n public class Type1MessageHandler : MessageHandler<Type1EventArgs>\n {\n public void HandleMessage(object sender, Type1EventArgs args)\n {\n Console.WriteLine(\"Type 1, \" + args.ToString());\n }\n }\n\n public class Type2MessageHandler : MessageHandler<Type2EventArgs>\n {\n public void HandleMessage(object sender, Type2EventArgs args)\n {\n Console.WriteLine(\"Type 2, \" + args.ToString());\n }\n }\n\n public class Type1EventArgs : EventArgs {}\n\n public class Type2EventArgs : EventArgs {}\n}\n</code></pre>\n\n<p>And an app.config file:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <configSections>\n <sectionGroup name=\"spring\">\n <section name=\"context\" type=\"Spring.Context.Support.ContextHandler, Spring.Core\"/>\n <section name=\"objects\" type=\"Spring.Context.Support.DefaultSectionHandler, Spring.Core\"/>\n </sectionGroup>\n </configSections>\n\n <spring>\n <context>\n <resource uri=\"config://spring/objects\"/>\n </context>\n <objects xmlns=\"http://www.springframework.net\">\n\n <object id=\"messageBroker\" type=\"Example.MessageBroker, Example\">\n <property name=\"handlers\">\n <dictionary key-type=\"System.Type\" value-type=\"object\">\n <entry key=\"Example.Type1EventArgs, Example\" value-ref=\"type1Handler\"/>\n <entry key=\"Example.Type2EventArgs, Example\" value-ref=\"type2Handler\"/>\n </dictionary>\n </property>\n </object>\n <object id=\"type1Handler\" type=\"Example.Type1MessageHandler, Example\"/>\n <object id=\"type2Handler\" type=\"Example.Type2MessageHandler, Example\"/>\n </objects>\n </spring>\n</configuration>\n</code></pre>\n\n<p>Output:</p>\n\n<pre>\nType 1, Example.Type1EventArgs\nType 2, Example.Type2EventArgs\nNo handler defined for event type: EventArgs\n</pre>\n\n<p>As you can see, <code>MessageBroker</code> doesn't know about any of the handlers, and the handlers don't know about <code>MessageBroker</code>. All of the mapping is done in the app.config file, so that if you need to handle a new event type, you can add it in the config file. This is especially nice if other teams are defining event types and handlers - they can just compile their stuff in a dll, you drop it into your deployment and simply add a mapping.</p>\n\n<p>The Dictionary has values of type object instead of <code>MessageHandler<></code> because the actual handlers can't be cast to <code>MessageHandler<EventArgs></code>, so I had to hack around that a bit. I think the solution is still clean, and it handles mapping errors well. Note that you'll also need to reference Spring.Core.dll in this project. You can find the libraries <a href=\"http://downloads.sourceforge.net/springnet/Spring.NET-1.1.2.zip?modtime=1210044370&big_mirror=0\" rel=\"nofollow noreferrer\">here</a>, and the documentation <a href=\"http://springframework.net/docs/1.1.2/reference/html/index.html\" rel=\"nofollow noreferrer\">here</a>. The <a href=\"http://springframework.net/docs/1.1.2/reference/html/objects.html#objects-dependencies\" rel=\"nofollow noreferrer\">dependency injection chapter</a> is relevant to this. Also note, there is no reason you need to use Spring.NET for this - the important idea here is dependency injection. Somehow, something is going to need to tell the broker to send messages of type a to x, and using an IoC container for dependency injection is a good way to have the broker not know about x, and vice versa.</p>\n\n<p>Some other SO question related to IoC and DI:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/139299/difference-between-dependency-injection-di-inversion-of-control-ioc\">Difference between Dependency Injection (DI) & Inversion of Control (IOC)</a></li>\n<li><a href=\"https://stackoverflow.com/questions/21288/which-cnet-dependency-injection-frameworks-are-worth-looking-into\">Which C#/.net Dependency Injection frameworks are worth looking into?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/148908/which-dependency-injection-tool-should-i-use\">Which Dependency Injection Tool Should I Use?</a></li>\n</ul>\n"
},
{
"answer_id": 189201,
"author": "Grzenio",
"author_id": 5363,
"author_profile": "https://Stackoverflow.com/users/5363",
"pm_score": 0,
"selected": false,
"text": "<p>I don't see the rest of your code, but I would try create a much smaller number of Event arg classes. Instead create a few that are similar to each other in terms of data contained and/or the way you handle them later and add a field that will tell you what exact type of event occured (probably you should use an enum). </p>\n\n<p>Ideally you would not only make this constructor much more readable, but also the way the messages are handled (group messages that are handled in a similar way in a single event handler)</p>\n"
},
{
"answer_id": 189208,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 5,
"selected": true,
"text": "<p>Have the classes that do the work register for events they're interested in...an <a href=\"http://msforge.net/blogs/paki/archive/2007/11/20/EventBroker-implementation-in-C_2300_-full-source-code.aspx\" rel=\"nofollow noreferrer\">event broker</a> pattern.</p>\n\n<pre><code>class EventBroker {\n private Dictionary<Type, Action<EventArgs>> messageHandlers;\n\n void Register<T>(Action<EventArgs> subscriber) where T:EventArgs {\n // may have to combine delegates if more than 1 listener\n messageHandlers[typeof(T)] = subscriber; \n }\n\n void Send<T>(T e) where T:EventArgs {\n var d = messageHandlers[typeof(T)];\n if (d != null) {\n d(e);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 189241,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 0,
"selected": false,
"text": "<p>Obviously you are in need of a dispatching mechanism: depending on the event you receive, you want to execute different code.</p>\n\n<p>You seem to be using the type system to identify the events, while it's actually meant to support polymorphism. As Chris Lively suggests, you could just as well (without abusing the type system) use an enumerate to identify the messages.</p>\n\n<p>Or you can embrace the power of the type system, and create a Registry object where every type of event is registered (by a static instance, a config file or whatsoever). Then you could use the Chain of Responsibility pattern to find the proper handler. Either the handler does the handling itself, or it may be a Factory, creating an object that handles the event.</p>\n\n<p>The latter method looks a bit underspecified and overengineered, but in the case of 99 event types (already), it seems appropriate to me.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536/"
] |
Running FxCop on my code, I get this warning:
>
> Microsoft.Maintainability :
> 'FooBar.ctor is coupled with 99
> different types from 9 different
> namespaces. Rewrite or refactor the
> method to decrease its class coupling,
> or consider moving the method to one
> of the other types it is tightly
> coupled with. A class coupling above
> 40 indicates poor maintainability, a
> class coupling between 40 and 30
> indicates moderate maintainability,
> and a class coupling below 30
> indicates good maintainability.
>
>
>
My class is a landing zone for all messages from the server. The server can send us messages of different EventArgs types:
```
public FooBar()
{
var messageHandlers = new Dictionary<Type, Action<EventArgs>>();
messageHandlers.Add(typeof(YouHaveBeenLoggedOutEventArgs), HandleSignOut);
messageHandlers.Add(typeof(TestConnectionEventArgs), HandleConnectionTest);
// ... etc for 90 other types
}
```
The "HandleSignOut" and "HandleConnectionTest" methods have little code in them; they usually pass the work off to a function in another class.
How can I make this class better with lower coupling?
|
Have the classes that do the work register for events they're interested in...an [event broker](http://msforge.net/blogs/paki/archive/2007/11/20/EventBroker-implementation-in-C_2300_-full-source-code.aspx) pattern.
```
class EventBroker {
private Dictionary<Type, Action<EventArgs>> messageHandlers;
void Register<T>(Action<EventArgs> subscriber) where T:EventArgs {
// may have to combine delegates if more than 1 listener
messageHandlers[typeof(T)] = subscriber;
}
void Send<T>(T e) where T:EventArgs {
var d = messageHandlers[typeof(T)];
if (d != null) {
d(e);
}
}
}
```
|
189,172 |
<p>I'm told that the template system in C++ is Turing-complete at compile time. This is mentioned in <a href="https://stackoverflow.com/questions/75538/hidden-features-of-c#75627">this post</a> and also on <a href="http://en.wikipedia.org/wiki/C%2B%2B" rel="noreferrer">wikipedia</a>.</p>
<p>Can you provide a nontrivial example of a computation that exploits this property?</p>
<p>Is this fact useful in practice?</p>
|
[
{
"answer_id": 189187,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 5,
"selected": false,
"text": "<p>\"<a href=\"http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.14.3670\" rel=\"noreferrer\">C++ Templates Are Turing Complete</a>\" gives an implementation of a Turing machine in templates ... which is non-trivial and proves the point in a very direct way. Of course, it also isn't very useful!</p>\n"
},
{
"answer_id": 189198,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>It may be useful if you want to compute constants at compile time, at least in theory. Check out <a href=\"http://en.wikipedia.org/wiki/Template_metaprogramming\" rel=\"nofollow noreferrer\">template metaprogramming</a>.</p>\n"
},
{
"answer_id": 189203,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 3,
"selected": false,
"text": "<p>I think it's called <a href=\"http://en.wikipedia.org/wiki/Template_metaprogramming\" rel=\"noreferrer\">template meta-programming</a>. </p>\n"
},
{
"answer_id": 189204,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": false,
"text": "<p>My C++ is a bit rusty, so the may not be perfect, but it's close.</p>\n\n<pre><code>template <int N> struct Factorial\n{\n enum { val = Factorial<N-1>::val * N };\n};\n\ntemplate <> struct Factorial<0>\n{\n enum { val = 1 };\n}\n\nconst int num = Factorial<10>::val; // num set to 10! at compile time.\n</code></pre>\n\n<p>The point is to demonstrate that the compiler is completely evaluating the recursive definition until it reaches an answer.</p>\n"
},
{
"answer_id": 189309,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 2,
"selected": false,
"text": "<p>It's also fun to point out that it is a purely functional language albeit nearly impossible to debug. If you look at <a href=\"https://stackoverflow.com/questions/189172/c-templates-turing-complete#189204\">James</a> post you will see what I mean by it being functional. In general it's not the most useful feature of C++. It wasn't designed to do this. It's something that was discovered.</p>\n"
},
{
"answer_id": 189444,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 8,
"selected": true,
"text": "<p>Example</p>\n\n<pre><code>#include <iostream>\n\ntemplate <int N> struct Factorial\n{\n enum { val = Factorial<N-1>::val * N };\n};\n\ntemplate<>\nstruct Factorial<0>\n{\n enum { val = 1 };\n};\n\nint main()\n{\n // Note this value is generated at compile time.\n // Also note that most compilers have a limit on the depth of the recursion available.\n std::cout << Factorial<4>::val << \"\\n\";\n}\n</code></pre>\n\n<p>That was a little fun but not very practical.<br></p>\n\n<p>To answer the second part of the question:<br>\n<b>Is this fact useful in practice?</b></p>\n\n<p>Short Answer: Sort of.</p>\n\n<p>Long Answer: Yes, but only if you are a template daemon.</p>\n\n<p>To turn out good programming using template meta-programming that is really useful for others to use (ie a library) is really really tough (though do-able). To Help boost even has <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/mpl/doc/index.html\" rel=\"noreferrer\">MPL</a> aka (Meta Programming Library). But try debugging a compiler error in your template code and you will be in for a long hard ride.</p>\n\n<p>But a good practical example of it being used for something useful: </p>\n\n<p>Scott Meyers has been working extensions to the C++ language (I use the term loosely) using the templating facilities. You can read about his work here '<a href=\"http://www.artima.com/cppsource/codefeaturesP.html\" rel=\"noreferrer\">Enforcing Code Features</a>'</p>\n"
},
{
"answer_id": 189595,
"author": "yoav.aviram",
"author_id": 25287,
"author_profile": "https://Stackoverflow.com/users/25287",
"pm_score": 3,
"selected": false,
"text": "<p>The Book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201704315\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Modern C++ Design - Generic Programming and Design Pattern</a> by Andrei Alexandrescu is the best place to get hands on experience with useful and powerful generic programing patterns.</p>\n"
},
{
"answer_id": 191116,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>You can check this article from Dr. Dobbs on a FFT implementation with templates which I think not that trivial.\nThe main point is to allow the compiler to perform a better optimization than for non template implementations as the FFT algorithm uses a lot of constants ( sin tables for instance ) </p>\n\n<p><a href=\"http://www.ddj.com/cpp/199500857\" rel=\"nofollow noreferrer\">part I</a></p>\n\n<p><a href=\"http://www.ddj.com/hpc-high-performance-computing/199702312\" rel=\"nofollow noreferrer\">part II</a></p>\n"
},
{
"answer_id": 191258,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 0,
"selected": false,
"text": "<p>A <a href=\"http://en.wikipedia.org/wiki/Turing_machine\" rel=\"nofollow noreferrer\">Turing machine</a> is Turing-complete, but that doesn't mean you should want to use one for production code.</p>\n\n<p>Trying to do anything non-trivial with templates is in my experience messy, ugly and pointless. You have no way to \"debug\" your \"code\", compile-time error messages will be cryptic and usually in the most unlikely places, and you can achieve the same performance benefits in different ways. (Hint: 4! = 24). Worse, your code is incomprehensible to the average C++ programmer, and will be likely be non-portable due to wide ranging levels of support within current compilers. </p>\n\n<p>Templates are great for generic code generation (container classes, class wrappers, mix-ins), but no - in my opinion the Turing Completeness of templates is <strong>NOT USEFUL</strong> in practice. </p>\n"
},
{
"answer_id": 191587,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 1,
"selected": false,
"text": "<p>An example which is reasonably useful is a ratio class. There are a few variants floating around. Catching the D==0 case is fairly simple with partial overloads. The real computing is in calculating the GCD of N and D and compile time. This is essential when you're using these ratios in compile-time calculations.</p>\n\n<p>Example: When you're calculating centimeters(5)*kilometers(5), at compile time you'll be multiplying ratio<1,100> and ratio<1000,1>. To prevent overflow, you want a ratio<10,1> instead of a ratio<1000,100>.</p>\n"
},
{
"answer_id": 275295,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 8,
"selected": false,
"text": "<p>I've done a turing machine in C++11. Features that C++11 adds are not significant for the turing machine indeed. It just provides for arbitrary length rule lists using variadic templates, instead of using perverse macro metaprogramming :). The names for the conditions are used to output a diagram on stdout. i've removed that code to keep the sample short.</p>\n\n<pre><code>#include <iostream>\n\ntemplate<bool C, typename A, typename B>\nstruct Conditional {\n typedef A type;\n};\n\ntemplate<typename A, typename B>\nstruct Conditional<false, A, B> {\n typedef B type;\n};\n\ntemplate<typename...>\nstruct ParameterPack;\n\ntemplate<bool C, typename = void>\nstruct EnableIf { };\n\ntemplate<typename Type>\nstruct EnableIf<true, Type> {\n typedef Type type;\n};\n\ntemplate<typename T>\nstruct Identity {\n typedef T type;\n};\n\n// define a type list \ntemplate<typename...>\nstruct TypeList;\n\ntemplate<typename T, typename... TT>\nstruct TypeList<T, TT...> {\n typedef T type;\n typedef TypeList<TT...> tail;\n};\n\ntemplate<>\nstruct TypeList<> {\n\n};\n\ntemplate<typename List>\nstruct GetSize;\n\ntemplate<typename... Items>\nstruct GetSize<TypeList<Items...>> {\n enum { value = sizeof...(Items) };\n};\n\ntemplate<typename... T>\nstruct ConcatList;\n\ntemplate<typename... First, typename... Second, typename... Tail>\nstruct ConcatList<TypeList<First...>, TypeList<Second...>, Tail...> {\n typedef typename ConcatList<TypeList<First..., Second...>, \n Tail...>::type type;\n};\n\ntemplate<typename T>\nstruct ConcatList<T> {\n typedef T type;\n};\n\ntemplate<typename NewItem, typename List>\nstruct AppendItem;\n\ntemplate<typename NewItem, typename...Items>\nstruct AppendItem<NewItem, TypeList<Items...>> {\n typedef TypeList<Items..., NewItem> type;\n};\n\ntemplate<typename NewItem, typename List>\nstruct PrependItem;\n\ntemplate<typename NewItem, typename...Items>\nstruct PrependItem<NewItem, TypeList<Items...>> {\n typedef TypeList<NewItem, Items...> type;\n};\n\ntemplate<typename List, int N, typename = void>\nstruct GetItem {\n static_assert(N > 0, \"index cannot be negative\");\n static_assert(GetSize<List>::value > 0, \"index too high\");\n typedef typename GetItem<typename List::tail, N-1>::type type;\n};\n\ntemplate<typename List>\nstruct GetItem<List, 0> {\n static_assert(GetSize<List>::value > 0, \"index too high\");\n typedef typename List::type type;\n};\n\ntemplate<typename List, template<typename, typename...> class Matcher, typename... Keys>\nstruct FindItem {\n static_assert(GetSize<List>::value > 0, \"Could not match any item.\");\n typedef typename List::type current_type;\n typedef typename Conditional<Matcher<current_type, Keys...>::value, \n Identity<current_type>, // found!\n FindItem<typename List::tail, Matcher, Keys...>>\n ::type::type type;\n};\n\ntemplate<typename List, int I, typename NewItem>\nstruct ReplaceItem {\n static_assert(I > 0, \"index cannot be negative\");\n static_assert(GetSize<List>::value > 0, \"index too high\");\n typedef typename PrependItem<typename List::type, \n typename ReplaceItem<typename List::tail, I-1,\n NewItem>::type>\n ::type type;\n};\n\ntemplate<typename NewItem, typename Type, typename... T>\nstruct ReplaceItem<TypeList<Type, T...>, 0, NewItem> {\n typedef TypeList<NewItem, T...> type;\n};\n\nenum Direction {\n Left = -1,\n Right = 1\n};\n\ntemplate<typename OldState, typename Input, typename NewState, \n typename Output, Direction Move>\nstruct Rule {\n typedef OldState old_state;\n typedef Input input;\n typedef NewState new_state;\n typedef Output output;\n static Direction const direction = Move;\n};\n\ntemplate<typename A, typename B>\nstruct IsSame {\n enum { value = false }; \n};\n\ntemplate<typename A>\nstruct IsSame<A, A> {\n enum { value = true };\n};\n\ntemplate<typename Input, typename State, int Position>\nstruct Configuration {\n typedef Input input;\n typedef State state;\n enum { position = Position };\n};\n\ntemplate<int A, int B>\nstruct Max {\n enum { value = A > B ? A : B };\n};\n\ntemplate<int n>\nstruct State {\n enum { value = n };\n static char const * name;\n};\n\ntemplate<int n>\nchar const* State<n>::name = \"unnamed\";\n\nstruct QAccept {\n enum { value = -1 };\n static char const* name;\n};\n\nstruct QReject {\n enum { value = -2 };\n static char const* name; \n};\n\n#define DEF_STATE(ID, NAME) \\\n typedef State<ID> NAME ; \\\n NAME :: name = #NAME ;\n\ntemplate<int n>\nstruct Input {\n enum { value = n };\n static char const * name;\n\n template<int... I>\n struct Generate {\n typedef TypeList<Input<I>...> type;\n };\n};\n\ntemplate<int n>\nchar const* Input<n>::name = \"unnamed\";\n\ntypedef Input<-1> InputBlank;\n\n#define DEF_INPUT(ID, NAME) \\\n typedef Input<ID> NAME ; \\\n NAME :: name = #NAME ;\n\ntemplate<typename Config, typename Transitions, typename = void> \nstruct Controller {\n typedef Config config;\n enum { position = config::position };\n\n typedef typename Conditional<\n static_cast<int>(GetSize<typename config::input>::value) \n <= static_cast<int>(position),\n AppendItem<InputBlank, typename config::input>,\n Identity<typename config::input>>::type::type input;\n typedef typename config::state state;\n\n typedef typename GetItem<input, position>::type cell;\n\n template<typename Item, typename State, typename Cell>\n struct Matcher {\n typedef typename Item::old_state checking_state;\n typedef typename Item::input checking_input;\n enum { value = IsSame<State, checking_state>::value && \n IsSame<Cell, checking_input>::value\n };\n };\n typedef typename FindItem<Transitions, Matcher, state, cell>::type rule;\n\n typedef typename ReplaceItem<input, position, typename rule::output>::type new_input;\n typedef typename rule::new_state new_state;\n typedef Configuration<new_input, \n new_state, \n Max<position + rule::direction, 0>::value> new_config;\n\n typedef Controller<new_config, Transitions> next_step;\n typedef typename next_step::end_config end_config;\n typedef typename next_step::end_input end_input;\n typedef typename next_step::end_state end_state;\n enum { end_position = next_step::position };\n};\n\ntemplate<typename Input, typename State, int Position, typename Transitions>\nstruct Controller<Configuration<Input, State, Position>, Transitions, \n typename EnableIf<IsSame<State, QAccept>::value || \n IsSame<State, QReject>::value>::type> {\n typedef Configuration<Input, State, Position> config;\n enum { position = config::position };\n typedef typename Conditional<\n static_cast<int>(GetSize<typename config::input>::value) \n <= static_cast<int>(position),\n AppendItem<InputBlank, typename config::input>,\n Identity<typename config::input>>::type::type input;\n typedef typename config::state state;\n\n typedef config end_config;\n typedef input end_input;\n typedef state end_state;\n enum { end_position = position };\n};\n\ntemplate<typename Input, typename Transitions, typename StartState>\nstruct TuringMachine {\n typedef Input input;\n typedef Transitions transitions;\n typedef StartState start_state;\n\n typedef Controller<Configuration<Input, StartState, 0>, Transitions> controller;\n typedef typename controller::end_config end_config;\n typedef typename controller::end_input end_input;\n typedef typename controller::end_state end_state;\n enum { end_position = controller::end_position };\n};\n\n#include <ostream>\n\ntemplate<>\nchar const* Input<-1>::name = \"_\";\n\nchar const* QAccept::name = \"qaccept\";\nchar const* QReject::name = \"qreject\";\n\nint main() {\n DEF_INPUT(1, x);\n DEF_INPUT(2, x_mark);\n DEF_INPUT(3, split);\n\n DEF_STATE(0, start);\n DEF_STATE(1, find_blank);\n DEF_STATE(2, go_back);\n\n /* syntax: State, Input, NewState, Output, Move */\n typedef TypeList< \n Rule<start, x, find_blank, x_mark, Right>,\n Rule<find_blank, x, find_blank, x, Right>,\n Rule<find_blank, split, find_blank, split, Right>,\n Rule<find_blank, InputBlank, go_back, x, Left>,\n Rule<go_back, x, go_back, x, Left>,\n Rule<go_back, split, go_back, split, Left>,\n Rule<go_back, x_mark, start, x, Right>,\n Rule<start, split, QAccept, split, Left>> rules;\n\n /* syntax: initial input, rules, start state */\n typedef TuringMachine<TypeList<x, x, x, x, split>, rules, start> double_it;\n static_assert(IsSame<double_it::end_input, \n TypeList<x, x, x, x, split, x, x, x, x>>::value, \n \"Hmm... This is borky!\");\n}\n</code></pre>\n"
},
{
"answer_id": 801678,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>The factorial example actually does not show that templates are Turing complete, as much as it shows that they support Primitive Recursion. The easiest way to show that templates are turing complete is by the Church-Turing thesis, that is by implementing either a Turing machine (messy and a bit pointless) or the three rules (app, abs var) of the untyped lambda calculus. The latter is much simpler and far more interesting. </p>\n\n<p>What is being discussed is an extremely useful feature when you understand that C++ templates allow pure functional programming at compile time, a formalism that is expressive, powerful and elegant but also very complicated to write if you have little experience. Also notice how many people find that just getting heavily templatized code can often require a big effort: this is exactly the case with (pure) functional languages, which make compiling harder but surprisingly yield code that does not require debugging.</p>\n"
},
{
"answer_id": 1607179,
"author": "lsalamon",
"author_id": 47733,
"author_profile": "https://Stackoverflow.com/users/47733",
"pm_score": 0,
"selected": false,
"text": "<p>Just another example of how not to program :</p>\n\n<pre>\ntemplate<int Depth, int A, typename B>\nstruct K17 {\n static const int x =\n K17 <Depth+1, 0, K17<Depth,A,B> >::x\n + K17 <Depth+1, 1, K17<Depth,A,B> >::x\n + K17 <Depth+1, 2, K17<Depth,A,B> >::x\n + K17 <Depth+1, 3, K17<Depth,A,B> >::x\n + K17 <Depth+1, 4, K17<Depth,A,B> >::x;\n};\ntemplate <int A, typename B>\nstruct K17 <16,A,B> { static const int x = 1; };\nstatic const int z = K17 <0,0,int>::x;\nvoid main(void) { }\n</pre>\n\n<p>Post at <a href=\"http://cpptruths.blogspot.com/2005/11/c-templates-are-turing-complete.html\" rel=\"nofollow noreferrer\">C++ templates are turing complete</a></p>\n"
},
{
"answer_id": 2222729,
"author": "Sebastian Mach",
"author_id": 76722,
"author_profile": "https://Stackoverflow.com/users/76722",
"pm_score": 4,
"selected": false,
"text": "<p>To give a non-trivial example: <a href=\"https://github.com/phresnel/metatrace\" rel=\"nofollow noreferrer\">https://github.com/phresnel/metatrace</a> , a C++ compile time ray tracer.</p>\n<p>Note that C++0x will add a non-template, compile-time, turing-complete facility in form of <code>constexpr</code>:</p>\n<pre><code>constexpr unsigned int fac (unsigned int u) {\n return (u<=1) ? (1) : (u*fac(u-1));\n}\n</code></pre>\n<p>You can use <code>constexpr</code>-expression everywhere where you need compile time constants, but you can also call <code>constexpr</code>-functions with non-const parameters.</p>\n<p>One cool thing is that this will finally enable compile time floating point math, though the standard explicitly states that compile time floating point arithmetics do not have to match runtime floating point arithmetics:</p>\n<blockquote>\n<pre><code>bool f(){\n char array[1+int(1+0.2-0.1-0.1)]; //Must be evaluated during translation\n int size=1+int(1+0.2-0.1-0.1); //May be evaluated at runtime\n return sizeof(array)==size;\n}\n</code></pre>\n<p>It is unspecified whether the value of f() will be true or false.</p>\n</blockquote>\n"
},
{
"answer_id": 36113234,
"author": "Victor Komarov",
"author_id": 3046221,
"author_profile": "https://Stackoverflow.com/users/3046221",
"pm_score": 3,
"selected": false,
"text": "<p>Well, here's a compile time Turing Machine implementation running a 4-state 2-symbol busy beaver</p>\n\n<pre><code>#include <iostream>\n\n#pragma mark - Tape\n\nconstexpr int Blank = -1;\n\ntemplate<int... xs>\nclass Tape {\npublic:\n using type = Tape<xs...>;\n constexpr static int length = sizeof...(xs);\n};\n\n#pragma mark - Print\n\ntemplate<class T>\nvoid print(T);\n\ntemplate<>\nvoid print(Tape<>) {\n std::cout << std::endl;\n}\n\ntemplate<int x, int... xs>\nvoid print(Tape<x, xs...>) {\n if (x == Blank) {\n std::cout << \"_ \";\n } else {\n std::cout << x << \" \";\n }\n print(Tape<xs...>());\n}\n\n#pragma mark - Concatenate\n\ntemplate<class, class>\nclass Concatenate;\n\ntemplate<int... xs, int... ys>\nclass Concatenate<Tape<xs...>, Tape<ys...>> {\npublic:\n using type = Tape<xs..., ys...>;\n};\n\n#pragma mark - Invert\n\ntemplate<class>\nclass Invert;\n\ntemplate<>\nclass Invert<Tape<>> {\npublic:\n using type = Tape<>;\n};\n\ntemplate<int x, int... xs>\nclass Invert<Tape<x, xs...>> {\npublic:\n using type = typename Concatenate<\n typename Invert<Tape<xs...>>::type,\n Tape<x>\n >::type;\n};\n\n#pragma mark - Read\n\ntemplate<int, class>\nclass Read;\n\ntemplate<int n, int x, int... xs>\nclass Read<n, Tape<x, xs...>> {\npublic:\n using type = typename std::conditional<\n (n == 0),\n std::integral_constant<int, x>,\n Read<n - 1, Tape<xs...>>\n >::type::type;\n};\n\n#pragma mark - N first and N last\n\ntemplate<int, class>\nclass NLast;\n\ntemplate<int n, int x, int... xs>\nclass NLast<n, Tape<x, xs...>> {\npublic:\n using type = typename std::conditional<\n (n == sizeof...(xs)),\n Tape<xs...>,\n NLast<n, Tape<xs...>>\n >::type::type;\n};\n\ntemplate<int, class>\nclass NFirst;\n\ntemplate<int n, int... xs>\nclass NFirst<n, Tape<xs...>> {\npublic:\n using type = typename Invert<\n typename NLast<\n n, typename Invert<Tape<xs...>>::type\n >::type\n >::type;\n};\n\n#pragma mark - Write\n\ntemplate<int, int, class>\nclass Write;\n\ntemplate<int pos, int x, int... xs>\nclass Write<pos, x, Tape<xs...>> {\npublic:\n using type = typename Concatenate<\n typename Concatenate<\n typename NFirst<pos, Tape<xs...>>::type,\n Tape<x>\n >::type,\n typename NLast<(sizeof...(xs) - pos - 1), Tape<xs...>>::type\n >::type;\n};\n\n#pragma mark - Move\n\ntemplate<int, class>\nclass Hold;\n\ntemplate<int pos, int... xs>\nclass Hold<pos, Tape<xs...>> {\npublic:\n constexpr static int position = pos;\n using tape = Tape<xs...>;\n};\n\ntemplate<int, class>\nclass Left;\n\ntemplate<int pos, int... xs>\nclass Left<pos, Tape<xs...>> {\npublic:\n constexpr static int position = typename std::conditional<\n (pos > 0),\n std::integral_constant<int, pos - 1>,\n std::integral_constant<int, 0>\n >::type();\n\n using tape = typename std::conditional<\n (pos > 0),\n Tape<xs...>,\n Tape<Blank, xs...>\n >::type;\n};\n\ntemplate<int, class>\nclass Right;\n\ntemplate<int pos, int... xs>\nclass Right<pos, Tape<xs...>> {\npublic:\n constexpr static int position = pos + 1;\n\n using tape = typename std::conditional<\n (pos < sizeof...(xs) - 1),\n Tape<xs...>,\n Tape<xs..., Blank>\n >::type;\n};\n\n#pragma mark - States\n\ntemplate <int>\nclass Stop {\npublic:\n constexpr static int write = -1;\n template<int pos, class tape> using move = Hold<pos, tape>;\n template<int x> using next = Stop<x>;\n};\n\n#define ADD_STATE(_state_) \\\ntemplate<int> \\\nclass _state_ { };\n\n#define ADD_RULE(_state_, _read_, _write_, _move_, _next_) \\\ntemplate<> \\\nclass _state_<_read_> { \\\npublic: \\\n constexpr static int write = _write_; \\\n template<int pos, class tape> using move = _move_<pos, tape>; \\\n template<int x> using next = _next_<x>; \\\n};\n\n#pragma mark - Machine\n\ntemplate<template<int> class, int, class>\nclass Machine;\n\ntemplate<template<int> class State, int pos, int... xs>\nclass Machine<State, pos, Tape<xs...>> {\n constexpr static int symbol = typename Read<pos, Tape<xs...>>::type();\n using state = State<symbol>;\n\n template<int x>\n using nextState = typename State<symbol>::template next<x>;\n\n using modifiedTape = typename Write<pos, state::write, Tape<xs...>>::type;\n using move = typename state::template move<pos, modifiedTape>;\n\n constexpr static int nextPos = move::position;\n using nextTape = typename move::tape;\n\npublic:\n using step = Machine<nextState, nextPos, nextTape>;\n};\n\n#pragma mark - Run\n\ntemplate<class>\nclass Run;\n\ntemplate<template<int> class State, int pos, int... xs>\nclass Run<Machine<State, pos, Tape<xs...>>> {\n using step = typename Machine<State, pos, Tape<xs...>>::step;\n\npublic:\n using type = typename std::conditional<\n std::is_same<State<0>, Stop<0>>::value,\n Tape<xs...>,\n Run<step>\n >::type::type;\n};\n\nADD_STATE(A);\nADD_STATE(B);\nADD_STATE(C);\nADD_STATE(D);\n\nADD_RULE(A, Blank, 1, Right, B);\nADD_RULE(A, 1, 1, Left, B);\n\nADD_RULE(B, Blank, 1, Left, A);\nADD_RULE(B, 1, Blank, Left, C);\n\nADD_RULE(C, Blank, 1, Right, Stop);\nADD_RULE(C, 1, 1, Left, D);\n\nADD_RULE(D, Blank, 1, Right, D);\nADD_RULE(D, 1, Blank, Right, A);\n\nusing tape = Tape<Blank>;\nusing machine = Machine<A, 0, tape>;\nusing result = Run<machine>::type;\n\nint main() {\n print(result());\n return 0;\n}\n</code></pre>\n\n<p>Ideone proof run: <a href=\"https://ideone.com/MvBU3Z\" rel=\"noreferrer\">https://ideone.com/MvBU3Z</a></p>\n\n<p>Explanation: <a href=\"http://victorkomarov.blogspot.ru/2016/03/compile-time-turing-machine.html\" rel=\"noreferrer\">http://victorkomarov.blogspot.ru/2016/03/compile-time-turing-machine.html</a></p>\n\n<p>Github with more examples: <a href=\"https://github.com/fnz/CTTM\" rel=\"noreferrer\">https://github.com/fnz/CTTM</a></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18770/"
] |
I'm told that the template system in C++ is Turing-complete at compile time. This is mentioned in [this post](https://stackoverflow.com/questions/75538/hidden-features-of-c#75627) and also on [wikipedia](http://en.wikipedia.org/wiki/C%2B%2B).
Can you provide a nontrivial example of a computation that exploits this property?
Is this fact useful in practice?
|
Example
```
#include <iostream>
template <int N> struct Factorial
{
enum { val = Factorial<N-1>::val * N };
};
template<>
struct Factorial<0>
{
enum { val = 1 };
};
int main()
{
// Note this value is generated at compile time.
// Also note that most compilers have a limit on the depth of the recursion available.
std::cout << Factorial<4>::val << "\n";
}
```
That was a little fun but not very practical.
To answer the second part of the question:
**Is this fact useful in practice?**
Short Answer: Sort of.
Long Answer: Yes, but only if you are a template daemon.
To turn out good programming using template meta-programming that is really useful for others to use (ie a library) is really really tough (though do-able). To Help boost even has [MPL](http://www.boost.org/doc/libs/1_36_0/libs/mpl/doc/index.html) aka (Meta Programming Library). But try debugging a compiler error in your template code and you will be in for a long hard ride.
But a good practical example of it being used for something useful:
Scott Meyers has been working extensions to the C++ language (I use the term loosely) using the templating facilities. You can read about his work here '[Enforcing Code Features](http://www.artima.com/cppsource/codefeaturesP.html)'
|
189,213 |
<p>Using the following query and results, I'm looking for the most recent entry where the ChargeId and ChargeType are unique.</p>
<pre><code>select chargeId, chargeType, serviceMonth from invoice
CHARGEID CHARGETYPE SERVICEMONTH
1 101 R 8/1/2008
2 161 N 2/1/2008
3 101 R 2/1/2008
4 101 R 3/1/2008
5 101 R 4/1/2008
6 101 R 5/1/2008
7 101 R 6/1/2008
8 101 R 7/1/2008
</code></pre>
<p>Desired:</p>
<pre><code> CHARGEID CHARGETYPE SERVICEMONTH
1 101 R 8/1/2008
2 161 N 2/1/2008
</code></pre>
|
[
{
"answer_id": 189221,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 8,
"selected": true,
"text": "<p>You can use a <strong>GROUP BY</strong> to group items by type and id. Then you can use the <strong>MAX()</strong> Aggregate function to get the most recent service month. The below returns a result set with ChargeId, ChargeType, and MostRecentServiceMonth</p>\n\n<pre><code>SELECT\n CHARGEID,\n CHARGETYPE,\n MAX(SERVICEMONTH) AS \"MostRecentServiceMonth\"\nFROM INVOICE\nGROUP BY CHARGEID, CHARGETYPE\n</code></pre>\n"
},
{
"answer_id": 189227,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 4,
"selected": false,
"text": "<pre><code>SELECT chargeId, chargeType, MAX(serviceMonth) AS serviceMonth \nFROM invoice\nGROUP BY chargeId, chargeType\n</code></pre>\n"
},
{
"answer_id": 189264,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 6,
"selected": false,
"text": "<p>So this isn't what the requester was asking for but it is the answer to \"SQL selecting rows by most recent date\".</p>\n\n<p>Modified from <a href=\"http://wiki.lessthandot.com/index.php/Returning_The_Maximum_Value_For_A_Row\" rel=\"noreferrer\">http://wiki.lessthandot.com/index.php/Returning_The_Maximum_Value_For_A_Row</a></p>\n\n<pre><code>SELECT t.chargeId, t.chargeType, t.serviceMonth FROM( \n SELECT chargeId,MAX(serviceMonth) AS serviceMonth\n FROM invoice\n GROUP BY chargeId) x \n JOIN invoice t ON x.chargeId =t.chargeId\n AND x.serviceMonth = t.serviceMonth\n</code></pre>\n"
},
{
"answer_id": 38122817,
"author": "pari elanchezhiyan",
"author_id": 6533361,
"author_profile": "https://Stackoverflow.com/users/6533361",
"pm_score": 1,
"selected": false,
"text": "<pre><code>select to.chargeid,t0.po,i.chargetype from invoice i\ninner join\n(select chargeid,max(servicemonth)po from invoice \ngroup by chargeid)t0\non i.chargeid=t0.chargeid\n</code></pre>\n\n<p>The above query will work if the distinct charge id has different chargetype combinations.Hope this simple query helps with little performance time into consideration...</p>\n"
},
{
"answer_id": 39016684,
"author": "sujeet",
"author_id": 2144484,
"author_profile": "https://Stackoverflow.com/users/2144484",
"pm_score": 3,
"selected": false,
"text": "<p>I see most of the developers use inline query without looking out it's impact on huge data.</p>\n\n<p>in simple you can achieve this by:</p>\n\n<pre><code>select a.chargeId, a.chargeType, a.serviceMonth \nfrom invoice a\nleft outer join invoice b\non a.chargeId=b.chargeId and a.serviceMonth <b.serviceMonth \nwhere b.chargeId is null\norder by a.serviceMonth desc\n</code></pre>\n"
},
{
"answer_id": 72804170,
"author": "Bozon",
"author_id": 4879179,
"author_profile": "https://Stackoverflow.com/users/4879179",
"pm_score": 0,
"selected": false,
"text": "<p>Demo at <a href=\"http://sqlfiddle.com/#!17/e5dff/8/1\" rel=\"nofollow noreferrer\">sqlfiddle</a>:</p>\n<ol>\n<li>Classical way.</li>\n</ol>\n<pre class=\"lang-sql prettyprint-override\"><code>select \n chargeid, \n chargetype,\n SERVICEMONTH\nfrom invoice t0\nwhere t0.SERVICEMONTH = (\n select max(SERVICEMONTH) \n from invoice t1 \n where t1.chargeid = t0.chargeid\n and t1.chargetype = t0.chargetype\n);\n</code></pre>\n<ol start=\"2\">\n<li>Using window functions.</li>\n</ol>\n<pre class=\"lang-sql prettyprint-override\"><code>with w_o as (\n select\n chargeid, \n chargetype,\n SERVICEMONTH,\n row_number() OVER (PARTITION BY chargeid, chargetype ORDER BY SERVICEMONTH DESC) rn\n from invoice\n)\nselect\n chargeid, \n chargetype,\n SERVICEMONTH\nfrom w_o\nwhere rn = 1;\n</code></pre>\n<p>It is nice to understand and be able to use both styles.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16345/"
] |
Using the following query and results, I'm looking for the most recent entry where the ChargeId and ChargeType are unique.
```
select chargeId, chargeType, serviceMonth from invoice
CHARGEID CHARGETYPE SERVICEMONTH
1 101 R 8/1/2008
2 161 N 2/1/2008
3 101 R 2/1/2008
4 101 R 3/1/2008
5 101 R 4/1/2008
6 101 R 5/1/2008
7 101 R 6/1/2008
8 101 R 7/1/2008
```
Desired:
```
CHARGEID CHARGETYPE SERVICEMONTH
1 101 R 8/1/2008
2 161 N 2/1/2008
```
|
You can use a **GROUP BY** to group items by type and id. Then you can use the **MAX()** Aggregate function to get the most recent service month. The below returns a result set with ChargeId, ChargeType, and MostRecentServiceMonth
```
SELECT
CHARGEID,
CHARGETYPE,
MAX(SERVICEMONTH) AS "MostRecentServiceMonth"
FROM INVOICE
GROUP BY CHARGEID, CHARGETYPE
```
|
189,228 |
<p>When writing async method implementations using the BeginInvoke/EndInvoke pattern the code might look something like the following (and to save you guessing this is an async wrapper around a cache):</p>
<pre><code>IAsyncResult BeginPut(string key, object value)
{
Action<string, object> put = this.cache.Put;
return put.BeginInvoke(key, value, null, null);
}
void EndPut(IAsyncResult asyncResult)
{
var put = (Action<string, object>)((AsyncResult)asyncResult).AsyncDelegate;
put.EndInvoke(asyncResult);
}
</code></pre>
<p>This works perfectly well because it's known what the type of delegate is, so it can be cast. However it starts to get messy when you have two <code>Put</code> methods, because although the method returns void you seemingly have to cast it to a strongly typed delegate to end the invocation, e.g.</p>
<pre><code>IAsyncResult BeginPut(string key, object value)
{
Action<string, object> put = this.cache.Put;
return put.BeginInvoke(key, value, null, null);
}
IAsyncResult BeginPut(string region, string key, object value)
{
Action<string, string, object> put = this.cache.Put;
return put.BeginInvoke(region, key, value, null, null);
}
void EndPut(IAsyncResult asyncResult)
{
var put = ((AsyncResult)asyncResult).AsyncDelegate;
var put1 = put as Action<string, object>;
if (put1 != null)
{
put1.EndInvoke(asyncResult);
return;
}
var put2 = put as Action<string, string, object>;
if (put2 != null)
{
put2.EndInvoke(asyncResult);
return;
}
throw new ArgumentException("Invalid async result", "asyncResult");
}
</code></pre>
<p>I'm hoping there is a cleaner way to do this, because the only thing I care about the delegate is the return type (in this case void) and not the arguments that were supplied to it. But I've racked my brains and asked others in the office, and nobody can think of the answer.</p>
<p>I know one solution is to write a custom <code>IAsyncResult</code>, but that's such a difficult task with the potential threading issues around things like lazy instantiation of the <code>WaitHandle</code> that I'd rather have this slightly hacky looking code than go down that route.</p>
<p>Any ideas on how to end the invocation without a cascading set of <code>is</code> checks?</p>
|
[
{
"answer_id": 189266,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "<p>Why not avoid the problem by just going back to the more general overload:</p>\n\n<pre><code>IAsyncResult BeginPut(string key, object value) {\n return this.BeginPut(null, key, value);\n}\n\nIAsyncResult BeginPut(string region, string key, object value) {\n Action<string, string, object> put = this.Put;\n return put.BeginInvoke(region, key, value, null, null);\n}\n\nvoid EndPut(IAsyncResult asyncResult) {\n var put = (Action<string, string, object>)((AsyncResult)asyncResult).AsyncDelegate;\n put.EndInvoke(asyncResult);\n}\n</code></pre>\n"
},
{
"answer_id": 189292,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Edit:</strong> Please see my other answer. It <em>can</em> be cleaner.</p>\n\n<p>I don't think there is a way to make this cleaner. You essentially made this inevitable by using the same <code>EndPut</code> method to end more than one type of async call. You could just as well be following the normal pattern by passing <code>EndPut</code> and the <code>put</code> delegate as the last two parameters to <code>BeginInvoke()</code> (callback and asyncstate), and you would still have to test what type the delegate is in order call <code>EndInvoke()</code>.</p>\n\n<p>Casting them to <code>Delegate</code> doesn't help at all.</p>\n\n<p>I like Mark Brackett's idea. I think it comes down to these options:</p>\n\n<ul>\n<li>Join them completely by having one overload call another. One delegate, one callback.</li>\n<li>Separate them completely by having two callbacks for calling <code>EndInvoke()</code>.</li>\n</ul>\n\n<p>Aside from those, the only thing is to make your code just a little cleaner and use a <code>switch</code> or lookup dictionary using <code>asyncResult.AsyncState.GetType()</code>, passing the <code>put</code> delegate as that state object.</p>\n"
},
{
"answer_id": 189325,
"author": "Joel B Fant",
"author_id": 22211,
"author_profile": "https://Stackoverflow.com/users/22211",
"pm_score": 3,
"selected": true,
"text": "<p>I was wrong, there is a cleaner way.</p>\n\n<p>You create <code>Action( IAsyncResult )</code> delegates for the specific <code>EndInvoke()</code> method in the same context where you already know the specific type of the delegate, passing it as the AsyncState. I'm passing <code>EndPut()</code> as the callback for convenience.</p>\n\n<pre><code>IAsyncResult BeginPut( string key, object value ) {\n Action<string, object> put = this.Put;\n return put.BeginInvoke( key, value, EndPut,\n new Action<IAsyncResult>( put.EndInvoke ) );\n}\n\nIAsyncResult BeginPut( string region, string key, object value ) {\n Action<string, string, object> put = this.Put;\n return put.BeginInvoke( region, key, value, EndPut,\n new Action<IAsyncResult>( put.EndInvoke ) );\n}\n</code></pre>\n\n<p>And then you finish it off.</p>\n\n<pre><code>void EndPut( IAsyncResult asyncResult ) {\n var del = asyncResult.AsyncState as Action<IAsyncResult>;\n del( asyncResult );\n}\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13552/"
] |
When writing async method implementations using the BeginInvoke/EndInvoke pattern the code might look something like the following (and to save you guessing this is an async wrapper around a cache):
```
IAsyncResult BeginPut(string key, object value)
{
Action<string, object> put = this.cache.Put;
return put.BeginInvoke(key, value, null, null);
}
void EndPut(IAsyncResult asyncResult)
{
var put = (Action<string, object>)((AsyncResult)asyncResult).AsyncDelegate;
put.EndInvoke(asyncResult);
}
```
This works perfectly well because it's known what the type of delegate is, so it can be cast. However it starts to get messy when you have two `Put` methods, because although the method returns void you seemingly have to cast it to a strongly typed delegate to end the invocation, e.g.
```
IAsyncResult BeginPut(string key, object value)
{
Action<string, object> put = this.cache.Put;
return put.BeginInvoke(key, value, null, null);
}
IAsyncResult BeginPut(string region, string key, object value)
{
Action<string, string, object> put = this.cache.Put;
return put.BeginInvoke(region, key, value, null, null);
}
void EndPut(IAsyncResult asyncResult)
{
var put = ((AsyncResult)asyncResult).AsyncDelegate;
var put1 = put as Action<string, object>;
if (put1 != null)
{
put1.EndInvoke(asyncResult);
return;
}
var put2 = put as Action<string, string, object>;
if (put2 != null)
{
put2.EndInvoke(asyncResult);
return;
}
throw new ArgumentException("Invalid async result", "asyncResult");
}
```
I'm hoping there is a cleaner way to do this, because the only thing I care about the delegate is the return type (in this case void) and not the arguments that were supplied to it. But I've racked my brains and asked others in the office, and nobody can think of the answer.
I know one solution is to write a custom `IAsyncResult`, but that's such a difficult task with the potential threading issues around things like lazy instantiation of the `WaitHandle` that I'd rather have this slightly hacky looking code than go down that route.
Any ideas on how to end the invocation without a cascading set of `is` checks?
|
I was wrong, there is a cleaner way.
You create `Action( IAsyncResult )` delegates for the specific `EndInvoke()` method in the same context where you already know the specific type of the delegate, passing it as the AsyncState. I'm passing `EndPut()` as the callback for convenience.
```
IAsyncResult BeginPut( string key, object value ) {
Action<string, object> put = this.Put;
return put.BeginInvoke( key, value, EndPut,
new Action<IAsyncResult>( put.EndInvoke ) );
}
IAsyncResult BeginPut( string region, string key, object value ) {
Action<string, string, object> put = this.Put;
return put.BeginInvoke( region, key, value, EndPut,
new Action<IAsyncResult>( put.EndInvoke ) );
}
```
And then you finish it off.
```
void EndPut( IAsyncResult asyncResult ) {
var del = asyncResult.AsyncState as Action<IAsyncResult>;
del( asyncResult );
}
```
|
189,239 |
<p>What I'm trying to do with <code>FileStream</code> in C#/.NET is to open two streams: one appending to a file and the other reading those writes asynchronously (for unit testing some network connection handling code). I can't figure out how to get the <em>writer</em> stream to open the file in non-exlusive locking mode and thus the code always throws an exception:</p>
<blockquote>
<p>The process cannot access the file
'C:\test.txt' because it is being used
by another process.</p>
</blockquote>
<p>Here's a smattering of code which demonstrates the issue:</p>
<pre><code>FileStream fwriter = new FileStream("C:\\test.txt", FileMode.Append,
FileAccess.Write, FileShare.Read);
FileStream freader = new FileStream("C:\\test.txt", FileMode.Open,
FileAccess.Read, FileShare.Read);
</code></pre>
|
[
{
"answer_id": 189245,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 4,
"selected": true,
"text": "<p>See this question: <a href=\"https://stackoverflow.com/questions/124946/c-file-readwrite-fileshare-doesnt-appear-to-work\">C# file read/write fileshare doesn’t appear to work</a></p>\n\n<p>In short, your freader has to specify FileShare.Write to allow for the fact that there is already a writer on the file.</p>\n"
},
{
"answer_id": 189254,
"author": "Grzenio",
"author_id": 5363,
"author_profile": "https://Stackoverflow.com/users/5363",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure if it helps, but if you are only unit testing, wouldn't it be easier to use a memory stream instead of files?</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9642/"
] |
What I'm trying to do with `FileStream` in C#/.NET is to open two streams: one appending to a file and the other reading those writes asynchronously (for unit testing some network connection handling code). I can't figure out how to get the *writer* stream to open the file in non-exlusive locking mode and thus the code always throws an exception:
>
> The process cannot access the file
> 'C:\test.txt' because it is being used
> by another process.
>
>
>
Here's a smattering of code which demonstrates the issue:
```
FileStream fwriter = new FileStream("C:\\test.txt", FileMode.Append,
FileAccess.Write, FileShare.Read);
FileStream freader = new FileStream("C:\\test.txt", FileMode.Open,
FileAccess.Read, FileShare.Read);
```
|
See this question: [C# file read/write fileshare doesn’t appear to work](https://stackoverflow.com/questions/124946/c-file-readwrite-fileshare-doesnt-appear-to-work)
In short, your freader has to specify FileShare.Write to allow for the fact that there is already a writer on the file.
|
189,280 |
<p>I use NHibernate for my dataacess, and for awhile not I've been using SQLite for local integration tests. I've been using a file, but I thought I would out the :memory: option. When I fire up any of the integration tests, the database seems to be created (NHibernate spits out the table creation sql) but interfacting with the database causes an error.</p>
<p>Has anyone every gotten NHibernate working with an in memory database? Is it even possible? The connection string I'm using is this:</p>
<pre><code>Data Source=:memory:;Version=3;New=True
</code></pre>
|
[
{
"answer_id": 192084,
"author": "chills42",
"author_id": 23855,
"author_profile": "https://Stackoverflow.com/users/23855",
"pm_score": 0,
"selected": false,
"text": "<p>Just a wild guess, but is the sql output by NHibernate using a command unsupported by sqlite?</p>\n\n<p>Also, What happens if you use a file instead of memory? (System.IO.Path.GetTempFileName() would work i think...)</p>\n"
},
{
"answer_id": 193400,
"author": "Sean Carpenter",
"author_id": 729,
"author_profile": "https://Stackoverflow.com/users/729",
"pm_score": 6,
"selected": true,
"text": "<p>A SQLite memory database only exists as long as the connection to it remains open. To use it in unit tests with NHibernate:<br>\n1. Open an ISession at the beginning of your test (maybe in a [SetUp] method).<br>\n2. Use the connection from that session in your SchemaExport call.<br>\n3. Use that same session in your tests.<br>\n4. Close the session at the end of your test (maybe in a [TearDown] method).</p>\n"
},
{
"answer_id": 196979,
"author": "Stefan Steinegger",
"author_id": 2658202,
"author_profile": "https://Stackoverflow.com/users/2658202",
"pm_score": 3,
"selected": false,
"text": "<p>We are using SQLite in memory for all our database tests. We are using a single ADO connection for the tests that is reused for all NH sessions opened by the same test. </p>\n\n<ol>\n<li>Before every test: create connection</li>\n<li>Create schema on this connection</li>\n<li>Run test. The same connection is used for all sessions</li>\n<li>After test: close connection</li>\n</ol>\n\n<p>This allows also running tests with several sessions included. The SessionFactory is also created once for all tests, because the reading of the mapping files takes quite some time.</p>\n\n<hr>\n\n<p>Edit</p>\n\n<h2>Use of the Shared Cache</h2>\n\n<p>Since System.Data.Sqlite 1.0.82 (or <a href=\"http://www.sqlite.org/releaselog/3_7_13.html\" rel=\"nofollow noreferrer\">Sqlite 3.7.13</a>), there is a <a href=\"http://www.sqlite.org/sharedcache.html\" rel=\"nofollow noreferrer\">Shared Cache</a>, which allows several connections to share the same data, also for <a href=\"http://www.sqlite.org/inmemorydb.html\" rel=\"nofollow noreferrer\">In-Memory databases</a>. This allows creation of the in-memory-database in one connection, and use it in another. (I didn't try it yet, but in theory, this should work):</p>\n\n<ul>\n<li>Change the connection string to <code>file::memory:?cache=shared</code></li>\n<li>Open a connection and create the schema</li>\n<li>Keep this connection open until the end of the test</li>\n<li>Let NH create other connections (normal behavior) during the test.</li>\n</ul>\n"
},
{
"answer_id": 224374,
"author": "Tim Scott",
"author_id": 29493,
"author_profile": "https://Stackoverflow.com/users/29493",
"pm_score": 0,
"selected": false,
"text": "<p>I am doing it with <a href=\"https://rhino-tools.svn.sourceforge.net/svnroot/rhino-tools/trunk/rhino-commons/\" rel=\"nofollow noreferrer\">Rhino Commons</a>. If you don't want to use Rhino Commons you can study the source do see how it does it. The only problem I have had is that SQLite does not support nested transactions. This forced me to change my code to support integration testing. Integration testing with in memory database is so awesome, I decided it was a fair compromise.</p>\n"
},
{
"answer_id": 492289,
"author": "Anders B",
"author_id": 41324,
"author_profile": "https://Stackoverflow.com/users/41324",
"pm_score": 1,
"selected": false,
"text": "<p>I hade alot off problems with SQLite memory database.\nSo now we are using SQLite working with files on a ramdrive disk.</p>\n"
},
{
"answer_id": 4501759,
"author": "Julien Bérubé",
"author_id": 309236,
"author_profile": "https://Stackoverflow.com/users/309236",
"pm_score": 3,
"selected": false,
"text": "<p>I had similar problems that lasted even after opening the ISession as stated above, and adding \"Pooling=True;Max Pool Size=1\" to my connection string. It helped, but I still had some cases where the connection would close during a test (usually right after committing a transaction).</p>\n\n<p>What finally worked for me was setting the property \"connection.release_mode\" to \"on_close\" in my SessionFactory configuration.</p>\n\n<p>My configuration in the app.config file now look likes this:</p>\n\n<pre><code> <hibernate-configuration xmlns=\"urn:nhibernate-configuration-2.2\">\n <reflection-optimizer use=\"true\" />\n <session-factory>\n <property name=\"connection.connection_string_name\">testSqlLiteDB</property>\n <property name=\"connection.driver_class\">NHibernate.Driver.SQLite20Driver</property>\n <property name=\"connection.provider\">NHibernate.Connection.DriverConnectionProvider</property>\n <property name=\"connection.release_mode\">on_close</property>\n <property name=\"dialect\">NHibernate.Dialect.SQLiteDialect</property>\n <property name=\"proxyfactory.factory_class\">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>\n <property name=\"query.substitutions\">true=1;false=0</property>\n </session-factory>\n </hibernate-configuration>\n</code></pre>\n\n<p>Hope it helps!</p>\n"
},
{
"answer_id": 15574248,
"author": "decates",
"author_id": 792525,
"author_profile": "https://Stackoverflow.com/users/792525",
"pm_score": 4,
"selected": false,
"text": "<p>I was able to use a SQLite in-memory database and avoid having to rebuild the schema for each test by using SQLite's <a href=\"http://www.sqlite.org/inmemorydb.html#sharedmemdb\">support for 'Shared Cache'</a>, which allows an in-memory database to be shared across connections.</p>\n\n<p>I did the following in <em>AssemblyInitialize</em> (I'm using MSTest):</p>\n\n<ul>\n<li><p>Configure NHibernate (Fluently) to use SQLite with the following connection string:</p>\n\n<pre><code>FullUri=file:memorydb.db?mode=memory&cache=shared\n</code></pre></li>\n<li><p>Use that configuration to create a hbm2ddl.<strong>SchemaExport</strong> object, and execute it on a separate connection (but with that same connection string again).</p></li>\n<li>Leave that connection open, and referenced by a static field, until <em>AssemblyCleanup</em>, at which point it is closed and disposed of. This is because SQLite needs at least one active connection to be held on the in-memory database to know it's still required and avoid tidying up.</li>\n</ul>\n\n<p>Before each test runs, a new session is created, and the test runs in a transaction which is rolled back at the end. </p>\n\n<p>Here is an example of the test assembly-level code:</p>\n\n<pre><code>[TestClass]\npublic static class SampleAssemblySetup\n{\n private const string ConnectionString = \"FullUri=file:memorydb.db?mode=memory&cache=shared\";\n private static SQLiteConnection _connection;\n\n [AssemblyInitialize]\n public static void AssemblyInit(TestContext context)\n {\n var configuration = Fluently.Configure()\n .Database(SQLiteConfiguration.Standard.ConnectionString(ConnectionString))\n .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.Load(\"MyMappingsAssembly\")))\n .ExposeConfiguration(x => x.SetProperty(\"current_session_context_class\", \"call\"))\n .BuildConfiguration();\n\n // Create the schema in the database\n // Because it's an in-memory database, we hold this connection open until all the tests are finished\n var schemaExport = new SchemaExport(configuration);\n _connection = new SQLiteConnection(ConnectionString);\n _connection.Open();\n schemaExport.Execute(false, true, false, _connection, null);\n }\n\n [AssemblyCleanup]\n public static void AssemblyTearDown()\n {\n if (_connection != null)\n {\n _connection.Dispose();\n _connection = null;\n }\n }\n}\n</code></pre>\n\n<p>And a base class for each unit test class/fixture:</p>\n\n<pre><code>public class TestBase\n{\n [TestInitialize]\n public virtual void Initialize()\n {\n NHibernateBootstrapper.InitializeSession();\n var transaction = SessionFactory.Current.GetCurrentSession().BeginTransaction();\n }\n\n [TestCleanup]\n public virtual void Cleanup()\n {\n var currentSession = SessionFactory.Current.GetCurrentSession();\n if (currentSession.Transaction != null)\n {\n currentSession.Transaction.Rollback();\n currentSession.Close();\n }\n\n NHibernateBootstrapper.CleanupSession();\n }\n}\n</code></pre>\n\n<p>Resource management could improve, I admit, but these are unit tests after all (suggested improvements welcome!).</p>\n"
},
{
"answer_id": 17012018,
"author": "Drexter",
"author_id": 2341271,
"author_profile": "https://Stackoverflow.com/users/2341271",
"pm_score": 0,
"selected": false,
"text": "<p>Just want to thank decates. Been trying to solve this for a couple of months now and all I had to do was add <br/></p>\n\n<pre><code>FullUri=file:memorydb.db?mode=memory&cache=shared\n</code></pre>\n\n<p>to the connection string in my nhibernate config file. Also using just NHibernate with *.hbm.xml and not FNH and didn't really have to modify my code at all!</p>\n"
},
{
"answer_id": 54147397,
"author": "jenspo",
"author_id": 812317,
"author_profile": "https://Stackoverflow.com/users/812317",
"pm_score": 0,
"selected": false,
"text": "<p>I got the same error, when I forgot to import the SQLite Nuget package.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5802/"
] |
I use NHibernate for my dataacess, and for awhile not I've been using SQLite for local integration tests. I've been using a file, but I thought I would out the :memory: option. When I fire up any of the integration tests, the database seems to be created (NHibernate spits out the table creation sql) but interfacting with the database causes an error.
Has anyone every gotten NHibernate working with an in memory database? Is it even possible? The connection string I'm using is this:
```
Data Source=:memory:;Version=3;New=True
```
|
A SQLite memory database only exists as long as the connection to it remains open. To use it in unit tests with NHibernate:
1. Open an ISession at the beginning of your test (maybe in a [SetUp] method).
2. Use the connection from that session in your SchemaExport call.
3. Use that same session in your tests.
4. Close the session at the end of your test (maybe in a [TearDown] method).
|
189,293 |
<p>I have a subroutine that takes a filehandle as an argument. How do I make a filehandle from a file path specified on the command line? I don't want to do any processing of this file myself, I just want to pass it off to this other subroutine, which returns an array of hashes with all the parsed data from the file.</p>
<p>Here's what the command line input I'm using looks like:</p>
<p><code>$ ./getfile.pl /path/to/some/file.csv</code></p>
<p>Here's what the beginning of the subroutine I'm calling looks like:</p>
<pre><code>sub parse {
my $handle = shift;
my @data = <$handle>;
while (my $line = shift(@data)) {
# do stuff
}
}
</code></pre>
|
[
{
"answer_id": 189314,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": -1,
"selected": false,
"text": "<p>Am I missing something or are you just looking for the open() call?</p>\n\n<pre><code>open($fh, \"<$ARGV[0]\") or die \"couldn't open $ARGV[0]: $!\";\ndo_something_with_fh($fh);\nclose($fh);\n</code></pre>\n"
},
{
"answer_id": 189316,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 5,
"selected": true,
"text": "<p>Command line arguments are available in the predefined <code>@ARGV</code> array. You can get the file name from there and use <code>open</code> to open a filehandle to it. Assuming that you want read-only access to the file, you would do it this way:</p>\n\n<pre><code>my $file = shift @ARGV;\nopen(my $fh, '<', $file) or die \"Can't read file '$file' [$!]\\n\";\nparse($fh);\n</code></pre>\n\n<p>Note that the <code>or die...</code> checks the call <code>open</code> for success and dies with an error message if it wasn't. The built-in variable <code>$!</code> will contain the (OS dependent) error message on failure that tells you why the call wasn't successful. e.g. \"Permission denied.\"</p>\n"
},
{
"answer_id": 189842,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 3,
"selected": false,
"text": "<p><code>parse(*ARGV)</code> is the simplest solution: the explanation is a bit long, but an important part of learning how to use Perl effectively is to learn Perl.</p>\n\n<p>When you use a null filehandle (<code><></code>), it actually reads from the magical <code>ARGV</code> filehandle, which has special semantics: it reads from all the files named in <code>@ARGV</code>, or <code>STDIN</code> if <code>@ARGV</code> is empty.</p>\n\n<p>From <code>perldoc perlop</code>:</p>\n\n<blockquote>\n <p>The null filehandle <code><></code> is special: it can be used to emulate the\n behavior of sed and awk. Input from <code><></code> comes either from standard\n input, or from each file listed on the command line. Here’s how it\n works: the first time <code><></code> is evaluated, the <code>@ARGV</code> array is checked, and\n if it is empty, <code>$ARGV[0]</code> is set to <code>\"-\"</code>, which when opened gives you\n standard input. The <code>@ARGV</code> array is then processed as a list of\n filenames. The loop</p>\n\n<pre><code>while (<>) {\n ... # code for each line\n}\n</code></pre>\n \n <p>is equivalent to the following Perl-like pseudo code:</p>\n\n<pre><code>unshift(@ARGV, '-') unless @ARGV;\nwhile ($ARGV = shift) {\n open(ARGV, $ARGV);\n while (<ARGV>) {\n ... # code for each line\n }\n}\n</code></pre>\n \n <p>except that it isn’t so cumbersome to say, and will actually work. It\n really does shift the <code>@ARGV</code> array and put the current filename into the\n <code>$ARGV</code> variable. It also uses filehandle <code>ARGV</code> internally--<code><></code> is just a\n synonym for <code><ARGV></code>, which is magical. (The pseudo code above doesn’t\n work because it treats <code><ARGV></code> as non-magical.)</p>\n</blockquote>\n\n<p>You don't have to use <code><></code> in a <code>while</code> loop -- <code>my $data = <></code> will read one line from the first non-empty file, <code>my @data = <>;</code> will slurp it all up at once, and you can pass <code>*ARGV</code> around as if it were a normal filehandle.</p>\n"
},
{
"answer_id": 192889,
"author": "Steve Klabnik",
"author_id": 24817,
"author_profile": "https://Stackoverflow.com/users/24817",
"pm_score": 1,
"selected": false,
"text": "<p>This is what the -n switch is for!</p>\n\n<p>Take your parse method, and do this:</p>\n\n<pre><code>#!/usr/bin/perl -n\n\n#do stuff\n</code></pre>\n\n<p>Each line is stored in $_. So you run</p>\n\n<p>./getfile.pl /path/to.csv</p>\n\n<p>And it does this.</p>\n\n<p>See <a href=\"http://www.perl.com/pub/a/2004/08/09/commandline.html?page=2\" rel=\"nofollow noreferrer\" title=\"here\">here</a> and <a href=\"http://perldoc.perl.org/perlrun.html\" rel=\"nofollow noreferrer\">here</a> for some more info about these. I like -p too, and have found the combo of -a and -F to be really useful.</p>\n\n<p>Also, if you want to do some extra processing, add BEGIN and end blocks.</p>\n\n<pre><code>#!/usr/bin/perl -n\n\nBEGIN {\n my $accumulator;\n}\n\n# do stuff\n\nEND {\n print process_total($accumulator);\n}\n</code></pre>\n\n<p>or whatever. This is very, very useful.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6406/"
] |
I have a subroutine that takes a filehandle as an argument. How do I make a filehandle from a file path specified on the command line? I don't want to do any processing of this file myself, I just want to pass it off to this other subroutine, which returns an array of hashes with all the parsed data from the file.
Here's what the command line input I'm using looks like:
`$ ./getfile.pl /path/to/some/file.csv`
Here's what the beginning of the subroutine I'm calling looks like:
```
sub parse {
my $handle = shift;
my @data = <$handle>;
while (my $line = shift(@data)) {
# do stuff
}
}
```
|
Command line arguments are available in the predefined `@ARGV` array. You can get the file name from there and use `open` to open a filehandle to it. Assuming that you want read-only access to the file, you would do it this way:
```
my $file = shift @ARGV;
open(my $fh, '<', $file) or die "Can't read file '$file' [$!]\n";
parse($fh);
```
Note that the `or die...` checks the call `open` for success and dies with an error message if it wasn't. The built-in variable `$!` will contain the (OS dependent) error message on failure that tells you why the call wasn't successful. e.g. "Permission denied."
|
189,308 |
<h2>Problem</h2>
<p>Our web host provider is changing the IP address of one of the servers we are on. We have been given a time frame for when the switch will take place, but no exact details. Therefore, our current <em>poor man's</em> check requires a periodic page refresh on a browser to see if our website is still there.</p>
<h2>Question</h2>
<p>We are all programmers here and this is killing me that any manual checking is required. I would know how to do this in other languages, but want to know if there is a way to write a script in <strong>PowerShell</strong> to tackle this problem. Does anyone know how I might going about this?</p>
|
[
{
"answer_id": 189653,
"author": "aphoria",
"author_id": 2441,
"author_profile": "https://Stackoverflow.com/users/2441",
"pm_score": 0,
"selected": false,
"text": "<p>This will list the IP Address for each network adapter in your system.</p>\n\n<pre><code>Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Select-Object -Property IPAddress\n</code></pre>\n"
},
{
"answer_id": 189794,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 3,
"selected": true,
"text": "<p>If you can alert if the page is gone or does not have an expected value, you could use a script like</p>\n\n<pre><code>$ip = 192.168.1.1\n$webclient = new-object System.Net.WebClient\n$regex = 'regular expression to match something on your page'\n$ping = new-object System.Net.NetworkInformation.Ping\n\n\ndo \n{\n $result = $ping.Send($ip)\n if ($result.status -ne 'TimedOut' )\n {\n $page = $webclient.downloadstring(\"http://$ip\")\n if (($page -notmatch $regex) -or ($page -match '404') -or ($page -eq $null))\n { break}\n }\n} while ($true)\n\nwrite-host \"The website has moved\"\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189308",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4916/"
] |
Problem
-------
Our web host provider is changing the IP address of one of the servers we are on. We have been given a time frame for when the switch will take place, but no exact details. Therefore, our current *poor man's* check requires a periodic page refresh on a browser to see if our website is still there.
Question
--------
We are all programmers here and this is killing me that any manual checking is required. I would know how to do this in other languages, but want to know if there is a way to write a script in **PowerShell** to tackle this problem. Does anyone know how I might going about this?
|
If you can alert if the page is gone or does not have an expected value, you could use a script like
```
$ip = 192.168.1.1
$webclient = new-object System.Net.WebClient
$regex = 'regular expression to match something on your page'
$ping = new-object System.Net.NetworkInformation.Ping
do
{
$result = $ping.Send($ip)
if ($result.status -ne 'TimedOut' )
{
$page = $webclient.downloadstring("http://$ip")
if (($page -notmatch $regex) -or ($page -match '404') -or ($page -eq $null))
{ break}
}
} while ($true)
write-host "The website has moved"
```
|
189,339 |
<p>I've just got a fresh Drupal 6 install. The CSS didn't work. Then I realized that a "?U" was appended, and Drupal couldn't find it. Does anyone know where to unset this? </p>
<pre><code><link type="text/css" rel="stylesheet" media="all" href="/modules/node/node.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/admin.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/defaults.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/system.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/system-menus.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/user/user.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/themes/bluemarine/style.css?U" />
</code></pre>
|
[
{
"answer_id": 189394,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": false,
"text": "<p>the ?U (or really any alphabet) is just a method drupal uses to cache information. it has no relevance to the location of the file (ie, node.css and node.css?U is in the same location to drupal).</p>\n\n<p>it sounds like you may have a different issue. perhaps you enabled your cache and moved things around? you may need to clear your cache. or, if you've modified your install variables perhaps you're picking up the wrong base path or something. it's hard to tell the exact issue based on the limited information given.</p>\n"
},
{
"answer_id": 189413,
"author": "Nick Sergeant",
"author_id": 22468,
"author_profile": "https://Stackoverflow.com/users/22468",
"pm_score": 0,
"selected": false,
"text": "<p>Did you install Drupal into a sub-directory? Like:</p>\n\n<pre><code>http://domain.com/drupal\n</code></pre>\n\n<p>This would certainly cause the problems you speak of, though Drupal should have properly accommodated for that.</p>\n"
},
{
"answer_id": 189544,
"author": "liangzan",
"author_id": 11927,
"author_profile": "https://Stackoverflow.com/users/11927",
"pm_score": 1,
"selected": false,
"text": "<p>You're right. Its because of the cache. I configured nginx to serve css files directly. But after I modified the configuration, it works fine now. Thank you!</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11927/"
] |
I've just got a fresh Drupal 6 install. The CSS didn't work. Then I realized that a "?U" was appended, and Drupal couldn't find it. Does anyone know where to unset this?
```
<link type="text/css" rel="stylesheet" media="all" href="/modules/node/node.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/admin.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/defaults.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/system.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/system-menus.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/user/user.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/themes/bluemarine/style.css?U" />
```
|
the ?U (or really any alphabet) is just a method drupal uses to cache information. it has no relevance to the location of the file (ie, node.css and node.css?U is in the same location to drupal).
it sounds like you may have a different issue. perhaps you enabled your cache and moved things around? you may need to clear your cache. or, if you've modified your install variables perhaps you're picking up the wrong base path or something. it's hard to tell the exact issue based on the limited information given.
|
189,363 |
<p>How do I write a regular expression to find all lines containing 665 and not having .pdf</p>
<p>I can't seem to find how to do not in regex. This is for Notepad++ syntax if it matters.</p>
<p>Thanks</p>
|
[
{
"answer_id": 189383,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 2,
"selected": false,
"text": "<p>The feature you'r looking for is look ahead patterns</p>\n\n<pre><code>665(?!.*\\.pdf)\n</code></pre>\n"
},
{
"answer_id": 190086,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 3,
"selected": true,
"text": "<p>If <code>.pdf</code> will only occur after <code>665</code>, the negative lookahead assertion <code>665(?!.*\\.pdf)</code> should work fine. Otherwise, I prefer to use two regexs, one to match, one to fail. In Perl syntax that would be:</p>\n\n<pre><code>/665/ && !/\\.pdf/\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
] |
How do I write a regular expression to find all lines containing 665 and not having .pdf
I can't seem to find how to do not in regex. This is for Notepad++ syntax if it matters.
Thanks
|
If `.pdf` will only occur after `665`, the negative lookahead assertion `665(?!.*\.pdf)` should work fine. Otherwise, I prefer to use two regexs, one to match, one to fail. In Perl syntax that would be:
```
/665/ && !/\.pdf/
```
|
189,368 |
<p>Here's my situation - I want to create a resized jpeg image from a user uploaded image, and then send it to S3 for storage, but am looking to avoid writing the resized jpeg to the disk and then reloading it for the S3 request.</p>
<p>Is there a way to do this completely in memory, with the image data JPEG formatted, saved in a variable?</p>
|
[
{
"answer_id": 189381,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 2,
"selected": false,
"text": "<p>The Imagemagick library will let you do that. There are plenty of PHP wrappers like <a href=\"http://uk.php.net/imagick\" rel=\"nofollow noreferrer\">this</a> one around for it (there's even <a href=\"http://uk.php.net/manual/en/book.imagick.php#78717\" rel=\"nofollow noreferrer\">example code</a> for what you want to do on that page ;) )</p>\n"
},
{
"answer_id": 189390,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": -1,
"selected": false,
"text": "<p>Maye by using the <a href=\"http://www.php.net/manual/en/book.image.php\" rel=\"nofollow noreferrer\">GD library</a>.</p>\n\n<p>There is a function to copy out a part of an image and resize it. Of course the part could be the whole image, that way you would only resize it.</p>\n\n<p>see <a href=\"http://www.php.net/manual/en/function.imagecopyresampled.php\" rel=\"nofollow noreferrer\">imagecopyresampled</a></p>\n"
},
{
"answer_id": 189410,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 3,
"selected": false,
"text": "<p>Once you've got the JPEG in memory (using <a href=\"http://ie.php.net/imagick\" rel=\"noreferrer\">ImageMagick</a>, <a href=\"http://ie.php.net/gd\" rel=\"noreferrer\">GD</a>, or your graphic library of choice), you'll need to upload the object from memory to S3.</p>\n\n<p>Many PHP S3 classes seem to only support file uploads, but the one at <a href=\"http://undesigned.org.za/2007/10/22/amazon-s3-php-class\" rel=\"noreferrer\">Undesigned</a> seems to do what we're after here - </p>\n\n<pre><code>// Manipulate image - assume ImageMagick, so $im is image object\n$im = new Imagick();\n// Get image source data\n$im->readimageblob($image_source);\n\n// Upload an object from a resource (requires size):\n$s3->putObject($s3->inputResource($im->getimageblob(), $im->getSize()), \n $bucketName, $uploadName, S3::ACL_PUBLIC_READ);\n</code></pre>\n\n<p>If you're using GD instead, you can use\n<a href=\"http://ie2.php.net/manual/en/function.imagecreatefromstring.php\" rel=\"noreferrer\">imagecreatefromstring</a> to read an image in from a stream, but I'm not sure whether you can get the size of the resulting object, as required by <code>s3->inputResource</code> above - <a href=\"http://ie2.php.net/manual/en/function.getimagesize.php\" rel=\"noreferrer\">getimagesize</a> returns the height, width, etc, but not the size of the image resource.</p>\n"
},
{
"answer_id": 404337,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 3,
"selected": false,
"text": "<p>This can be done using the GD library and output buffering. I don't know how efficient this is compared with other methods, but it doesn't require explicit creation of files.</p>\n\n<pre><code>//$image contains the GD image resource you want to store\n\nob_start();\nimagejpeg($image);\n$jpeg_file_contents = ob_get_contents();\nob_end_clean();\n\n//now send $jpeg_file_contents to S3\n</code></pre>\n"
},
{
"answer_id": 404358,
"author": "Jacco",
"author_id": 22674,
"author_profile": "https://Stackoverflow.com/users/22674",
"pm_score": 4,
"selected": false,
"text": "<p>Most people using PHP choose either <a href=\"http://www.php.net/manual/en/book.imagick.php\" rel=\"nofollow noreferrer\">ImageMagick</a> or <a href=\"http://www.php.net/manual/en/ref.image.php\" rel=\"nofollow noreferrer\">Gd2</a></p>\n\n<p>I've never used Imagemagick; the Gd2 method:</p>\n\n<pre><code><?php\n\n// assuming your uploaded file was 'userFileName'\n\nif ( ! is_uploaded_file(validateFilePath($_FILES[$userFileName]['tmp_name'])) ) {\n trigger_error('not an uploaded file', E_USER_ERROR);\n}\n$srcImage = imagecreatefromjpeg( $_FILES[$userFileName]['tmp_name'] );\n\n// Resize your image (copy from srcImage to dstImage)\nimagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, RESIZED_IMAGE_WIDTH, RESIZED_IMAGE_HEIGHT, imagesx($srcImage), imagesy($srcImage));\n\n// Storing your resized image in a variable\nob_start(); // start a new output buffer\n imagejpeg( $dstImage, NULL, JPEG_QUALITY);\n $resizedJpegData = ob_get_contents();\nob_end_clean(); // stop this output buffer\n\n// free up unused memmory (if images are expected to be large)\nunset($srcImage);\nunset($dstImage);\n\n// your resized jpeg data is now in $resizedJpegData\n// Use your Undesigned method calls to store the data.\n\n// (Many people want to send it as a Hex stream to the DB:)\n$dbHandle->storeResizedImage( $resizedJpegData );\n?>\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 11218549,
"author": "benipsen",
"author_id": 296073,
"author_profile": "https://Stackoverflow.com/users/296073",
"pm_score": 3,
"selected": false,
"text": "<p>Pretty late to the game on this one, but if you are using the the S3 library mentioned by ConroyP and Imagick you should use the putObjectString() method instead of putObject() due the fact getImageBlob returns a string. Example that finally worked for me:</p>\n\n<pre><code>$headers = array(\n 'Content-Type' => 'image/jpeg'\n);\n$s3->putObjectString($im->getImageBlob(), $bucket, $file_name, S3::ACL_PUBLIC_READ, array(), $headers);\n</code></pre>\n\n<p>I struggled with this one a bit, hopefully it helps someone else!</p>\n"
},
{
"answer_id": 19335120,
"author": "Bart",
"author_id": 158651,
"author_profile": "https://Stackoverflow.com/users/158651",
"pm_score": 3,
"selected": false,
"text": "<p>Realize this is an old thread, but I spent some time banging my head against the wall on this today, and thought I would capture my solution here for the next guy. </p>\n\n<p>This method uses <a href=\"http://aws.amazon.com/sdkforphp/\">AWS SDK for PHP 2</a> and GD for the image resize (Imagick could also be easily used).</p>\n\n<pre><code>require_once('vendor/aws/aws-autoloader.php');\n\nuse Aws\\Common\\Aws;\n\ndefine('AWS_BUCKET', 'your-bucket-name-here');\n\n// Configure AWS factory \n$aws = Aws::factory(array(\n 'key' => 'your-key-here',\n 'secret' => 'your-secret-here',\n 'region' => 'your-region-here'\n));\n\n// Create reference to S3\n$s3 = $aws->get('S3');\n$s3->createBucket(array('Bucket' => AWS_BUCKET));\n$s3->waitUntilBucketExists(array('Bucket' => AWS_BUCKET));\n$s3->registerStreamWrapper();\n\n// Do your GD resizing here (omitted for brevity)\n\n// Capture image stream in output buffer\nob_start();\nimagejpeg($imageRes);\n$imageFileContents = ob_get_contents();\nob_end_clean();\n\n// Send stream to S3\n$context = stream_context_create(\n array(\n 's3' => array(\n 'ContentType'=> 'image/jpeg'\n )\n )\n);\n$s3Stream = fopen('s3://'.AWS_BUCKET.'/'.$filename, 'w', false, $context);\nfwrite($s3Stream, $imageFileContents);\nfclose($s3Stream);\n\nunset($context, $imageFileContents, $s3Stream);\n</code></pre>\n"
},
{
"answer_id": 46008439,
"author": "Julien Fastré",
"author_id": 1572236,
"author_profile": "https://Stackoverflow.com/users/1572236",
"pm_score": 1,
"selected": false,
"text": "<p>I encounter the same problem, using openstack object store and <a href=\"https://github.com/php-opencloud/openstack\" rel=\"nofollow noreferrer\">php-opencloud</a> library.</p>\n<p>Here is my solution, which does <strong>not</strong> use the <code>ob_start</code> and <code>ob_end_clean</code> function, but store the image in memory and in temp file. <a href=\"http://php.net/manual/en/wrappers.php.php\" rel=\"nofollow noreferrer\">The size of the memory and the temp file may be adapted at runtime</a>.</p>\n<pre><code>// $image is a resource created by gd2\nvar_dump($image); // resource(2) of type (gd)\n\n// we create a resource in memory + temp file \n$tmp = fopen('php://temp', '$r+');\n\n// we write the image into our resource\n\\imagejpeg($image, $tmp);\n\n// the image is now in $tmp, and you can handle it as a stream\n// you can, then, upload it as a stream (not tested but mentioned in doc http://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-s3.html#uploading-from-a-stream)\n$s3->putObject(array(\n 'Bucket' => $bucket,\n 'Key' => 'data_from_stream.txt',\n 'Body' => $tmp\n));\n\n// or, for the ones who prefers php-opencloud :\n$container->createObject([\n 'name' => 'data_from_stream.txt',\n 'stream' => \\Guzzle\\Psr7\\stream_for($tmp),\n 'contentType' => 'image/jpeg'\n]);\n</code></pre>\n<hr />\n<p>About <code>php://temp</code> (<a href=\"http://php.net/manual/en/wrappers.php.php\" rel=\"nofollow noreferrer\">from the official documentation of php</a>):</p>\n<blockquote>\n<p>php://memory and php://temp are read-write streams that allow temporary data to be stored in a file-like wrapper. The only difference between the two is that php://memory will always store its data in memory, whereas php://temp will use a temporary file once the amount of data stored hits a predefined limit (the default is 2 MB). The location of this temporary file is determined in the same way as the sys_get_temp_dir() function.</p>\n<p>The memory limit of php://temp can be controlled by appending /maxmemory:NN, where NN is the maximum amount of data to keep in memory before using a temporary file, in bytes.</p>\n</blockquote>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24694/"
] |
Here's my situation - I want to create a resized jpeg image from a user uploaded image, and then send it to S3 for storage, but am looking to avoid writing the resized jpeg to the disk and then reloading it for the S3 request.
Is there a way to do this completely in memory, with the image data JPEG formatted, saved in a variable?
|
Most people using PHP choose either [ImageMagick](http://www.php.net/manual/en/book.imagick.php) or [Gd2](http://www.php.net/manual/en/ref.image.php)
I've never used Imagemagick; the Gd2 method:
```
<?php
// assuming your uploaded file was 'userFileName'
if ( ! is_uploaded_file(validateFilePath($_FILES[$userFileName]['tmp_name'])) ) {
trigger_error('not an uploaded file', E_USER_ERROR);
}
$srcImage = imagecreatefromjpeg( $_FILES[$userFileName]['tmp_name'] );
// Resize your image (copy from srcImage to dstImage)
imagecopyresampled($dstImage, $srcImage, 0, 0, 0, 0, RESIZED_IMAGE_WIDTH, RESIZED_IMAGE_HEIGHT, imagesx($srcImage), imagesy($srcImage));
// Storing your resized image in a variable
ob_start(); // start a new output buffer
imagejpeg( $dstImage, NULL, JPEG_QUALITY);
$resizedJpegData = ob_get_contents();
ob_end_clean(); // stop this output buffer
// free up unused memmory (if images are expected to be large)
unset($srcImage);
unset($dstImage);
// your resized jpeg data is now in $resizedJpegData
// Use your Undesigned method calls to store the data.
// (Many people want to send it as a Hex stream to the DB:)
$dbHandle->storeResizedImage( $resizedJpegData );
?>
```
Hope this helps.
|
189,375 |
<p>With a view to avoiding the construction of further barriers to migration whilst
enhancing an existing vb6 program.
Is there a way to achieve the same functionality as control arrays in vb6 without using them?</p>
|
[
{
"answer_id": 190443,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 0,
"selected": false,
"text": "<p>Well, you could always create your own array of controls in code :) Perhaps a better container, though, is a Collection or Dictionary object. Depending on what you want to do, you could perhaps create a wrapper class for the control with a custom collection class... but creating an object model is far nicer using generics in .NET so probably best to keep it simple in VB6 for now.</p>\n\n<p>VBA Userforms lack support for control arrays, so why not Google for suggestions on how to mimic control arrays with VBA, Userforms, Excel, etc.</p>\n\n<p>BTW have you tried migrating control arrays from VB6 to VB.NET? Just a guess but considering they are commonly used in VB I imagine they are handled quite well.</p>\n"
},
{
"answer_id": 191406,
"author": "RS Conley",
"author_id": 7890,
"author_profile": "https://Stackoverflow.com/users/7890",
"pm_score": 2,
"selected": true,
"text": "<p>In .NET you have a tag property. You can also have the same delegate handle events raised by multiple controls. Set the Tag property of the new control to the Index. </p>\n\n<pre><code>Private Sub MyButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click,Button2.Click\n\n Dim Btn As Button = CType(sender, Button)\n Dim Index As Integer = CType(Btn.Tag, Integer)\n' Do whatever you were doing in VB6 with the Index property\n\nEnd Sub\n</code></pre>\n\n<p>You also should look at the classes that inherit from BaseControlArray in the VB6.Compatibility which automates some of the work. I find the use of Tag to be less error prone in the conversion process than relying on the control name. However don't thank this as an absolute. You will have to decide whether the control name approach is best or the tag as index approach.</p>\n\n<p>In either case you can easily setup .NET to funnel the events raised by multiple controls into one handler. </p>\n"
},
{
"answer_id": 195949,
"author": "kjack",
"author_id": 6164,
"author_profile": "https://Stackoverflow.com/users/6164",
"pm_score": 0,
"selected": false,
"text": "<p>I did a bit of reading and experimentation over the last couple of days and it seems that there is no other way in vb6 to be able to do the things control arrays do.\nIf you already know the number of controls you'll be creating at runtime, at design time, then you can declare Private control object variables 'with events' and instance these at dynamically at runtime. If you need to create any more then you can do so but these won't have any code to fire in response to events. \nThis as far as I can see is the nub of the problem. there is no way to dynamically associate code with an event of a dynamically created control in vb6.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6164/"
] |
With a view to avoiding the construction of further barriers to migration whilst
enhancing an existing vb6 program.
Is there a way to achieve the same functionality as control arrays in vb6 without using them?
|
In .NET you have a tag property. You can also have the same delegate handle events raised by multiple controls. Set the Tag property of the new control to the Index.
```
Private Sub MyButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click,Button2.Click
Dim Btn As Button = CType(sender, Button)
Dim Index As Integer = CType(Btn.Tag, Integer)
' Do whatever you were doing in VB6 with the Index property
End Sub
```
You also should look at the classes that inherit from BaseControlArray in the VB6.Compatibility which automates some of the work. I find the use of Tag to be less error prone in the conversion process than relying on the control name. However don't thank this as an absolute. You will have to decide whether the control name approach is best or the tag as index approach.
In either case you can easily setup .NET to funnel the events raised by multiple controls into one handler.
|
189,392 |
<p>I'm trying to return a transparent GIF from an .aspx page for display within a web page. I am trying to get the image to have transparency, but I just keep getting Black being where the image should be Transparent.</p>
<p>Does anyone know what I'm doing wrong?</p>
<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
'' Change the response headers to output a GIF image.
Response.Clear()
Response.ContentType = "image/gif"
Dim width = 110
Dim height = width
'' Create a new 32-bit bitmap image
Dim b = New Bitmap(width, height)
'' Create Grahpics object for drawing
Dim g = Graphics.FromImage(b)
Dim rect = New Rectangle(0, 0, width - 1, height - 1)
'' Fill in with Transparent
Dim tbrush = New System.Drawing.SolidBrush(Color.Transparent)
g.FillRectangle(tbrush, rect)
'' Draw Circle Border
Dim bPen = Pens.Red
g.DrawPie(bPen, rect, 0, 365)
'' Fill in Circle
Dim cbrush = New SolidBrush(Color.LightBlue)
g.FillPie(cbrush, rect, 0, 365)
'' Clean up
g.Flush()
g.Dispose()
'' Make Transparent
b.MakeTransparent()
b.Save(Response.OutputStream, Imaging.ImageFormat.Gif)
Response.Flush()
Response.End()
End Sub
</code></pre>
|
[
{
"answer_id": 189447,
"author": "Jérôme Laban",
"author_id": 26346,
"author_profile": "https://Stackoverflow.com/users/26346",
"pm_score": 4,
"selected": true,
"text": "<p>Unfortunately, there is no easy way to create a transparent Gif using a Bitmap object. (See <a href=\"http://support.microsoft.com/default.aspx?scid=kb%3bEN-US%3bQ319061\" rel=\"noreferrer\">this KB article</a>)</p>\n\n<p>You can alternatively use the PNG format that supports transparency with the code you are using.</p>\n"
},
{
"answer_id": 189480,
"author": "Chris Pietschmann",
"author_id": 7831,
"author_profile": "https://Stackoverflow.com/users/7831",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, as Jerome stated, there isn't anyway to create transparent GIF's using a Bitmap object. Crap!</p>\n\n<p>Well, anyway, I changed my code to generate a PNG and all works as expected.</p>\n\n<p>There is one small work around I did need to do since you cannot write PNG's directly to the OutputStream. I needed to write the PNG to a MemoryStream, and then write that out to the OutputStream.</p>\n\n<p>Here's the final code for my implementation:</p>\n\n<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _\n Handles Me.Load\n '' Change the response headers to output a JPEG image.\n Response.Clear()\n Response.ContentType = \"image/png\"\n\n Dim width = 11\n Dim height = width\n\n '' Create a new 32-bit bitmap image\n Dim b = New Bitmap(width, height)\n\n '' Create Grahpics object for drawing\n Dim g = Graphics.FromImage(b)\n\n '' Fill the image with a color to be made Transparent after drawing is finished.\n g.Clear(Color.Gray)\n\n '' Get rectangle where the Circle will be drawn\n Dim rect = New Rectangle(0, 0, width - 1, height - 1)\n\n '' Draw Circle Border\n Dim bPen = Pens.Black\n g.DrawPie(bPen, rect, 0, 365)\n\n '' Fill in Circle\n Dim cbrush = New SolidBrush(Color.Red)\n g.FillPie(cbrush, rect, 0, 365)\n\n '' Clean up\n g.Flush()\n g.Dispose()\n\n '' Make Transparent\n b.MakeTransparent(Color.Gray)\n\n '' Write PNG to Memory Stream then write to OutputStream\n Dim ms = New MemoryStream()\n b.Save(ms, Imaging.ImageFormat.Png)\n ms.WriteTo(Response.OutputStream)\n\n Response.Flush()\n Response.End()\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 189547,
"author": "seanb",
"author_id": 3354,
"author_profile": "https://Stackoverflow.com/users/3354",
"pm_score": 2,
"selected": false,
"text": "<p>It is <em>possible</em>, but <em>not easy</em>.</p>\n<p>If you are able to use unsafe code in your project, there are a few methods to use pointers to rip through the colour table and make the transparency work.</p>\n<p>A sample forms app by Bob Powell is available at <a href=\"https://web.archive.org/web/20141227173018/http://bobpowell.net/giftransparency.aspx\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20141227173018/http://bobpowell.net/giftransparency.aspx</a>. I used a variation on this method in a web handler, and it seemed to work fine.</p>\n<p>If you are only using a limited colour palette, you can reduce the colour table processing to just the colours you need (can't remember exactly how I did that...).</p>\n<p>That being said, png is substantially easier.</p>\n"
},
{
"answer_id": 2140779,
"author": "Grégoire Lafortune",
"author_id": 259380,
"author_profile": "https://Stackoverflow.com/users/259380",
"pm_score": 2,
"selected": false,
"text": "<p>here is some code to have a gif (that already have transparency in it) transformed (supposed you want to resize it) in bitmap and then can be showed properly with it's transparency.</p>\n\n<pre><code>imagePath = System.Web.HttpContext.Current.Request.MapPath(libraryPath + reqImageFile);\nSystem.Drawing.Image image = null;\nBitmap resizedImage = null;\n\nif (reqWidth == 0) { reqWidth = image.Width; }\nif (reqHeight == 0) { reqHeight = image.Height; }\nimage = System.Drawing.Image.FromFile(imagePath);\nreqWidth = image.Width;\nreqHeight = image.Height;\n\n//here is the transparency 'special' treatment\nresizedImage = new Bitmap(reqWidth, reqHeight, PixelFormat.Format8bppIndexed);\nColorPalette pal = resizedImage.Palette;\nfor (int i = 0; i < pal.Entries.Length; i++)\n{\n Color col = pal.Entries[i];\n pal.Entries[i] = Color.FromArgb(0, col.R, col.G, col.B);\n}\nresizedImage.Palette = pal;\nBitmapData src = ((Bitmap)image).LockBits(new Rectangle(0, 0, reqWidth, reqHeight), ImageLockMode.ReadOnly, image.PixelFormat);\nBitmapData dst = resizedImage.LockBits(new Rectangle(0, 0, resizedImage.Width, resizedImage.Height),\nImageLockMode.WriteOnly, resizedImage.PixelFormat);\n((Bitmap)image).UnlockBits(src);\nresizedImage.UnlockBits(dst);\n</code></pre>\n\n<p>Good luck !</p>\n\n<p>Grégoire Lafortune</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7831/"
] |
I'm trying to return a transparent GIF from an .aspx page for display within a web page. I am trying to get the image to have transparency, but I just keep getting Black being where the image should be Transparent.
Does anyone know what I'm doing wrong?
```
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Me.Load
'' Change the response headers to output a GIF image.
Response.Clear()
Response.ContentType = "image/gif"
Dim width = 110
Dim height = width
'' Create a new 32-bit bitmap image
Dim b = New Bitmap(width, height)
'' Create Grahpics object for drawing
Dim g = Graphics.FromImage(b)
Dim rect = New Rectangle(0, 0, width - 1, height - 1)
'' Fill in with Transparent
Dim tbrush = New System.Drawing.SolidBrush(Color.Transparent)
g.FillRectangle(tbrush, rect)
'' Draw Circle Border
Dim bPen = Pens.Red
g.DrawPie(bPen, rect, 0, 365)
'' Fill in Circle
Dim cbrush = New SolidBrush(Color.LightBlue)
g.FillPie(cbrush, rect, 0, 365)
'' Clean up
g.Flush()
g.Dispose()
'' Make Transparent
b.MakeTransparent()
b.Save(Response.OutputStream, Imaging.ImageFormat.Gif)
Response.Flush()
Response.End()
End Sub
```
|
Unfortunately, there is no easy way to create a transparent Gif using a Bitmap object. (See [this KB article](http://support.microsoft.com/default.aspx?scid=kb%3bEN-US%3bQ319061))
You can alternatively use the PNG format that supports transparency with the code you are using.
|
189,415 |
<p>I have the following string:</p>
<p><code>$_='364*84252';</code></p>
<p>The question is: how to replace <code>*</code> in the string with something else? I've tried <code>s/\*/$i/</code>, but there is an error: <code>Quantifier follows nothing in regex</code>. On the other hand <code>s/'*'/$i/</code> doesn't cause any errors, but it also doesn't seem to have any effect at all.</p>
|
[
{
"answer_id": 189428,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "<p>Something else is weird here...</p>\n\n<pre><code>~> cat test.pl\n$a = \"234*343\";\n$i = \"FOO\";\n\n$a =~ s/\\*/$i/;\nprint $a;\n\n~> perl test.pl\n234FOO343\n</code></pre>\n\n<p>Found something:</p>\n\n<pre><code>~> cat test.pl\n$a = \"234*343\";\n$i = \"*4\";\n\n$a =~ m/$i/;\nprint $a;\n\n~> perl test.pl\nQuantifier follows nothing in regex; marked by <-- HERE in m/* <-- HERE 4/ at test.pl line 4.\n</code></pre>\n\n<p>Solution, escape the special characters from the variable using <code>\\Q</code> and <code>\\E</code>, for example (TIMTOWTDI)</p>\n\n<pre><code>~> cat test.pl\n$a = \"234*343\";\n$i = \"*4\";\n\n$a =~ m/\\Q$i\\E/;\nprint $a;\n\n~> perl test.pl\n234*343\n</code></pre>\n"
},
{
"answer_id": 189439,
"author": "Tanktalus",
"author_id": 23512,
"author_profile": "https://Stackoverflow.com/users/23512",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$ perl -le '$_=\"364*84252\";s/\\*/xx/;print'\n364xx84252\n</code></pre>\n\n<p>Definitely works. Perhaps you're using double-quotes in a oneline instead of single quotes? I'm not sure - I can't reproduce your results at all. You'll need to give a bit more background to your problem, preferably with code we can run to reproduce your results.</p>\n"
},
{
"answer_id": 189440,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The error must be coming from <code>$i</code>. <code>s/\\*/foo/</code> works fine.</p>\n"
},
{
"answer_id": 189488,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 2,
"selected": false,
"text": "<p><em>It must be a psh issue then. Running script with perl xx.pl does not throw any errors. Thanks for help ;)</em></p>\n\n<p>Strings do their own escaping of backslashes. In this case you should probably double the backslashes to <code>s/\\\\*/$i/</code></p>\n"
},
{
"answer_id": 4330084,
"author": "Ryan Speight",
"author_id": 527294,
"author_profile": "https://Stackoverflow.com/users/527294",
"pm_score": 0,
"selected": false,
"text": "<p>try </p>\n\n<pre><code>$VARIABLE =~ s/\\Q*\\E//;\n</code></pre>\n"
},
{
"answer_id": 4330117,
"author": "Ryan Speight",
"author_id": 527294,
"author_profile": "https://Stackoverflow.com/users/527294",
"pm_score": 1,
"selected": false,
"text": "<p>Better yet use </p>\n\n<pre><code>$InputLine =~ s/\\Q*\\E//g; \n</code></pre>\n\n<p>This should remove the asterisks anywhere in the variable string.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have the following string:
`$_='364*84252';`
The question is: how to replace `*` in the string with something else? I've tried `s/\*/$i/`, but there is an error: `Quantifier follows nothing in regex`. On the other hand `s/'*'/$i/` doesn't cause any errors, but it also doesn't seem to have any effect at all.
|
Something else is weird here...
```
~> cat test.pl
$a = "234*343";
$i = "FOO";
$a =~ s/\*/$i/;
print $a;
~> perl test.pl
234FOO343
```
Found something:
```
~> cat test.pl
$a = "234*343";
$i = "*4";
$a =~ m/$i/;
print $a;
~> perl test.pl
Quantifier follows nothing in regex; marked by <-- HERE in m/* <-- HERE 4/ at test.pl line 4.
```
Solution, escape the special characters from the variable using `\Q` and `\E`, for example (TIMTOWTDI)
```
~> cat test.pl
$a = "234*343";
$i = "*4";
$a =~ m/\Q$i\E/;
print $a;
~> perl test.pl
234*343
```
|
189,422 |
<p>I need to do a join across two different database servers (IPs 10.0.0.50 and 10.0.0.51). What's the best way?</p>
|
[
{
"answer_id": 189431,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 5,
"selected": true,
"text": "<p>You need to use sp_linkedserver to create a linked server.</p>\n\n<pre><code>sp_addlinkedserver [ @server= ] 'server' [ , [ @srvproduct= ] 'product_name' ] \n [ , [ @provider= ] 'provider_name' ]\n [ , [ @datasrc= ] 'data_source' ] \n [ , [ @location= ] 'location' ] \n [ , [ @provstr= ] 'provider_string' ] \n [ , [ @catalog= ] 'catalog' ] \n</code></pre>\n\n<p>More information available on <a href=\"http://msdn.microsoft.com/en-us/library/ms190479.aspx\" rel=\"noreferrer\">MSDN</a>.</p>\n"
},
{
"answer_id": 189432,
"author": "Kalid",
"author_id": 109,
"author_profile": "https://Stackoverflow.com/users/109",
"pm_score": 5,
"selected": false,
"text": "<p>The solution I found:</p>\n\n<p>1) Run a <a href=\"http://msdn.microsoft.com/en-us/library/aa259589(SQL.80).aspx\" rel=\"noreferrer\">stored proc</a></p>\n\n<pre><code>exec sp_addlinkedserver @server='10.0.0.51'\n</code></pre>\n\n<p>2) Verify that the servers were linked (lists linked servers)</p>\n\n<pre><code>exec sp_linkedservers\n</code></pre>\n\n<p>3) Run the query using the format</p>\n\n<pre><code> [10.0.0.51].DatabaseName.dbo.TableName\n</code></pre>\n"
},
{
"answer_id": 189576,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 3,
"selected": false,
"text": "<p>You can, as mentioned, use sp_addlinkedserver. However, you may also do this via Enterprise Manager (2000) or SQL Server Management Studio (2005). Under the \"Security\" node, there is a \"Linked Servers\" node, which you can use to add and configure Linked Servers. You can specify security settings, impersonation, etc.</p>\n\n<p>See these for SQL Server 2000:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa213778(SQL.80).aspx\" rel=\"noreferrer\">Configuring Linked Servers</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa213768(SQL.80).aspx\" rel=\"noreferrer\">Establishing Security For Linked Servers</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa213787(SQL.80).aspx\" rel=\"noreferrer\">Configuring OLEDB Providers for Distributed Queries</a></p>\n\n<p>See these for SQL Server 2005:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms188279(SQL.90).aspx\" rel=\"noreferrer\">Linking Servers</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms175537(SQL.90).aspx\" rel=\"noreferrer\">Security for Linked Servers</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms189580(SQL.90).aspx\" rel=\"noreferrer\">Configuring Linked Servers for Delegation</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms190918(SQL.90).aspx\" rel=\"noreferrer\">Configuring OLEDB Providers for Distributed Queries</a></p>\n"
},
{
"answer_id": 31883344,
"author": "MrSimpleMind",
"author_id": 1223532,
"author_profile": "https://Stackoverflow.com/users/1223532",
"pm_score": 4,
"selected": false,
"text": "<p>I know that the answers above are good, but wanted to share some details that I hope others will find helpful. Worth to mention is the user access part, which I think people will need help with.</p>\n\n<p><strong>set up the link:</strong></p>\n\n<p><code>exec sp_addlinkedserver @server='10.10.0.10\\MyDS';</code></p>\n\n<p><strong>set up the access for remote user, example below:</strong></p>\n\n<p><code>exec sp_addlinkedsrvlogin '10.10.0.10\\MyDS', 'false', null, 'adm', 'pwd';</code></p>\n\n<p><strong>see the linked servers and user logins:</strong></p>\n\n<p><code>exec sp_linkedservers;</code></p>\n\n<p><code>select * from sys.servers;</code></p>\n\n<p><code>select * from sys.linked_logins;</code></p>\n\n<p><strong>run the remote query:</strong></p>\n\n<p><code>select * from [10.10.0.10\\MyDS].MyDB.dbo.TestTable;</code></p>\n\n<p><strong>drop the linked server and the created login users (adm/pwd)</strong></p>\n\n<p><code>exec sp_dropserver '10.10.0.10\\MyDS', 'droplogins'; -- drops server and logins</code></p>\n\n<p><strong>resources:</strong></p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/ms190479.aspx\" rel=\"noreferrer\">sp_addlinkedserver</a></p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/ms174310.aspx\" rel=\"noreferrer\">sp_dropserver</a></p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/ms189811.aspx\" rel=\"noreferrer\">sp_addlinkedsrvlogin</a></p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/ms186218.aspx\" rel=\"noreferrer\">sp_droplinkedsrvlogin</a></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/109/"
] |
I need to do a join across two different database servers (IPs 10.0.0.50 and 10.0.0.51). What's the best way?
|
You need to use sp\_linkedserver to create a linked server.
```
sp_addlinkedserver [ @server= ] 'server' [ , [ @srvproduct= ] 'product_name' ]
[ , [ @provider= ] 'provider_name' ]
[ , [ @datasrc= ] 'data_source' ]
[ , [ @location= ] 'location' ]
[ , [ @provstr= ] 'provider_string' ]
[ , [ @catalog= ] 'catalog' ]
```
More information available on [MSDN](http://msdn.microsoft.com/en-us/library/ms190479.aspx).
|
189,433 |
<p>I am running Visual Studio Team Edition 2008.
<br />
<br />
<br />
When I create a new website, I get a new file I've never seen before: <em>vwd.webinfo</em>.</p>
<p>The contents of this file is as follows:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<VisualWebDeveloper>
<!-- Visual Studio global web project settings. -->
<StartupServices>
<Service ID="{3259AA49-8AA1-44D3-9025-A0B520596A8C}"/>
</StartupServices>
</VisualWebDeveloper>
</code></pre>
<p>What do I need a "global web project settings" file for? What does it do, exactly?
<br />
<br />
<br />
Also; what is with the bloated <em>web.config</em> file? In standard ASP.NET version 2.0 website projects, the <em>web.config</em> file contains about 10 lines of code. But in a ASP.NET version 3.5 website project, it is filled with all sorts of weird settings.</p>
|
[
{
"answer_id": 189466,
"author": "mannu",
"author_id": 15858,
"author_profile": "https://Stackoverflow.com/users/15858",
"pm_score": 3,
"selected": true,
"text": "<p>It is created because you are using a file system web site. Read more about it here:\n<a href=\"http://msdn.microsoft.com/en-us/library/e5x4xz73.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/e5x4xz73.aspx</a></p>\n\n<p>What do you mean with \"bloat\" ? Can you please paste the bloat?</p>\n"
},
{
"answer_id": 189474,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 1,
"selected": false,
"text": "<p>Looks like that file is part of the File System Web Projects based on <a href=\"http://msdn.microsoft.com/en-us/library/e5x4xz73.aspx\" rel=\"nofollow noreferrer\">this MSDN page</a>. It seems they moved some features out of the project file and into that file (makes sense because the project file isn't in file system projects now).</p>\n\n<p>The \"bloated\" web.config file is due to all the new features in ASP.Net 3.5 such as AJAX. You can remove a lot of these items if you aren't using the features.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20946/"
] |
I am running Visual Studio Team Edition 2008.
When I create a new website, I get a new file I've never seen before: *vwd.webinfo*.
The contents of this file is as follows:
```
<?xml version="1.0" encoding="UTF-8"?>
<VisualWebDeveloper>
<!-- Visual Studio global web project settings. -->
<StartupServices>
<Service ID="{3259AA49-8AA1-44D3-9025-A0B520596A8C}"/>
</StartupServices>
</VisualWebDeveloper>
```
What do I need a "global web project settings" file for? What does it do, exactly?
Also; what is with the bloated *web.config* file? In standard ASP.NET version 2.0 website projects, the *web.config* file contains about 10 lines of code. But in a ASP.NET version 3.5 website project, it is filled with all sorts of weird settings.
|
It is created because you are using a file system web site. Read more about it here:
<http://msdn.microsoft.com/en-us/library/e5x4xz73.aspx>
What do you mean with "bloat" ? Can you please paste the bloat?
|
189,436 |
<p>When I try to test the AutoLotWCFService using "wcftestclient", I get the following error. What am I doing wrong? Any insight will help. This is a simple Web Service that has wshttpbinding with interface contract and the implementation in the service. Here is the long error message: The Web.Config file has 2 endpoints - one for Web Service itself and other for metaDataExchange. Its all pretty much default stuff. I can include the code if needed - it seems I cannot attach files here.</p>
<hr>
<pre><code>Error: Cannot obtain Metadata from http://localhost/AutoLotWCFService/Service.svc
If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address.
For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.
WS-Metadata Exchange Error
URI: http://localhost/AutoLotWCFService/Service.svc
Metadata contains a reference that cannot be resolved: 'http://localhost/AutoLotWCFService/Service.svc'.
The remote server returned an unexpected response: (405) Method not allowed.
The remote server returned an error: (405) Method Not Allowed.
HTTP GET Error URI: http://localhost/AutoLotWCFService/Service.svc
The document at the url http://localhost/AutoLotWCFService/Service.svc was not recognized as a known document type.The error message from each known type may help you fix the problem:
- Report from 'DISCO Document' is 'Name cannot begin with the '%' character, hexadecimal value 0x25. Line 1, position 2.'.
- Report from 'WSDL Document' is 'There is an error in XML document (1, 2).' -Name cannot begin with the '%' character, hexadecimal value 0x25. Line 1, position 2.
- Report from 'XML Schema' is 'Name cannot begin with the '%' character, hexadecimal value 0x25. Line 1, position 2.'.
</code></pre>
<hr>
|
[
{
"answer_id": 189459,
"author": "Craig Wilson",
"author_id": 25333,
"author_profile": "https://Stackoverflow.com/users/25333",
"pm_score": 0,
"selected": false,
"text": "<p>you need to make sure that the service behaviour configuration enables has a metadata tag with httpGetEnabled=\"true\"</p>\n\n<pre><code><serviceBehaviors>\n <behavior name=\"serviceBehavior\">\n <serviceMetadata httpGetEnabled=\"true\">\n </behavior>\n</serviceBehaviors>\n</code></pre>\n\n<p>In addition, make sure your service references that behavior.</p>\n\n<pre><code>\n<service name=\"blah\" behaviorConfiguration=\"serviceBehavior\">\n</code></pre>\n"
},
{
"answer_id": 198066,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks; believe it or not the problem of at least loading the service through wcftestclient was solved when I re-registered the ASPNET in IIS with aspnet-regiis. </p>\n\n<p>The next problem is to be able to invoke the methods exposed by the service through wcftestclient. What are the security issues that I have to deal with? I had to enable Anonymous login with windows auth. and still the invoke generated exceptions that pointed to something related to access violation. On searching some things point to installing certificates to be able to invoke.. Please enlighten if possible.</p>\n"
},
{
"answer_id": 582283,
"author": "VikingProgrammer",
"author_id": 70418,
"author_profile": "https://Stackoverflow.com/users/70418",
"pm_score": 4,
"selected": false,
"text": "<p>I recently had this problem whilst trying to host WCF on my Windows Vista Laptop under IIS7.</p>\n\n<p>I first recieved the following error : \"HTTP Error 404.3 - Not Found\" and one of the resolutions suggested was to \"Ensure that the expected handler for the current page is mapped.\"</p>\n\n<p>So I added a handler for the .svc file manually and defined it as a DiscoveryRequestHandler, thinking that this might help. This caused the problem you described above.</p>\n\n<p>The actual resolution was to delete the handler I had added, and to run the following commands: </p>\n\n<pre><code>CD c:\\windows\\Microsoft.Net\\Framework\\v3.0\\Windows Communication Foundation\\\nServiceModelReg -i\n</code></pre>\n\n<p>This resolved my issue and the service is working fine. I hope this might help shed some light on your problem. I can't be certain but this is probably because of the order in which I've installed the various packages on my dev laptop.</p>\n"
},
{
"answer_id": 3043838,
"author": "Mariusz Pawlowski",
"author_id": 367056,
"author_profile": "https://Stackoverflow.com/users/367056",
"pm_score": 0,
"selected": false,
"text": "<p>Try checking if service(name) in the Service Markup (right click on servicename.svc) matches the service(name) in your web.config file.</p>\n\n<p>Cheers!</p>\n"
},
{
"answer_id": 5361637,
"author": "cja100",
"author_id": 208795,
"author_profile": "https://Stackoverflow.com/users/208795",
"pm_score": 1,
"selected": false,
"text": "<p>If installing compenonts doesnt work try a repair, this uninstalls and then installs.</p>\n\n<pre><code>\"%WINDIR%\\Microsoft.Net\\Framework\\v3.0\\Windows Communication Foundation\\ServiceModelReg.exe\" -r\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
When I try to test the AutoLotWCFService using "wcftestclient", I get the following error. What am I doing wrong? Any insight will help. This is a simple Web Service that has wshttpbinding with interface contract and the implementation in the service. Here is the long error message: The Web.Config file has 2 endpoints - one for Web Service itself and other for metaDataExchange. Its all pretty much default stuff. I can include the code if needed - it seems I cannot attach files here.
---
```
Error: Cannot obtain Metadata from http://localhost/AutoLotWCFService/Service.svc
If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address.
For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.
WS-Metadata Exchange Error
URI: http://localhost/AutoLotWCFService/Service.svc
Metadata contains a reference that cannot be resolved: 'http://localhost/AutoLotWCFService/Service.svc'.
The remote server returned an unexpected response: (405) Method not allowed.
The remote server returned an error: (405) Method Not Allowed.
HTTP GET Error URI: http://localhost/AutoLotWCFService/Service.svc
The document at the url http://localhost/AutoLotWCFService/Service.svc was not recognized as a known document type.The error message from each known type may help you fix the problem:
- Report from 'DISCO Document' is 'Name cannot begin with the '%' character, hexadecimal value 0x25. Line 1, position 2.'.
- Report from 'WSDL Document' is 'There is an error in XML document (1, 2).' -Name cannot begin with the '%' character, hexadecimal value 0x25. Line 1, position 2.
- Report from 'XML Schema' is 'Name cannot begin with the '%' character, hexadecimal value 0x25. Line 1, position 2.'.
```
---
|
I recently had this problem whilst trying to host WCF on my Windows Vista Laptop under IIS7.
I first recieved the following error : "HTTP Error 404.3 - Not Found" and one of the resolutions suggested was to "Ensure that the expected handler for the current page is mapped."
So I added a handler for the .svc file manually and defined it as a DiscoveryRequestHandler, thinking that this might help. This caused the problem you described above.
The actual resolution was to delete the handler I had added, and to run the following commands:
```
CD c:\windows\Microsoft.Net\Framework\v3.0\Windows Communication Foundation\
ServiceModelReg -i
```
This resolved my issue and the service is working fine. I hope this might help shed some light on your problem. I can't be certain but this is probably because of the order in which I've installed the various packages on my dev laptop.
|
189,468 |
<p>I've had nothing but good luck from SO, so why not try again?</p>
<p>I have an application that needs to show a different image based on the season of the year (spring, summer, winter, fall). I have very specific start and end dates for these seasons.</p>
<p>What I would like from you geniuses is a method called GetSeason that takes a date as input and returns a String value of Spring, Summer, Winter or Fall. Here are the date ranges and their associated seasons:<br></p>
<p>Spring:3/1-4/30<br>
Summer:5/1-8/31<br>
Fall:9/1-10/31<br>
Winter: 11/1-2/28</p>
<p>Can someone provide a working method to return the proper season?
Thanks everyone!</p>
|
[
{
"answer_id": 189504,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 1,
"selected": false,
"text": "<p>Well, it could be as simple as</p>\n\n<pre><code>String getSeason(int month) {\n switch(month) {\n case 11:\n case 12:\n case 1:\n case 2:\n return \"winter\";\n case 3:\n case 4:\n return \"spring\";\n case 5:\n case 6:\n case 7:\n case 8:\n return \"summer\";\n default:\n return \"autumn\";\n }\n}\n</code></pre>\n\n<p>I have been chided in the comments into a better solution: enums:</p>\n\n<pre><code>public static Enum Season {\n WINTER(Arrays.asList(11,12,1,2)),\n SPRING(Arrays.asList(3,4)),\n SUMMER(Arrays.asList(5,6,7,8)),\n AUTUMN(Arrays.asList(9,10));\n\n Season(List<Integer> months) {\n this.monthlist = months;\n }\n private List<Integer> monthlist;\n public boolean inSeason(int month) {\n return this.monthlist.contains(month); // if months are 0 based, then insert +1 before the )\n }\n\n public static Season seasonForMonth(int month) {\n for(Season s: Season.values()) {\n if (s.inSeason(month))\n return s;\n }\n throw new IllegalArgumentException(\"Unknown month\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 189506,
"author": "Jorn",
"author_id": 8681,
"author_profile": "https://Stackoverflow.com/users/8681",
"pm_score": 0,
"selected": false,
"text": "<p>since in this range all seasons are full months, you can do a switch with the month from your date:</p>\n\n<pre><code>switch (date.getMonth()) {\n case Calendar.JANUARY:\n case Calendar.FEBRUARY:\n return \"winter\";\n case Calendar.MARCH:\n return \"spring\";\n //etc\n}\n</code></pre>\n\n<p>I recommend completing the entire switch using all 12 Calendar constants, instead of default for the last ones. You can then make sure your input was correct, for example with</p>\n\n<pre><code>default:\n throw new IllegalArgumentException();\n</code></pre>\n\n<p>at the end.</p>\n\n<p>You might also want to use an Enum for the season, instead of a simple string, depending on your use cases.</p>\n\n<p>Note the Date.getMonth() method is deprecated, you should use java.util.Calendar.get(Calendar.MONTH) instead. (just convert the Date to a Calendar using calendar.setDate(yourDate))</p>\n"
},
{
"answer_id": 189521,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 4,
"selected": true,
"text": "<p>Seems like just checking the month would do:</p>\n\n<pre><code>private static final String seasons[] = {\n \"Winter\", \"Winter\", \"Spring\", \"Spring\", \"Summer\", \"Summer\", \n \"Summer\", \"Summer\", \"Fall\", \"Fall\", \"Winter\", \"Winter\"\n};\npublic String getSeason( Date date ) {\n return seasons[ date.getMonth() ];\n}\n\n// As stated above, getMonth() is deprecated, but if you start with a Date, \n// you'd have to convert to Calendar before continuing with new Java, \n// and that's not fast.\n</code></pre>\n"
},
{
"answer_id": 189553,
"author": "helloandre",
"author_id": 50,
"author_profile": "https://Stackoverflow.com/users/50",
"pm_score": 1,
"selected": false,
"text": "<p>i feel patronized, but flattered. so i'll do it. </p>\n\n<p>This checks not only the month, but day of month. </p>\n\n<pre><code>import java.util.*\n\npublic String getSeason(Date today, int year){\n\n // the months are one less because GC is 0-based for the months, but not days.\n // i.e. 0 = January.\n String returnMe = \"\";\n\n GregorianCalender dateToday = new GregorianCalender(year, today.get(Calender.MONTH_OF_YEAR), today.get(Calender.DAY_OF_MONTH);\n GregorianCalender springstart = new GregorianCalender(year, 2, 1);\n GregorianCalender springend = new GregorianCalender(year, 3, 30);\n GregorianCalender summerstart = new GregorianCalender(year, 4, 1);\n GregorianCalender summerend = new GregorianCalender(year, 7, 31);\n GregorianCalender fallstart = new GregorianCalender(year, 8, 1);\n GregorianCalender fallend = new GregorianCalender(year, 9, 31);\n GregorianCalender winterstart = new GregorianCalender(year, 10, 1);\n GregorianCalender winterend = new GregorianCalender(year, 1, 28);\n\n if ((dateToday.after(springstart) && dateToday.before(springend)) || dateToday.equals(springstart) || dateToday.equals(springend)){\n returnMe = \"Spring\";\n\n else if ((dateToday.after(summerstart) && dateToday.before(summerend)) || dateToday.equals(summerstart) || dateToday.equals(summerend)){\n returnMe = \"Summer\";\n\n else if ((dateToday.after(fallstart) && dateToday.before(fallend)) || dateToday.equals(fallstart) || dateToday.equals(fallend)){\n returnMe = \"Fall\";\n\n else if ((dateToday.after(winterstart) && dateToday.before(winterend)) || dateToday.equals(winterstart) || dateToday.equals(winterend)){\n returnMe = \"Winter\";\n\n else {\n returnMe = \"Invalid\";\n }\n return returnMe;\n}\n</code></pre>\n\n<p>I'm sure this is hideous, and can be improved. let me know in the comments.</p>\n"
},
{
"answer_id": 4293499,
"author": "Hjohnson",
"author_id": 522492,
"author_profile": "https://Stackoverflow.com/users/522492",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public class lab6project1 {\n public static void main(String[] args) {\n Scanner keyboard = new Scanner(System.in);\n\n System.out.println(\"This program reports the season for a given day and month\");\n System.out.println(\"Please enter the month and day as integers with a space between the month and day\");\n\n int month = keyboard.nextInt();\n int day = keyboard.nextInt();\n\n\n if ((month == 1) || (month == 2)) {\n System.out.println(\"The season is Winter\");\n } else if ((month == 4) || (month == 5)) {\n System.out.println(\"The season is Spring\");\n } else if ((month == 7) || (month == 8)) {\n System.out.println(\"The season is Summer\");\n } else if ((month == 10) || (month == 11)) {\n System.out.println(\"The season is Fall\");\n } else if ((month == 3) && (day <= 19)) {\n System.out.println(\"The season is Winter\");\n } else if (month == 3) {\n System.out.println(\"The season is Spring\");\n } else if ((month == 6) && (day <= 20)) {\n System.out.println(\"The season is Spring\");\n } else if (month == 6) {\n System.out.println(\"The season is Summer\");\n } else if ((month == 9) && (day <= 20)) {\n System.out.println(\"The season is Summer\");\n } else if (month == 9) {\n System.out.println(\"The season is Autumn\");\n } else if ((month == 12) && (day <= 21)) {\n System.out.println(\"The season is Autumn\");\n } else if (month == 12) {\n System.out.println(\"The season is Winter\");\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 24925552,
"author": "ECE",
"author_id": 1877309,
"author_profile": "https://Stackoverflow.com/users/1877309",
"pm_score": 0,
"selected": false,
"text": "<p>Try using hash tables or enums. You could convert the date into some value (jan 1 being 1,...) and then create bins for a certain field. or you could do an enum with the month. {january: winter, february: winter, ...july:summer, etc}</p>\n"
},
{
"answer_id": 38033293,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 2,
"selected": false,
"text": "<p>Some good answers here, but they are outdated. The java.time classes make this work much easier.</p>\n\n<h1>java.time</h1>\n\n<p>The troublesome old classes bundled with the earliest versions of Java have been supplanted by the <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html\" rel=\"nofollow noreferrer\">java.time</a> classes built into Java 8 and later. See <a href=\"http://docs.oracle.com/javase/tutorial/datetime/TOC.html\" rel=\"nofollow noreferrer\">Oracle Tutorial</a>. Much of the functionality has been back-ported to Java 6 & 7 in <a href=\"http://www.threeten.org/threetenbp/\" rel=\"nofollow noreferrer\">ThreeTen-Backport</a> and further adapted to Android in <a href=\"https://github.com/JakeWharton/ThreeTenABP\" rel=\"nofollow noreferrer\">ThreeTenABP</a>.</p>\n\n<h2><code>Month</code></h2>\n\n<p>Given that seasons are defined here using whole months, we can make use of the handy <a href=\"http://docs.oracle.com/javase/8/docs/api/java/time/Month.html\" rel=\"nofollow noreferrer\"><code>Month</code></a> <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html\" rel=\"nofollow noreferrer\">enum</a>. Such enum values are better than mere integer values (1-12) because they are type-safe and you are guaranteed of valid values.</p>\n\n<h2><code>EnumSet</code></h2>\n\n<p>An <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html\" rel=\"nofollow noreferrer\"><code>EnumSet</code></a> is a fast-performing and compact-memory way to track a subset of enum values.</p>\n\n<pre><code>EnumSet<Month> spring = EnumSet.of( Month.MARCH , Month.APRIL );\nEnumSet<Month> summer = EnumSet.of( Month.MAY , Month.JUNE , Month.JULY , Month.AUGUST );\nEnumSet<Month> fall = EnumSet.of( Month.SEPTEMBER , Month.OCTOBER );\nEnumSet<Month> winter = EnumSet.of( Month.NOVEMBER , Month.DECEMBER , Month.JANUARY , Month.FEBRUARY );\n</code></pre>\n\n<p>As an example, we get the current moment for a particular time zone.</p>\n\n<pre><code>ZoneId zoneId = ZoneId.of( \"America/Montreal\" );\nZonedDateTime zdt = ZonedDateTime.now( zoneId );\n</code></pre>\n\n<p>Ask that date-time value for its <code>Month</code>.</p>\n\n<pre><code>Month month = Month.from( zdt );\n</code></pre>\n\n<p>Look for which season <code>EnumSet</code> has that particular Month value by calling <a href=\"http://docs.oracle.com/javase/8/docs/api/java/util/Set.html#contains-java.lang.Object-\" rel=\"nofollow noreferrer\"><code>contains</code></a>.</p>\n\n<pre><code>if ( spring.contains( month ) ) {\n …\n} else if ( summer.contains( month ) ) {\n …\n} else if ( fall.contains( month ) ) {\n …\n} else if ( winter.contains( month ) ) {\n …\n} else {\n // FIXME: Handle reaching impossible point as error condition.\n}\n</code></pre>\n\n<h2>Define your own “Season” enum</h2>\n\n<p>If you are using this season idea around your code base, I suggest defining your own enum, “Season”.</p>\n\n<p>The basic enum is simple: <code>public enum Season { SPRING, SUMMER, FALL, WINTER; }</code>. But we also add a static method <code>of</code> to do that lookup of which month maps to which season.</p>\n\n<pre><code>package work.basil.example;\n\nimport java.time.Month;\n\npublic enum Season {\n SPRING, SUMMER, FALL, WINTER;\n\n static public Season of ( final Month month ) {\n switch ( month ) {\n\n // Spring.\n case MARCH: // Java quirk: An enum switch case label must be the unqualified name of an enum. So cannot use `Month.MARCH` here, only `MARCH`.\n return Season.SPRING;\n\n case APRIL:\n return Season.SPRING;\n\n // Summer.\n case MAY:\n return Season.SUMMER;\n\n case JUNE:\n return Season.SUMMER;\n\n case JULY:\n return Season.SUMMER;\n\n case AUGUST:\n return Season.SUMMER;\n\n // Fall.\n case SEPTEMBER:\n return Season.FALL;\n\n case OCTOBER:\n return Season.FALL;\n\n // Winter.\n case NOVEMBER:\n return Season.WINTER;\n\n case DECEMBER:\n return Season.WINTER;\n\n case JANUARY:\n return Season.WINTER;\n\n case FEBRUARY:\n return Season.WINTER;\n\n default:\n System.out.println ( \"ERROR.\" ); // FIXME: Handle reaching impossible point as error condition.\n return null;\n }\n }\n\n}\n</code></pre>\n\n<p>Or use the switch expressions feature (<a href=\"https://openjdk.java.net/jeps/361\" rel=\"nofollow noreferrer\">JEP 361</a>) of Java 14.</p>\n\n<pre><code>package work.basil.example;\n\nimport java.time.Month;\nimport java.util.Objects;\n\npublic enum Season\n{\n SPRING, SUMMER, FALL, WINTER;\n\n static public Season of ( final Month month )\n {\n Objects.requireNonNull( month , \"ERROR - Received null where a `Month` is expected. Message # 0ac03df9-1c5a-4c2d-a22d-14c40e25c58b.\" );\n return\n switch ( Objects.requireNonNull( month ) )\n {\n // Spring.\n case MARCH , APRIL -> Season.SPRING;\n\n // Summer.\n case MAY , JUNE , JULY , AUGUST -> Season.SUMMER;\n\n // Fall.\n case SEPTEMBER , OCTOBER -> Season.FALL;\n\n // Winter.\n case NOVEMBER , DECEMBER , JANUARY , FEBRUARY -> Season.WINTER;\n }\n ;\n }\n}\n</code></pre>\n\n<p>Here is how to use that enum.</p>\n\n<pre><code>ZoneId zoneId = ZoneId.of ( \"America/Montreal\" );\nZonedDateTime zdt = ZonedDateTime.now ( zoneId );\nMonth month = Month.from ( zdt );\nSeason season = Season.of ( month );\n</code></pre>\n\n<p>Dump to console.</p>\n\n<pre><code>System.out.println ( \"zdt: \" + zdt + \" | month: \" + month + \" | season: \" + season );\n</code></pre>\n\n<blockquote>\n <p>zdt: 2016-06-25T18:23:14.695-04:00[America/Montreal] | month: JUNE | season: SUMMER</p>\n</blockquote>\n"
},
{
"answer_id": 39266771,
"author": "Volodymyr Machekhin",
"author_id": 4847691,
"author_profile": "https://Stackoverflow.com/users/4847691",
"pm_score": 0,
"selected": false,
"text": "<p>Simple solution </p>\n\n<pre><code> Calendar calendar = Calendar.getInstance();\n calendar.setTimeInMillis(timeInMills);\n int month = calendar.get(Calendar.MONTH);\n CurrentSeason = month == 11 ? 0 : (month + 1) / 3;\n</code></pre>\n"
},
{
"answer_id": 53662468,
"author": "Meno Hochschild",
"author_id": 2491410,
"author_profile": "https://Stackoverflow.com/users/2491410",
"pm_score": 0,
"selected": false,
"text": "<p>The title of your question is very general so most users will first think of astronomical seasons. Even though the detailed content of your question is limited to customized date ranges, this limitation might just be caused by the inability to calculate the astronomical case so I dare to post an answer to this old question also for the astronomical scenario.</p>\n\n<p>And most answers here are only based on full months. I give here two examples to address both astronomical seasons and seasons based on arbitrary date ranges.</p>\n\n<h2>a) mapping of arbitrary date ranges to seasons</h2>\n\n<p>Here <strong>we definitely need an extra information, the concrete time zone</strong> or offset otherwise we cannot translate an instant (like the oldfashioned <code>java.util.Date</code>-instance of your input) to a local representation using the combination of month and day. For simplicity I assume the system time zone.</p>\n\n<pre><code> // your input\n java.util.Date d = new java.util.Date();\n ZoneId tz = ZoneId.systemDefault();\n\n // extract the relevant month-day\n ZonedDateTime zdt = d.toInstant().atZone(tz);\n MonthDay md = MonthDay.of(zdt.getMonth(), zdt.getDayOfMonth());\n\n // a definition with day-of-month other than first is possible here\n MonthDay beginOfSpring = MonthDay.of(3, 1);\n MonthDay beginOfSummer = MonthDay.of(5, 1);\n MonthDay beginOfAutumn = MonthDay.of(9, 1);\n MonthDay beginOfWinter = MonthDay.of(11, 1);\n\n // determine the season\n Season result;\n\n if (md.isBefore(beginOfSpring)) {\n result = Season.WINTER;\n } else if (md.isBefore(beginOfSummer)) {\n result = Season.SPRING;\n } else if (md.isBefore(beginOfAutumn)) {\n result = Season.SUMMER;\n } else if (md.isBefore(beginOfWinter)) {\n result = Season.FALL;\n } else {\n result = Season.WINTER;\n }\n\n System.out.println(result);\n</code></pre>\n\n<p>I have used a simple helper enum like <code>public enum Season { SPRING, SUMMER, FALL, WINTER; }</code>.</p>\n\n<h2>b) astronomical seasons</h2>\n\n<p>Here we also need one extra information, namely if the season is on the northern or on the southern hemisphere. My library <a href=\"https://github.com/MenoData/Time4J\" rel=\"nofollow noreferrer\">Time4J</a> offers following solution based on the predefined enum <a href=\"http://time4j.net/javadoc-en/net/time4j/calendar/astro/AstronomicalSeason.html\" rel=\"nofollow noreferrer\">AstronomicalSeason</a> using the version v5.2:</p>\n\n<pre><code> // your input\n java.util.Date d = new java.util.Date();\n boolean isSouthern = false;\n\n Moment m = TemporalType.JAVA_UTIL_DATE.translate(d);\n AstronomicalSeason result = AstronomicalSeason.of(m);\n\n if (isSouthern) { // switch to southern equivalent if necessary\n result = result.onSouthernHemisphere();\n }\n\n System.out.println(result);\n</code></pre>\n"
},
{
"answer_id": 62012826,
"author": "Vadzim",
"author_id": 603516,
"author_profile": "https://Stackoverflow.com/users/603516",
"pm_score": 0,
"selected": false,
"text": "<p>In case just a season number for northern hemisphere is needed:</p>\n\n<pre><code>/**\n * @return 1 - winter, 2 - spring, 3 - summer, 4 - autumn\n */\nprivate static int getDateSeason(LocalDate date) {\n return date.plus(1, MONTHS).get(IsoFields.QUARTER_OF_YEAR);\n}\n</code></pre>\n\n<p>Via <a href=\"https://stackoverflow.com/questions/302658/how-do-i-discover-the-quarter-of-a-given-date/36765477#comment81156879_36765477\">How do I discover the Quarter of a given Date?</a>.</p>\n\n<hr>\n\n<p>And here is how to calculate season bounds for a given date:</p>\n\n<pre><code>private static LocalDate atStartOfSeason(LocalDate date) {\n return date.plus(1, MONTHS).with(IsoFields.DAY_OF_QUARTER, 1).minus(1, MONTHS);\n}\n\nprivate static LocalDate afterEndOfSeason(LocalDate date) {\n return atStartOfSeason(date).plus(3, MONTHS);\n}\n</code></pre>\n\n<p>Via <a href=\"https://stackoverflow.com/questions/36493649/how-to-get-the-first-date-and-last-date-of-current-quarter-in-java-util-date?rq=1#comment95686234_50702885\">How to get the first date and last date of current quarter in java.util.Date</a>.</p>\n"
},
{
"answer_id": 67847519,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>import java.util.Scanner;\n\npublic class Season {\n\npublic static void main (String[] args) {\n\n Scanner sc = new Scanner(System.in);\n\n System.out.println("Enter the month:");\n\n int mon=sc.nextInt();\n\n if(mon>12||mon<1)\n {\n System.out.println("Invalid month");\n }\n\n else if(mon>=3&&mon<=5)\n {\n System.out.println("Season:Spring");\n }\n\n else if(mon>=6&&mon<=8)\n {\n System.out.println("Season:Summer");\n }\n\n else if(mon>=9&&mon<=11)\n {\n System.out.println("Season:Autumn");\n }\n\n else if(mon==12||mon==1||mon==2)\n {\n System.out.println("Season:Winter");\n }\n}\n}\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172/"
] |
I've had nothing but good luck from SO, so why not try again?
I have an application that needs to show a different image based on the season of the year (spring, summer, winter, fall). I have very specific start and end dates for these seasons.
What I would like from you geniuses is a method called GetSeason that takes a date as input and returns a String value of Spring, Summer, Winter or Fall. Here are the date ranges and their associated seasons:
Spring:3/1-4/30
Summer:5/1-8/31
Fall:9/1-10/31
Winter: 11/1-2/28
Can someone provide a working method to return the proper season?
Thanks everyone!
|
Seems like just checking the month would do:
```
private static final String seasons[] = {
"Winter", "Winter", "Spring", "Spring", "Summer", "Summer",
"Summer", "Summer", "Fall", "Fall", "Winter", "Winter"
};
public String getSeason( Date date ) {
return seasons[ date.getMonth() ];
}
// As stated above, getMonth() is deprecated, but if you start with a Date,
// you'd have to convert to Calendar before continuing with new Java,
// and that's not fast.
```
|
189,479 |
<p>When I created the project I'm trying to deploy I selected that I wanted to target .NET Framework 2.0. After deploying the project I try to brows to it and get and error page that shows:</p>
<pre><code><compilation debug="true">
<assemblies>
<add assembly="System.Web.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
</code></pre>
<p>One of the selling points of VS2008 is that you can develop for and deploy to server running .NET2.0 what Am I doing wrong?</p>
|
[
{
"answer_id": 189487,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 1,
"selected": false,
"text": "<p>remove those references from your project and redeploy. if your project started as 3.5 it will still have references to some of those assemblies</p>\n"
},
{
"answer_id": 189491,
"author": "Eric Tuttleman",
"author_id": 25677,
"author_profile": "https://Stackoverflow.com/users/25677",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using features from the 3.5 framework, then you'll have to deploy to a 3.5 machine.</p>\n\n<p>Most information you'd probably need for this issue is in the question and answers here:\n<a href=\"https://stackoverflow.com/questions/167569/problems-executing-compiled-35-code-on-a-server-which-only-has-the-20-framework\">problems-executing-compiled-35-code-on-a-server-which-only-has-the-20-framework</a></p>\n"
},
{
"answer_id": 189494,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 2,
"selected": true,
"text": "<p>You are referencing assemblies of the .NET Framework 3.5, are you using EntityDataSources??</p>\n\n<p>Remove those 3.5 references...</p>\n\n<p>You also need the AJAX Extensions (System.Web.Extensions) for .NET 2.0 on the server.</p>\n"
},
{
"answer_id": 189513,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 2,
"selected": false,
"text": "<p>Right click on your project and select \"Properties.\" From there, select the \"Compile\" tab and click the \"Advanced Compile Options\" button down at the bottom left. The last drop down list item should be \"Target Framework\" and you can select 2.0 from there. As mentioned above, this is provided you're not using any 3.5 related technologies such as LINQ.</p>\n\n<p>Save, recompile and deploy. Once everything is set, you can go back and select the 3.5 option to target the 3.5 framework again.</p>\n\n<p>Hope this helps!</p>\n\n<p>Oh, one other thing to note. If you are using the AJAX Toolkit controls in your 3.5 application (calendar extender, auto-complete extender, etc.), you'll need to make sure you download the 1.0 Toolkit from the codeplex site since the 3.5 toolkit is not compatible with the 2.0 framework.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] |
When I created the project I'm trying to deploy I selected that I wanted to target .NET Framework 2.0. After deploying the project I try to brows to it and get and error page that shows:
```
<compilation debug="true">
<assemblies>
<add assembly="System.Web.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
```
One of the selling points of VS2008 is that you can develop for and deploy to server running .NET2.0 what Am I doing wrong?
|
You are referencing assemblies of the .NET Framework 3.5, are you using EntityDataSources??
Remove those 3.5 references...
You also need the AJAX Extensions (System.Web.Extensions) for .NET 2.0 on the server.
|
189,522 |
<p>any thoughts on this would be appreciated:</p>
<pre><code>std::string s1 = "hello";
std::string s2 = std::string(s1);
</code></pre>
<p>I'd now expect these two strings to be independent, i.e. I could append ", world" to s2 and s1 would still read "hello". This is what I find on windows and linux but running the code on a HP_UX machine it seems that s2 and s1 are the same string, so modifying s2 changes s1.</p>
<p>Does this sound absolutely crazy, anyone seen anything similar?</p>
|
[
{
"answer_id": 189538,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 2,
"selected": false,
"text": "<p>This must be a bug. std::string could do reference-counted strings as its implementation, but once it gets changed, it's supposed to \"fork\" the string.</p>\n"
},
{
"answer_id": 189539,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 1,
"selected": false,
"text": "<p>That sure sounds like a bug to me. Can anyone else who has access to HP/UX repro this?</p>\n\n<p>You're saying that this program displays the same text on both lines?</p>\n\n<pre><code>#include <stdio.h>\n#include <string>\n\nint main () \n{\n std::string s1 = \"hello\"; \n std::string s2 = std::string(s1); // note: std::string s2( s1); would reduce the number of copy ctor calls\n\n s2.append( \", world\");\n\n printf( \"%s\\n\", s1.c_str());\n printf( \"%s\\n\", s2.c_str());\n}\n</code></pre>\n"
},
{
"answer_id": 189556,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 1,
"selected": false,
"text": "<p>Do the two strings actually change differently, or are you using some other comparison (such as the addresses returned by c_str())?</p>\n\n<p>Some implementations of string don't copy the entire string when a copy is made so as to speed up the copying of long strings. If you attempt to make a change to either one, then the implementation should copy the string and make the appropriate changes (ideally as part of the same operation).</p>\n"
},
{
"answer_id": 189587,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 1,
"selected": false,
"text": "<p>It would certainly be a defect. This example is verbatim from the C++ standard:</p>\n\n<pre><code>string s1(\"abc\");\nstring::iterator i = s1.begin();\nstring s2 = s1;\n*i = ’a’; // Must modify only s1\n</code></pre>\n"
},
{
"answer_id": 191747,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": 3,
"selected": false,
"text": "<p>Although I could not reproduce the exact bug of the OP, I came across a similar bug in the HP-UX aCC compilers. I posted about it on the <a href=\"http://forums12.itrc.hp.com/service/forums/questionanswer.do?admit=109447627+1223649583692+28353475&threadId=1108413\" rel=\"noreferrer\">HP boards</a>, and eventually got a response from HP. Basically their versions 3.xx (3.70, 3.73, 3.67, etc.) of aCC have messed up std::string construction. We had to move to the 6.xx versions of the compiler. The problem we had at the time was that there was not a 6.xx compiler available for PA-RISC machines, just Itanium. I believe that a 6.xx compiler was released for PA-RISC in September 2007.</p>\n\n<p>The code that was giving the problem was:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n\nclass S : public std::string // An extension of std::string\n{\npublic:\n explicit S(const char* s)\n : std::string(s)\n {\n }\n};\n\nclass N // Wraps an int\n{\npublic:\n explicit N(int n)\n : _n(n)\n {}\n operator S() const // Converts to a string extension\n {\n return _n == 0 ? S(\"zero\") : (_n == 1 ? S(\"one\") : S(\"other\"));\n }\nprivate:\n int _n;\n};\n\nint main(int, char**)\n{\n N n0 = N(0);\n N n1 = N(1);\n\n std::string zero = n0;\n std::cout << \"zero = \" << zero << std::endl;\n std::string one = n1;\n std::cout << \"zero = \" << zero\n << \", one = \" << one << std::endl;\n\n return 0;\n}\n</code></pre>\n\n<p>This was printing:<br>\nzero = zero<br>\n<strong><em>zero = one</em></strong>, one = one</p>\n\n<p>In other words the construction of string one from n1 was clobbering another string completely (string zero).</p>\n\n<p>NOTES:<br>\nTo see the version of the compiler, type \"aCC -V\"<br>\nTo see the type of machine, type \"uname -m\" (9000/800 ==> PA-RISC, ia64 ==> Itanium) </p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26665/"
] |
any thoughts on this would be appreciated:
```
std::string s1 = "hello";
std::string s2 = std::string(s1);
```
I'd now expect these two strings to be independent, i.e. I could append ", world" to s2 and s1 would still read "hello". This is what I find on windows and linux but running the code on a HP\_UX machine it seems that s2 and s1 are the same string, so modifying s2 changes s1.
Does this sound absolutely crazy, anyone seen anything similar?
|
Although I could not reproduce the exact bug of the OP, I came across a similar bug in the HP-UX aCC compilers. I posted about it on the [HP boards](http://forums12.itrc.hp.com/service/forums/questionanswer.do?admit=109447627+1223649583692+28353475&threadId=1108413), and eventually got a response from HP. Basically their versions 3.xx (3.70, 3.73, 3.67, etc.) of aCC have messed up std::string construction. We had to move to the 6.xx versions of the compiler. The problem we had at the time was that there was not a 6.xx compiler available for PA-RISC machines, just Itanium. I believe that a 6.xx compiler was released for PA-RISC in September 2007.
The code that was giving the problem was:
```
#include <iostream>
#include <string>
class S : public std::string // An extension of std::string
{
public:
explicit S(const char* s)
: std::string(s)
{
}
};
class N // Wraps an int
{
public:
explicit N(int n)
: _n(n)
{}
operator S() const // Converts to a string extension
{
return _n == 0 ? S("zero") : (_n == 1 ? S("one") : S("other"));
}
private:
int _n;
};
int main(int, char**)
{
N n0 = N(0);
N n1 = N(1);
std::string zero = n0;
std::cout << "zero = " << zero << std::endl;
std::string one = n1;
std::cout << "zero = " << zero
<< ", one = " << one << std::endl;
return 0;
}
```
This was printing:
zero = zero
***zero = one***, one = one
In other words the construction of string one from n1 was clobbering another string completely (string zero).
NOTES:
To see the version of the compiler, type "aCC -V"
To see the type of machine, type "uname -m" (9000/800 ==> PA-RISC, ia64 ==> Itanium)
|
189,523 |
<p>I have already extracted the tag from the source document using grep but, now I cant seem to figure out how to easily extract the properties from the string. Also I want to avoid having to use any programs that would not usually be present on a standard installation. </p>
<pre><code>$tag='<img src="http://imgs.xkcd.com/comics/barrel_cropped_(1).jpg" title="Don't we all." alt="Barrel - Part 1" />'
</code></pre>
<p>I need to end up with the following variables</p>
<pre><code>$src="http://imgs.xkcd.com/comics/barrel_cropped_(1).jpg"
$title="Don't we all."
$alt="Barrel - Part 1"
</code></pre>
|
[
{
"answer_id": 189735,
"author": "GameFreak",
"author_id": 26659,
"author_profile": "https://Stackoverflow.com/users/26659",
"pm_score": 1,
"selected": false,
"text": "<p>I went with dacracot's suggestion of using sed although I would have prefered if he had given me some sample code </p>\n\n<pre><code>src=`echo $tag | sed 's/.*src=[\"]\\(.*\\)[\"] title=[\"]\\(.*\\)[\"] alt=[\"]\\(.*\\)[\"].*/\\1/'` \ntitle=`echo $tag | sed 's/.*src=[\"]\\(.*\\)[\"] title=[\"]\\(.*\\)[\"] alt=[\"]\\(.*\\)[\"].*/\\2/'` \nalt=`echo $tag | sed 's/.*src=[\"]\\(.*\\)[\"] title=[\"]\\(.*\\)[\"] alt=[\"]\\(.*\\)[\"].*/\\3/'`\n</code></pre>\n"
},
{
"answer_id": 189890,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"http://xmlstar.sourceforge.net/\" rel=\"nofollow noreferrer\">xmlstarlet</a>. Then, you don't even have to extract the element yourself:</p>\n\n<pre><code>$ echo $tag|xmlstarlet sel -t --value-of '//img/@src'\nhttp://imgs.xkcd.com/comics/barrel_cropped_(1).jpg\n</code></pre>\n\n<p>You can even turn this into a function</p>\n\n<pre><code>$ get_attribute() {\n echo $1 | xmlstarlet sel -t -o \"&quot;\" -v $2 -o \"&quot;\"\n }\n$ src=get_attribute $tag '//img/@src'\n</code></pre>\n\n<p>If you don't want to reparse the document several times, you can also do:</p>\n\n<pre><code>$ get_values() {\n eval file=\\${$#}\n eval $#= \n cmd=\"xmlstarlet sel \"\n for arg in $@\n do\n if [ -n $arg ]\n then\n var=${arg%%\\=*}\n expr=${arg#*=}\n cmd+=\" -t -o \\\"$var=&quot;\\\" -v $expr -o \\\"&quot;\\\" -n\"\n fi\n done\n eval $cmd $file\n }\n$ eval $(get_values src='//img/@src' title='//img/@title' your_file.xml)\n$ echo $src\nhttp://imgs.xkcd.com/comics/barrel_cropped_(1).jpg\n$ echo $title\nDon't we all.\n</code></pre>\n\n<p>I'm sure there's a better way to remove the last argument to a shell function, but I don't know it.</p>\n"
},
{
"answer_id": 3174307,
"author": "lmxy",
"author_id": 383018,
"author_profile": "https://Stackoverflow.com/users/383018",
"pm_score": 0,
"selected": false,
"text": "<p>If xmlstarlet is available on a standard installation and the sequence of src-title-alt does not change, you can use the following code as well:</p>\n\n<pre><code>tag='<img src=\"http://imgs.xkcd.com/comics/barrel_cropped_(1).jpg\" title=\"Don'\"'\"'t we all.\" alt=\"Barrel - Part 1\" />'\nxmlstarlet sel -T -t -m \"/img\" -m \"@*\" -v '.' -n <<< \"$tag\"\nIFS=$'\\n'\narray=( $(xmlstarlet sel -T -t -m \"/img\" -m \"@*\" -v '.' -n <<< \"$tag\") )\nsrc=\"${array[0]}\"\ntitle=\"${array[1]}\"\nalt=\"${array[2]}\"\n\nprintf \"%s\\n\" \"src: $src\" \"title: $title\" \"alt: $alt\"\n</code></pre>\n"
},
{
"answer_id": 16438923,
"author": "BeniBela",
"author_id": 1501222,
"author_profile": "https://Stackoverflow.com/users/1501222",
"pm_score": 0,
"selected": false,
"text": "<p>Since this bubbled up again, there is now my <a href=\"http://videlibri.sourceforge.net/xidel.html\" rel=\"nofollow\">Xidel</a> that has 2 features which make this task trivial:</p>\n\n<ul>\n<li><p>pattern matching on the xml </p></li>\n<li><p>exporting all matched variables to the shell</p></li>\n</ul>\n\n<p>So it becomes a single line:</p>\n\n<pre><code>eval $(xidel \"$tag\" -e '<img src=\"{$src}\" title=\"{$title}\" alt=\"{$alt}\"/>' --output-format bash)\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26659/"
] |
I have already extracted the tag from the source document using grep but, now I cant seem to figure out how to easily extract the properties from the string. Also I want to avoid having to use any programs that would not usually be present on a standard installation.
```
$tag='<img src="http://imgs.xkcd.com/comics/barrel_cropped_(1).jpg" title="Don't we all." alt="Barrel - Part 1" />'
```
I need to end up with the following variables
```
$src="http://imgs.xkcd.com/comics/barrel_cropped_(1).jpg"
$title="Don't we all."
$alt="Barrel - Part 1"
```
|
You can use [xmlstarlet](http://xmlstar.sourceforge.net/). Then, you don't even have to extract the element yourself:
```
$ echo $tag|xmlstarlet sel -t --value-of '//img/@src'
http://imgs.xkcd.com/comics/barrel_cropped_(1).jpg
```
You can even turn this into a function
```
$ get_attribute() {
echo $1 | xmlstarlet sel -t -o """ -v $2 -o """
}
$ src=get_attribute $tag '//img/@src'
```
If you don't want to reparse the document several times, you can also do:
```
$ get_values() {
eval file=\${$#}
eval $#=
cmd="xmlstarlet sel "
for arg in $@
do
if [ -n $arg ]
then
var=${arg%%\=*}
expr=${arg#*=}
cmd+=" -t -o \"$var="\" -v $expr -o \""\" -n"
fi
done
eval $cmd $file
}
$ eval $(get_values src='//img/@src' title='//img/@title' your_file.xml)
$ echo $src
http://imgs.xkcd.com/comics/barrel_cropped_(1).jpg
$ echo $title
Don't we all.
```
I'm sure there's a better way to remove the last argument to a shell function, but I don't know it.
|
189,549 |
<p>Is it possible to embed a pre-existing DLL into a compiled C# executable (so that you only have one file to distribute)? If it is possible, how would one go about doing it?</p>
<p>Normally, I'm cool with just leaving the DLLs outside and having the setup program handle everything, but there have been a couple of people at work who have asked me this and I honestly don't know.</p>
|
[
{
"answer_id": 189554,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 3,
"selected": false,
"text": "<p>You could add the DLLs as embedded resources, and then have your program unpack them into the application directory on startup (after checking to see if they're there already).</p>\n\n<p>Setup files are so easy to make, though, that I don't think this would be worth it.</p>\n\n<p>EDIT: This technique would be easy with .NET assemblies. With non-.NET DLLs it would be a lot more work (you'd have to figure out where to unpack the files and register them and so on).</p>\n"
},
{
"answer_id": 189558,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 6,
"selected": false,
"text": "<p>If they're actually managed assemblies, you can use <a href=\"https://github.com/dotnet/ILMerge\" rel=\"nofollow noreferrer\">ILMerge</a>. For native DLLs, you'll have a bit more work to do. </p>\n\n<p><strong>See also:</strong> <a href=\"https://stackoverflow.com/questions/72264/how-can-a-c-windows-dll-be-merged-into-a-c-application-exe\">How can a C++ windows dll be merged into a C# application exe?</a> </p>\n"
},
{
"answer_id": 189566,
"author": "Chris Charabaruk",
"author_id": 5697,
"author_profile": "https://Stackoverflow.com/users/5697",
"pm_score": 0,
"selected": false,
"text": "<p>It's possible but not all that easy, to create a hybrid native/managed assembly in C#. Were you using C++ instead it'd be a lot easier, as the Visual C++ compiler can create hybrid assemblies as easily as anything else.</p>\n\n<p>Unless you have a strict requirement to produce a hybrid assembly, I'd agree with MusiGenesis that this isn't really worth the trouble to do with C#. If you need to do it, perhaps look at moving to C++/CLI instead.</p>\n"
},
{
"answer_id": 189609,
"author": "Nathan",
"author_id": 541,
"author_profile": "https://Stackoverflow.com/users/541",
"pm_score": 3,
"selected": false,
"text": "<p>Another product that can handle this elegantly is SmartAssembly, at <a href=\"http://www.smartassembly.com/\" rel=\"nofollow noreferrer\">SmartAssembly.com</a>. This product will, in addition to merging all dependencies into a single DLL, (optionally) obfuscate your code, remove extra meta-data to reduce the resulting file size, and can also actually optimize the IL to increase runtime performance. </p>\n\n<p>There is also some kind of global exception handling/reporting feature it adds to your software (if desired) that could be useful. I believe it also has a command-line API so you can make it part of your build process.</p>\n"
},
{
"answer_id": 4043611,
"author": "keithwill",
"author_id": 488905,
"author_profile": "https://Stackoverflow.com/users/488905",
"pm_score": 0,
"selected": false,
"text": "<p>Generally you would need some form of post build tool to perform an assembly merge like you are describing. There is a free tool called Eazfuscator (eazfuscator.blogspot.com/) which is designed for bytecode mangling that also handles assembly merging. You can add this into a post build command line with Visual Studio to merge your assemblies, but your mileage will vary due to issues that will arise in any non trival assembly merging scenarios.</p>\n\n<p>You could also check to see if the build make untility NANT has the ability to merge assemblies after building, but I am not familiar enough with NANT myself to say whether the functionality is built in or not.</p>\n\n<p>There are also many many Visual Studio plugins that will perform assembly merging as part of building the application.</p>\n\n<p>Alternatively if you don't need this to be done automatically, there are a number of tools like ILMerge that will merge .net assemblies into a single file.</p>\n\n<p>The biggest issue I've had with merging assemblies is if they use any similar namespaces. Or worse, reference different versions of the same dll (my problems were generally with the NUnit dll files).</p>\n"
},
{
"answer_id": 4043653,
"author": "Bobby",
"author_id": 180239,
"author_profile": "https://Stackoverflow.com/users/180239",
"pm_score": 5,
"selected": false,
"text": "<p>Yes, it is possible to merge .NET executables with libraries. There are multiple tools available to get the job done:</p>\n\n<ul>\n<li><a href=\"http://www.microsoft.com/downloads/en/details.aspx?familyid=22914587-b4ad-4eae-87cf-b14ae6a939b0&displaylang=en\" rel=\"noreferrer\">ILMerge</a> is a utility that can be used to merge multiple .NET assemblies into a single assembly.</li>\n<li><a href=\"http://www.mono-project.com/Command-Line_Tools#Project_converstion_.26_deployment\" rel=\"noreferrer\">Mono mkbundle</a>, packages an exe and all assemblies with libmono into a single binary package.</li>\n<li><a href=\"https://github.com/gluck/il-repack\" rel=\"noreferrer\">IL-Repack</a> is a FLOSS alterantive to ILMerge, with some additional features.</li>\n</ul>\n\n<p>In addition this can be combined with the <a href=\"http://www.mono-project.com/Linker\" rel=\"noreferrer\">Mono Linker</a>, which does remove unused code and therefor makes the resulting assembly smaller.</p>\n\n<p>Another possibility is to use <a href=\"https://github.com/madebits/msnet-netz-compressor\" rel=\"noreferrer\">.NETZ</a>, which does not only allow compressing of an assembly, but also can pack the dlls straight into the exe. The difference to the above mentioned solutions is that .NETZ does not merge them, they stay separate assemblies but are packed into one package.</p>\n\n<blockquote>\n <p>.NETZ is a open source tool that compresses and packs the Microsoft .NET Framework executable (EXE, DLL) files in order to make them smaller. </p>\n</blockquote>\n"
},
{
"answer_id": 6362414,
"author": "Lars Holm Jensen",
"author_id": 348005,
"author_profile": "https://Stackoverflow.com/users/348005",
"pm_score": 7,
"selected": false,
"text": "<p>Just right-click your project in Visual Studio, choose Project Properties -> Resources -> Add Resource -> Add Existing File…\nAnd include the code below to your App.xaml.cs or equivalent.</p>\n\n<pre><code>public App()\n{\n AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);\n}\n\nSystem.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n{\n string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(\".dll\",\"\");\n\n dllName = dllName.Replace(\".\", \"_\");\n\n if (dllName.EndsWith(\"_resources\")) return null;\n\n System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + \".Properties.Resources\", System.Reflection.Assembly.GetExecutingAssembly());\n\n byte[] bytes = (byte[])rm.GetObject(dllName);\n\n return System.Reflection.Assembly.Load(bytes);\n}\n</code></pre>\n\n<p>Here's my original blog post:\n<a href=\"http://codeblog.larsholm.net/2011/06/embed-dlls-easily-in-a-net-assembly/\" rel=\"noreferrer\">http://codeblog.larsholm.net/2011/06/embed-dlls-easily-in-a-net-assembly/</a></p>\n"
},
{
"answer_id": 10600034,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=17630\" rel=\"noreferrer\">ILMerge</a> can combine assemblies to one single assembly provided the assembly has only managed code. You can use the commandline app, or add reference to the exe and programmatically merge. For a GUI version there is <a href=\"http://www.foss.kharkov.ua/g1/projects/eazfuscator/dotnet/Default.aspx#downloads\" rel=\"noreferrer\">Eazfuscator</a>, and also <a href=\"http://madebits.com/netz/\" rel=\"noreferrer\">.Netz</a> both of which are free. Paid apps include <a href=\"http://boxedapp.com/\" rel=\"noreferrer\">BoxedApp</a> and <a href=\"http://www.red-gate.com/products/dotnet-development/smartassembly/\" rel=\"noreferrer\">SmartAssembly</a>. </p>\n\n<p>If you have to merge assemblies with unmanaged code, I would suggest <a href=\"http://www.red-gate.com/products/dotnet-development/smartassembly/\" rel=\"noreferrer\">SmartAssembly</a>. I never had hiccups with <a href=\"http://www.red-gate.com/products/dotnet-development/smartassembly/\" rel=\"noreferrer\">SmartAssembly</a> but with all others. Here, it can embed the required dependencies as resources to your main exe.</p>\n\n<p>You can do all this manually not needing to worry if assembly is managed or in mixed mode by embedding dll to your resources and then relying on AppDomain's Assembly <code>ResolveHandler</code>. This is a one stop solution by adopting the worst case, ie assemblies with unmanaged code.</p>\n\n<pre><code>static void Main()\n{\n AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>\n {\n string assemblyName = new AssemblyName(args.Name).Name;\n if (assemblyName.EndsWith(\".resources\"))\n return null;\n\n string dllName = assemblyName + \".dll\";\n string dllFullPath = Path.Combine(GetMyApplicationSpecificPath(), dllName);\n\n using (Stream s = Assembly.GetEntryAssembly().GetManifestResourceStream(typeof(Program).Namespace + \".Resources.\" + dllName))\n {\n byte[] data = new byte[stream.Length];\n s.Read(data, 0, data.Length);\n\n //or just byte[] data = new BinaryReader(s).ReadBytes((int)s.Length);\n\n File.WriteAllBytes(dllFullPath, data);\n }\n\n return Assembly.LoadFrom(dllFullPath);\n };\n}\n</code></pre>\n\n<p>The key here is to write the bytes to a file and load from its location. To avoid chicken and egg problem, you have to ensure you declare the handler before accessing assembly and that you do not access the assembly members (or instantiate anything that has to deal with the assembly) inside the loading (assembly resolving) part. Also take care to ensure <code>GetMyApplicationSpecificPath()</code> is not any temp directory since temp files could be attempted to get erased by other programs or by yourself (not that it will get deleted while your program is accessing the dll, but at least its a nuisance. AppData is good location). Also note that you have to write the bytes each time, you cant load from location just 'cos the dll already resides there.</p>\n\n<p>For managed dlls, you need not write bytes, but directly load from the location of the dll, or just read the bytes and load the assembly from memory. Like this or so:</p>\n\n<pre><code> using (Stream s = Assembly.GetEntryAssembly().GetManifestResourceStream(typeof(Program).Namespace + \".Resources.\" + dllName))\n {\n byte[] data = new byte[stream.Length];\n s.Read(data, 0, data.Length);\n return Assembly.Load(data);\n }\n\n //or just\n\n return Assembly.LoadFrom(dllFullPath); //if location is known.\n</code></pre>\n\n<p>If the assembly is fully unmanaged, you can see this <a href=\"https://stackoverflow.com/questions/666799/embedding-unmanaged-dll-into-a-managed-c-sharp-dll\">link</a> or <a href=\"http://bsmadhu.wordpress.com/2012/03/19/embedding-c-libraryexe-inside-net-assembly/\" rel=\"noreferrer\">this</a> as to how to load such dlls.</p>\n"
},
{
"answer_id": 19270093,
"author": "Anton Shepelev",
"author_id": 2862241,
"author_profile": "https://Stackoverflow.com/users/2862241",
"pm_score": 3,
"selected": false,
"text": "<p>Neither the ILMerge approach nor Lars Holm Jensen's handling the AssemblyResolve event will work for a plugin host. Say executable <em>H</em> loads assembly <em>P</em> dynamically and accesses it via interface <em>IP</em> defined in an separate assembly. To embed <em>IP</em> into <em>H</em> one shall need a little modification to Lars's code:</p>\n\n<pre><code>Dictionary<string, Assembly> loaded = new Dictionary<string,Assembly>();\nAppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>\n{ Assembly resAssembly;\n string dllName = args.Name.Contains(\",\") ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(\".dll\",\"\");\n dllName = dllName.Replace(\".\", \"_\");\n if ( !loaded.ContainsKey( dllName ) )\n { if (dllName.EndsWith(\"_resources\")) return null;\n System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + \".Properties.Resources\", System.Reflection.Assembly.GetExecutingAssembly());\n byte[] bytes = (byte[])rm.GetObject(dllName);\n resAssembly = System.Reflection.Assembly.Load(bytes);\n loaded.Add(dllName, resAssembly);\n }\n else\n { resAssembly = loaded[dllName]; }\n return resAssembly;\n}; \n</code></pre>\n\n<p>The trick to handle repeated attempts to resolve the same assembly and return the existing one instead of creating a new instance.</p>\n\n<p><strong>EDIT:</strong>\nLest it spoil .NET's serialization, make sure to return null for all assemblies not embedded in yours, thereby defaulting to the standard behaviour. You can get a list of these libraries by:</p>\n\n<pre><code>static HashSet<string> IncludedAssemblies = new HashSet<string>();\nstring[] resources = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();\nfor(int i = 0; i < resources.Length; i++)\n{ IncludedAssemblies.Add(resources[i]); }\n</code></pre>\n\n<p>and just return null if the passed assembly does not belong to <code>IncludedAssemblies</code> .</p>\n"
},
{
"answer_id": 19806004,
"author": "Steve",
"author_id": 1330601,
"author_profile": "https://Stackoverflow.com/users/1330601",
"pm_score": 4,
"selected": false,
"text": "<p>The <a href=\"http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx\">excerpt by Jeffrey Richter</a> is very good. In short, add the library's as embedded resources and add a callback before anything else. Here is a version of the code (found in the comments of his page) that I put at the start of Main method for a console app (just make sure that any calls that use the library's are in a different method to Main).</p>\n\n<pre><code>AppDomain.CurrentDomain.AssemblyResolve += (sender, bargs) =>\n {\n String dllName = new AssemblyName(bargs.Name).Name + \".dll\";\n var assem = Assembly.GetExecutingAssembly();\n String resourceName = assem.GetManifestResourceNames().FirstOrDefault(rn => rn.EndsWith(dllName));\n if (resourceName == null) return null; // Not found, maybe another handler will find it\n using (var stream = assem.GetManifestResourceStream(resourceName))\n {\n Byte[] assemblyData = new Byte[stream.Length];\n stream.Read(assemblyData, 0, assemblyData.Length);\n return Assembly.Load(assemblyData);\n }\n };\n</code></pre>\n"
},
{
"answer_id": 20306095,
"author": "Matthias",
"author_id": 568266,
"author_profile": "https://Stackoverflow.com/users/568266",
"pm_score": 11,
"selected": true,
"text": "<p>I highly recommend to use <a href=\"https://github.com/Fody/Costura\" rel=\"noreferrer\">Costura.Fody</a> - by far the best and easiest way to embed resources in your assembly. It's available as NuGet package.</p>\n\n<pre><code>Install-Package Costura.Fody\n</code></pre>\n\n<p>After adding it to the project, it will automatically embed all references that are copied to the output directory into your <em>main</em> assembly. You might want to clean the embedded files by adding a target to your project:</p>\n\n<pre><code>Install-CleanReferencesTarget\n</code></pre>\n\n<p>You'll also be able to specify whether to include the pdb's, exclude certain assemblies, or extracting the assemblies on the fly. As far as I know, also unmanaged assemblies are supported.</p>\n\n<p><strong>Update</strong></p>\n\n<p>Currently, some people are trying to add <a href=\"https://github.com/Fody/Fody/issues/206\" rel=\"noreferrer\">support for DNX</a>.</p>\n\n<p><strong>Update 2</strong></p>\n\n<p>For the lastest Fody version, you will need to have MSBuild 16 (so Visual Studio 2019). Fody version 4.2.1 will do MSBuild 15. (reference: <a href=\"https://stackoverflow.com/questions/55795625/fody-is-only-supported-on-msbuild-16-and-above-current-version-15\">Fody is only supported on MSBuild 16 and above. Current version: 15</a>)</p>\n"
},
{
"answer_id": 28041275,
"author": "Ivan Ferrer Villa",
"author_id": 382515,
"author_profile": "https://Stackoverflow.com/users/382515",
"pm_score": 2,
"selected": false,
"text": "<p>It may sound simplistic, but WinRar gives the option to compress a bunch of files to a self-extracting executable.<br>\nIt has lots of configurable options: final icon, extract files to given path, file to execute after extraction, custom logo/texts for popup shown during extraction, no popup window at all, license agreement text, etc.<br>\nMay be useful in some cases.</p>\n"
},
{
"answer_id": 28919741,
"author": "Josh",
"author_id": 1480854,
"author_profile": "https://Stackoverflow.com/users/1480854",
"pm_score": 4,
"selected": false,
"text": "<p>To expand on <a href=\"https://stackoverflow.com/a/4043653/1480854\">@Bobby's asnwer</a> above. You can edit your .csproj to use <a href=\"https://github.com/peters/ILRepack.MSBuild.Task\" rel=\"noreferrer\">IL-Repack</a> to automatically package all files into a single assembly when you build.</p>\n\n<ol>\n<li>Install the nuget ILRepack.MSBuild.Task package with <code>Install-Package ILRepack.MSBuild.Task</code></li>\n<li>Edit the AfterBuild section of your .csproj</li>\n</ol>\n\n<p>Here is a simple sample that merges ExampleAssemblyToMerge.dll into your project output.</p>\n\n<pre><code><!-- ILRepack -->\n<Target Name=\"AfterBuild\" Condition=\"'$(Configuration)' == 'Release'\">\n\n <ItemGroup>\n <InputAssemblies Include=\"$(OutputPath)\\$(AssemblyName).exe\" />\n <InputAssemblies Include=\"$(OutputPath)\\ExampleAssemblyToMerge.dll\" />\n </ItemGroup>\n\n <ILRepack \n Parallel=\"true\"\n Internalize=\"true\"\n InputAssemblies=\"@(InputAssemblies)\"\n TargetKind=\"Exe\"\n OutputFile=\"$(OutputPath)\\$(AssemblyName).exe\"\n />\n</Target>\n</code></pre>\n"
},
{
"answer_id": 36916920,
"author": "Mark Llewellyn",
"author_id": 6267034,
"author_profile": "https://Stackoverflow.com/users/6267034",
"pm_score": 2,
"selected": false,
"text": "<p>I use the csc.exe compiler called from a .vbs script.</p>\n\n<p>In your xyz.cs script, add the following lines after the directives (my example is for the Renci SSH):</p>\n\n<pre><code>using System;\nusing Renci;//FOR THE SSH\nusing System.Net;//FOR THE ADDRESS TRANSLATION\nusing System.Reflection;//FOR THE Assembly\n\n//+ref>\"C:\\Program Files (x86)\\Microsoft\\ILMerge\\Renci.SshNet.dll\"\n//+res>\"C:\\Program Files (x86)\\Microsoft\\ILMerge\\Renci.SshNet.dll\"\n//+ico>\"C:\\Program Files (x86)\\Microsoft CAPICOM 2.1.0.2 SDK\\Samples\\c_sharp\\xmldsig\\resources\\Traffic.ico\"\n</code></pre>\n\n<p>The ref, res and ico tags will be picked up by the .vbs script below to form the csc command.</p>\n\n<p>Then add the assembly resolver caller in the Main:</p>\n\n<pre><code>public static void Main(string[] args)\n{\n AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);\n .\n</code></pre>\n\n<p>...and add the resolver itself somewhere in the class:</p>\n\n<pre>\n static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)\n {\n String resourceName = new AssemblyName(args.Name).Name + \".dll\";\n\n using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))\n {\n Byte[] assemblyData = new Byte[stream.Length];\n stream.Read(assemblyData, 0, assemblyData.Length);\n return Assembly.Load(assemblyData);\n }\n\n }\n</pre>\n\n<p>I name the vbs script to match the .cs filename (e.g. ssh.vbs looks for ssh.cs); this makes running the script numerous times a lot easier, but if you aren't an idiot like me then a generic script could pick up the target .cs file from a drag-and-drop:</p>\n\n<pre>\n Dim name_,oShell,fso\n Set oShell = CreateObject(\"Shell.Application\")\n Set fso = CreateObject(\"Scripting.fileSystemObject\")\n\n 'TAKE THE VBS SCRIPT NAME AS THE TARGET FILE NAME\n '################################################\n name_ = Split(wscript.ScriptName, \".\")(0)\n\n 'GET THE EXTERNAL DLL's AND ICON NAMES FROM THE .CS FILE\n '#######################################################\n Const OPEN_FILE_FOR_READING = 1\n Set objInputFile = fso.OpenTextFile(name_ & \".cs\", 1)\n\n 'READ EVERYTHING INTO AN ARRAY\n '#############################\n inputData = Split(objInputFile.ReadAll, vbNewline)\n\n For each strData In inputData\n\n if left(strData,7)=\"//+ref>\" then \n csc_references = csc_references & \" /reference:\" & trim(replace(strData,\"//+ref>\",\"\")) & \" \"\n end if\n\n if left(strData,7)=\"//+res>\" then \n csc_resources = csc_resources & \" /resource:\" & trim(replace(strData,\"//+res>\",\"\")) & \" \"\n end if\n\n if left(strData,7)=\"//+ico>\" then \n csc_icon = \" /win32icon:\" & trim(replace(strData,\"//+ico>\",\"\")) & \" \"\n end if\n Next\n\n objInputFile.Close\n\n\n 'COMPILE THE FILE\n '################\n oShell.ShellExecute \"c:\\windows\\microsoft.net\\framework\\v3.5\\csc.exe\", \"/warn:1 /target:exe \" & csc_references & csc_resources & csc_icon & \" \" & name_ & \".cs\", \"\", \"runas\", 2\n\n\n WScript.Quit(0)\n</pre>\n"
},
{
"answer_id": 57749050,
"author": "Marcell Toth",
"author_id": 10614791,
"author_profile": "https://Stackoverflow.com/users/10614791",
"pm_score": 4,
"selected": false,
"text": "<h2>.NET Core 3.0 natively supports compiling to a single .exe</h2>\n\n<p>The feature is enabled by the usage of the following property in your project file (.csproj):</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code> <PropertyGroup>\n <PublishSingleFile>true</PublishSingleFile>\n </PropertyGroup>\n</code></pre>\n\n<p>This is done without any external tool. </p>\n\n<p>See my answer <a href=\"https://stackoverflow.com/a/56092826/10614791\">for this question</a> for further details.</p>\n"
},
{
"answer_id": 62929101,
"author": "Ludovic Feltz",
"author_id": 2576706,
"author_profile": "https://Stackoverflow.com/users/2576706",
"pm_score": 3,
"selected": false,
"text": "<p>The following method <strong>DO NOT use external tools</strong> and <strong>AUTOMATICALLY include all needed DLL</strong> (no manual action required, everything done at compilation)</p>\n<p>I read a lot of answer here saying to use <em>ILMerge</em>, <em>ILRepack</em> or <em>Jeffrey Ritcher</em> method but none of that worked with <em>WPF applications</em> nor was easy to use.</p>\n<p>When you have a lot of DLL it can be hard to manually include the one you need in your exe. The best method i found was explained by Wegged <a href=\"https://stackoverflow.com/a/4995039/2576706\">here on StackOverflow</a></p>\n<p>Copy pasted his answer here for clarity (all credit to <a href=\"https://stackoverflow.com/users/428702/wegged\">Wegged</a>)</p>\n<hr />\n<h2>1) Add this to your <code>.csproj</code> file:</h2>\n<pre><code><Target Name="AfterResolveReferences">\n <ItemGroup>\n <EmbeddedResource Include="@(ReferenceCopyLocalPaths)" Condition="'%(ReferenceCopyLocalPaths.Extension)' == '.dll'">\n <LogicalName>%(ReferenceCopyLocalPaths.DestinationSubDirectory)%(ReferenceCopyLocalPaths.Filename)%(ReferenceCopyLocalPaths.Extension)</LogicalName>\n </EmbeddedResource>\n </ItemGroup>\n</Target>\n</code></pre>\n<h2>2) Make your Main <code>Program.cs</code> look like this:</h2>\n<pre><code>[STAThreadAttribute]\npublic static void Main()\n{\n AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;\n App.Main();\n}\n</code></pre>\n<h2>3) Add the <code>OnResolveAssembly</code> method:</h2>\n<pre><code>private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)\n{\n Assembly executingAssembly = Assembly.GetExecutingAssembly();\n AssemblyName assemblyName = new AssemblyName(args.Name);\n\n var path = assemblyName.Name + ".dll";\n if (assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture) == false) path = String.Format(@"{0}\\{1}", assemblyName.CultureInfo, path);\n\n using (Stream stream = executingAssembly.GetManifestResourceStream(path))\n {\n if (stream == null) return null;\n\n var assemblyRawBytes = new byte[stream.Length];\n stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);\n return Assembly.Load(assemblyRawBytes);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 71585933,
"author": "Chester Ayala",
"author_id": 15052050,
"author_profile": "https://Stackoverflow.com/users/15052050",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using .NET Core 3.0</p>\n<p>You can do this with the dotnet publish command with PublishSingleFile property:</p>\n<blockquote>\n<p>dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true</p>\n</blockquote>\n<p>The only downside is you end up with a single EXE file with a huge size.</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5133/"
] |
Is it possible to embed a pre-existing DLL into a compiled C# executable (so that you only have one file to distribute)? If it is possible, how would one go about doing it?
Normally, I'm cool with just leaving the DLLs outside and having the setup program handle everything, but there have been a couple of people at work who have asked me this and I honestly don't know.
|
I highly recommend to use [Costura.Fody](https://github.com/Fody/Costura) - by far the best and easiest way to embed resources in your assembly. It's available as NuGet package.
```
Install-Package Costura.Fody
```
After adding it to the project, it will automatically embed all references that are copied to the output directory into your *main* assembly. You might want to clean the embedded files by adding a target to your project:
```
Install-CleanReferencesTarget
```
You'll also be able to specify whether to include the pdb's, exclude certain assemblies, or extracting the assemblies on the fly. As far as I know, also unmanaged assemblies are supported.
**Update**
Currently, some people are trying to add [support for DNX](https://github.com/Fody/Fody/issues/206).
**Update 2**
For the lastest Fody version, you will need to have MSBuild 16 (so Visual Studio 2019). Fody version 4.2.1 will do MSBuild 15. (reference: [Fody is only supported on MSBuild 16 and above. Current version: 15](https://stackoverflow.com/questions/55795625/fody-is-only-supported-on-msbuild-16-and-above-current-version-15))
|
189,555 |
<p>I want to download and parse webpage using python, but to access it I need a couple of cookies set. Therefore I need to login over https to the webpage first. The login moment involves sending two POST params (username, password) to /login.php. During the login request I want to retrieve the cookies from the response header and store them so I can use them in the request to download the webpage /data.php.</p>
<p>How would I do this in python (preferably 2.6)? If possible I only want to use builtin modules.</p>
|
[
{
"answer_id": 189580,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 8,
"selected": true,
"text": "<pre><code>import urllib, urllib2, cookielib\n\nusername = 'myuser'\npassword = 'mypassword'\n\ncj = cookielib.CookieJar()\nopener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))\nlogin_data = urllib.urlencode({'username' : username, 'j_password' : password})\nopener.open('http://www.example.com/login.php', login_data)\nresp = opener.open('http://www.example.com/hiddenpage.php')\nprint resp.read()\n</code></pre>\n\n<p><code>resp.read()</code> is the straight html of the page you want to open, and you can use <code>opener</code> to view any page using your session cookie.</p>\n"
},
{
"answer_id": 12103969,
"author": "Boden Garman",
"author_id": 584423,
"author_profile": "https://Stackoverflow.com/users/584423",
"pm_score": 7,
"selected": false,
"text": "<p>Here's a version using the excellent <a href=\"http://docs.python-requests.org/en/latest/index.html\" rel=\"noreferrer\">requests</a> library:</p>\n\n<pre><code>from requests import session\n\npayload = {\n 'action': 'login',\n 'username': USERNAME,\n 'password': PASSWORD\n}\n\nwith session() as c:\n c.post('http://example.com/login.php', data=payload)\n response = c.get('http://example.com/protected_page.php')\n print(response.headers)\n print(response.text)\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26668/"
] |
I want to download and parse webpage using python, but to access it I need a couple of cookies set. Therefore I need to login over https to the webpage first. The login moment involves sending two POST params (username, password) to /login.php. During the login request I want to retrieve the cookies from the response header and store them so I can use them in the request to download the webpage /data.php.
How would I do this in python (preferably 2.6)? If possible I only want to use builtin modules.
|
```
import urllib, urllib2, cookielib
username = 'myuser'
password = 'mypassword'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://www.example.com/login.php', login_data)
resp = opener.open('http://www.example.com/hiddenpage.php')
print resp.read()
```
`resp.read()` is the straight html of the page you want to open, and you can use `opener` to view any page using your session cookie.
|
189,559 |
<p>Conditions: do not modify the original lists; JDK only, no external libraries. Bonus points for a one-liner or a JDK 1.3 version.</p>
<p>Is there a simpler way than:</p>
<pre class="lang-java prettyprint-override"><code>List<String> newList = new ArrayList<String>();
newList.addAll(listOne);
newList.addAll(listTwo);
</code></pre>
|
[
{
"answer_id": 189568,
"author": "Tim",
"author_id": 5284,
"author_profile": "https://Stackoverflow.com/users/5284",
"pm_score": 5,
"selected": false,
"text": "<p>Slightly simpler:</p>\n\n<pre><code>List<String> newList = new ArrayList<String>(listOne);\nnewList.addAll(listTwo);\n</code></pre>\n"
},
{
"answer_id": 189569,
"author": "AdamC",
"author_id": 16476,
"author_profile": "https://Stackoverflow.com/users/16476",
"pm_score": 9,
"selected": false,
"text": "<p>Off the top of my head, I can shorten it by one line:</p>\n\n<pre><code>List<String> newList = new ArrayList<String>(listOne);\nnewList.addAll(listTwo);\n</code></pre>\n"
},
{
"answer_id": 189572,
"author": "Jorn",
"author_id": 8681,
"author_profile": "https://Stackoverflow.com/users/8681",
"pm_score": 5,
"selected": false,
"text": "<p>A little shorter would be:</p>\n\n<pre><code>List<String> newList = new ArrayList<String>(listOne);\nnewList.addAll(listTwo);\n</code></pre>\n"
},
{
"answer_id": 189699,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 7,
"selected": false,
"text": "<p>Probably not simpler, but intriguing and ugly:</p>\n\n<pre><code>List<String> newList = new ArrayList<String>() { { addAll(listOne); addAll(listTwo); } };\n</code></pre>\n\n<p>Don't use it in production code... ;)</p>\n"
},
{
"answer_id": 189742,
"author": "deterb",
"author_id": 15585,
"author_profile": "https://Stackoverflow.com/users/15585",
"pm_score": 4,
"selected": false,
"text": "<p>You can do a oneliner if the target list is predeclared.</p>\n\n<pre><code>(newList = new ArrayList<String>(list1)).addAll(list2);\n</code></pre>\n"
},
{
"answer_id": 189752,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 3,
"selected": false,
"text": "<p>You could do it with a static import and a helper class</p>\n\n<p><em>nb</em> the generification of this class could probably be improved</p>\n\n<pre><code>public class Lists {\n\n private Lists() { } // can't be instantiated\n\n public static List<T> join(List<T>... lists) {\n List<T> result = new ArrayList<T>();\n for(List<T> list : lists) {\n result.addAll(list);\n }\n return results;\n }\n\n}\n</code></pre>\n\n<p>Then you can do things like</p>\n\n<pre><code>import static Lists.join;\nList<T> result = join(list1, list2, list3, list4);\n</code></pre>\n"
},
{
"answer_id": 190165,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": -1,
"selected": false,
"text": "<p>I can't improve on the two-liner in the general case without introducing your own utility method, but if you do have lists of Strings and you're willing to assume those Strings don't contain commas, you can pull this long one-liner:</p>\n\n<pre><code>List<String> newList = new ArrayList<String>(Arrays.asList((listOne.toString().subString(1, listOne.length() - 1) + \", \" + listTwo.toString().subString(1, listTwo.length() - 1)).split(\", \")));\n</code></pre>\n\n<p>If you drop the generics, this should be JDK 1.4 compliant (though I haven't tested that). Also not recommended for production code ;-)</p>\n"
},
{
"answer_id": 190713,
"author": "ddimitrov",
"author_id": 18187,
"author_profile": "https://Stackoverflow.com/users/18187",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not claiming that it's simple, but you mentioned bonus for one-liners ;-)</p>\n\n<pre><code>Collection mergedList = Collections.list(new sun.misc.CompoundEnumeration(new Enumeration[] {\n new Vector(list1).elements(),\n new Vector(list2).elements(),\n ...\n}))\n</code></pre>\n"
},
{
"answer_id": 190918,
"author": "alex",
"author_id": 26787,
"author_profile": "https://Stackoverflow.com/users/26787",
"pm_score": 2,
"selected": false,
"text": "<p>Use a Helper class.</p>\n\n<p>I suggest:</p>\n\n<pre><code>public static <E> Collection<E> addAll(Collection<E> dest, Collection<? extends E>... src) {\n for(Collection<? extends E> c : src) {\n dest.addAll(c);\n }\n\n return dest;\n}\n\npublic static void main(String[] args) {\n System.out.println(addAll(new ArrayList<Object>(), Arrays.asList(1,2,3), Arrays.asList(\"a\", \"b\", \"c\")));\n\n // does not compile\n // System.out.println(addAll(new ArrayList<Integer>(), Arrays.asList(1,2,3), Arrays.asList(\"a\", \"b\", \"c\")));\n\n System.out.println(addAll(new ArrayList<Integer>(), Arrays.asList(1,2,3), Arrays.asList(4, 5, 6)));\n}\n</code></pre>\n"
},
{
"answer_id": 3581132,
"author": "Guillermo",
"author_id": 432521,
"author_profile": "https://Stackoverflow.com/users/432521",
"pm_score": 9,
"selected": false,
"text": "<p>You could use the <a href=\"https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/ListUtils.html\" rel=\"noreferrer\">Apache commons-collections</a> library:</p>\n\n<pre><code>List<String> newList = ListUtils.union(list1, list2);\n</code></pre>\n"
},
{
"answer_id": 6874135,
"author": "Yuri Geinish",
"author_id": 318558,
"author_profile": "https://Stackoverflow.com/users/318558",
"pm_score": 6,
"selected": false,
"text": "<p>Found this question looking to concatenate arbitrary amount of lists, not minding external libraries. So, perhaps it will help someone else:</p>\n\n<pre><code>com.google.common.collect.Iterables#concat()\n</code></pre>\n\n<p>Useful if you want to apply the same logic to a number of different collections in one for().</p>\n"
},
{
"answer_id": 7317532,
"author": "nirmal",
"author_id": 930312,
"author_profile": "https://Stackoverflow.com/users/930312",
"pm_score": 0,
"selected": false,
"text": "<p>No way near one-liner, but I think this is the simplest:</p>\n\n<pre><code>List<String> newList = new ArrayList<String>(l1);\nnewList.addAll(l2);\n\nfor(String w:newList)\n System.out.printf(\"%s \", w);\n</code></pre>\n"
},
{
"answer_id": 11666257,
"author": "Olivier Faucheux",
"author_id": 1166992,
"author_profile": "https://Stackoverflow.com/users/1166992",
"pm_score": 3,
"selected": false,
"text": "<p>The smartest in my opinion:</p>\n\n<pre><code>/**\n * @param smallLists\n * @return one big list containing all elements of the small ones, in the same order.\n */\npublic static <E> List<E> concatenate (final List<E> ... smallLists)\n{\n final ArrayList<E> bigList = new ArrayList<E>();\n for (final List<E> list: smallLists)\n {\n bigList.addAll(list);\n }\n return bigList;\n}\n</code></pre>\n"
},
{
"answer_id": 13868047,
"author": "Martin",
"author_id": 1358179,
"author_profile": "https://Stackoverflow.com/users/1358179",
"pm_score": 6,
"selected": false,
"text": "<p>Not simpler, but without resizing overhead:</p>\n\n<pre><code>List<String> newList = new ArrayList<>(listOne.size() + listTwo.size());\nnewList.addAll(listOne);\nnewList.addAll(listTwo);\n</code></pre>\n"
},
{
"answer_id": 13868352,
"author": "Kevin K",
"author_id": 292728,
"author_profile": "https://Stackoverflow.com/users/292728",
"pm_score": 7,
"selected": false,
"text": "<p>One of your requirements is to preserve the original lists. If you create a new list and use <code>addAll()</code>, you are effectively doubling the number of references to the objects in your lists. This could lead to memory problems if your lists are very large.</p>\n<p>If you don't need to modify the concatenated result, you can avoid this using a custom list implementation. The custom implementation class is more than one line, obviously...but using it is short and sweet.</p>\n<p>CompositeUnmodifiableList.java:</p>\n<pre><code>public class CompositeUnmodifiableList<E> extends AbstractList<E> {\n\n private final List<? extends E> list1;\n private final List<? extends E> list2;\n\n public CompositeUnmodifiableList(List<? extends E> list1, List<? extends E> list2) {\n this.list1 = list1;\n this.list2 = list2;\n }\n \n @Override\n public E get(int index) {\n if (index < list1.size()) {\n return list1.get(index);\n }\n return list2.get(index-list1.size());\n }\n\n @Override\n public int size() {\n return list1.size() + list2.size();\n }\n}\n</code></pre>\n<p>Usage:</p>\n<pre><code>List<String> newList = new CompositeUnmodifiableList<String>(listOne,listTwo);\n</code></pre>\n"
},
{
"answer_id": 13990351,
"author": "Ram Pasupula",
"author_id": 1921533,
"author_profile": "https://Stackoverflow.com/users/1921533",
"pm_score": -1,
"selected": false,
"text": "<pre><code>public class TestApp {\n\n/**\n * @param args\n */\npublic static void main(String[] args) {\n System.out.println(\"Hi\");\n Set<List<String>> bcOwnersList = new HashSet<List<String>>();\n List<String> bclist = new ArrayList<String>();\n List<String> bclist1 = new ArrayList<String>();\n List<String> object = new ArrayList<String>();\n object.add(\"BC11\");\n object.add(\"C2\");\n bclist.add(\"BC1\");\n bclist.add(\"BC2\");\n bclist.add(\"BC3\");\n bclist.add(\"BC4\");\n bclist.add(\"BC5\");\n bcOwnersList.add(bclist);\n bcOwnersList.add(object);\n\n bclist1.add(\"BC11\");\n bclist1.add(\"BC21\");\n bclist1.add(\"BC31\");\n bclist1.add(\"BC4\");\n bclist1.add(\"BC5\");\n\n List<String> listList= new ArrayList<String>();\n for(List<String> ll : bcOwnersList){\n listList = (List<String>) CollectionUtils.union(listList,CollectionUtils.intersection(ll, bclist1));\n }\n /*for(List<String> lists : listList){\n test = (List<String>) CollectionUtils.union(test, listList);\n }*/\n for(Object l : listList){\n System.out.println(l.toString());\n }\n System.out.println(bclist.contains(\"BC\"));\n\n}\n\n}\n</code></pre>\n"
},
{
"answer_id": 18687790,
"author": "Dale Emery",
"author_id": 780017,
"author_profile": "https://Stackoverflow.com/users/780017",
"pm_score": 10,
"selected": false,
"text": "<p>In Java 8:</p>\n<pre><code>List<String> newList = Stream.concat(listOne.stream(), listTwo.stream())\n .collect(Collectors.toList());\n</code></pre>\n<p>Java 16+:</p>\n<pre><code>List<String> newList = Stream.concat(listOne.stream(), listTwo.stream()).toList();\n</code></pre>\n"
},
{
"answer_id": 18689435,
"author": "ceklock",
"author_id": 1366353,
"author_profile": "https://Stackoverflow.com/users/1366353",
"pm_score": 5,
"selected": false,
"text": "<p>This is simple and just one line, but will add the contents of listTwo to listOne. Do you really need to put the contents in a third list?</p>\n\n<pre><code>Collections.addAll(listOne, listTwo.toArray());\n</code></pre>\n"
},
{
"answer_id": 22850433,
"author": "Mark",
"author_id": 3486249,
"author_profile": "https://Stackoverflow.com/users/3486249",
"pm_score": 8,
"selected": false,
"text": "<p>Another Java 8 one-liner:</p>\n\n<pre><code>List<String> newList = Stream.of(listOne, listTwo)\n .flatMap(Collection::stream)\n .collect(Collectors.toList());\n</code></pre>\n\n<p>As a bonus, since <code>Stream.of()</code> is variadic, you may concatenate as many lists as you like.</p>\n\n<pre><code>List<String> newList = Stream.of(listOne, listTwo, listThree)\n .flatMap(Collection::stream)\n .collect(Collectors.toList());\n</code></pre>\n"
},
{
"answer_id": 24715402,
"author": "martyglaubitz",
"author_id": 657341,
"author_profile": "https://Stackoverflow.com/users/657341",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public static <T> List<T> merge(List<T>... args) {\n final List<T> result = new ArrayList<>();\n\n for (List<T> list : args) {\n result.addAll(list);\n }\n\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 34090554,
"author": "SpaceTrucker",
"author_id": 1466267,
"author_profile": "https://Stackoverflow.com/users/1466267",
"pm_score": 6,
"selected": false,
"text": "<p>Here is a java 8 solution using two lines:</p>\n\n<pre><code>List<Object> newList = new ArrayList<>();\nStream.of(list1, list2).forEach(newList::addAll);\n</code></pre>\n\n<p>Be aware that this method should not be used if</p>\n\n<ul>\n<li>the origin of <code>newList</code> is not known and it may already be shared with other threads</li>\n<li>the stream that modifies <code>newList</code> is a parallel stream and access to <code>newList</code> is not synchronized or threadsafe</li>\n</ul>\n\n<p>due to side effect considerations.</p>\n\n<p>Both of the above conditions do not apply for the above case of joining two lists, so this is safe.</p>\n\n<p>Based on <a href=\"https://stackoverflow.com/a/18290985/1466267\">this answer</a> to another question.</p>\n"
},
{
"answer_id": 37386846,
"author": "akhil_mittal",
"author_id": 1216775,
"author_profile": "https://Stackoverflow.com/users/1216775",
"pm_score": 6,
"selected": false,
"text": "<blockquote>\n <p>Java 8 (<code>Stream.of</code> and <code>Stream.concat</code>)</p>\n</blockquote>\n\n<p>The proposed solution is for three lists though it can be applied for two lists as well. In Java 8 we can make use of <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#of-T...-\" rel=\"noreferrer\">Stream.of</a> or <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#concat-java.util.stream.Stream-java.util.stream.Stream-\" rel=\"noreferrer\">Stream.concat</a> as:</p>\n\n<pre><code>List<String> result1 = Stream.concat(Stream.concat(list1.stream(),list2.stream()),list3.stream()).collect(Collectors.toList());\nList<String> result2 = Stream.of(list1,list2,list3).flatMap(Collection::stream).collect(Collectors.toList());\n</code></pre>\n\n<p><code>Stream.concat</code> takes two streams as input and creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream. As we have three lists we have used this method (<code>Stream.concat</code>) two times.</p>\n\n<p>We can also write a utility class with a method that takes any number of lists (using <a href=\"https://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html\" rel=\"noreferrer\">varargs</a>) and returns a concatenated list as:</p>\n\n<pre><code>public static <T> List<T> concatenateLists(List<T>... collections) {\n return Arrays.stream(collections).flatMap(Collection::stream).collect(Collectors.toList()); \n}\n</code></pre>\n\n<p>Then we can make use of this method as:</p>\n\n<pre><code>List<String> result3 = Utils.concatenateLists(list1,list2,list3);\n</code></pre>\n"
},
{
"answer_id": 40119122,
"author": "shinzou",
"author_id": 4279201,
"author_profile": "https://Stackoverflow.com/users/4279201",
"pm_score": 0,
"selected": false,
"text": "<p>Here's an approach using streams and java 8 if your lists have different types and you want to combine them to a list of another type.</p>\n\n<pre><code>public static void main(String[] args) {\n List<String> list2 = new ArrayList<>();\n List<Pair<Integer, String>> list1 = new ArrayList<>();\n\n list2.add(\"asd\");\n list2.add(\"asdaf\");\n list1.add(new Pair<>(1, \"werwe\"));\n list1.add(new Pair<>(2, \"tyutyu\"));\n\n Stream stream = Stream.concat(list1.stream(), list2.stream());\n\n List<Pair<Integer, String>> res = (List<Pair<Integer, String>>) stream\n .map(item -> {\n if (item instanceof String) {\n return new Pair<>(0, item);\n }\n else {\n return new Pair<>(((Pair<Integer, String>)item).getKey(), ((Pair<Integer, String>)item).getValue());\n }\n })\n .collect(Collectors.toList());\n}\n</code></pre>\n"
},
{
"answer_id": 40559634,
"author": "Saravana",
"author_id": 3344829,
"author_profile": "https://Stackoverflow.com/users/3344829",
"pm_score": 3,
"selected": false,
"text": "<p>another one liner solution using <code>Java8</code> stream, since <code>flatMap</code> solution is already posted, here is a solution without <code>flatMap</code></p>\n\n<pre><code>List<E> li = lol.stream().collect(ArrayList::new, List::addAll, List::addAll);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>List<E> ints = Stream.of(list1, list2).collect(ArrayList::new, List::addAll, List::addAll);\n</code></pre>\n\n<p>code</p>\n\n<pre><code> List<List<Integer>> lol = Arrays.asList(Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6));\n List<Integer> li = lol.stream().collect(ArrayList::new, List::addAll, List::addAll);\n System.out.println(lol);\n System.out.println(li);\n</code></pre>\n\n<p>output</p>\n\n<pre><code>[[1, 2, 3], [4, 5, 6]]\n[1, 2, 3, 4, 5, 6]\n</code></pre>\n"
},
{
"answer_id": 40870053,
"author": "cslysy",
"author_id": 1749126,
"author_profile": "https://Stackoverflow.com/users/1749126",
"pm_score": 3,
"selected": false,
"text": "<p>Java 8 version with support for joining by object key:</p>\n\n<pre><code>public List<SomeClass> mergeLists(final List<SomeClass> left, final List<SomeClass> right, String primaryKey) {\n final Map<Object, SomeClass> mergedList = new LinkedHashMap<>();\n\n Stream.concat(left.stream(), right.stream())\n .map(someObject -> new Pair<Object, SomeClass>(someObject.getSomeKey(), someObject))\n .forEach(pair-> mergedList.put(pair.getKey(), pair.getValue()));\n\n return new ArrayList<>(mergedList.values());\n}\n</code></pre>\n"
},
{
"answer_id": 42990654,
"author": "Nitin Jain",
"author_id": 4139773,
"author_profile": "https://Stackoverflow.com/users/4139773",
"pm_score": 4,
"selected": false,
"text": "<p>In <strong>Java 8</strong> (the other way):</p>\n\n<pre><code>List<?> newList = \nStream.of(list1, list2).flatMap(List::stream).collect(Collectors.toList());\n</code></pre>\n"
},
{
"answer_id": 47457484,
"author": "Jan Weitz",
"author_id": 1378313,
"author_profile": "https://Stackoverflow.com/users/1378313",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to do this statically you can the following.</p>\n\n<p>The examples uses 2 EnumSets in natural-order (==Enum-order) <code>A, B</code> and joins then in an <code>ALL</code> list.</p>\n\n<pre><code>public static final EnumSet<MyType> CATEGORY_A = EnumSet.of(A_1, A_2);\npublic static final EnumSet<MyType> CATEGORY_B = EnumSet.of(B_1, B_2, B_3);\n\npublic static final List<MyType> ALL = \n Collections.unmodifiableList(\n new ArrayList<MyType>(CATEGORY_A.size() + CATEGORY_B.size())\n {{\n addAll(CATEGORY_A);\n addAll(CATEGORY_B);\n }}\n );\n</code></pre>\n"
},
{
"answer_id": 48904406,
"author": "Langusten Gustel",
"author_id": 1431044,
"author_profile": "https://Stackoverflow.com/users/1431044",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public static <T> List<T> merge(@Nonnull final List<T>... list) {\n // calculate length first\n int mergedLength = 0;\n for (List<T> ts : list) {\n mergedLength += ts.size();\n }\n\n final List<T> mergedList = new ArrayList<>(mergedLength);\n\n for (List<T> ts : list) {\n mergedList.addAll(ts);\n }\n\n return mergedList;\n }\n</code></pre>\n"
},
{
"answer_id": 50418885,
"author": "Daniel Hári",
"author_id": 1386911,
"author_profile": "https://Stackoverflow.com/users/1386911",
"pm_score": 4,
"selected": false,
"text": "<p>You can create your generic <strong>Java 8</strong> utility method to concat <strong>any number of lists</strong>.</p>\n\n<pre><code>@SafeVarargs\npublic static <T> List<T> concat(List<T>... lists) {\n return Stream.of(lists).flatMap(List::stream).collect(Collectors.toList());\n}\n</code></pre>\n"
},
{
"answer_id": 55517693,
"author": "benez",
"author_id": 3583589,
"author_profile": "https://Stackoverflow.com/users/3583589",
"pm_score": -1,
"selected": false,
"text": "<pre><code>import java.util.AbstractList;\nimport java.util.List;\n\n\n/**\n * The {@code ConcatList} is a lightweight view of two {@code List}s.\n * <p>\n * This implementation is <em>not</em> thread-safe even though the underlying lists can be.\n * \n * @param <E>\n * the type of elements in this list\n */\npublic class ConcatList<E> extends AbstractList<E> {\n\n /** The first underlying list. */\n private final List<E> list1;\n /** The second underlying list. */\n private final List<E> list2;\n\n /**\n * Constructs a new {@code ConcatList} from the given two lists.\n * \n * @param list1\n * the first list\n * @param list2\n * the second list\n */\n public ConcatList(final List<E> list1, final List<E> list2) {\n this.list1 = list1;\n this.list2 = list2;\n }\n\n @Override\n public E get(final int index) {\n return getList(index).get(getListIndex(index));\n }\n\n @Override\n public E set(final int index, final E element) {\n return getList(index).set(getListIndex(index), element);\n }\n\n @Override\n public void add(final int index, final E element) {\n getList(index).add(getListIndex(index), element);\n }\n\n @Override\n public E remove(final int index) {\n return getList(index).remove(getListIndex(index));\n }\n\n @Override\n public int size() {\n return list1.size() + list2.size();\n }\n\n @Override\n public boolean contains(final Object o) {\n return list1.contains(o) || list2.contains(o);\n }\n\n @Override\n public void clear() {\n list1.clear();\n list2.clear();\n }\n\n /**\n * Returns the index within the corresponding list related to the given index.\n * \n * @param index\n * the index in this list\n * \n * @return the index of the underlying list\n */\n private int getListIndex(final int index) {\n final int size1 = list1.size();\n return index >= size1 ? index - size1 : index;\n }\n\n /**\n * Returns the list that corresponds to the given index.\n * \n * @param index\n * the index in this list\n * \n * @return the underlying list that corresponds to that index\n */\n private List<E> getList(final int index) {\n return index >= list1.size() ? list2 : list1;\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 60854305,
"author": "Himank Batra",
"author_id": 12543660,
"author_profile": "https://Stackoverflow.com/users/12543660",
"pm_score": 3,
"selected": false,
"text": "<p>We can join 2 lists using java8 with 2 approaches.</p>\n\n<pre><code> List<String> list1 = Arrays.asList(\"S\", \"T\");\n List<String> list2 = Arrays.asList(\"U\", \"V\");\n</code></pre>\n\n<p>1) Using concat :</p>\n\n<pre><code> List<String> collect2 = Stream.concat(list1.stream(), list2.stream()).collect(toList());\n System.out.println(\"collect2 = \" + collect2); // collect2 = [S, T, U, V]\n</code></pre>\n\n<p>2) Using flatMap : </p>\n\n<pre><code> List<String> collect3 = Stream.of(list1, list2).flatMap(Collection::stream).collect(toList());\n System.out.println(\"collect3 = \" + collect3); // collect3 = [S, T, U, V]\n</code></pre>\n"
},
{
"answer_id": 61083016,
"author": "Raymond Chenon",
"author_id": 311420,
"author_profile": "https://Stackoverflow.com/users/311420",
"pm_score": 3,
"selected": false,
"text": "<p>Almost of answers suggest to use an ArrayList.</p>\n\n<pre><code>List<String> newList = new LinkedList<>(listOne);\nnewList.addAll(listTwo);\n</code></pre>\n\n<p>Prefer to use a LinkedList for efficient add operations.</p>\n\n<p>ArrayList add is O(1) amortized, but O(n) worst-case since the array must be resized and copied.\nWhile LinkedList add is always constant O(1).</p>\n\n<p>more infos <a href=\"https://stackoverflow.com/a/322742/311420\">https://stackoverflow.com/a/322742/311420</a></p>\n"
},
{
"answer_id": 70102879,
"author": "lqbweb",
"author_id": 1043677,
"author_profile": "https://Stackoverflow.com/users/1043677",
"pm_score": 2,
"selected": false,
"text": "<p>My favourite way, using fluent api and Guava:</p>\n<pre><code>List<String> combined = ImmutableList.<String>builder().addAll(list1).addAll(list2).build()\n</code></pre>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17294/"
] |
Conditions: do not modify the original lists; JDK only, no external libraries. Bonus points for a one-liner or a JDK 1.3 version.
Is there a simpler way than:
```java
List<String> newList = new ArrayList<String>();
newList.addAll(listOne);
newList.addAll(listTwo);
```
|
In Java 8:
```
List<String> newList = Stream.concat(listOne.stream(), listTwo.stream())
.collect(Collectors.toList());
```
Java 16+:
```
List<String> newList = Stream.concat(listOne.stream(), listTwo.stream()).toList();
```
|
189,562 |
<p>There are many ways of doing debugging, using a debugger is one, but the simple one for the humble, lazy, programmer is to just add a bunch of print statements to your code.</p>
<p>i.e.</p>
<pre><code> def foo(x):
print 'Hey wow, we got to foo!', x
...
print 'foo is returning:', bar
return bar
</code></pre>
<p>Is there a proper name for this style of debugging?</p>
|
[
{
"answer_id": 189570,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 7,
"selected": true,
"text": "<p>Yes - it's known as <strong><code>printf()</code> debugging</strong>, named after the ubiquitous C function:</p>\n\n<blockquote>\n <p>Used\n to describe debugging work done by\n inserting commands that output more or\n less carefully chosen status\n information at key points in the\n program flow, observing that\n information and deducing what's wrong\n based on that information.</p>\n</blockquote>\n\n<p>-- <a href=\"http://everything2.com/title/printf%2528%2529%2520debugging\" rel=\"noreferrer\">printf() debugging@everything2</a></p>\n\n<p>Native users of other languages no doubt refer to it by the default print / log / or trace command available for their coding platform of choice, but i've heard the \"printf()\" name used to refere to this technique in many languages other than C. Perhaps this is due to its history: while BASIC and FORTRAN had basic but serviceable <code>PRINT</code> commands, C generally required a bit more work to format various data types: <code>printf()</code> was (and often still is) <em>by far</em> the most convenient means to this end, providing many built-in formatting options. Its cousin, <code>fprintf()</code>, takes another parameter, the stream to write to: this allowed a careful \"debugger\" to direct diagnostic information to <code>stderr</code> (possibly itself redirected to a log file) while leaving the output of the program uncorrupted. </p>\n\n<p>Although often looked down on by users of modern debugging software, printf() debugging continues to prove itself indispensable: the wildly popular FireBug tool for the Firefox web browser (and similar tools now available for other browsers) is built around a console window into which web page scripts can log errors or diagnostic messages containing formatted data.</p>\n"
},
{
"answer_id": 189583,
"author": "RWendi",
"author_id": 15152,
"author_profile": "https://Stackoverflow.com/users/15152",
"pm_score": 3,
"selected": false,
"text": "<p>me and my team mates calling it \"Oldschool Debuging\".</p>\n"
},
{
"answer_id": 189590,
"author": "David Segonds",
"author_id": 13673,
"author_profile": "https://Stackoverflow.com/users/13673",
"pm_score": 5,
"selected": false,
"text": "<p>I call it Tracing.</p>\n"
},
{
"answer_id": 189596,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 1,
"selected": false,
"text": "<p>Manual Assertions? Debugger Phobia?</p>\n"
},
{
"answer_id": 189615,
"author": "Sergio Acosta",
"author_id": 2954,
"author_profile": "https://Stackoverflow.com/users/2954",
"pm_score": 3,
"selected": false,
"text": "<p>I have also heard the term <strong>\"MessageBox debugging\"</strong> from the VB crowd to refer to this 'style' of 'debugging'.</p>\n"
},
{
"answer_id": 189620,
"author": "Don Wakefield",
"author_id": 3778,
"author_profile": "https://Stackoverflow.com/users/3778",
"pm_score": 3,
"selected": false,
"text": "<p>In the same sense as <a href=\"http://en.wikipedia.org/wiki/Exploratory_programming\" rel=\"nofollow noreferrer\">exploratory programming</a>, I like calling it <em>exploratory debugging</em>. This follows when the debugger is not powerful enough to examine complex types in the program, or invoke helper functions separately, or you just don't know enough about a bug to use said features directly.</p>\n"
},
{
"answer_id": 189630,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 2,
"selected": false,
"text": "<p>I usually refer to it as tracing.</p>\n\n<p>Note that in Visual Studio you can set breakpoints which just add tracing. Right click on a breakpoint, select \"when hit...\" and check the \"Print a message\" option.</p>\n"
},
{
"answer_id": 189639,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 6,
"selected": false,
"text": "<p>I've heard it called <strong>Caveman Debugging</strong></p>\n"
},
{
"answer_id": 189651,
"author": "Dr8k",
"author_id": 6014,
"author_profile": "https://Stackoverflow.com/users/6014",
"pm_score": 2,
"selected": false,
"text": "<p>Also, in .Net you can add debugging statements (I think it actually is Debug.WriteLine) to output to the console. These statments are only included in debug builds - the compiler will automatically leave them out when you do a release build.</p>\n"
},
{
"answer_id": 189658,
"author": "humble_guru",
"author_id": 23961,
"author_profile": "https://Stackoverflow.com/users/23961",
"pm_score": 2,
"selected": false,
"text": "<p>I embedded systems its often the only method to instrument the code. Unfortunately printing takes time and effects the real-time flow of the system. So we also instrument via \"tracing\" where information about the state of the system (function entry exit etc) is written to a internal buffer to be dumped and parsed later. Real embedded programmers can debug by blinking an LED ;)</p>\n"
},
{
"answer_id": 189703,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Classic Debugging</p>\n"
},
{
"answer_id": 190132,
"author": "An̲̳̳drew",
"author_id": 17035,
"author_profile": "https://Stackoverflow.com/users/17035",
"pm_score": 3,
"selected": false,
"text": "<p>I call this \"Hi, Mom\" programming.</p>\n"
},
{
"answer_id": 190144,
"author": "Nrj",
"author_id": 11614,
"author_profile": "https://Stackoverflow.com/users/11614",
"pm_score": 2,
"selected": false,
"text": "<p>verbose debugging !</p>\n"
},
{
"answer_id": 190185,
"author": "NeilDurant",
"author_id": 26718,
"author_profile": "https://Stackoverflow.com/users/26718",
"pm_score": 3,
"selected": false,
"text": "<p><em>Seat of your pants debugging</em> :)</p>\n\n<p>When you're on an embedded system, when you're at the bleeding edge and the language you're coding in doesn't have a debugger yet, when your debugger is behaving strangely and you want to restore some sanity, and you want to understand how re-entrancy is working in multi-threaded code,....</p>\n"
},
{
"answer_id": 190187,
"author": "Jonathan",
"author_id": 14850,
"author_profile": "https://Stackoverflow.com/users/14850",
"pm_score": 2,
"selected": false,
"text": "<p>(Good logging is incredibly valuable for debugging problems in running production systems. Lots of useless verbose print statements aren't, but logging something interesting when something important or unexpected occurred is incredibly important. If the only way you know how to debug problems is with a debugger, you're going to find yourself in quite the tight spot when the service you've built is broken for some of your users but you can't reproduce the problem locally.)</p>\n"
},
{
"answer_id": 190200,
"author": "ayaz",
"author_id": 23191,
"author_profile": "https://Stackoverflow.com/users/23191",
"pm_score": 1,
"selected": false,
"text": "<p>I have always known it by the term 'quick-and-dirty debugging', or just 'dirty debugging' in short.</p>\n"
},
{
"answer_id": 238686,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 5,
"selected": false,
"text": "<p>I thought the following quote would be apropos:</p>\n\n<blockquote>\n <p>\"The most effective debugging tool is still careful thought, coupled with judiciously placed print statements.\" </p>\n \n <p>— Brian Kernighan, \"Unix for Beginners\" (1979)</p>\n</blockquote>\n"
},
{
"answer_id": 12035472,
"author": "styts",
"author_id": 238222,
"author_profile": "https://Stackoverflow.com/users/238222",
"pm_score": 2,
"selected": false,
"text": "<p>I've heard \"<strong>Gutenberg debugging</strong>\" being used, in the honor of <a href=\"http://en.wikipedia.org/wiki/Johannes_Gutenberg\" rel=\"nofollow\">the guy who invented the printing press</a>.</p>\n"
},
{
"answer_id": 20286949,
"author": "Calmarius",
"author_id": 58805,
"author_profile": "https://Stackoverflow.com/users/58805",
"pm_score": 2,
"selected": false,
"text": "<p>I would call it simply \"<strong>logging</strong>\".</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14648/"
] |
There are many ways of doing debugging, using a debugger is one, but the simple one for the humble, lazy, programmer is to just add a bunch of print statements to your code.
i.e.
```
def foo(x):
print 'Hey wow, we got to foo!', x
...
print 'foo is returning:', bar
return bar
```
Is there a proper name for this style of debugging?
|
Yes - it's known as **`printf()` debugging**, named after the ubiquitous C function:
>
> Used
> to describe debugging work done by
> inserting commands that output more or
> less carefully chosen status
> information at key points in the
> program flow, observing that
> information and deducing what's wrong
> based on that information.
>
>
>
-- [printf() debugging@everything2](http://everything2.com/title/printf%2528%2529%2520debugging)
Native users of other languages no doubt refer to it by the default print / log / or trace command available for their coding platform of choice, but i've heard the "printf()" name used to refere to this technique in many languages other than C. Perhaps this is due to its history: while BASIC and FORTRAN had basic but serviceable `PRINT` commands, C generally required a bit more work to format various data types: `printf()` was (and often still is) *by far* the most convenient means to this end, providing many built-in formatting options. Its cousin, `fprintf()`, takes another parameter, the stream to write to: this allowed a careful "debugger" to direct diagnostic information to `stderr` (possibly itself redirected to a log file) while leaving the output of the program uncorrupted.
Although often looked down on by users of modern debugging software, printf() debugging continues to prove itself indispensable: the wildly popular FireBug tool for the Firefox web browser (and similar tools now available for other browsers) is built around a console window into which web page scripts can log errors or diagnostic messages containing formatted data.
|
189,588 |
<p>I've been led to believe that for single variable assignment in T-SQL, <code>set</code> is the best way to go about things, for two reasons:</p>
<ul>
<li>it's the ANSI standard for variable assignment</li>
<li>it's actually faster than doing a SELECT (for a single variable)</li>
</ul>
<p>So...</p>
<pre><code>SELECT @thingy = 'turnip shaped'
</code></pre>
<p>becomes</p>
<pre><code>SET @thingy = 'turnip shaped'
</code></pre>
<p>But how fast, is <em>fast</em>? Am I ever really going to notice the difference?</p>
|
[
{
"answer_id": 189597,
"author": "Mark",
"author_id": 26310,
"author_profile": "https://Stackoverflow.com/users/26310",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at the \"execution plan\", it should tell you the cost of each line of your statement</p>\n"
},
{
"answer_id": 189600,
"author": "Saif Khan",
"author_id": 23667,
"author_profile": "https://Stackoverflow.com/users/23667",
"pm_score": 1,
"selected": false,
"text": "<p>I don't speed is an issue, it has to do with more with the assignment feature set. I came across <a href=\"http://vyaskn.tripod.com/differences_between_set_and_select.htm\" rel=\"nofollow noreferrer\">this</a> a while ago and there is something new in SQL Server 2008...I heard, try googling SQL Set vs Select SQL SERVER 2008</p>\n"
},
{
"answer_id": 189727,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 4,
"selected": true,
"text": "<p>SET is faster on single runs. You can prove this easily enough. Whether or not it makes a difference is up to you, but I prefer SET, since I don't see the point of SELECT if all the code is doing is an assignment. I prefer to keep SELECT confined to SELECT statements from tables, views, etc.</p>\n\n<p>Here is a sample script, with the number of runs set to 1:</p>\n\n<pre><code>SET NOCOUNT ON\n\nDECLARE @runs int\nDECLARE @i int, @j int\nSET @runs = 1\nSET @i = 0\nSET @j = 0\n\nDECLARE @dtStartDate datetime, @dtEndDate datetime\n\n\nWHILE @runs > 0\n BEGIN\n SET @j = 0\n SET @dtStartDate = CURRENT_TIMESTAMP\n WHILE @j < 1000000\n BEGIN\n SET @i = @j\n SET @j = @j + 1\n END\n SELECT @dtEndDate = CURRENT_TIMESTAMP\n SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SET_MILLISECONDS\n\n\n SET @j = 0\n SET @dtStartDate = CURRENT_TIMESTAMP\n WHILE @j < 1000000\n BEGIN\n SELECT @i = @j\n SET @j = @j + 1\n END\n SELECT @dtEndDate = CURRENT_TIMESTAMP\n SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SELECT_MILLISECONDS\n\n SET @runs = @runs - 1\n END\n</code></pre>\n\n<p>RESULTS:</p>\n\n<p>Run #1:</p>\n\n<p>SET_MILLISECONDS </p>\n\n<p>5093</p>\n\n<p>SELECT_MILLISECONDS </p>\n\n<p>5186</p>\n\n<p>Run #2:</p>\n\n<p>SET_MILLISECONDS </p>\n\n<p>4876</p>\n\n<p>SELECT_MILLISECONDS </p>\n\n<p>5466</p>\n\n<p>Run #3:</p>\n\n<p>SET_MILLISECONDS </p>\n\n<p>4936</p>\n\n<p>SELECT_MILLISECONDS </p>\n\n<p>5453</p>\n\n<p>Run #4:</p>\n\n<p>SET_MILLISECONDS </p>\n\n<p>4920</p>\n\n<p>SELECT_MILLISECONDS </p>\n\n<p>5250</p>\n\n<p>Run #5:</p>\n\n<p>SET_MILLISECONDS </p>\n\n<p>4860</p>\n\n<p>SELECT_MILLISECONDS </p>\n\n<p>5093</p>\n\n<p><strong>Oddly, if you crank the number of runs up to say, 10, the SET begins to lag behind.</strong></p>\n\n<p>Here is a 10-run result:</p>\n\n<p>SET_MILLISECONDS </p>\n\n<p>5140</p>\n\n<p>SELECT_MILLISECONDS </p>\n\n<p>5266</p>\n\n<p>SET_MILLISECONDS </p>\n\n<p>5250</p>\n\n<p>SELECT_MILLISECONDS </p>\n\n<p>5466</p>\n\n<p>SET_MILLISECONDS </p>\n\n<p>5220</p>\n\n<p>SELECT_MILLISECONDS </p>\n\n<p>5280</p>\n\n<p>SET_MILLISECONDS </p>\n\n<p>5376</p>\n\n<p>SELECT_MILLISECONDS </p>\n\n<p>5280</p>\n\n<p>SET_MILLISECONDS </p>\n\n<p>5233</p>\n\n<p>SELECT_MILLISECONDS </p>\n\n<p>5453</p>\n\n<p>SET_MILLISECONDS </p>\n\n<p>5343</p>\n\n<p>SELECT_MILLISECONDS </p>\n\n<p>5423</p>\n\n<p>SET_MILLISECONDS </p>\n\n<p>5360</p>\n\n<p>SELECT_MILLISECONDS </p>\n\n<p>5156</p>\n\n<p>SET_MILLISECONDS </p>\n\n<p>5686</p>\n\n<p>SELECT_MILLISECONDS </p>\n\n<p>5233</p>\n\n<p>SET_MILLISECONDS </p>\n\n<p>5436</p>\n\n<p>SELECT_MILLISECONDS </p>\n\n<p>5500</p>\n\n<p>SET_MILLISECONDS </p>\n\n<p>5610</p>\n\n<p>SELECT_MILLISECONDS </p>\n\n<p>5266</p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] |
I've been led to believe that for single variable assignment in T-SQL, `set` is the best way to go about things, for two reasons:
* it's the ANSI standard for variable assignment
* it's actually faster than doing a SELECT (for a single variable)
So...
```
SELECT @thingy = 'turnip shaped'
```
becomes
```
SET @thingy = 'turnip shaped'
```
But how fast, is *fast*? Am I ever really going to notice the difference?
|
SET is faster on single runs. You can prove this easily enough. Whether or not it makes a difference is up to you, but I prefer SET, since I don't see the point of SELECT if all the code is doing is an assignment. I prefer to keep SELECT confined to SELECT statements from tables, views, etc.
Here is a sample script, with the number of runs set to 1:
```
SET NOCOUNT ON
DECLARE @runs int
DECLARE @i int, @j int
SET @runs = 1
SET @i = 0
SET @j = 0
DECLARE @dtStartDate datetime, @dtEndDate datetime
WHILE @runs > 0
BEGIN
SET @j = 0
SET @dtStartDate = CURRENT_TIMESTAMP
WHILE @j < 1000000
BEGIN
SET @i = @j
SET @j = @j + 1
END
SELECT @dtEndDate = CURRENT_TIMESTAMP
SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SET_MILLISECONDS
SET @j = 0
SET @dtStartDate = CURRENT_TIMESTAMP
WHILE @j < 1000000
BEGIN
SELECT @i = @j
SET @j = @j + 1
END
SELECT @dtEndDate = CURRENT_TIMESTAMP
SELECT DATEDIFF(millisecond, @dtStartDate, @dtEndDate) AS SELECT_MILLISECONDS
SET @runs = @runs - 1
END
```
RESULTS:
Run #1:
SET\_MILLISECONDS
5093
SELECT\_MILLISECONDS
5186
Run #2:
SET\_MILLISECONDS
4876
SELECT\_MILLISECONDS
5466
Run #3:
SET\_MILLISECONDS
4936
SELECT\_MILLISECONDS
5453
Run #4:
SET\_MILLISECONDS
4920
SELECT\_MILLISECONDS
5250
Run #5:
SET\_MILLISECONDS
4860
SELECT\_MILLISECONDS
5093
**Oddly, if you crank the number of runs up to say, 10, the SET begins to lag behind.**
Here is a 10-run result:
SET\_MILLISECONDS
5140
SELECT\_MILLISECONDS
5266
SET\_MILLISECONDS
5250
SELECT\_MILLISECONDS
5466
SET\_MILLISECONDS
5220
SELECT\_MILLISECONDS
5280
SET\_MILLISECONDS
5376
SELECT\_MILLISECONDS
5280
SET\_MILLISECONDS
5233
SELECT\_MILLISECONDS
5453
SET\_MILLISECONDS
5343
SELECT\_MILLISECONDS
5423
SET\_MILLISECONDS
5360
SELECT\_MILLISECONDS
5156
SET\_MILLISECONDS
5686
SELECT\_MILLISECONDS
5233
SET\_MILLISECONDS
5436
SELECT\_MILLISECONDS
5500
SET\_MILLISECONDS
5610
SELECT\_MILLISECONDS
5266
|
189,610 |
<p>Imagine I have a chunk of initialisation code at the top of a stored procedure with a number of variable assignments:</p>
<pre><code>SET @proc = 'sp_madeupname'
SET @magic_number = 42
SET @tomorrows_date = DATEADD(dd, 1, GETDATE())
...
</code></pre>
<p>Clearly doing all of the above as one SELECT would be faster:</p>
<pre><code>SELECT
@proc = 'sp_madeupname'
,@magic_number = 42
,@tomorrows_date = DATEADD(dd, 1, GETDATE())
...
</code></pre>
<p>But <em>how much</em> faster? Say if this stored procedure was executed as part of a loop, several thousand times, is it going to make any significant difference to the performance?</p>
|
[
{
"answer_id": 189626,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "<p>I've thought about it but never tested it.</p>\n\n<p>In my experience, the optimizer is pretty good, so I would think it makes no difference, but I'd run some tests if you thought it was really useful.</p>\n\n<p>I think doing multiple assignments can be useful from a maintenance point of view, if you want some things which should always be done together to not be broken up with a cut and paste or refactoring.</p>\n\n<p>For the same reason, code which is relatively modular can benefit from separate initialization, since this is more easily cut and pasted to refactor during maintenance.</p>\n"
},
{
"answer_id": 190196,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 3,
"selected": true,
"text": "<p>In this case, SELECT wins, performance-wise, when performing multiple assignments.</p>\n\n<p>Here is some more information about it:</p>\n\n<p><a href=\"http://www.sqlmag.com/Articles/ArticleID/94555/94555.html\" rel=\"nofollow noreferrer\">SELECT vs. SET: Optimizing Loops</a></p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] |
Imagine I have a chunk of initialisation code at the top of a stored procedure with a number of variable assignments:
```
SET @proc = 'sp_madeupname'
SET @magic_number = 42
SET @tomorrows_date = DATEADD(dd, 1, GETDATE())
...
```
Clearly doing all of the above as one SELECT would be faster:
```
SELECT
@proc = 'sp_madeupname'
,@magic_number = 42
,@tomorrows_date = DATEADD(dd, 1, GETDATE())
...
```
But *how much* faster? Say if this stored procedure was executed as part of a loop, several thousand times, is it going to make any significant difference to the performance?
|
In this case, SELECT wins, performance-wise, when performing multiple assignments.
Here is some more information about it:
[SELECT vs. SET: Optimizing Loops](http://www.sqlmag.com/Articles/ArticleID/94555/94555.html)
|
189,622 |
<p>I frequently encounter some definitions for Win32API structures (but not limited to it) that have a <code>cbSize</code> member as in the following example.</p>
<pre><code>typedef struct _TEST {
int cbSize;
// other members follow
} TEST, *PTEST;
</code></pre>
<p>And then we use it like this:</p>
<pre><code>TEST t = { sizeof(TEST) };
...
</code></pre>
<p>or</p>
<pre><code>TEST t;
t.cbSize = sizeof(TEST);
...
</code></pre>
<p>My initial guess is that this could potentially be used for versioning. A DLL that receives a pointer for a struct like this can check if the <code>cbSize</code> member has the expected value with which the DLL was compiled. Or to check if proper packing is done for the struct. But I would like to here from you.</p>
<p><strong>What is the purpose of the <code>cbSize</code> member in some C++ structures on Win32API?</strong></p>
|
[
{
"answer_id": 189628,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 5,
"selected": true,
"text": "<blockquote>\n <p>My initial guess is that this could\n potentially be used for versioning.</p>\n</blockquote>\n\n<p>That's one reason. I think it's the more usual one.</p>\n\n<p>Another is for structures that have variable length data.</p>\n\n<p>I don't think that checking for correct packing or bugs in the caller are a particular reasoning behind it, but it would have that effect.</p>\n"
},
{
"answer_id": 189637,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 1,
"selected": false,
"text": "<p>Partially versioning, mostly safety... to prevent the called function from poking into memory that wasn't part of the struct passed in.</p>\n"
},
{
"answer_id": 189667,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 4,
"selected": false,
"text": "<p>It is used for versioning. A good example is the <a href=\"http://msdn.microsoft.com/en-us/library/ms724451(VS.85).aspx\" rel=\"noreferrer\">GetVersionEx</a> call. You can pass in either an <a href=\"http://msdn.microsoft.com/en-us/library/ms724834(VS.85).aspx\" rel=\"noreferrer\">OSVERSIONINFO</a> or <a href=\"http://msdn.microsoft.com/en-us/library/ms724833(VS.85).aspx\" rel=\"noreferrer\">OSVERSIONINFOEX</a>. The OSVERSIONINFOEX is a superset of OSVERSIONINFO, and the only way the OS knows which you have passed in is by the dwOSVersionInfoSize member.</p>\n"
},
{
"answer_id": 189734,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 2,
"selected": false,
"text": "<p>It also lets the <strong>WIN32 API</strong> do a minimal amount of sanity checking on the data being passed in. </p>\n\n<p>For example a commom mistake is for a <strong>WIN32</strong> structure to be passed in with an <em>incorrect</em> or <em>uninitialised</em> <strong>cbSize</strong> and when this happens the <strong>WIN32 API</strong> usually just returns a failed result, rather than try to process what appears to be corrupted data. </p>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/189622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6508/"
] |
I frequently encounter some definitions for Win32API structures (but not limited to it) that have a `cbSize` member as in the following example.
```
typedef struct _TEST {
int cbSize;
// other members follow
} TEST, *PTEST;
```
And then we use it like this:
```
TEST t = { sizeof(TEST) };
...
```
or
```
TEST t;
t.cbSize = sizeof(TEST);
...
```
My initial guess is that this could potentially be used for versioning. A DLL that receives a pointer for a struct like this can check if the `cbSize` member has the expected value with which the DLL was compiled. Or to check if proper packing is done for the struct. But I would like to here from you.
**What is the purpose of the `cbSize` member in some C++ structures on Win32API?**
|
>
> My initial guess is that this could
> potentially be used for versioning.
>
>
>
That's one reason. I think it's the more usual one.
Another is for structures that have variable length data.
I don't think that checking for correct packing or bugs in the caller are a particular reasoning behind it, but it would have that effect.
|
189,645 |
<p>Given the following code (that doesn't work):</p>
<pre><code>while True:
# Snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok.lower() == "y": break 2 # This doesn't work :(
if ok.lower() == "n": break
# Do more processing with menus and stuff
</code></pre>
<p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p>
|
[
{
"answer_id": 189664,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 7,
"selected": false,
"text": "<p>First, ordinary logic is helpful. </p>\n\n<p>If, for some reason, the terminating conditions can't be worked out, exceptions are a fall-back plan. </p>\n\n<pre><code>class GetOutOfLoop( Exception ):\n pass\n\ntry:\n done= False\n while not done:\n isok= False\n while not (done or isok):\n ok = get_input(\"Is this ok? (y/n)\")\n if ok in (\"y\", \"Y\") or ok in (\"n\", \"N\") : \n done= True # probably better\n raise GetOutOfLoop\n # other stuff\nexcept GetOutOfLoop:\n pass\n</code></pre>\n\n<p>For this specific example, an exception may not be necessary. </p>\n\n<p>On other other hand, we often have \"Y\", \"N\" and \"Q\" options in character-mode applications. For the \"Q\" option, we want an immediate exit. That's more exceptional.</p>\n"
},
{
"answer_id": 189666,
"author": "Matt J",
"author_id": 18528,
"author_profile": "https://Stackoverflow.com/users/18528",
"pm_score": 6,
"selected": false,
"text": "<p>First, you may also consider making the process of getting and validating the input a function; within that function, you can just return the value if its correct, and keep spinning in the <em>while</em> loop if not. This essentially obviates the problem you solved, and can usually be applied in the more general case (breaking out of multiple loops). If you absolutely must keep this structure in your code, and really don't want to deal with bookkeeping booleans...</p>\n\n<p>You may also use <em>goto</em> in the following way (using an April Fools module from <a href=\"http://entrian.com/goto/\" rel=\"noreferrer\">here</a>):</p>\n\n<pre><code>#import the stuff\nfrom goto import goto, label\n\nwhile True:\n #snip: print out current state\n while True:\n ok = get_input(\"Is this ok? (y/n)\")\n if ok == \"y\" or ok == \"Y\": goto .breakall\n if ok == \"n\" or ok == \"N\": break\n #do more processing with menus and stuff\nlabel .breakall\n</code></pre>\n\n<p>I know, I know, \"thou shalt not use goto\" and all that, but it works well in strange cases like this.</p>\n"
},
{
"answer_id": 189685,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 10,
"selected": true,
"text": "<p>My first instinct would be to refactor the nested loop into a function and use <code>return</code> to break out. </p>\n"
},
{
"answer_id": 189696,
"author": "quick_dry",
"author_id": 3716,
"author_profile": "https://Stackoverflow.com/users/3716",
"pm_score": 4,
"selected": false,
"text": "<pre class=\"lang-python prettyprint-override\"><code>keeplooping = True\nwhile keeplooping:\n # Do stuff\n while keeplooping:\n # Do some other stuff\n if finisheddoingstuff():\n keeplooping = False\n</code></pre>\n<p>or something like that.</p>\n<p>You could set a variable in the inner loop, and check it in the outer loop immediately after the inner loop exits, breaking if appropriate. I kind of like the GOTO method, provided you don't mind using an April Fool's joke module - it’s not Pythonic, but it does make sense.</p>\n"
},
{
"answer_id": 189838,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 4,
"selected": false,
"text": "<p>This isn't the prettiest way to do it, but in my opinion, it's the best way.</p>\n<pre><code>def loop():\n while True:\n #snip: print out current state\n while True:\n ok = get_input("Is this ok? (y/n)")\n if ok == "y" or ok == "Y": return\n if ok == "n" or ok == "N": break\n #do more processing with menus and stuff\n</code></pre>\n<p>I'm pretty sure you could work out something using recursion here as well, but I don't know if that's a good option for you.</p>\n"
},
{
"answer_id": 190070,
"author": "John Fouhy",
"author_id": 15154,
"author_profile": "https://Stackoverflow.com/users/15154",
"pm_score": 7,
"selected": false,
"text": "<p><a href=\"http://www.python.org/dev/peps/pep-3136/\" rel=\"noreferrer\">PEP 3136</a> proposes labeled break/continue. Guido <a href=\"http://mail.python.org/pipermail/python-3000/2007-July/008663.html\" rel=\"noreferrer\">rejected it</a> because \"code so complicated to require this feature is very rare\". The PEP does mention some workarounds, though (such as the exception technique), while Guido feels refactoring to use return will be simpler in most cases.</p>\n"
},
{
"answer_id": 2621659,
"author": "Matt Billenstein",
"author_id": 314462,
"author_profile": "https://Stackoverflow.com/users/314462",
"pm_score": 3,
"selected": false,
"text": "<p>Factor your loop logic into an iterator that yields the loop variables and returns when done -- here is a simple one that lays out images in rows/columns until we're out of images or out of places to put them:</p>\n\n<pre><code>def it(rows, cols, images):\n i = 0\n for r in xrange(rows):\n for c in xrange(cols):\n if i >= len(images):\n return\n yield r, c, images[i]\n i += 1 \n\nfor r, c, image in it(rows=4, cols=4, images=['a.jpg', 'b.jpg', 'c.jpg']):\n ... do something with r, c, image ...\n</code></pre>\n\n<p>This has the advantage of splitting up the complicated loop logic and the processing...</p>\n"
},
{
"answer_id": 3150107,
"author": "yak",
"author_id": 380157,
"author_profile": "https://Stackoverflow.com/users/380157",
"pm_score": 9,
"selected": false,
"text": "<p>Here's another approach that is short. The disadvantage is that you can only break the outer loop, but sometimes it's exactly what you want.</p>\n\n<pre><code>for a in xrange(10):\n for b in xrange(20):\n if something(a, b):\n # Break the inner loop...\n break\n else:\n # Continue if the inner loop wasn't broken.\n continue\n # Inner loop was broken, break the outer.\n break\n</code></pre>\n\n<p>This uses the for / else construct explained at: <a href=\"https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops\">Why does python use 'else' after for and while loops?</a></p>\n\n<p>Key insight: It only <em>seems</em> as if the outer loop always breaks. <strong>But if the inner loop doesn't break, the outer loop won't either.</strong> </p>\n\n<p>The <code>continue</code> statement is the magic here. It's in the for-else clause. <a href=\"https://stackoverflow.com/a/9980752/673991\">By definition</a> that happens if there's no inner break. In that situation <code>continue</code> neatly circumvents the outer break.</p>\n"
},
{
"answer_id": 3171971,
"author": "Mark Dickinson",
"author_id": 270986,
"author_profile": "https://Stackoverflow.com/users/270986",
"pm_score": 6,
"selected": false,
"text": "<p>I tend to agree that refactoring into a function is usually the best approach for this sort of situation, but for when you <em>really</em> need to break out of nested loops, here's an interesting variant of the exception-raising approach that @S.Lott described. It uses Python's <code>with</code> statement to make the exception raising look a bit nicer. Define a new context manager (you only have to do this once) with:</p>\n\n<pre><code>from contextlib import contextmanager\n@contextmanager\ndef nested_break():\n class NestedBreakException(Exception):\n pass\n try:\n yield NestedBreakException\n except NestedBreakException:\n pass\n</code></pre>\n\n<p>Now you can use this context manager as follows:</p>\n\n<pre><code>with nested_break() as mylabel:\n while True:\n print \"current state\"\n while True:\n ok = raw_input(\"Is this ok? (y/n)\")\n if ok == \"y\" or ok == \"Y\": raise mylabel\n if ok == \"n\" or ok == \"N\": break\n print \"more processing\"\n</code></pre>\n\n<p>Advantages: (1) it's slightly cleaner (no explicit try-except block), and (2) you get a custom-built <code>Exception</code> subclass for each use of <code>nested_break</code>; no need to declare your own <code>Exception</code> subclass each time.</p>\n"
},
{
"answer_id": 6564670,
"author": "krvolok",
"author_id": 827133,
"author_profile": "https://Stackoverflow.com/users/827133",
"pm_score": 6,
"selected": false,
"text": "<p>Introduce a new variable that you'll use as a 'loop breaker'. First assign something to it(False,0, etc.), and then, inside the outer loop, before you break from it, change the value to something else(True,1,...). Once the loop exits make the 'parent' loop check for that value. Let me demonstrate:</p>\n\n<pre><code>breaker = False #our mighty loop exiter!\nwhile True:\n while True:\n if conditionMet:\n #insert code here...\n breaker = True \n break\n if breaker: # the interesting part!\n break # <--- !\n</code></pre>\n\n<p>If you have an infinite loop, this is the only way out; for other loops execution is really a lot faster. This also works if you have many nested loops. You can exit all, or just a few. Endless possibilities! Hope this helped!</p>\n"
},
{
"answer_id": 10930656,
"author": "alu5",
"author_id": 1442038,
"author_profile": "https://Stackoverflow.com/users/1442038",
"pm_score": -1,
"selected": false,
"text": "<p>Similar like the one before, but more compact.\n(Booleans are just numbers)</p>\n\n<pre><code>breaker = False #our mighty loop exiter!\nwhile True:\n while True:\n ok = get_input(\"Is this ok? (y/n)\")\n breaker+= (ok.lower() == \"y\")\n break\n\n if breaker: # the interesting part!\n break # <--- !\n</code></pre>\n"
},
{
"answer_id": 11974716,
"author": "Nathan Garabedian",
"author_id": 546302,
"author_profile": "https://Stackoverflow.com/users/546302",
"pm_score": 1,
"selected": false,
"text": "<p>My reason for coming here is that i had an outer loop and an inner loop like so:</p>\n\n<pre><code>for x in array:\n for y in dont_use_these_values:\n if x.value==y:\n array.remove(x) # fixed, was array.pop(x) in my original answer\n continue\n\n do some other stuff with x\n</code></pre>\n\n<p>As you can see, it won't actually go to the next x, but will go to the next y instead.</p>\n\n<p>what i found to solve this simply was to run through the array twice instead:</p>\n\n<pre><code>for x in array:\n for y in dont_use_these_values:\n if x.value==y:\n array.remove(x) # fixed, was array.pop(x) in my original answer\n continue\n\nfor x in array:\n do some other stuff with x\n</code></pre>\n\n<p>I know this was a specific case of OP's question, but I am posting it in the hope that it will help someone think about their problem differently while keeping things simple.</p>\n"
},
{
"answer_id": 13252668,
"author": "Mauro",
"author_id": 1459120,
"author_profile": "https://Stackoverflow.com/users/1459120",
"pm_score": 4,
"selected": false,
"text": "<p>Keep looping if two conditions are true.</p>\n<p>I think this is a more Pythonic way:</p>\n<pre><code>dejaVu = True\n\nwhile dejaVu:\n while True:\n ok = raw_input("Is this ok? (y/n)")\n if ok == "y" or ok == "Y" or ok == "n" or ok == "N":\n dejaVu = False\n break\n</code></pre>\n"
},
{
"answer_id": 15559616,
"author": "Rusty Rob",
"author_id": 632088,
"author_profile": "https://Stackoverflow.com/users/632088",
"pm_score": 2,
"selected": false,
"text": "<p>Try using an infinite generator.</p>\n\n<pre><code>from itertools import repeat\ninputs = (get_input(\"Is this ok? (y/n)\") for _ in repeat(None))\nresponse = (i.lower()==\"y\" for i in inputs if i.lower() in (\"y\", \"n\"))\n\nwhile True:\n #snip: print out current state\n if next(response):\n break\n #do more processing with menus and stuff\n</code></pre>\n"
},
{
"answer_id": 17092776,
"author": "RufusVS",
"author_id": 925592,
"author_profile": "https://Stackoverflow.com/users/925592",
"pm_score": 2,
"selected": false,
"text": "<pre><code># this version uses a level counter to choose how far to break out\n\nbreak_levels = 0\nwhile True:\n # snip: print out current state\n while True:\n ok = get_input(\"Is this ok? (y/n)\")\n if ok == \"y\" or ok == \"Y\":\n break_levels = 1 # how far nested, excluding this break\n break\n if ok == \"n\" or ok == \"N\":\n break # normal break\n if break_levels:\n break_levels -= 1\n break # pop another level\nif break_levels:\n break_levels -= 1\n break\n\n# ...and so on\n</code></pre>\n"
},
{
"answer_id": 17093146,
"author": "RufusVS",
"author_id": 925592,
"author_profile": "https://Stackoverflow.com/users/925592",
"pm_score": 2,
"selected": false,
"text": "<pre><code># this version breaks up to a certain label\n\nbreak_label = None\nwhile True:\n # snip: print out current state\n while True:\n ok = get_input(\"Is this ok? (y/n)\")\n if ok == \"y\" or ok == \"Y\":\n break_label = \"outer\" # specify label to break to\n break\n if ok == \"n\" or ok == \"N\":\n break\n if break_label:\n if break_label != \"inner\":\n break # propagate up\n break_label = None # we have arrived!\nif break_label:\n if break_label != \"outer\":\n break # propagate up\n break_label = None # we have arrived!\n\n#do more processing with menus and stuff\n</code></pre>\n"
},
{
"answer_id": 32023069,
"author": "Loax",
"author_id": 1526490,
"author_profile": "https://Stackoverflow.com/users/1526490",
"pm_score": 2,
"selected": false,
"text": "<p>In this case, as pointed out by others as well, functional decomposition is the way to go. Code in Python 3:</p>\n\n<pre><code>def user_confirms():\n while True:\n answer = input(\"Is this OK? (y/n) \").strip().lower()\n if answer in \"yn\":\n return answer == \"y\"\n\ndef main():\n while True:\n # do stuff\n if user_confirms():\n break\n</code></pre>\n"
},
{
"answer_id": 33121569,
"author": "holroy",
"author_id": 1548472,
"author_profile": "https://Stackoverflow.com/users/1548472",
"pm_score": 2,
"selected": false,
"text": "<p>There is a hidden trick in the Python <code>while ... else</code> structure which can be used to simulate the double break without much code changes/additions. In essence if the <code>while</code> condition is false, the <code>else</code> block is triggered. Neither exceptions, <code>continue</code> or <code>break</code> trigger the <code>else</code> block. For more information see answers to \"<a href=\"https://stackoverflow.com/q/3295938/1548472\">Else clause on Python while statement</a>\", or <a href=\"//docs.python.org/2.7/reference/compound_stmts.html#the-while-statement\" rel=\"nofollow noreferrer\">Python doc on while (v2.7)</a>.</p>\n\n<pre><code>while True:\n #snip: print out current state\n ok = \"\"\n while ok != \"y\" and ok != \"n\":\n ok = get_input(\"Is this ok? (y/n)\")\n if ok == \"n\" or ok == \"N\":\n break # Breaks out of inner loop, skipping else\n\n else:\n break # Breaks out of outer loop\n\n #do more processing with menus and stuff\n</code></pre>\n\n<p>The only downside is that you need to move the double breaking condition into the <code>while</code> condition (or add a flag variable). Variations of this exists also for the <code>for</code> loop, where the <code>else</code> block is triggered after loop completion.</p>\n"
},
{
"answer_id": 40120729,
"author": "Skycc",
"author_id": 7031759,
"author_profile": "https://Stackoverflow.com/users/7031759",
"pm_score": 1,
"selected": false,
"text": "<p>probably little trick like below will do if not prefer to refactorial into function</p>\n\n<p>added 1 break_level variable to control the while loop condition</p>\n\n<pre><code>break_level = 0\n# while break_level < 3: # if we have another level of nested loop here\nwhile break_level < 2:\n #snip: print out current state\n while break_level < 1:\n ok = get_input(\"Is this ok? (y/n)\")\n if ok == \"y\" or ok == \"Y\": break_level = 2 # break 2 level\n if ok == \"n\" or ok == \"N\": break_level = 1 # break 1 level\n</code></pre>\n"
},
{
"answer_id": 40917562,
"author": "Peeyush Kushwaha",
"author_id": 1412255,
"author_profile": "https://Stackoverflow.com/users/1412255",
"pm_score": 2,
"selected": false,
"text": "<p>Another way of reducing your iteration to a single-level loop would be via the use of generators as also specified in the <a href=\"https://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"nofollow noreferrer\">python reference</a></p>\n\n<pre><code>for i, j in ((i, j) for i in A for j in B):\n print(i , j)\n if (some_condition):\n break\n</code></pre>\n\n<p>You could scale it up to any number of levels for the loop</p>\n\n<p>The downside is that you can no longer break only a single level. It's all or nothing.</p>\n\n<p>Another downside is that it doesn't work with a while loop. I originally wanted to post this answer on <a href=\"https://stackoverflow.com/questions/21293336/python-break-out-of-all-loops\">Python - `break` out of all loops</a> but unfortunately that's closed as a duplicate of this one </p>\n"
},
{
"answer_id": 42946779,
"author": "helmsdeep",
"author_id": 4120359,
"author_profile": "https://Stackoverflow.com/users/4120359",
"pm_score": 1,
"selected": false,
"text": "<p>You can define a variable( for example <em>break_statement</em> ), then change it to a different value when two-break condition occurs and use it in if statement to break from second loop also. </p>\n\n<pre><code>while True:\n break_statement=0\n while True:\n ok = raw_input(\"Is this ok? (y/n)\")\n if ok == \"n\" or ok == \"N\": \n break\n if ok == \"y\" or ok == \"Y\": \n break_statement=1\n break\n if break_statement==1:\n break\n</code></pre>\n"
},
{
"answer_id": 44517453,
"author": "user",
"author_id": 3075942,
"author_profile": "https://Stackoverflow.com/users/3075942",
"pm_score": 2,
"selected": false,
"text": "<p>I'd like to remind you that functions in Python can be created right in the middle of the code and can access the surrounding variables transparently for reading and with <code>nonlocal</code> or <code>global</code> declaration for writing.</p>\n\n<p>So you can use a function as a \"breakable control structure\", defining a place you want to return to:</p>\n\n<pre><code>def is_prime(number):\n\n foo = bar = number\n\n def return_here():\n nonlocal foo, bar\n init_bar = bar\n while foo > 0:\n bar = init_bar\n while bar >= foo:\n if foo*bar == number:\n return\n bar -= 1\n foo -= 1\n\n return_here()\n\n if foo == 1:\n print(number, 'is prime')\n else:\n print(number, '=', bar, '*', foo)\n</code></pre>\n\n<hr>\n\n<pre><code>>>> is_prime(67)\n67 is prime\n>>> is_prime(117)\n117 = 13 * 9\n>>> is_prime(16)\n16 = 4 * 4\n</code></pre>\n"
},
{
"answer_id": 45328126,
"author": "Daniel L.",
"author_id": 7108248,
"author_profile": "https://Stackoverflow.com/users/7108248",
"pm_score": -1,
"selected": false,
"text": "<p>Hopefully this helps:</p>\n\n<pre><code>x = True\ny = True\nwhile x == True:\n while y == True:\n ok = get_input(\"Is this ok? (y/n)\") \n if ok == \"y\" or ok == \"Y\":\n x,y = False,False #breaks from both loops\n if ok == \"n\" or ok == \"N\": \n break #breaks from just one\n</code></pre>\n"
},
{
"answer_id": 46889357,
"author": "Prasad",
"author_id": 1190882,
"author_profile": "https://Stackoverflow.com/users/1190882",
"pm_score": -1,
"selected": false,
"text": "<p>Since this question has become a standard question for breaking into a particular loop, I would like to give my answer with example using <code>Exception</code>. </p>\n\n<p>Although there exists no label named breaking of loop in multipally looped construct, we can make use of <a href=\"https://docs.python.org/3/tutorial/errors.html#user-defined-exceptions\" rel=\"nofollow noreferrer\">User-defined Exceptions</a> to break into a particular loop of our choice. Consider the following example where let us print all numbers upto 4 digits in base-6 numbering system: </p>\n\n<pre><code>class BreakLoop(Exception):\n def __init__(self, counter):\n Exception.__init__(self, 'Exception 1')\n self.counter = counter\n\nfor counter1 in range(6): # Make it 1000\n try:\n thousand = counter1 * 1000\n for counter2 in range(6): # Make it 100\n try:\n hundred = counter2 * 100\n for counter3 in range(6): # Make it 10\n try:\n ten = counter3 * 10\n for counter4 in range(6):\n try:\n unit = counter4\n value = thousand + hundred + ten + unit\n if unit == 4 :\n raise BreakLoop(4) # Don't break from loop\n if ten == 30: \n raise BreakLoop(3) # Break into loop 3\n if hundred == 500:\n raise BreakLoop(2) # Break into loop 2\n if thousand == 2000:\n raise BreakLoop(1) # Break into loop 1\n\n print('{:04d}'.format(value))\n except BreakLoop as bl:\n if bl.counter != 4:\n raise bl\n except BreakLoop as bl:\n if bl.counter != 3:\n raise bl\n except BreakLoop as bl:\n if bl.counter != 2:\n raise bl\n except BreakLoop as bl:\n pass\n</code></pre>\n\n<p>When we print the output, we will never get any value whose unit place is with 4. In that case, we don't break from any loop as <code>BreakLoop(4)</code> is raised and caught in same loop. Similarly, whenever ten place is having 3, we break into third loop using <code>BreakLoop(3)</code>. Whenever hundred place is having 5, we break into second loop using <code>BreakLoop(2)</code> and whenver the thousand place is having 2, we break into first loop using <code>BreakLoop(1)</code>.</p>\n\n<p>In short, raise your Exception (in-built or user defined) in the inner loops, and catch it in the loop from where you want to resume your control to. If you want to break from all loops, catch the Exception outside all the loops. (I have not shown this case in example).</p>\n"
},
{
"answer_id": 46985239,
"author": "Justas",
"author_id": 407108,
"author_profile": "https://Stackoverflow.com/users/407108",
"pm_score": 5,
"selected": false,
"text": "<p>To break out of multiple nested loops, without refactoring into a function, make use of a \"simulated goto statement\" with the built-in <a href=\"https://docs.python.org/2/library/exceptions.html#exceptions.StopIteration\" rel=\"noreferrer\">StopIteration exception</a>:</p>\n\n<pre><code>try:\n for outer in range(100):\n for inner in range(100):\n if break_early():\n raise StopIteration\n\nexcept StopIteration: pass\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/questions/1257744/can-i-use-break-to-exit-multiple-nested-for-loops\">this discussion</a> on the use of goto statements for breaking out of nested loops.</p>\n"
},
{
"answer_id": 49136435,
"author": "Erico9001",
"author_id": 9211400,
"author_profile": "https://Stackoverflow.com/users/9211400",
"pm_score": -1,
"selected": false,
"text": "<p>The way I solve this is by defining a variable that is referenced to determine if you break to the next level or not. In this example, this variable is called 'shouldbreak'.</p>\n\n<pre><code>Variable_That_Counts_To_Three=1\nwhile 1==1:\n shouldbreak='no'\n Variable_That_Counts_To_Five=0\n while 2==2:\n Variable_That_Counts_To_Five+=1\n print(Variable_That_Counts_To_Five)\n if Variable_That_Counts_To_Five == 5:\n if Variable_That_Counts_To_Three == 3:\n shouldbreak='yes'\n break\n print('Three Counter = ' + str(Variable_That_Counts_To_Three))\n Variable_That_Counts_To_Three+=1\n if shouldbreak == 'yes':\n break\n\nprint('''\nThis breaks out of two loops!''')\n</code></pre>\n\n<p>This gives a lot of control over how exactly you want the program to break, allowing you to choose when you want to break and how many levels to go down.</p>\n"
},
{
"answer_id": 49663931,
"author": "Rafiq",
"author_id": 3600487,
"author_profile": "https://Stackoverflow.com/users/3600487",
"pm_score": 2,
"selected": false,
"text": "<p><strong>By using a function:</strong></p>\n\n<pre><code>def myloop():\n for i in range(1,6,1): # 1st loop\n print('i:',i)\n for j in range(1,11,2): # 2nd loop\n print(' i, j:' ,i, j)\n for k in range(1,21,4): # 3rd loop\n print(' i,j,k:', i,j,k)\n if i%3==0 and j%3==0 and k%3==0:\n return # getting out of all loops\n\nmyloop()\n</code></pre>\n\n<p>Try running the above codes by commenting out the <code>return</code> as well.</p>\n\n<p><strong>Without using any function:</strong></p>\n\n<pre><code>done = False\nfor i in range(1,6,1): # 1st loop\n print('i:', i)\n for j in range(1,11,2): # 2nd loop\n print(' i, j:' ,i, j)\n for k in range(1,21,4): # 3rd loop\n print(' i,j,k:', i,j,k)\n if i%3==0 and j%3==0 and k%3==0:\n done = True\n break # breaking from 3rd loop\n if done: break # breaking from 2nd loop\n if done: break # breaking from 1st loop\n</code></pre>\n\n<p>Now, run the above codes as is first and then try running by commenting out each line containing <code>break</code> one at a time from the bottom.</p>\n"
},
{
"answer_id": 50310192,
"author": "one_observation",
"author_id": 1055658,
"author_profile": "https://Stackoverflow.com/users/1055658",
"pm_score": 2,
"selected": false,
"text": "<p>An easy way to turn multiple loops into a single, breakable loop is to use <code>numpy.ndindex</code></p>\n\n<pre><code>for i in range(n):\n for j in range(n):\n val = x[i, j]\n break # still inside the outer loop!\n\nfor i, j in np.ndindex(n, n):\n val = x[i, j]\n break # you left the only loop there was!\n</code></pre>\n\n<p>You do have to index into your objects, as opposed to being able to iterate through the values explicitly, but at least in simple cases it seems to be approximately 2-20 times simpler than most of the answers suggested.</p>\n"
},
{
"answer_id": 55002089,
"author": "Harun Altay",
"author_id": 6193320,
"author_profile": "https://Stackoverflow.com/users/6193320",
"pm_score": 2,
"selected": false,
"text": "<h1>Solutions in two ways</h1>\n<p>With an example: Are these two matrices equal/same? <br/>\nmatrix1 and matrix2 are the same size, n, two-dimensional matrices.</p>\n<p><strong>First solution</strong>, <em>without a function</em></p>\n<pre><code>same_matrices = True\ninner_loop_broken_once = False\nn = len(matrix1)\n\nfor i in range(n):\n for j in range(n):\n\n if matrix1[i][j] != matrix2[i][j]:\n same_matrices = False\n inner_loop_broken_once = True\n break\n\n if inner_loop_broken_once:\n break\n</code></pre>\n<hr />\n<p><strong>Second solution</strong>, <em>with a function</em></p>\n<p>This is the final solution for my case.</p>\n<pre><code>def are_two_matrices_the_same (matrix1, matrix2):\n n = len(matrix1)\n for i in range(n):\n for j in range(n):\n if matrix1[i][j] != matrix2[i][j]:\n return False\n return True\n</code></pre>\n"
},
{
"answer_id": 61562303,
"author": "Fateh",
"author_id": 11809159,
"author_profile": "https://Stackoverflow.com/users/11809159",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an implementation that seems to work:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>break_ = False\nfor i in range(10):\n if break_:\n break\n for j in range(10):\n if j == 3:\n break_ = True\n break\n else:\n print(i, j)\n</code></pre>\n\n<p>The only draw back is that you have to define <code>break_</code> before the loops.</p>\n"
},
{
"answer_id": 61948529,
"author": "Muhammad Faizan Fareed",
"author_id": 7300865,
"author_profile": "https://Stackoverflow.com/users/7300865",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>There is no way to do this from a language level. Some languages have\n a goto others have a break that takes an argument, python does not.</p>\n \n <p>The best options are:</p>\n \n <ol>\n <li><p>Set a flag which is checked by the outer loop, or set the outer\n loops condition.</p></li>\n <li><p>Put the loop in a function and use return to break out of all the loops at once.</p></li>\n <li><p>Reformulate your logic.</p></li>\n </ol>\n</blockquote>\n\n<p><a href=\"https://www.quora.com/How-do-I-break-out-of-a-specific-inner-or-outer-loop-in-python\" rel=\"noreferrer\">Credit goes to Vivek Nagarajan, Programmer since 1987</a></p>\n\n<hr>\n\n<p><strong>Using Function</strong> </p>\n\n<pre><code>def doMywork(data):\n for i in data:\n for e in i:\n return \n</code></pre>\n\n<p><strong>Using flag</strong></p>\n\n<pre><code>is_break = False\nfor i in data:\n if is_break:\n break # outer loop break\n for e in i:\n is_break = True\n break # inner loop break\n</code></pre>\n"
},
{
"answer_id": 66587485,
"author": "kcEmenike",
"author_id": 8327117,
"author_profile": "https://Stackoverflow.com/users/8327117",
"pm_score": 2,
"selected": false,
"text": "<p>What I would personally do is use a boolean that toggles when I am ready to break out the outer loop. For example</p>\n<pre><code>while True:\n #snip: print out current state\n quit = False\n while True:\n ok = input("Is this ok? (y/n)")\n if ok.lower() == "y":\n quit = True\n break # this should work now :-)\n if ok.lower() == "n":\n quit = True\n break # This should work too :-)\n if quit:\n break\n #do more processing with menus and stuff\n</code></pre>\n"
},
{
"answer_id": 70636271,
"author": "thanos.a",
"author_id": 2110865,
"author_profile": "https://Stackoverflow.com/users/2110865",
"pm_score": 0,
"selected": false,
"text": "<p>Trying to <strong>minimal</strong> changes to the OP's question, I just added a flag before breaking the 1st for loop and check that flag on the outer loop to see if we need to brake once again.</p>\n<pre><code>break_2 = False\nwhile True:\n # Snip: print out current state\n if break_2: break\n while True:\n ok = get_input("Is this ok? (y/n)")\n if ok.lower() == "y": break_2 = True\n if break_2: break\n if ok.lower() == "n": break\n # Do more processing with menus and stuff\n</code></pre>\n"
},
{
"answer_id": 72463676,
"author": "Charlie Clark",
"author_id": 2385133,
"author_profile": "https://Stackoverflow.com/users/2385133",
"pm_score": 0,
"selected": false,
"text": "<p>I came across this recently and, wanting to avoid a duplicate return statement, which can conceal logical errors, looked at @yak's idea. This works well within nested for loops but is not very elegant. An alternative is to check for the condition before the next loop:</p>\n<pre class=\"lang-py prettyprint-override\"><code>b = None\nfor a in range(10):\n if something(a, b): # should never = True if b is None\n break\n for b in range(20):\n pass\n</code></pre>\n<p>This might not work everywhere but is adaptable and, if required, has the advantage of allowing the condition to be duplicated rather than a potential result.</p>\n"
},
{
"answer_id": 72577907,
"author": "Wendel",
"author_id": 2057463,
"author_profile": "https://Stackoverflow.com/users/2057463",
"pm_score": 0,
"selected": false,
"text": "<pre><code>while True:\n # Snip: print out current state\n while True:\n ok = get_input("Is this ok? (y/n)")\n if ok.lower() == "y": \n break_2 = True\n if ok.lower() == "n": \n break\n if break_2:\n break\n</code></pre>\n"
},
{
"answer_id": 74120229,
"author": "Warlax56",
"author_id": 10818367,
"author_profile": "https://Stackoverflow.com/users/10818367",
"pm_score": 0,
"selected": false,
"text": "<p>If you just need to test an edge case inside a complex nest of for loops, you can throw in a <code>1/0</code> to raise an exception. I promise I won't tell anyone. This comes in handy when you quickly want to test a single iteration of a deeply nested for loop, and you don't want to track down a large amount of <code>break</code> statements or comment out a significant amount of code.</p>\n<p>Yes, you could wrap it in a function and use return, but in some contexts that can be infeasibly cumbersome.</p>\n<p>example for entry level programmers:</p>\n<pre><code>for i in first_iter:\n for j in second_iter:\n for k in third_iter:\n print(i_want_to_run_this_once_and_stop_executing(i,j,k))\n 1/0\n code_that_takes_a_long_time()\n expensive_code()\n</code></pre>\n<p>in big jupyter notebook scripts that do some heavy data pre-processing, this is especially handy.</p>\n"
},
{
"answer_id": 74600459,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": -1,
"selected": false,
"text": "<p><code>break</code> for outer and inner <code>while</code> loops:</p>\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n while True:\n print('Breaks inner "while" loop')\n break # Here\n print('Breaks outer "while" loop')\n break # Here\n</code></pre>\n<p>Or, <code>break</code> for outer and inner <code>while</code> loops with <code>if</code> statement:</p>\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n while True:\n if True:\n print('Breaks inner "while" loop')\n break # Here\n print('Breaks outer "while" loop')\n break # Here\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Breaks inner "while" loop\nBreaks outer "while" loop\n</code></pre>\n<p><code>break</code> for outer and inner <code>for</code> loops:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for _ in iter(int, 1):\n for _ in iter(int, 1):\n print('Breaks inner "for" loop')\n break # Here\n print('Breaks outer "for" loop')\n break # Here\n</code></pre>\n<p>Or, <code>break</code> for outer and inner <code>for</code> loops with <code>if</code> statement:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for _ in iter(int, 1):\n for _ in iter(int, 1):\n if True:\n print('Breaks inner "for" loop')\n break # Here\n print('Breaks outer "for" loop')\n break # Here\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Breaks inner "for" loop\nBreaks outer "for" loop\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] |
Given the following code (that doesn't work):
```
while True:
# Snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok.lower() == "y": break 2 # This doesn't work :(
if ok.lower() == "n": break
# Do more processing with menus and stuff
```
Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?
|
My first instinct would be to refactor the nested loop into a function and use `return` to break out.
|
189,680 |
<p>i am looking for opinions if the following problem maybe has a better/different/common solution:</p>
<hr>
<p>I have a database for products which contains the names of the products in english (the default language of this application) and i need translations of the names if available.</p>
<p>Currently i have this setup:</p>
<p>A product table</p>
<pre><code>CREATE TABLE products
(
id serial NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT products_pkey PRIMARY KEY (id)
)
</code></pre>
<p>and a product localization table</p>
<pre><code>CREATE TABLE products_l10n
(
product_id serial NOT NULL,
"language" character(2) NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT products_l10n_pkey PRIMARY KEY (product_id, language),
CONSTRAINT products_l10n_product_id_fkey FOREIGN KEY (product_id)
REFERENCES products (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
)
</code></pre>
<p>and i use the following query to retrieve a list of localized products (german in this case) with fallback to the default english names:</p>
<pre><code>SELECT p.id, COALESCE(pl.name, p.name)
from products p LEFT
JOIN products_l10n pl ON p.id = pl.product_id AND language = 'de';
</code></pre>
<p>The SQL code is in postgres dialect. Data is stored as UTF-8.</p>
|
[
{
"answer_id": 189693,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 4,
"selected": true,
"text": "<p>Looks good to me. The one thing I might change is the way you handle languages: that should probably be a separate table. Thus, you would have:</p>\n\n<pre><code>CREATE TABLE products_l10n\n(\n product_id serial NOT NULL,\n language_id int NOT NULL,\n \"name\" character varying(255) NOT NULL,\n CONSTRAINT products_l10n_pkey PRIMARY KEY (product_id, language),\n CONSTRAINT products_l10n_product_id_fkey FOREIGN KEY (product_id)\n REFERENCES products (id) MATCH SIMPLE\n ON UPDATE CASCADE ON DELETE CASCADE\n CONSTRAINT products_l10n_language_id_fkey FOREIGN KEY (language_id)\n REFERENCES languages (id) MATCH SIMPLE\n ON UPDATE CASCADE ON DELETE CASCADE\n)\n\nCREATE TABLE languages\n)\n id serial not null\n \"language\" character(2) NOT NULL\n)\n</code></pre>\n\n<p>Besides that, I think you've got just about the best possible solution.</p>\n"
},
{
"answer_id": 189715,
"author": "Rob Williams",
"author_id": 26682,
"author_profile": "https://Stackoverflow.com/users/26682",
"pm_score": 0,
"selected": false,
"text": "<p>Looks decent to me.</p>\n\n<p>Obviously you should put the localized name into a Unicode column, which you could opt to put the English default into an ASCII field (assuming the database supports that). It may be best to just do Unicode throughout and \"forget\" about it.</p>\n"
},
{
"answer_id": 189717,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "<p>Looks good - similar to my preferred localization technique - what about wide characters (Japanese)? We always used nvarchar to handle that.</p>\n\n<p>What we actually found, however in our international purchasing operation, was that there was no consistency across international boundaries on products, since the suppliers in each country were different, so we internationalized/localized our interface, but the databases were completely distinct.</p>\n"
},
{
"answer_id": 189763,
"author": "Chris Shaffer",
"author_id": 6744,
"author_profile": "https://Stackoverflow.com/users/6744",
"pm_score": 1,
"selected": false,
"text": "<p>The only variation I can offer is that you may also want to include country/dialect possibility; eg, instead of just English (en), use English US (en-US). That way you can account for variations all the way (eg, British spellings, French Canadian probably has differences from the French spoken in France, etc).</p>\n"
},
{
"answer_id": 193126,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 0,
"selected": false,
"text": "<p>The only complicating factor that others have not mentioned is code sets - will you be able to handle Hebrew, Arabic, Russian, Chinese, Japanese? If everything is Unicode, you only have to worry about GB18030 (Chinese), which is (IIUC) a superset of Unicode.</p>\n"
},
{
"answer_id": 2198106,
"author": "Emmanuel",
"author_id": 265983,
"author_profile": "https://Stackoverflow.com/users/265983",
"pm_score": 0,
"selected": false,
"text": "<p>When dealing with this kind of thing, i use to build a product table containing no name at all, and a product_translation table holding only names (and more, obviously).</p>\n\n<p>Then i end up with this kind of query:</p>\n\n<pre>\nSELECT \n i.id, \n i.price, \n it.label \nFROM \n items i \n LEFT JOIN items_trans it \n ON i.id=it.item_id AND it.lang_id=(\n SELECT lang_id\n FROM items_trans\n WHERE item_id=i.id\n ORDER BY\n (lang_id=1) DESC,\n (lang_id=0) DESC\n LIMIT 1\n )\n</pre>\n\n<p>What do you think ?</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21566/"
] |
i am looking for opinions if the following problem maybe has a better/different/common solution:
---
I have a database for products which contains the names of the products in english (the default language of this application) and i need translations of the names if available.
Currently i have this setup:
A product table
```
CREATE TABLE products
(
id serial NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT products_pkey PRIMARY KEY (id)
)
```
and a product localization table
```
CREATE TABLE products_l10n
(
product_id serial NOT NULL,
"language" character(2) NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT products_l10n_pkey PRIMARY KEY (product_id, language),
CONSTRAINT products_l10n_product_id_fkey FOREIGN KEY (product_id)
REFERENCES products (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
)
```
and i use the following query to retrieve a list of localized products (german in this case) with fallback to the default english names:
```
SELECT p.id, COALESCE(pl.name, p.name)
from products p LEFT
JOIN products_l10n pl ON p.id = pl.product_id AND language = 'de';
```
The SQL code is in postgres dialect. Data is stored as UTF-8.
|
Looks good to me. The one thing I might change is the way you handle languages: that should probably be a separate table. Thus, you would have:
```
CREATE TABLE products_l10n
(
product_id serial NOT NULL,
language_id int NOT NULL,
"name" character varying(255) NOT NULL,
CONSTRAINT products_l10n_pkey PRIMARY KEY (product_id, language),
CONSTRAINT products_l10n_product_id_fkey FOREIGN KEY (product_id)
REFERENCES products (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
CONSTRAINT products_l10n_language_id_fkey FOREIGN KEY (language_id)
REFERENCES languages (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
)
CREATE TABLE languages
)
id serial not null
"language" character(2) NOT NULL
)
```
Besides that, I think you've got just about the best possible solution.
|
189,725 |
<p>During recent discussions at work, someone referred to a trampoline function.</p>
<p>I have read the description at <a href="http://en.wikipedia.org/wiki/Trampoline_(computers)" rel="noreferrer">Wikipedia</a>. It is enough to give a general idea of the functionality, but I would like something a bit more concrete.</p>
<p>Do you have a simple snippet of code that would illustrate a trampoline?</p>
|
[
{
"answer_id": 189749,
"author": "Gerald",
"author_id": 19404,
"author_profile": "https://Stackoverflow.com/users/19404",
"pm_score": 5,
"selected": false,
"text": "<p>I'll give you an example that I used in an anti-cheat patch for an online game.</p>\n\n<p>I needed to be able to scan all files that were being loaded by the game for modification. So the most robust way I found to do this was to use a trampoline for CreateFileA. So when the game was launched I would find the address for CreateFileA using GetProcAddress, then I would modify the first few bytes of the function and insert assembly code that would jump to my own \"trampoline\" function, where I would do some things, and then I would jump back to the next location in CreateFile after my jmp code. To be able to do it reliably is a little trickier than that, but the basic concept is just to hook one function, force it to redirect to another function, and then jump back to the original function.</p>\n\n<p>Edit: Microsoft has a framework for this type of thing that you can look at. Called <a href=\"http://research.microsoft.com/sn/detours/\" rel=\"noreferrer\">Detours</a></p>\n"
},
{
"answer_id": 189818,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 3,
"selected": false,
"text": "<p>Here's an example of nested functions:</p>\n\n<pre><code>#include <stdlib.h>\n#include <string.h>\n/* sort an array, starting at address `base`,\n * containing `nmemb` members, separated by `size`,\n * comparing on the first `nbytes` only. */\nvoid sort_bytes(void *base, size_t nmemb, size_t size, size_t nbytes) {\n int compar(const void *a, const void *b) {\n return memcmp(a, b, nbytes);\n }\n qsort(base, nmemb, size, compar);\n}\n</code></pre>\n\n<p><code>compar</code> can't be an external function, because it uses <code>nbytes</code>, which only exists during the <code>sort_bytes</code> call. On some architectures, a small stub function -- the trampoline -- is generated at runtime, and contains the stack location of the <em>current</em> invocation of <code>sort_bytes</code>. When called, it jumps to the <code>compar</code> code, passing that address.</p>\n\n<p>This mess isn't required on architectures like PowerPC, where the ABI specifies that a function pointer is actually a \"fat pointer\", a structure containing both a pointer to the executable code and another pointer to data. However, on x86, a function pointer is just a pointer.</p>\n"
},
{
"answer_id": 489860,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>There is also the LISP sense of 'trampoline' as described on Wikipedia:</p>\n\n<blockquote>\n <p>Used in some LISP implementations, a\n trampoline is a loop that iteratively\n invokes thunk-returning functions. A\n single trampoline is sufficient to\n express all control transfers of a\n program; a program so expressed is\n trampolined or in \"trampolined style\";\n converting a program to trampolined\n style is trampolining. Trampolined\n functions can be used to implement\n tail recursive function calls in\n stack-oriented languages</p>\n</blockquote>\n\n<p>Let us say we are using Javascript and want to write the naive Fibonacci function in continuation-passing-style. The reason we would do this is not relevant - to port Scheme to JS for instance, or to play with CPS which we have to use anyway to call server-side functions.</p>\n\n<p>So, the first attempt is</p>\n\n<pre><code>function fibcps(n, c) {\n if (n <= 1) {\n c(n);\n } else {\n fibcps(n - 1, function (x) {\n fibcps(n - 2, function (y) {\n c(x + y)\n })\n });\n }\n}\n</code></pre>\n\n<p>But, running this with <code>n = 25</code> in Firefox gives an error 'Too much recursion!'. Now this is exactly the problem (missing tail-call optimization in Javascript) that trampolining solves. Instead of making a (recursive) call to a function, let us <code>return</code> an instruction (thunk) to call that function, to be interpreted in a loop.</p>\n\n<pre><code>function fibt(n, c) {\n function trampoline(x) {\n while (x && x.func) {\n x = x.func.apply(null, x.args);\n }\n }\n\n function fibtramp(n, c) {\n if (n <= 1) {\n return {func: c, args: [n]};\n } else {\n return {\n func: fibtramp,\n args: [n - 1,\n function (x) {\n return {\n func: fibtramp,\n args: [n - 2, function (y) {\n return {func: c, args: [x + y]}\n }]\n }\n }\n ]\n }\n }\n }\n\n trampoline({func: fibtramp, args: [n, c]});\n}\n</code></pre>\n"
},
{
"answer_id": 489892,
"author": "MSN",
"author_id": 6210,
"author_profile": "https://Stackoverflow.com/users/6210",
"pm_score": 0,
"selected": false,
"text": "<p>For C, a trampoline would be a function pointer:</p>\n\n<pre><code>size_t (*trampoline_example)(const char *, const char *);\ntrampoline_example= strcspn;\nsize_t result_1= trampoline_example(\"xyzbxz\", \"abc\");\n\ntrampoline_example= strspn;\nsize_t result_2= trampoline_example(\"xyzbxz\", \"abc\");\n</code></pre>\n\n<p>Edit: More esoteric trampolines would be implicitly generated by the compiler. One such use would be a jump table. (Although there are clearly more complicated ones the farther down you start attempting to generate complicated code.)</p>\n"
},
{
"answer_id": 1112003,
"author": "boxofrats",
"author_id": 35591,
"author_profile": "https://Stackoverflow.com/users/35591",
"pm_score": 3,
"selected": false,
"text": "<p>I am currently experimenting with ways to implement tail call optimization for a Scheme interpreter, and so at the moment I am trying to figure out whether the trampoline would be feasible for me.</p>\n\n<p>As I understand it, it is basically just a series of function calls performed by a trampoline function. Each function is called a thunk and returns the next step in the computation until the program terminates (empty continuation).</p>\n\n<p>Here is the first piece of code that I wrote to improve my understanding of the trampoline:</p>\n\n<pre><code>#include <stdio.h>\n\ntypedef void *(*CONTINUATION)(int);\n\nvoid trampoline(CONTINUATION cont)\n{\n int counter = 0;\n CONTINUATION currentCont = cont;\n while (currentCont != NULL) {\n currentCont = (CONTINUATION) currentCont(counter);\n counter++;\n }\n printf(\"got off the trampoline - happy happy joy joy !\\n\");\n}\n\nvoid *thunk3(int param)\n{\n printf(\"*boing* last thunk\\n\");\n return NULL;\n}\n\nvoid *thunk2(int param)\n{\n printf(\"*boing* thunk 2\\n\");\n return thunk3;\n}\n\nvoid *thunk1(int param)\n{\n printf(\"*boing* thunk 1\\n\");\n return thunk2;\n}\n\nint main(int argc, char **argv)\n{\n trampoline(thunk1);\n}\n</code></pre>\n\n<p>results in:</p>\n\n<pre><code>meincompi $ ./trampoline \n*boing* thunk 1\n*boing* thunk 2\n*boing* last thunk\ngot off the trampoline - happy happy joy joy !\n</code></pre>\n"
},
{
"answer_id": 11921515,
"author": "Piotr Kukielka",
"author_id": 704905,
"author_profile": "https://Stackoverflow.com/users/704905",
"pm_score": 5,
"selected": false,
"text": "<p>Let me add few examples for factorial function implemented with trampolines, in different languages:</p>\n\n<p>Scala:</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>sealed trait Bounce[A]\ncase class Done[A](result: A) extends Bounce[A]\ncase class Call[A](thunk: () => Bounce[A]) extends Bounce[A]\n\ndef trampoline[A](bounce: Bounce[A]): A = bounce match {\n case Call(thunk) => trampoline(thunk())\n case Done(x) => x\n}\n\ndef factorial(n: Int, product: BigInt): Bounce[BigInt] = {\n if (n <= 2) Done(product)\n else Call(() => factorial(n - 1, n * product))\n}\n\nobject Factorial extends Application {\n println(trampoline(factorial(100000, 1)))\n}\n</code></pre>\n\n<p>Java:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.math.BigInteger;\n\nclass Trampoline<T> \n{\n public T get() { return null; }\n public Trampoline<T> run() { return null; }\n\n T execute() {\n Trampoline<T> trampoline = this;\n\n while (trampoline.get() == null) {\n trampoline = trampoline.run();\n }\n\n return trampoline.get();\n }\n}\n\npublic class Factorial\n{\n public static Trampoline<BigInteger> factorial(final int n, final BigInteger product)\n {\n if(n <= 1) {\n return new Trampoline<BigInteger>() { public BigInteger get() { return product; } };\n } \n else {\n return new Trampoline<BigInteger>() { \n public Trampoline<BigInteger> run() { \n return factorial(n - 1, product.multiply(BigInteger.valueOf(n)));\n } \n };\n }\n }\n\n public static void main( String [ ] args )\n {\n System.out.println(factorial(100000, BigInteger.ONE).execute());\n }\n}\n</code></pre>\n\n<p>C (unlucky without big numbers implementation):</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n\ntypedef struct _trampoline_data {\n void(*callback)(struct _trampoline_data*);\n void* parameters;\n} trampoline_data;\n\nvoid trampoline(trampoline_data* data) {\n while(data->callback != NULL)\n data->callback(data);\n}\n\n//-----------------------------------------\n\ntypedef struct _factorialParameters {\n int n;\n int product;\n} factorialParameters;\n\nvoid factorial(trampoline_data* data) {\n factorialParameters* parameters = (factorialParameters*) data->parameters;\n\n if (parameters->n <= 1) {\n data->callback = NULL;\n }\n else {\n parameters->product *= parameters->n;\n parameters->n--;\n }\n}\n\nint main() {\n factorialParameters params = {5, 1};\n trampoline_data t = {&factorial, &params};\n\n trampoline(&t);\n printf(\"\\n%d\\n\", params.product);\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 33590722,
"author": "thenry",
"author_id": 5538451,
"author_profile": "https://Stackoverflow.com/users/5538451",
"pm_score": -1,
"selected": false,
"text": "<pre><code>typedef void* (*state_type)(void);\nvoid* state1();\nvoid* state2();\nvoid* state1() {\n return state2;\n}\nvoid* state2() {\n return state1;\n}\n// ...\nstate_type state = state1;\nwhile (1) {\n state = state();\n}\n// ...\n</code></pre>\n"
},
{
"answer_id": 58674093,
"author": "RandomProgrammer",
"author_id": 58864,
"author_profile": "https://Stackoverflow.com/users/58864",
"pm_score": 1,
"selected": false,
"text": "<p>Now that C# has <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions\" rel=\"nofollow noreferrer\">Local Functions</a>, the <a href=\"http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata\" rel=\"nofollow noreferrer\">Bowling Game coding kata</a> can be elegantly solved with a trampoline:</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.Linq;\n\nclass Game\n{\n internal static int RollMany(params int[] rs) \n {\n return Trampoline(1, 0, rs.ToList());\n\n int Trampoline(int frame, int rsf, IEnumerable<int> rs) =>\n frame == 11 ? rsf\n : rs.Count() == 0 ? rsf\n : rs.First() == 10 ? Trampoline(frame + 1, rsf + rs.Take(3).Sum(), rs.Skip(1))\n : rs.Take(2).Sum() == 10 ? Trampoline(frame + 1, rsf + rs.Take(3).Sum(), rs.Skip(2))\n : Trampoline(frame + 1, rsf + rs.Take(2).Sum(), rs.Skip(2));\n }\n}\n</code></pre>\n\n<p>The method <code>Game.RollMany</code> is called with a number of rolls: typically 20 rolls if there are no spares or strikes.</p>\n\n<p>The first line immediately calls the trampoline function: <code>return Trampoline(1, 0, rs.ToList());</code>. This local function recursively traverses the rolls array. The local function (the trampoline) allows the traversal to start with two additional values: start with <code>frame</code> 1 and the <code>rsf</code> (result so far) 0.</p>\n\n<p>Within the local function there is ternary operator that handles five cases:</p>\n\n<ul>\n<li>Game ends at frame 11: return the result so far</li>\n<li>Game ends if there are no more rolls: return the result so far</li>\n<li>Strike: calculate the frame score and continue traversal</li>\n<li>Spare: calculate the frame score and continue traversal</li>\n<li>Normal score: calculate the frame score and continue traversal</li>\n</ul>\n\n<p>Continuing the traversal is done by calling the trampoline again, but now with updated values.</p>\n\n<p>For more information, search for: \"<a href=\"https://duckduckgo.com/?q=tail%20recursion%20accumulator&atb=v189-6&ia=web\" rel=\"nofollow noreferrer\">tail recursion accumulator</a>\". Keep in mind that the compiler does not optimize tail recursion. So as elegant as this solution may be, it will likely not be the fasted.</p>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
] |
During recent discussions at work, someone referred to a trampoline function.
I have read the description at [Wikipedia](http://en.wikipedia.org/wiki/Trampoline_(computers)). It is enough to give a general idea of the functionality, but I would like something a bit more concrete.
Do you have a simple snippet of code that would illustrate a trampoline?
|
There is also the LISP sense of 'trampoline' as described on Wikipedia:
>
> Used in some LISP implementations, a
> trampoline is a loop that iteratively
> invokes thunk-returning functions. A
> single trampoline is sufficient to
> express all control transfers of a
> program; a program so expressed is
> trampolined or in "trampolined style";
> converting a program to trampolined
> style is trampolining. Trampolined
> functions can be used to implement
> tail recursive function calls in
> stack-oriented languages
>
>
>
Let us say we are using Javascript and want to write the naive Fibonacci function in continuation-passing-style. The reason we would do this is not relevant - to port Scheme to JS for instance, or to play with CPS which we have to use anyway to call server-side functions.
So, the first attempt is
```
function fibcps(n, c) {
if (n <= 1) {
c(n);
} else {
fibcps(n - 1, function (x) {
fibcps(n - 2, function (y) {
c(x + y)
})
});
}
}
```
But, running this with `n = 25` in Firefox gives an error 'Too much recursion!'. Now this is exactly the problem (missing tail-call optimization in Javascript) that trampolining solves. Instead of making a (recursive) call to a function, let us `return` an instruction (thunk) to call that function, to be interpreted in a loop.
```
function fibt(n, c) {
function trampoline(x) {
while (x && x.func) {
x = x.func.apply(null, x.args);
}
}
function fibtramp(n, c) {
if (n <= 1) {
return {func: c, args: [n]};
} else {
return {
func: fibtramp,
args: [n - 1,
function (x) {
return {
func: fibtramp,
args: [n - 2, function (y) {
return {func: c, args: [x + y]}
}]
}
}
]
}
}
}
trampoline({func: fibtramp, args: [n, c]});
}
```
|
189,751 |
<p>I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like</p>
<pre><code>- url: (.*)/
static_files: static\1/index.html
upload: static/index.html
- url: /
static_dir: static
</code></pre>
<p>with all the static html/jpg files stored under the static directory. The above works for files that exist, but returns a null length file if they don't. The answer is probably to write a python script to return a 404 error, but how do you set things up to serve the static files that exist but run the script for files that don't?</p>
<p>Here is the log from fetching a non-existent file (nosuch.html) on the development application server:</p>
<pre><code>ERROR 2008-11-25 20:08:34,084 dev_appserver.py] Error encountered reading file "/usr/home/ctuffli/www/tufflinet/static/nosuch.html":
[Errno 2] No such file or directory: '/usr/home/ctuffli/www/tufflinet/static/nosuch.html'
INFO 2008-11-25 20:08:34,088 dev_appserver.py] "GET /nosuch.html HTTP/1.1" 404 -
</code></pre>
|
[
{
"answer_id": 189935,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 6,
"selected": true,
"text": "<p>You need to register a catch-all script handler. Append this at the end of your app.yaml:</p>\n\n<pre><code>- url: /.*\n script: main.py\n</code></pre>\n\n<p>In main.py you will need to put this code:</p>\n\n<pre><code>from google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nclass NotFoundPageHandler(webapp.RequestHandler):\n def get(self):\n self.error(404)\n self.response.out.write('<Your 404 error html page>')\n\napplication = webapp.WSGIApplication([('/.*', NotFoundPageHandler)],\n debug=True)\n\ndef main():\n run_wsgi_app(application)\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>Replace <code><Your 404 error html page></code> with something meaningful. Or better use a template, you can read how to do that <a href=\"http://code.google.com/appengine/docs/gettingstarted/templates.html\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Please let me know if you have problems setting this up.</p>\n"
},
{
"answer_id": 855877,
"author": "Zee Spencer",
"author_id": 91163,
"author_profile": "https://Stackoverflow.com/users/91163",
"pm_score": 2,
"selected": false,
"text": "<p>A significantly simpler way to do this without requiring any CPU cycles is to place this handler at the bottom of your app.yaml</p>\n\n<pre><code>- url: /.*\n static_files: views/404.html\n upload: views/404.html\n</code></pre>\n\n<p>This then allows you to place a static 404.html file in your views directory. No need for a python handler. Anything that isn't handled in your app.yaml already will hit that.</p>\n"
},
{
"answer_id": 3722135,
"author": "jonmiddleton",
"author_id": 315908,
"author_profile": "https://Stackoverflow.com/users/315908",
"pm_score": 5,
"selected": false,
"text": "<p>google app engine now has <a href=\"https://cloud.google.com/appengine/docs/python/config/appconfig?csw=1#Python_app_yaml_Custom_error_responses\" rel=\"nofollow noreferrer\">Custom Error Responses</a></p>\n\n<p>so you can now add an error_handlers section to your app.yaml, as in this example:</p>\n\n<pre><code>error_handlers:\n\n- file: default_error.html\n\n- error_code: over_quota\n file: over_quota.html\n</code></pre>\n"
},
{
"answer_id": 4041691,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 2,
"selected": false,
"text": "<p>The dev_appserver is already returning 404 responses for anything that doesn't match the mapping, or does match the mapping but doesn't exist. The 404 response itself has no body, but it's still a 404:</p>\n\n<pre><code>$ wget -O - http://127.0.0.1:8080/foo\n--2010-10-28 10:54:51-- http://127.0.0.1:8080/foo\nConnecting to 127.0.0.1:8080... connected.\nHTTP request sent, awaiting response... 404 \n2010-10-28 10:54:51 ERROR 404: (no description).\n\n$ wget -O - http://127.0.0.1:8080/foo/\n--2010-10-28 10:54:54-- http://127.0.0.1:8080/foo/\nConnecting to 127.0.0.1:8080... connected.\nHTTP request sent, awaiting response... 404 \n2010-10-28 10:54:54 ERROR 404: (no description).\n</code></pre>\n\n<p>If you want to return a more user-friendly error page, follow jonmiddleton's advice and specify a custom 404 page.</p>\n"
},
{
"answer_id": 5160778,
"author": "zahanm",
"author_id": 640185,
"author_profile": "https://Stackoverflow.com/users/640185",
"pm_score": 0,
"selected": false,
"text": "<p>I can't comment on jonmiddleton's answer, but the custom error responses is for App engine specific errors by the look of it.\nI don't see a way to specify a custom 404 page.</p>\n\n<p>Django let's you <a href=\"http://docs.djangoproject.com/en/dev/topics/http/urls/#handler404\" rel=\"nofollow\">specify</a> one though.</p>\n"
},
{
"answer_id": 10861989,
"author": "TeknasVaruas",
"author_id": 1088579,
"author_profile": "https://Stackoverflow.com/users/1088579",
"pm_score": 2,
"selected": false,
"text": "<p>You can create a function to handle your errors for any of the status codes. You're case being 404, define a function like this: </p>\n\n<pre><code>def Handle404(request, response, exception):\n response.out.write(\"Your error message\") \n response.set_status(404)`\n</code></pre>\n\n<p>You can pass anything - HTML / plain-text / templates in the <code>response.out.write</code> function. Now, add the following declaration after your <code>app</code> declaration.</p>\n\n<p><code>app.error_handlers[404] = Handle404</code></p>\n\n<p>This worked for me.</p>\n"
},
{
"answer_id": 17082291,
"author": "JackNova",
"author_id": 298022,
"author_profile": "https://Stackoverflow.com/users/298022",
"pm_score": 0,
"selected": false,
"text": "<p>My approach is to handle both 404 and permanent redirects in a catch all handler that I put as the last one. This is usefull when I redesign and app and rename/substitute urls:</p>\n\n<pre><code>app = webapp2.WSGIApplication([\n ...\n ...\n ('/.*', ErrorsHandler)\n], debug=True)\n\n\nclass ErrorsHandler(webapp2.RequestHandler):\n def get(self):\n p = self.request.path_qs\n if p in ['/index.html', 'resources-that-I-removed']: \n return self.redirect('/and-substituted-with-this', permanent=True)\n else: \n self.error(404)\n template = jinja_environment.get_template('404.html')\n context = {\n 'page_title': '404',\n }\n self.response.out.write(template.render(context))\n</code></pre>\n"
},
{
"answer_id": 22150908,
"author": "Romain",
"author_id": 145997,
"author_profile": "https://Stackoverflow.com/users/145997",
"pm_score": 2,
"selected": false,
"text": "<p><code>webapp2</code> provides the <code>error_handlers</code> dictionary that you can use to serve custom error pages.\nExample below:</p>\n\n<pre><code>def handle_404(request, response, exception):\n logging.warn(str(exception))\n response.set_status(404)\n h = YourAppBaseHandler(request, response)\n h.render_template('notfound')\n\ndef handle_500(request, response, exception):\n logging.error(str(exception))\n response.set_status(500)\n h = YourAppBaseHandler(request, response)\n h.render_template('servererror')\n\napp = webapp2.WSGIApplication([\n webapp2.Route('/', MainHandler, name='home')\n ], debug=True)\napp.error_handlers[404] = handle_404\napp.error_handlers[500] = handle_500\n</code></pre>\n\n<p>More details are available on <code>webapp2</code>'s documentation pages: <a href=\"http://webapp-improved.appspot.com/guide/app.html#error-handlers\" rel=\"nofollow\">http://webapp-improved.appspot.com/guide/app.html#error-handlers</a></p>\n"
},
{
"answer_id": 34583480,
"author": "husayt",
"author_id": 15461,
"author_profile": "https://Stackoverflow.com/users/15461",
"pm_score": 2,
"selected": false,
"text": "<p>I have reviewed all the above given answers and used the following at the end as the most universal 404 solution:</p>\n\n<p>Add this link at the end of <code>app.yaml</code></p>\n\n<pre><code>- url: /(.*) \n script: 404.app\n</code></pre>\n\n<p>and create <code>404.py</code> with the following content</p>\n\n<pre><code>import webapp2\nfrom google.appengine.ext.webapp import template\n\nclass NotFound(webapp2.RequestHandler):\n def get(self):\n self.error(404)\n self.response.out.write(template.render('404.html', {}))\n\napp = webapp2.WSGIApplication([\n ('/.*', NotFound)\n], debug=True)\n</code></pre>\n\n<p>This will display contents of <code>404.html</code> file with 404 error code.</p>\n\n<p>The advantage of this solution is simplicity, correctness of bahaviour and flexibility, as it allows to use a static <code>404.html</code> file as error page content.</p>\n\n<p>I also want to warn against some of the solutions suggested above. </p>\n\n<ul>\n<li><code>Custom Error Responses</code> don not work with 404 error</li>\n<li>Also don't use static files, as they would return 200 instead of 404 error. This can cause a lot of headache ahead.</li>\n</ul>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189751",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26683/"
] |
I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like
```
- url: (.*)/
static_files: static\1/index.html
upload: static/index.html
- url: /
static_dir: static
```
with all the static html/jpg files stored under the static directory. The above works for files that exist, but returns a null length file if they don't. The answer is probably to write a python script to return a 404 error, but how do you set things up to serve the static files that exist but run the script for files that don't?
Here is the log from fetching a non-existent file (nosuch.html) on the development application server:
```
ERROR 2008-11-25 20:08:34,084 dev_appserver.py] Error encountered reading file "/usr/home/ctuffli/www/tufflinet/static/nosuch.html":
[Errno 2] No such file or directory: '/usr/home/ctuffli/www/tufflinet/static/nosuch.html'
INFO 2008-11-25 20:08:34,088 dev_appserver.py] "GET /nosuch.html HTTP/1.1" 404 -
```
|
You need to register a catch-all script handler. Append this at the end of your app.yaml:
```
- url: /.*
script: main.py
```
In main.py you will need to put this code:
```
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
class NotFoundPageHandler(webapp.RequestHandler):
def get(self):
self.error(404)
self.response.out.write('<Your 404 error html page>')
application = webapp.WSGIApplication([('/.*', NotFoundPageHandler)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
```
Replace `<Your 404 error html page>` with something meaningful. Or better use a template, you can read how to do that [here](http://code.google.com/appengine/docs/gettingstarted/templates.html).
Please let me know if you have problems setting this up.
|
189,765 |
<p>I have a query that ran fine on SQL2005 but moving the database to SQL2008 gives me the error from the title.</p>
<p>The code that is the problem is a call to CONTAINS, CONTAINSTABLE or FREETEXT with an empty parameter. However I'm trying to only call or join when there is a value like such</p>
<pre><code>where (@search_term = '' or (FREETEXT(lst.search_text, @search_term)))
</code></pre>
<p>or</p>
<pre><code>left join containstable (listing_search_text, search_text, @search_term) ftb on l.listing_id = ftb.[key]
and len(@search_term) > 0
</code></pre>
<p>However I cannot find any workaround for this to work on SQL2008. Any ideas?</p>
<p>I know I can do dynamic SQL or have a if statement with two different cases (select with FT join, select without FT join. Any better workaround which doesn't require doing this?</p>
|
[
{
"answer_id": 347232,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 6,
"selected": false,
"text": "<p>I found the answer to this today when converting my own database from SQL 2005 to SQL 2008.</p>\n\n<p>Pass <code>\"\"</code> for your search term and change the @search_term = <code>''</code> test to be <code>@search_term = '\"\"'</code>\nSQL server will ignore the double quotes and not throw an error.</p>\n\n<p>For example, the following would actually returns all records in the Users table:</p>\n\n<pre><code>declare @SearchTerm nvarchar(250)\n\nSET @SearchTerm = '\"\"'\n\nselect UserId, U.Description, U.UserName\nfrom dbo.Users U\nWHERE ((@SearchTerm = '\"\"') OR CONTAINS( (U.Description, U.UserName), @SearchTerm))\n</code></pre>\n\n<p>If you are using .Net, you might grab a copy of E. W. Bachtal's FullTextSearch class. His site is very informative: <a href=\"http://ewbi.blogs.com/develops/\" rel=\"noreferrer\">http://ewbi.blogs.com/develops/</a></p>\n"
},
{
"answer_id": 5209595,
"author": "whiplashtony",
"author_id": 477019,
"author_profile": "https://Stackoverflow.com/users/477019",
"pm_score": 4,
"selected": false,
"text": "<p>This solution didn't work for me on SQL 2008. The answer seemed pretty clear and was deemed useful but I would get time outs on a table with 2M records. In fact it locked up a server just running the query in SSMS.</p>\n\n<p>It didn't seem to like the OR in the where clause but I could run the query fine separating the conditions. </p>\n\n<p>I ended up using a UNION successfully as a workaround. </p>\n\n<pre><code>declare @SearchTerm nvarchar(250)\n\nSET @SearchTerm = '\"\"'\n\nselect UserId, U.Description, U.UserName\nfrom dbo.Users U\nWHERE ((@SearchTerm = '\"\"') \n\nUNION \n\nselect UserId, U.Description, U.UserName\nfrom dbo.Users U\nWHERE CONTAINS( (U.Description, U.UserName), @SearchTerm)) \n</code></pre>\n"
},
{
"answer_id": 20503890,
"author": "beachboy301",
"author_id": 3038470,
"author_profile": "https://Stackoverflow.com/users/3038470",
"pm_score": 2,
"selected": false,
"text": "<p>The problem with FTS and the OR operand was fixed in SP2 CU4. The OR condition should run ok without having to UNION if you are on that level or later. We tried a very recent update of SP2 CU8 and FTS works with OR now. Also, searches such as 3.12 which would fail before now work just fine.</p>\n"
},
{
"answer_id": 45588071,
"author": "Abhishek Chandel",
"author_id": 6889690,
"author_profile": "https://Stackoverflow.com/users/6889690",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Just ADD Double quotes.</strong>\nYou can check for empty string and then add double quotes in it.</p>\n\n<pre><code>Set @search_term = case when @search_term = '' then '\"\"' else @Address End\n</code></pre>\n\n<p>Here you go -</p>\n\n<pre><code>where (@search_term = '\"\"' or (FREETEXT(lst.search_text, @search_term)))\n</code></pre>\n"
},
{
"answer_id": 67170285,
"author": "FloverOwe",
"author_id": 6885037,
"author_profile": "https://Stackoverflow.com/users/6885037",
"pm_score": 1,
"selected": false,
"text": "<p>I found that using "a" as the default works if SQL-Server is <a href=\"https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/transform-noise-words-server-configuration-option?view=sql-server-ver15\" rel=\"nofollow noreferrer\">configured to ignore "noise words".</a></p>\n<pre><code>SET @SearchPhrase = coalesce(@SearchPhrase, 'a'); /* replace with 'a' if null parameter */ \nSELECT ... WHERE \n (@SearchPhrase = 'a' OR contains(Search_Text, @SearchPhrase)) \n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6084/"
] |
I have a query that ran fine on SQL2005 but moving the database to SQL2008 gives me the error from the title.
The code that is the problem is a call to CONTAINS, CONTAINSTABLE or FREETEXT with an empty parameter. However I'm trying to only call or join when there is a value like such
```
where (@search_term = '' or (FREETEXT(lst.search_text, @search_term)))
```
or
```
left join containstable (listing_search_text, search_text, @search_term) ftb on l.listing_id = ftb.[key]
and len(@search_term) > 0
```
However I cannot find any workaround for this to work on SQL2008. Any ideas?
I know I can do dynamic SQL or have a if statement with two different cases (select with FT join, select without FT join. Any better workaround which doesn't require doing this?
|
I found the answer to this today when converting my own database from SQL 2005 to SQL 2008.
Pass `""` for your search term and change the @search\_term = `''` test to be `@search_term = '""'`
SQL server will ignore the double quotes and not throw an error.
For example, the following would actually returns all records in the Users table:
```
declare @SearchTerm nvarchar(250)
SET @SearchTerm = '""'
select UserId, U.Description, U.UserName
from dbo.Users U
WHERE ((@SearchTerm = '""') OR CONTAINS( (U.Description, U.UserName), @SearchTerm))
```
If you are using .Net, you might grab a copy of E. W. Bachtal's FullTextSearch class. His site is very informative: <http://ewbi.blogs.com/develops/>
|
189,770 |
<p>How would you go about retrieving the @@IDENTITY value for each row when the SQLDataAdapater.Update is executed on a table?</p>
<p>eg. Is it possible to modify/intercept the InsertCommand, generated by the SQLCommandBuilder, to say add an output parameter, and then retrieve its value in the da.RowUpdated event???</p>
|
[
{
"answer_id": 347232,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 6,
"selected": false,
"text": "<p>I found the answer to this today when converting my own database from SQL 2005 to SQL 2008.</p>\n\n<p>Pass <code>\"\"</code> for your search term and change the @search_term = <code>''</code> test to be <code>@search_term = '\"\"'</code>\nSQL server will ignore the double quotes and not throw an error.</p>\n\n<p>For example, the following would actually returns all records in the Users table:</p>\n\n<pre><code>declare @SearchTerm nvarchar(250)\n\nSET @SearchTerm = '\"\"'\n\nselect UserId, U.Description, U.UserName\nfrom dbo.Users U\nWHERE ((@SearchTerm = '\"\"') OR CONTAINS( (U.Description, U.UserName), @SearchTerm))\n</code></pre>\n\n<p>If you are using .Net, you might grab a copy of E. W. Bachtal's FullTextSearch class. His site is very informative: <a href=\"http://ewbi.blogs.com/develops/\" rel=\"noreferrer\">http://ewbi.blogs.com/develops/</a></p>\n"
},
{
"answer_id": 5209595,
"author": "whiplashtony",
"author_id": 477019,
"author_profile": "https://Stackoverflow.com/users/477019",
"pm_score": 4,
"selected": false,
"text": "<p>This solution didn't work for me on SQL 2008. The answer seemed pretty clear and was deemed useful but I would get time outs on a table with 2M records. In fact it locked up a server just running the query in SSMS.</p>\n\n<p>It didn't seem to like the OR in the where clause but I could run the query fine separating the conditions. </p>\n\n<p>I ended up using a UNION successfully as a workaround. </p>\n\n<pre><code>declare @SearchTerm nvarchar(250)\n\nSET @SearchTerm = '\"\"'\n\nselect UserId, U.Description, U.UserName\nfrom dbo.Users U\nWHERE ((@SearchTerm = '\"\"') \n\nUNION \n\nselect UserId, U.Description, U.UserName\nfrom dbo.Users U\nWHERE CONTAINS( (U.Description, U.UserName), @SearchTerm)) \n</code></pre>\n"
},
{
"answer_id": 20503890,
"author": "beachboy301",
"author_id": 3038470,
"author_profile": "https://Stackoverflow.com/users/3038470",
"pm_score": 2,
"selected": false,
"text": "<p>The problem with FTS and the OR operand was fixed in SP2 CU4. The OR condition should run ok without having to UNION if you are on that level or later. We tried a very recent update of SP2 CU8 and FTS works with OR now. Also, searches such as 3.12 which would fail before now work just fine.</p>\n"
},
{
"answer_id": 45588071,
"author": "Abhishek Chandel",
"author_id": 6889690,
"author_profile": "https://Stackoverflow.com/users/6889690",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Just ADD Double quotes.</strong>\nYou can check for empty string and then add double quotes in it.</p>\n\n<pre><code>Set @search_term = case when @search_term = '' then '\"\"' else @Address End\n</code></pre>\n\n<p>Here you go -</p>\n\n<pre><code>where (@search_term = '\"\"' or (FREETEXT(lst.search_text, @search_term)))\n</code></pre>\n"
},
{
"answer_id": 67170285,
"author": "FloverOwe",
"author_id": 6885037,
"author_profile": "https://Stackoverflow.com/users/6885037",
"pm_score": 1,
"selected": false,
"text": "<p>I found that using "a" as the default works if SQL-Server is <a href=\"https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/transform-noise-words-server-configuration-option?view=sql-server-ver15\" rel=\"nofollow noreferrer\">configured to ignore "noise words".</a></p>\n<pre><code>SET @SearchPhrase = coalesce(@SearchPhrase, 'a'); /* replace with 'a' if null parameter */ \nSELECT ... WHERE \n (@SearchPhrase = 'a' OR contains(Search_Text, @SearchPhrase)) \n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1885/"
] |
How would you go about retrieving the @@IDENTITY value for each row when the SQLDataAdapater.Update is executed on a table?
eg. Is it possible to modify/intercept the InsertCommand, generated by the SQLCommandBuilder, to say add an output parameter, and then retrieve its value in the da.RowUpdated event???
|
I found the answer to this today when converting my own database from SQL 2005 to SQL 2008.
Pass `""` for your search term and change the @search\_term = `''` test to be `@search_term = '""'`
SQL server will ignore the double quotes and not throw an error.
For example, the following would actually returns all records in the Users table:
```
declare @SearchTerm nvarchar(250)
SET @SearchTerm = '""'
select UserId, U.Description, U.UserName
from dbo.Users U
WHERE ((@SearchTerm = '""') OR CONTAINS( (U.Description, U.UserName), @SearchTerm))
```
If you are using .Net, you might grab a copy of E. W. Bachtal's FullTextSearch class. His site is very informative: <http://ewbi.blogs.com/develops/>
|
189,787 |
<p>I have never seen a way to do this nicely, i would be interested in seeing how others do it. Currently i format it like this:</p>
<pre><code>public Booking createVehicleBooking(Long officeId,
Long start,
Long end,
String origin,
String destination,
String purpose,
String requirements,
Integer numberOfPassengers) throws ServiceException {
/*..Code..*/
}
</code></pre>
|
[
{
"answer_id": 189793,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": false,
"text": "<pre><code>public Booking createVehicleBooking(\n Long officeId, \n Long start, \n Long end,\n String origin, \n String destination, \n String purpose, \n String requirements, \n Integer numberOfPassengers)\n\nthrows ServiceException {\n/*..Code..*/\n}\n</code></pre>\n"
},
{
"answer_id": 189834,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 5,
"selected": true,
"text": "<p>A large set of parameters like this is often (but not always) an indicator that you could be using an object to represent the parameter set. This is especially true if either:</p>\n\n<ul>\n<li><p>There are several methods with similar large parameter sets, that can be replaced with a single method taking a parameter object.</p></li>\n<li><p>The method is called <code>create...</code></p></li>\n</ul>\n\n<p>So your above code could become (pardon my C++, I'm a Java developer):</p>\n\n<pre><code>class BuildVehicleBooking {\n Long officeId;\n Long start;\n Long end;\n String origin;\n String destination;\n String purpose; \n String requirements;\n Integer numberOfPassengers;\n\n Booking createVehicleBooking () throws ServiceException { ... }\n}\n</code></pre>\n\n<p>This is the <strong>Builder Pattern</strong>. The advantage of this pattern is that you can build up a complex set of parameters in pieces, including multiple variations on how the parameters relate to each other, and even overwriting parameters as new information becomes available, before finally calling the <code>create</code> method at the end.</p>\n\n<p>Another potential advantage is that you could add a <code>verifyParameters</code> method that checked their consistence before you go as far as <code>creating</code> the final object. This is applicable in cases where creating the object involves non-reversible steps, such as writing to a file or database.</p>\n\n<p>Note that, as with all patterns, this doesn't apply in every case and may not apply in yours. If your code is simple enough then this pattern may be over-engineering it. If the code is getting messy, refactoring into this pattern can be a good way to simplify it.</p>\n"
},
{
"answer_id": 189969,
"author": "Brody",
"author_id": 17131,
"author_profile": "https://Stackoverflow.com/users/17131",
"pm_score": 2,
"selected": false,
"text": "<p>I'be inclined to go about it with several objects instead of just one.</p>\n\n<p>So it becomes</p>\n\n<pre><code>public Booking createVehicleBooking(Long officeId, DateRange dates, TripDetails trip)\n</code></pre>\n\n<p>While DateRange and Trip details contain only the relevant portions of the data. Although arguably the dateRange could be part of the trip while Requirements and Number of Passengers could be remoived from TripDetails and made part of the request.</p>\n\n<p>In fact there are several ways to dice the data but I'd have to say breaking your large list into groups of related parameters and building an object for them will allow a clearer programming style and increase possible reuse.</p>\n\n<p>And remember it is always possible to imbed objects in object thus allowing you to have</p>\n\n<pre><code>public Booking createVehicleBooking(BookingParameters parameters)\n</code></pre>\n\n<p>While BookingParameters Contains TripDetails and DateRange objects as well as the other parameters.</p>\n"
},
{
"answer_id": 30202173,
"author": "miguel",
"author_id": 11015,
"author_profile": "https://Stackoverflow.com/users/11015",
"pm_score": 2,
"selected": false,
"text": "<p>On the calling side I like to simulate named parameters by using comments like this:</p>\n\n<pre><code>booking.createVehicleBooking(\n getOfficeId(), // Long officeId \n startVariable, // Long start \n 42, // Long end\n getOrigin(), // String origin \n \"destination\", // String destination \n \"purpose\", // String purpose \n \"requirements\", // String requirements\n 3 // Integer numberOfPassengers\n);\n</code></pre>\n"
},
{
"answer_id": 38547710,
"author": "Evvo",
"author_id": 973085,
"author_profile": "https://Stackoverflow.com/users/973085",
"pm_score": 1,
"selected": false,
"text": "<p>I like the one param per line approach that you're showing. I find it's very easy to scan it visually and see what's present.</p>\n\n<p>I find that when people use something like Guice you often end up with a large number of params and this makes it easier to read.</p>\n"
},
{
"answer_id": 46275233,
"author": "Rich",
"author_id": 8261,
"author_profile": "https://Stackoverflow.com/users/8261",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"https://google.github.io/styleguide/javaguide.html\" rel=\"nofollow noreferrer\">Google Java Style Guide</a> does not address this directly, but I agree with how they've formatted things in Guava, i.e.</p>\n\n<p>In <a href=\"https://github.com/google/guava/blob/3a053c298ce800315a92365fbc8f62a08babc09d/guava/src/com/google/common/collect/Collections2.java#L268\" rel=\"nofollow noreferrer\">com.google.common.collect.Collections2.transform</a>:</p>\n\n<pre><code>public static <F, T> Collection<T> transform(\n Collection<F> fromCollection, Function<? super F, T> function) {\n return new TransformedCollection<>(fromCollection, function);\n}\n</code></pre>\n\n<p>In <a href=\"https://github.com/google/guava/blob/3a053c298ce800315a92365fbc8f62a08babc09d/guava/src/com/google/common/collect/ImmutableRangeMap.java#L56\" rel=\"nofollow noreferrer\">com.google.common.collect.ImmutableRangeMap.toImmutableRangeMap</a></p>\n\n<pre><code>public static <T, K extends Comparable<? super K>, V>\n Collector<T, ?, ImmutableRangeMap<K, V>> toImmutableRangeMap(\n Function<? super T, Range<K>> keyFunction,\n Function<? super T, ? extends V> valueFunction) {\n return CollectCollectors.toImmutableRangeMap(keyFunction, valueFunction);\n}\n</code></pre>\n\n<p>I think the rules are:</p>\n\n<ul>\n<li>(Try to keep it on one line if possible)</li>\n<li>Break after the method name and brace</li>\n<li>Indent the parameters one extra level to distinguish them from the body</li>\n</ul>\n\n<p>Personally, I prefer to break after each parameter if I have to break at all, i.e.</p>\n\n<pre><code>public static Foo makeFoo(\n Foo foo,\n Bar bar,\n Baz baz)\n throws FooException {\n f();\n}\n</code></pre>\n"
}
] |
2008/10/10
|
[
"https://Stackoverflow.com/questions/189787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24390/"
] |
I have never seen a way to do this nicely, i would be interested in seeing how others do it. Currently i format it like this:
```
public Booking createVehicleBooking(Long officeId,
Long start,
Long end,
String origin,
String destination,
String purpose,
String requirements,
Integer numberOfPassengers) throws ServiceException {
/*..Code..*/
}
```
|
A large set of parameters like this is often (but not always) an indicator that you could be using an object to represent the parameter set. This is especially true if either:
* There are several methods with similar large parameter sets, that can be replaced with a single method taking a parameter object.
* The method is called `create...`
So your above code could become (pardon my C++, I'm a Java developer):
```
class BuildVehicleBooking {
Long officeId;
Long start;
Long end;
String origin;
String destination;
String purpose;
String requirements;
Integer numberOfPassengers;
Booking createVehicleBooking () throws ServiceException { ... }
}
```
This is the **Builder Pattern**. The advantage of this pattern is that you can build up a complex set of parameters in pieces, including multiple variations on how the parameters relate to each other, and even overwriting parameters as new information becomes available, before finally calling the `create` method at the end.
Another potential advantage is that you could add a `verifyParameters` method that checked their consistence before you go as far as `creating` the final object. This is applicable in cases where creating the object involves non-reversible steps, such as writing to a file or database.
Note that, as with all patterns, this doesn't apply in every case and may not apply in yours. If your code is simple enough then this pattern may be over-engineering it. If the code is getting messy, refactoring into this pattern can be a good way to simplify it.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.