qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
54,546 | <p>Assemblies A and B are privately deployed and strongly named. Assembly A contains references to Assembly B. There are two versions of Assembly B: B1 and B2. I want to be able to indicate for Assembly A that it may bind to either B1 or B2 -- ideally, by incorporating this information into the assembly itself. What are my options?</p>
<p>I'm somewhat familiar with versioning policy and the way it applies to the GAC, but I don't want to be dependent on these assemblies being in the GAC.</p>
| [
{
"answer_id": 54553,
"author": "Aaron Fischer",
"author_id": 5618,
"author_profile": "https://Stackoverflow.com/users/5618",
"pm_score": 1,
"selected": false,
"text": "<p>You can set version policy in your app.config file. Alternatively you can manually load these assemblies with a call to <code>Assembly.LoadFrom()</code> when this is done assembly version is not considered.</p>\n"
},
{
"answer_id": 55560,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 3,
"selected": true,
"text": "<p>There are several places you can indicate to the .Net Framework that a specific version of a strongly typed library should be preferred over another. These are:</p>\n\n<ul>\n<li>Publisher Policy file</li>\n<li>machine.config file</li>\n<li>app.config file</li>\n</ul>\n\n<p>All these methods utilise the <a href=\"http://msdn.microsoft.com/en-us/library/eftw1fys.aspx\" rel=\"nofollow noreferrer\" title=\".NET Framework General Reference - <bindingRedirect> Element\">\"<bindingRedirect>\"</a> element which can instruct the .Net Framework to bind a version or range of versions of an assembly to a specific version.</p>\n\n<p>Here is a short example of the tag in use to bind all versions of an assembly up until version 2.0 to version 2.5:</p>\n\n<pre><code><assemblyBinding>\n <dependantAssembly>\n <assemblyIdentity name=\"foo\" publicKeyToken=\"00000000000\" culture=\"neutral\" />\n <bindingRedirect oldVersion=\"0.0.0.0 - 2.0.0.0\" newVersion=\"2.5.0.0\" />\n </dependantAssembly>\n</assemblyBinding>\n</code></pre>\n\n<p>There are lots of details so it's best if you read about <a href=\"http://msdn.microsoft.com/en-us/library/7wd6ex19.aspx\" rel=\"nofollow noreferrer\" title=\".NET Framework Developer's Guide - Redirecting Assembly Versions\">Redirecting Assembly Versions on MSDN</a> to decide which method is best for your case.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/533/"
] | Assemblies A and B are privately deployed and strongly named. Assembly A contains references to Assembly B. There are two versions of Assembly B: B1 and B2. I want to be able to indicate for Assembly A that it may bind to either B1 or B2 -- ideally, by incorporating this information into the assembly itself. What are my options?
I'm somewhat familiar with versioning policy and the way it applies to the GAC, but I don't want to be dependent on these assemblies being in the GAC. | There are several places you can indicate to the .Net Framework that a specific version of a strongly typed library should be preferred over another. These are:
* Publisher Policy file
* machine.config file
* app.config file
All these methods utilise the ["<bindingRedirect>"](http://msdn.microsoft.com/en-us/library/eftw1fys.aspx ".NET Framework General Reference - <bindingRedirect> Element") element which can instruct the .Net Framework to bind a version or range of versions of an assembly to a specific version.
Here is a short example of the tag in use to bind all versions of an assembly up until version 2.0 to version 2.5:
```
<assemblyBinding>
<dependantAssembly>
<assemblyIdentity name="foo" publicKeyToken="00000000000" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0 - 2.0.0.0" newVersion="2.5.0.0" />
</dependantAssembly>
</assemblyBinding>
```
There are lots of details so it's best if you read about [Redirecting Assembly Versions on MSDN](http://msdn.microsoft.com/en-us/library/7wd6ex19.aspx ".NET Framework Developer's Guide - Redirecting Assembly Versions") to decide which method is best for your case. |
54,566 | <p>So I'm refactoring my code to implement more OOP. I set up a class to hold page attributes.</p>
<pre><code>class PageAtrributes
{
private $db_connection;
private $page_title;
public function __construct($db_connection)
{
$this->db_connection = $db_connection;
$this->page_title = '';
}
public function get_page_title()
{
return $this->page_title;
}
public function set_page_title($page_title)
{
$this->page_title = $page_title;
}
}
</code></pre>
<p>Later on I call the set_page_title() function like so</p>
<pre><code>function page_properties($objPortal) {
$objPage->set_page_title($myrow['title']);
}
</code></pre>
<p>When I do I receive the error message:</p>
<blockquote>
<p>Call to a member function set_page_title() on a non-object</p>
</blockquote>
<p>So what am I missing?</p>
| [
{
"answer_id": 54572,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 7,
"selected": true,
"text": "<p>It means that <code>$objPage</code> is not an instance of an object. Can we see the code you used to initialize the variable?</p>\n\n<p>As you expect a specific object type, you can also make use of <a href=\"http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration\" rel=\"noreferrer\">PHPs type-hinting feature<sup><em>Docs</em></sup></a> to get the error when your logic is violated:</p>\n\n<pre><code>function page_properties(PageAtrributes $objPortal) { \n ...\n $objPage->set_page_title($myrow['title']);\n}\n</code></pre>\n\n<p>This function will only accept <code>PageAtrributes</code> for the first parameter.</p>\n"
},
{
"answer_id": 54580,
"author": "Scott Gottreu",
"author_id": 2863,
"author_profile": "https://Stackoverflow.com/users/2863",
"pm_score": 0,
"selected": false,
"text": "<p>I realized that I wasn't passing <strong>$objPage</strong> into <strong>page_properties()</strong>. It works fine now.</p>\n"
},
{
"answer_id": 9621419,
"author": "Steve Breese",
"author_id": 1257523,
"author_profile": "https://Stackoverflow.com/users/1257523",
"pm_score": 2,
"selected": false,
"text": "<p>I recommend the accepted answer above. If you are in a pinch, however, you could declare the object as a global within the <strong>page_properties</strong> function.</p>\n\n<pre><code>$objPage = new PageAtrributes;\n\nfunction page_properties() {\n global $objPage;\n $objPage->set_page_title($myrow['title']);\n}\n</code></pre>\n"
},
{
"answer_id": 11807579,
"author": "Ahmad",
"author_id": 800816,
"author_profile": "https://Stackoverflow.com/users/800816",
"pm_score": 0,
"selected": false,
"text": "<p>you can use 'use' in function like bellow example</p>\n\n<pre><code>function page_properties($objPortal) use($objPage){ \n $objPage->set_page_title($myrow['title']);\n}\n</code></pre>\n"
},
{
"answer_id": 13055964,
"author": "David Urry",
"author_id": 511554,
"author_profile": "https://Stackoverflow.com/users/511554",
"pm_score": 5,
"selected": false,
"text": "<p>There's an easy way to produce this error:</p>\n\n<pre><code> $joe = null;\n $joe->anything();\n</code></pre>\n\n<p>Will render the error:</p>\n\n<blockquote>\n <p>Fatal error: Call to a member function <code>anything()</code> on a non-object in /Applications/XAMPP/xamppfiles/htdocs/casMail/dao/server.php on line 23</p>\n</blockquote>\n\n<p>It would be a lot better if <strong>PHP</strong> would just say, </p>\n\n<blockquote>\n <p>Fatal error: Call from Joe is not defined because (a) joe is null or (b) joe does not define <code>anything()</code> in on line <##>.</p>\n</blockquote>\n\n<p>Usually you have build your class so that <code>$joe</code> is not defined in the constructor or </p>\n"
},
{
"answer_id": 13668122,
"author": "dipole_moment",
"author_id": 1869326,
"author_profile": "https://Stackoverflow.com/users/1869326",
"pm_score": 3,
"selected": false,
"text": "<p>Either <code>$objPage</code> is not an instance variable OR your are overwriting <code>$objPage</code> with something that is not an instance of class <code>PageAttributes</code>. </p>\n"
},
{
"answer_id": 19642992,
"author": "Gui Lui",
"author_id": 2923742,
"author_profile": "https://Stackoverflow.com/users/2923742",
"pm_score": 2,
"selected": false,
"text": "<p>It could also mean that when you initialized your object, you may have re-used the object name in another part of your code. Therefore changing it's aspect from an object to a standard variable. </p>\n\n<p>IE</p>\n\n<pre><code>$game = new game;\n\n$game->doGameStuff($gameReturn);\n\nforeach($gameArray as $game)\n{\n $game['STUFF']; // No longer an object and is now a standard variable pointer for $game.\n}\n\n\n\n$game->doGameStuff($gameReturn); // Wont work because $game is declared as a standard variable. You need to be careful when using common variable names and were they are declared in your code.\n</code></pre>\n"
},
{
"answer_id": 20092552,
"author": "Falc",
"author_id": 3012422,
"author_profile": "https://Stackoverflow.com/users/3012422",
"pm_score": 2,
"selected": false,
"text": "<pre><code>function page_properties($objPortal) { \n $objPage->set_page_title($myrow['title']);\n}\n</code></pre>\n\n<p>looks like different names of variables $objPortal vs $objPage</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2863/"
] | So I'm refactoring my code to implement more OOP. I set up a class to hold page attributes.
```
class PageAtrributes
{
private $db_connection;
private $page_title;
public function __construct($db_connection)
{
$this->db_connection = $db_connection;
$this->page_title = '';
}
public function get_page_title()
{
return $this->page_title;
}
public function set_page_title($page_title)
{
$this->page_title = $page_title;
}
}
```
Later on I call the set\_page\_title() function like so
```
function page_properties($objPortal) {
$objPage->set_page_title($myrow['title']);
}
```
When I do I receive the error message:
>
> Call to a member function set\_page\_title() on a non-object
>
>
>
So what am I missing? | It means that `$objPage` is not an instance of an object. Can we see the code you used to initialize the variable?
As you expect a specific object type, you can also make use of [PHPs type-hinting feature*Docs*](http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration) to get the error when your logic is violated:
```
function page_properties(PageAtrributes $objPortal) {
...
$objPage->set_page_title($myrow['title']);
}
```
This function will only accept `PageAtrributes` for the first parameter. |
54,567 | <p>I've got an <code>JComboBox</code> with a custom <code>inputVerifyer</code> set to limit MaxLength when it's set to editable.</p>
<p>The verify method never seems to get called.<br>
The same verifyer gets invoked on a <code>JTextField</code> fine.</p>
<p>What might I be doing wrong?</p>
| [
{
"answer_id": 54614,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 1,
"selected": false,
"text": "<p>Show us a small section of your code.</p>\n\n<pre><code>package inputverifier;\n\nimport javax.swing.*;\n\n class Go {\n public static void main(String[] args) {\n java.awt.EventQueue.invokeLater(new Runnable() { public void run() {\n runEDT();\n }});\n }\n private static void runEDT() {\n new JFrame(\"combo thing\") {{\n setLayout(new java.awt.GridLayout(2, 1));\n add(new JComboBox() {{\n setEditable(true);\n setInputVerifier(new InputVerifier() {\n @Override public boolean verify(JComponent input) {\n System.err.println(\"Hi!\");\n return true;\n }\n });\n }});\n add(new JTextField());\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n pack();\n setVisible(true);\n }};\n } \n}\n</code></pre>\n\n<p><a href=\"http://bugs.sun.com\" rel=\"nofollow noreferrer\">Looks like it's a problem with JComboBox being a composite component.</a> I'd suggest avoiding such nasty UI solutions.</p>\n"
},
{
"answer_id": 54799,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 4,
"selected": true,
"text": "<p>I found a workaround. I thought I'd let the next person with this problem know about. </p>\n\n<p>Basically. Instead of setting the inputVerifier on the ComboBox you set it to it's \"Editor Component\". </p>\n\n<pre><code>JComboBox combo = new JComboBox();\nJTextField tf = (JTextField)(combo.getEditor().getEditorComponent());\ntf.setInputVerifier(verifyer);\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] | I've got an `JComboBox` with a custom `inputVerifyer` set to limit MaxLength when it's set to editable.
The verify method never seems to get called.
The same verifyer gets invoked on a `JTextField` fine.
What might I be doing wrong? | I found a workaround. I thought I'd let the next person with this problem know about.
Basically. Instead of setting the inputVerifier on the ComboBox you set it to it's "Editor Component".
```
JComboBox combo = new JComboBox();
JTextField tf = (JTextField)(combo.getEditor().getEditorComponent());
tf.setInputVerifier(verifyer);
``` |
54,578 | <p>How do I capture the output of "%windir%/system32/pnputil.exe -e"?
(assume windows vista 32-bit)</p>
<p>Bonus for technical explanation of why the app normally writes output to the cmd shell, but when stdout and/or stderr are redirected then the app writes nothing to the console or to stdout/stderr?</p>
<pre>
C:\Windows\System32>PnPutil.exe --help
Microsoft PnP Utility {...}
C:\Windows\System32>pnputil -e > c:\foo.txt
C:\Windows\System32>type c:\foo.txt
C:\Windows\System32>dir c:\foo.txt
Volume in drive C has no label.
Volume Serial Number is XXXX-XXXX
Directory of c:\
09/10/2008 12:10 PM 0 foo.txt
1 File(s) 0 bytes
</pre>
| [
{
"answer_id": 54588,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 0,
"selected": false,
"text": "<p>Some applications are written so that it works in piping scenarios well e.g.</p>\n\n<pre><code>svn status | find \"? \"\n</code></pre>\n\n<p>is a command that pipes output of <code>svn status</code> into <code>find \"? \"</code> so it would filter subversion output down to unknown files (marked with a question mark) in my repos.</p>\n\n<p>Imagine if svn status would also output a header that says \"Copyright ? 2009\" That very specific header line would also show up. Which is <em>not</em> what I expect.</p>\n\n<p>So certain tools, like those of Sysinternals' will write any header information <em>only</em> if it is printed directly to the command window, if any kind of redirection is detected, then those header information will not be written as by the reason above.</p>\n\n<p>Header information becomes noise when used in piping/automation scenarios.</p>\n\n<p>I suppose if you can't use <code>></code> to output to a file, its because the tool is hardwired not to do so. You'll need an indirect means to capture it.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 54619,
"author": "JeffJ",
"author_id": 5429,
"author_profile": "https://Stackoverflow.com/users/5429",
"pm_score": 0,
"selected": false,
"text": "<p>As alluded to in the question, but not clearly stated, \"pnputil -e 2> c:\\foo.txt\" does not have the intended result either. This one directs nothing into the file but it does send the output to the console.</p>\n"
},
{
"answer_id": 54662,
"author": "Peter Ritchie",
"author_id": 5620,
"author_profile": "https://Stackoverflow.com/users/5620",
"pm_score": 0,
"selected": false,
"text": "<p>There's only two output streams. If \"> c:\\foo.txt\" doesn't work, and \"2> C:\\foo.txt\" doesn't work then nothing is being output.</p>\n\n<p>You can merge the standard error into the standard output (2>&1) so all output is through standard output:</p>\n\n<p>pnputil -e 1>c:\\foo.txt 2>&1</p>\n\n<p>If that doesn't output anything to foo.txt then pnputil must be detecting redirection and stopping output.</p>\n"
},
{
"answer_id": 54681,
"author": "JeffJ",
"author_id": 5429,
"author_profile": "https://Stackoverflow.com/users/5429",
"pm_score": 1,
"selected": false,
"text": "<p>I think I found the technical answer for why it behaves this way. The MSDN page for WriteConsole says that redirecting standard output to a file causes WriteConsole to fail and that WriteFile should be used instead. The debugger confirms that pnputil.exe does call kernel32!WriteConsoleW and kernel32!WriteConsoleInputW.</p>\n\n<p>Hmm, I should have asked this as two separate questions.</p>\n\n<p>I'm still looking for an answer for how to scrape the output from this command. The accepted answer will be one that answers this part of the question.</p>\n"
},
{
"answer_id": 54862,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": true,
"text": "<p>Doesn't seem like there is an easy way at all. You would have to start hooking the call to WriteConsole and dumping the string buffers. See <a href=\"http://objectmix.com/tcl/366746-autoexpect-under-windows-later-mac-linux.html#post1359780\" rel=\"nofollow noreferrer\">this post</a> for a similar discussion.</p>\n\n<p>Of course, if this is a one off for interactive use then just select all the output from the command window and copy it to the clipboard. (Make sure you cmd window buffer is big enough to store all the output).</p>\n"
},
{
"answer_id": 665987,
"author": "schlenk",
"author_id": 60725,
"author_profile": "https://Stackoverflow.com/users/60725",
"pm_score": 0,
"selected": false,
"text": "<p>You could have tried Expect for Windows to do this kind of things, it would tell the tool that there was a console and hook the WriteConsole calls for you.\n<a href=\"http://docs.activestate.com/activetcl/8.5/expect4win/welcome.html\" rel=\"nofollow noreferrer\">Expect for Windows</a></p>\n"
},
{
"answer_id": 2457336,
"author": "John Weinel",
"author_id": 295063,
"author_profile": "https://Stackoverflow.com/users/295063",
"pm_score": 0,
"selected": false,
"text": "<p>Click on the system menu icon (upper left hand corner->properties->layout)</p>\n\n<p>Change the screen buffer size</p>\n\n<p>cls</p>\n\n<p>pnputil -e</p>\n\n<p>;-P</p>\n"
},
{
"answer_id": 8152245,
"author": "Vardhan",
"author_id": 1049736,
"author_profile": "https://Stackoverflow.com/users/1049736",
"pm_score": 1,
"selected": false,
"text": "<p>If you know the driver name and have the driver,\npnputil.exe -a d:\\pnpdriver*.inf</p>\n\n<p>This gives list of corresponding oemXX.inf for the drivers you are looking.</p>\n"
},
{
"answer_id": 46796987,
"author": "Tim LaGrange",
"author_id": 8791813,
"author_profile": "https://Stackoverflow.com/users/8791813",
"pm_score": 0,
"selected": false,
"text": "<p>So I am looking for the same type of information, and came across this:\n<a href=\"https://sysadminstricks.com/tricks/windows-tricks/cleaning-up-windows-driver-store-folder.html\" rel=\"nofollow noreferrer\">https://sysadminstricks.com/tricks/windows-tricks/cleaning-up-windows-driver-store-folder.html</a>.\nWhile the syntax is wrong, it seems to have done the trick for me (with a little correction):</p>\n\n<pre><code>pnputil.exe -e > c:\\driveroutput.txt\n</code></pre>\n\n<p>When that command is executed, it does <em>not</em> output to the command line, but it does generate <code>driveroutput.txt</code> to the root of <code>C:</code>.\nOpening the text file does, in fact, show that I now have an output of the enumerated OEM drivers on my PC.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5429/"
] | How do I capture the output of "%windir%/system32/pnputil.exe -e"?
(assume windows vista 32-bit)
Bonus for technical explanation of why the app normally writes output to the cmd shell, but when stdout and/or stderr are redirected then the app writes nothing to the console or to stdout/stderr?
```
C:\Windows\System32>PnPutil.exe --help
Microsoft PnP Utility {...}
C:\Windows\System32>pnputil -e > c:\foo.txt
C:\Windows\System32>type c:\foo.txt
C:\Windows\System32>dir c:\foo.txt
Volume in drive C has no label.
Volume Serial Number is XXXX-XXXX
Directory of c:\
09/10/2008 12:10 PM 0 foo.txt
1 File(s) 0 bytes
``` | Doesn't seem like there is an easy way at all. You would have to start hooking the call to WriteConsole and dumping the string buffers. See [this post](http://objectmix.com/tcl/366746-autoexpect-under-windows-later-mac-linux.html#post1359780) for a similar discussion.
Of course, if this is a one off for interactive use then just select all the output from the command window and copy it to the clipboard. (Make sure you cmd window buffer is big enough to store all the output). |
54,579 | <p>Does anyone know of a good example of how to expose a WCF service programatically without the use of a configuration file? I know the service object model is much richer now with WCF, so I know it's possible. I just have not seen an example of how to do so. Conversely, I would like to see how consuming without a configuration file is done as well.</p>
<p>Before anyone asks, I have a very specific need to do this without configuration files. I would normally not recommend such a practice, but as I said, there is a very specific need in this case.</p>
| [
{
"answer_id": 54583,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 3,
"selected": false,
"text": "<p>It is not easy on the server <a href=\"http://blogs.msdn.com/drnick/archive/2006/12/04/overriding-the-default-configuration-file.aspx\" rel=\"nofollow noreferrer\">side</a>..</p>\n\n<p>For client side, you can use <a href=\"http://msdn.microsoft.com/en-us/library/ms734681.aspx\" rel=\"nofollow noreferrer\">ChannelFactory</a></p>\n"
},
{
"answer_id": 56304,
"author": "Paul Lalonde",
"author_id": 5782,
"author_profile": "https://Stackoverflow.com/users/5782",
"pm_score": 2,
"selected": false,
"text": "<p>All WCF configuration can be done programatically. So it's possible to create both servers and clients without a config file. </p>\n\n<p>I recommend the book \"Programming WCF Services\" by Juval Lowy, which contains many examples of programmatic configuration.</p>\n"
},
{
"answer_id": 292810,
"author": "devios1",
"author_id": 238948,
"author_profile": "https://Stackoverflow.com/users/238948",
"pm_score": 8,
"selected": true,
"text": "<p>Consuming a web service without a config file is very simple, as I've discovered. You simply need to create a binding object and address object and pass them either to the constructor of the client proxy or to a generic ChannelFactory instance. You can look at the default app.config to see what settings to use, then create a static helper method somewhere that instantiates your proxy:</p>\n\n<pre><code>internal static MyServiceSoapClient CreateWebServiceInstance() {\n BasicHttpBinding binding = new BasicHttpBinding();\n // I think most (or all) of these are defaults--I just copied them from app.config:\n binding.SendTimeout = TimeSpan.FromMinutes( 1 );\n binding.OpenTimeout = TimeSpan.FromMinutes( 1 );\n binding.CloseTimeout = TimeSpan.FromMinutes( 1 );\n binding.ReceiveTimeout = TimeSpan.FromMinutes( 10 );\n binding.AllowCookies = false;\n binding.BypassProxyOnLocal = false;\n binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;\n binding.MessageEncoding = WSMessageEncoding.Text;\n binding.TextEncoding = System.Text.Encoding.UTF8;\n binding.TransferMode = TransferMode.Buffered;\n binding.UseDefaultWebProxy = true;\n return new MyServiceSoapClient( binding, new EndpointAddress( \"http://www.mysite.com/MyService.asmx\" ) );\n}\n</code></pre>\n"
},
{
"answer_id": 774811,
"author": "Tone",
"author_id": 58523,
"author_profile": "https://Stackoverflow.com/users/58523",
"pm_score": 2,
"selected": false,
"text": "<p>I found the blog post at the link below around this topic very interesting. </p>\n\n<p>One idea I like is that of being able to just pass in a binding or behavior or address XML section from the configuration to the appropriate WCF object and let it handle the assigning of the properties - currently you cannot do this. </p>\n\n<p>Like others on the web I am having issues around needing my WCF implementation to use a different configuration file than that of my hosting application (which is a .NET 2.0 Windows service).</p>\n\n<p><a href=\"http://salvoz.com/blog/2007/12/09/programmatically-setting-wcf-configuration/\" rel=\"nofollow noreferrer\">http://salvoz.com/blog/2007/12/09/programmatically-setting-wcf-configuration/</a></p>\n"
},
{
"answer_id": 774918,
"author": "Steve",
"author_id": 48552,
"author_profile": "https://Stackoverflow.com/users/48552",
"pm_score": 2,
"selected": false,
"text": "<p>It's very easy to do on both the client and the server side. Juval Lowy's book has excellent examples. </p>\n\n<p>As to your comment about the configuration files, I would say that the configuration files are a poor man's second to doing it in code. Configuration files are great when you control every client that will connect to your server and make sure they're updated, and that users can't find them and change anything. I find the WCF configuration file model to be limiting, mildly difficult to design, and a maintenance nightmare. All in all, I think it was a very poor decision by MS to make the configuration files the default way of doing things.</p>\n\n<p>EDIT: One of the things you can't do with the configuration file is to create services with non-default constructors. This leads to static/global variables and singletons and other types of non-sense in WCF.</p>\n"
},
{
"answer_id": 2345064,
"author": "John Wigger",
"author_id": 280648,
"author_profile": "https://Stackoverflow.com/users/280648",
"pm_score": 4,
"selected": false,
"text": "<p>If you are interested in eliminating the usage of the System.ServiceModel section in the web.config for IIS hosting, I have posted an example of how to do that here (<a href=\"http://bejabbers2.blogspot.com/2010/02/wcf-zero-config-in-net-35-part-ii.html\" rel=\"noreferrer\">http://bejabbers2.blogspot.com/2010/02/wcf-zero-config-in-net-35-part-ii.html</a>). I show how to customize a ServiceHost to create both metadata and wshttpbinding endpoints. I do it in a general purpose way that doesn't require additional coding. For those who aren't immediately upgrading to .NET 4.0 this can be pretty convenient.</p>\n"
},
{
"answer_id": 8925111,
"author": "S. M. Khaled Reza",
"author_id": 1158316,
"author_profile": "https://Stackoverflow.com/users/1158316",
"pm_score": 4,
"selected": false,
"text": "<p>Here, this is complete and working code. I think it will help you a lot. I was searching and never finds a complete code that's why I tried to put complete and working code. Good luck.</p>\n\n<pre><code>public class ValidatorClass\n{\n WSHttpBinding BindingConfig;\n EndpointIdentity DNSIdentity;\n Uri URI;\n ContractDescription ConfDescription;\n\n public ValidatorClass()\n { \n // In constructor initializing configuration elements by code\n BindingConfig = ValidatorClass.ConfigBinding();\n DNSIdentity = ValidatorClass.ConfigEndPoint();\n URI = ValidatorClass.ConfigURI();\n ConfDescription = ValidatorClass.ConfigContractDescription();\n }\n\n\n public void MainOperation()\n {\n var Address = new EndpointAddress(URI, DNSIdentity);\n var Client = new EvalServiceClient(BindingConfig, Address);\n Client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;\n Client.Endpoint.Contract = ConfDescription;\n Client.ClientCredentials.UserName.UserName = \"companyUserName\";\n Client.ClientCredentials.UserName.Password = \"companyPassword\";\n Client.Open();\n\n string CatchData = Client.CallServiceMethod();\n\n Client.Close();\n }\n\n\n\n public static WSHttpBinding ConfigBinding()\n {\n // ----- Programmatic definition of the SomeService Binding -----\n var wsHttpBinding = new WSHttpBinding();\n\n wsHttpBinding.Name = \"BindingName\";\n wsHttpBinding.CloseTimeout = TimeSpan.FromMinutes(1);\n wsHttpBinding.OpenTimeout = TimeSpan.FromMinutes(1);\n wsHttpBinding.ReceiveTimeout = TimeSpan.FromMinutes(10);\n wsHttpBinding.SendTimeout = TimeSpan.FromMinutes(1);\n wsHttpBinding.BypassProxyOnLocal = false;\n wsHttpBinding.TransactionFlow = false;\n wsHttpBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;\n wsHttpBinding.MaxBufferPoolSize = 524288;\n wsHttpBinding.MaxReceivedMessageSize = 65536;\n wsHttpBinding.MessageEncoding = WSMessageEncoding.Text;\n wsHttpBinding.TextEncoding = Encoding.UTF8;\n wsHttpBinding.UseDefaultWebProxy = true;\n wsHttpBinding.AllowCookies = false;\n\n wsHttpBinding.ReaderQuotas.MaxDepth = 32;\n wsHttpBinding.ReaderQuotas.MaxArrayLength = 16384;\n wsHttpBinding.ReaderQuotas.MaxStringContentLength = 8192;\n wsHttpBinding.ReaderQuotas.MaxBytesPerRead = 4096;\n wsHttpBinding.ReaderQuotas.MaxNameTableCharCount = 16384;\n\n wsHttpBinding.ReliableSession.Ordered = true;\n wsHttpBinding.ReliableSession.InactivityTimeout = TimeSpan.FromMinutes(10);\n wsHttpBinding.ReliableSession.Enabled = false;\n\n wsHttpBinding.Security.Mode = SecurityMode.Message;\n wsHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;\n wsHttpBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;\n wsHttpBinding.Security.Transport.Realm = \"\";\n\n wsHttpBinding.Security.Message.NegotiateServiceCredential = true;\n wsHttpBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;\n wsHttpBinding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic256;\n // ----------- End Programmatic definition of the SomeServiceServiceBinding --------------\n\n return wsHttpBinding;\n\n }\n\n public static Uri ConfigURI()\n {\n // ----- Programmatic definition of the Service URI configuration -----\n Uri URI = new Uri(\"http://localhost:8732/Design_Time_Addresses/TestWcfServiceLibrary/EvalService/\");\n\n return URI;\n }\n\n public static EndpointIdentity ConfigEndPoint()\n {\n // ----- Programmatic definition of the Service EndPointIdentitiy configuration -----\n EndpointIdentity DNSIdentity = EndpointIdentity.CreateDnsIdentity(\"tempCert\");\n\n return DNSIdentity;\n }\n\n\n public static ContractDescription ConfigContractDescription()\n {\n // ----- Programmatic definition of the Service ContractDescription Binding -----\n ContractDescription Contract = ContractDescription.GetContract(typeof(IEvalService), typeof(EvalServiceClient));\n\n return Contract;\n }\n}\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5469/"
] | Does anyone know of a good example of how to expose a WCF service programatically without the use of a configuration file? I know the service object model is much richer now with WCF, so I know it's possible. I just have not seen an example of how to do so. Conversely, I would like to see how consuming without a configuration file is done as well.
Before anyone asks, I have a very specific need to do this without configuration files. I would normally not recommend such a practice, but as I said, there is a very specific need in this case. | Consuming a web service without a config file is very simple, as I've discovered. You simply need to create a binding object and address object and pass them either to the constructor of the client proxy or to a generic ChannelFactory instance. You can look at the default app.config to see what settings to use, then create a static helper method somewhere that instantiates your proxy:
```
internal static MyServiceSoapClient CreateWebServiceInstance() {
BasicHttpBinding binding = new BasicHttpBinding();
// I think most (or all) of these are defaults--I just copied them from app.config:
binding.SendTimeout = TimeSpan.FromMinutes( 1 );
binding.OpenTimeout = TimeSpan.FromMinutes( 1 );
binding.CloseTimeout = TimeSpan.FromMinutes( 1 );
binding.ReceiveTimeout = TimeSpan.FromMinutes( 10 );
binding.AllowCookies = false;
binding.BypassProxyOnLocal = false;
binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
binding.MessageEncoding = WSMessageEncoding.Text;
binding.TextEncoding = System.Text.Encoding.UTF8;
binding.TransferMode = TransferMode.Buffered;
binding.UseDefaultWebProxy = true;
return new MyServiceSoapClient( binding, new EndpointAddress( "http://www.mysite.com/MyService.asmx" ) );
}
``` |
54,612 | <p>Is there a way to have Linux read ahead when cloning a disk? I use the program named "dd" to clone disks. The last time I did this it seemed as though the OS was reading then writing but never at the same time. Ideally, the destination disk would be constantly writing without waiting that's of course if the source disk can keep up.</p>
<p>UPDATE: I normally choose a large block size when cloning (ex. 16M or 32MB).</p>
| [
{
"answer_id": 54631,
"author": "Thomas Kammeyer",
"author_id": 4410,
"author_profile": "https://Stackoverflow.com/users/4410",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe you can use two processes</p>\n\n<pre><code>dd if=indevfile | dd of=outdevfile\n</code></pre>\n\n<p>I'll assume you can set the other dd options as it suits you.\nThis has some overhead but should allow asynchrony between reading\none disk and writing the other.</p>\n"
},
{
"answer_id": 54639,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 0,
"selected": false,
"text": "<p>Are you sure it isn't doing that at the same time? I would expect the disk caches to make sure it that happens. If not, non-blocking or even asynchronous reads/writes may help,</p>\n"
},
{
"answer_id": 54642,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 3,
"selected": false,
"text": "<p>You might try increasing the block size using the bs argument; by default, I believe dd uses a block size equal to the disk's preferred block size, which will mean many more reads and writes to copy an entire disk. Linux's dd supports human-readable suffixes:</p>\n\n<pre><code>dd if=/dev/sda of=/dev/sdb bs=1M\n</code></pre>\n"
},
{
"answer_id": 54682,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 0,
"selected": false,
"text": "<p>About your update: How big are the caches of your HDs? (specially the writing one). It may be that that is too much and you may need to reduce it to prevent unnecessary blocking.</p>\n"
},
{
"answer_id": 55793,
"author": "John Vasileff",
"author_id": 5076,
"author_profile": "https://Stackoverflow.com/users/5076",
"pm_score": 4,
"selected": true,
"text": "<p>Commodore Jaeger is right about:</p>\n\n<pre><code>dd if=/dev/sda of=/dev/sdb bs=1M\n</code></pre>\n\n<p>Also, adjusting \"readahead\" on the drives usually improves performance. The default may be something like 256, and optimal 1024. Each setup is different, so you would have to run benchmarks to find the best value.</p>\n\n<pre><code># blockdev --getra /dev/sda\n256\n# blockdev --setra 1024 /dev/sda\n# blockdev --getra /dev/sda\n1024\n# blockdev --help\nUsage:\n blockdev -V\n blockdev --report [devices]\n blockdev [-v|-q] commands devices\nAvailable commands:\n --getsz (get size in 512-byte sectors)\n --setro (set read-only)\n --setrw (set read-write)\n --getro (get read-only)\n --getss (get sectorsize)\n --getbsz (get blocksize)\n --setbsz BLOCKSIZE (set blocksize)\n --getsize (get 32-bit sector count)\n --getsize64 (get size in bytes)\n --setra READAHEAD (set readahead)\n --getra (get readahead)\n --flushbufs (flush buffers)\n --rereadpt (reread partition table)\n --rmpart PARTNO (disable partition)\n --rmparts (disable all partitions)\n#\n</code></pre>\n"
},
{
"answer_id": 13249678,
"author": "SteveMenard",
"author_id": 1802853,
"author_profile": "https://Stackoverflow.com/users/1802853",
"pm_score": 3,
"selected": false,
"text": "<p>The fastest for me:</p>\n\n<pre><code>dd if=/dev/sda bs=1M iflag=direct | dd of=/dev/sdb bs=1M oflag=direct\n</code></pre>\n\n<p>reaches ~100MiB/s, whereas other options (single process, no direct, default 512b block size, ...) don't even reach 30MiB/s...</p>\n\n<p>To watch the progress, run in another console:</p>\n\n<pre><code>watch -n 60 killall -USR1 dd\n</code></pre>\n"
},
{
"answer_id": 24758991,
"author": "Paolinux",
"author_id": 1901651,
"author_profile": "https://Stackoverflow.com/users/1901651",
"pm_score": 2,
"selected": false,
"text": "<p>if the two disks use different channel (e.g., SATA) you can use high performance tool like fastDD. The authors claim:</p>\n\n<blockquote>\n <p>\"In this work, we reviewed the problem of reliably and efficiently\n copying data, recalling all the hardware and software mechanisms which\n intervene and interfer in the copying process. Our consideration have\n been coded in fastdd, a C++ program able to copy data very\n efficiently, as we show in our test.\"</p>\n</blockquote>\n\n<p>Moreover the tool keeps a syntax very similar to the old <code>dd</code>.</p>\n\n<p><a href=\"http://www.dei.unipd.it/~zagonico/fastdd/\" rel=\"nofollow\">http://www.dei.unipd.it/~zagonico/fastdd/</a></p>\n\n<p><a href=\"https://github.com/zagonico86/fastdd\" rel=\"nofollow\">https://github.com/zagonico86/fastdd</a></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4778/"
] | Is there a way to have Linux read ahead when cloning a disk? I use the program named "dd" to clone disks. The last time I did this it seemed as though the OS was reading then writing but never at the same time. Ideally, the destination disk would be constantly writing without waiting that's of course if the source disk can keep up.
UPDATE: I normally choose a large block size when cloning (ex. 16M or 32MB). | Commodore Jaeger is right about:
```
dd if=/dev/sda of=/dev/sdb bs=1M
```
Also, adjusting "readahead" on the drives usually improves performance. The default may be something like 256, and optimal 1024. Each setup is different, so you would have to run benchmarks to find the best value.
```
# blockdev --getra /dev/sda
256
# blockdev --setra 1024 /dev/sda
# blockdev --getra /dev/sda
1024
# blockdev --help
Usage:
blockdev -V
blockdev --report [devices]
blockdev [-v|-q] commands devices
Available commands:
--getsz (get size in 512-byte sectors)
--setro (set read-only)
--setrw (set read-write)
--getro (get read-only)
--getss (get sectorsize)
--getbsz (get blocksize)
--setbsz BLOCKSIZE (set blocksize)
--getsize (get 32-bit sector count)
--getsize64 (get size in bytes)
--setra READAHEAD (set readahead)
--getra (get readahead)
--flushbufs (flush buffers)
--rereadpt (reread partition table)
--rmpart PARTNO (disable partition)
--rmparts (disable all partitions)
#
``` |
54,626 | <p>This code is from <em>Prototype.js</em>. I've looked at probably 20 different tutorials, and I can't figure out why this is not working. The response I get is null.</p>
<pre><code>new Ajax.Request(/path/to / xml / file.xml, {
method: "get",
contentType: "application/xml",
onSuccess: function(transport) {
alert(transport.responseXML);
}
});
</code></pre>
<p>If I change the <code>responseXML</code> to <code>responseText</code>, then it alerts to me the XML file as a string. This is not a PHP page serving up XML, but an actual XML file, so I know it is not the response headers.</p>
| [
{
"answer_id": 54637,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 3,
"selected": true,
"text": "<p>If transport.responseXML is null but you have a value for transport.responseText then I believe it's because it's not a valid XML file.</p>\n\n<p><strong>Edit:</strong> I just noticed that in our code here whenever we request an XML file we set the content type to 'text/xml'. I have no idea if that makes a difference or not.</p>\n"
},
{
"answer_id": 12488558,
"author": "riverX",
"author_id": 1682030,
"author_profile": "https://Stackoverflow.com/users/1682030",
"pm_score": 1,
"selected": false,
"text": "<p>Just want to share my afternoon working on the issue with a NULL result for <strong>responseXML</strong> responses. My results were exactly as described in the question: responseText was filled with the XML file, responseXML was NULL. As i was totally sure my file is in valid XML format, the error must be somewhere different.</p>\n\n<p>As mentioned in the <strong>Prototype v1.7</strong> documentation, i set the content type to <strong>\"application/xml\"</strong>. The response sent was constantly \"text/html\", no matter what. </p>\n\n<p>To make it short, the problem i ran into was, that my XML file had the ending <strong>\".gpx\"</strong> as it's a de facto standard for GPS coordinates. The mime-types collection of my local XAMPP Apache installation only foresees the endings \"xml\" and \"xsl\". After adding \"gpx\" and restarting the server the program ran smoothly as it's supposed to be.</p>\n\n<p>In my case, there are three solutions:</p>\n\n<p>1) edit the \"mime.types\" file of Apache. Using an XAMPP installation, you might find it under \"C:\\xampp\\apache\\conf\\mime.types\". Search for the \"application/xml\" record and change as follows:</p>\n\n<pre><code>application/xml xml xsl gpx\n</code></pre>\n\n<p>Don't forget to restart the server!</p>\n\n<p>2) add the mime type in a <strong>.htaccess</strong> of the appropriate folder. Open or create a .htaccess file and add following line:</p>\n\n<pre><code>AddType application/xml xml xsl gpx\n</code></pre>\n\n<p>3) during upload process, change file type to \"xml\" instead of whatever you have</p>\n\n<p>Hope i safe some time to one of you guys.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This code is from *Prototype.js*. I've looked at probably 20 different tutorials, and I can't figure out why this is not working. The response I get is null.
```
new Ajax.Request(/path/to / xml / file.xml, {
method: "get",
contentType: "application/xml",
onSuccess: function(transport) {
alert(transport.responseXML);
}
});
```
If I change the `responseXML` to `responseText`, then it alerts to me the XML file as a string. This is not a PHP page serving up XML, but an actual XML file, so I know it is not the response headers. | If transport.responseXML is null but you have a value for transport.responseText then I believe it's because it's not a valid XML file.
**Edit:** I just noticed that in our code here whenever we request an XML file we set the content type to 'text/xml'. I have no idea if that makes a difference or not. |
54,686 | <p>Does any one know how do I get the current open windows or process of a local machine using Java? </p>
<p>What I'm trying to do is: list the current open task, windows or process open, like in Windows Taskmanager, but using a multi-platform approach - using only Java if it's possible.</p>
| [
{
"answer_id": 54696,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 3,
"selected": false,
"text": "<p>The only way I can think of doing it is by invoking a command line application that does the job for you and then screenscraping the output (like Linux's ps and Window's tasklist). </p>\n\n<p>Unfortunately, that'll mean you'll have to write some parsing routines to read the data from both.</p>\n\n<pre><code>Process proc = Runtime.getRuntime().exec (\"tasklist.exe\");\nInputStream procOutput = proc.getInputStream ();\nif (0 == proc.waitFor ()) {\n // TODO scan the procOutput for your data\n}\n</code></pre>\n"
},
{
"answer_id": 54950,
"author": "ràmäyác",
"author_id": 4358,
"author_profile": "https://Stackoverflow.com/users/4358",
"pm_score": 7,
"selected": false,
"text": "<p>This is another approach to parse the the process list from the command \"<strong>ps -e</strong>\":</p>\n\n<pre><code>try {\n String line;\n Process p = Runtime.getRuntime().exec(\"ps -e\");\n BufferedReader input =\n new BufferedReader(new InputStreamReader(p.getInputStream()));\n while ((line = input.readLine()) != null) {\n System.out.println(line); //<-- Parse data here.\n }\n input.close();\n} catch (Exception err) {\n err.printStackTrace();\n}\n</code></pre>\n\n<p>If you are using Windows, then you should change the line: \"Process p = Runtime.getRun...\" etc... (3rd line), for one that looks like this:</p>\n\n<pre><code>Process p = Runtime.getRuntime().exec\n (System.getenv(\"windir\") +\"\\\\system32\\\\\"+\"tasklist.exe\");\n</code></pre>\n\n<p>Hope the info helps!</p>\n"
},
{
"answer_id": 55002,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 2,
"selected": false,
"text": "<p>There is no platform-neutral way of doing this. In the 1.6 release of Java, a \"<a href=\"http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html\" rel=\"nofollow noreferrer\">Desktop</a>\" class was added the allows portable ways of browsing, editing, mailing, opening, and printing URI's. It is possible this class may someday be extended to support processes, but I doubt it.</p>\n\n<p>If you are only curious in Java processes, you can use the <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/management/ManagementFactory.html\" rel=\"nofollow noreferrer\">java.lang.management</a> api for getting thread/memory information on the JVM.</p>\n"
},
{
"answer_id": 4465630,
"author": "SamWest",
"author_id": 545373,
"author_profile": "https://Stackoverflow.com/users/545373",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://yajsw.sourceforge.net/\" rel=\"noreferrer\">YAJSW</a> (Yet Another Java Service Wrapper) looks like it has JNA-based implementations of its org.rzo.yajsw.os.TaskList interface for win32, linux, bsd and solaris and is under an LGPL license. I haven't tried calling this code directly, but YAJSW works really well when I've used it in the past, so you shouldn't have too many worries.</p>\n"
},
{
"answer_id": 9463010,
"author": "Emmanuel Bourg",
"author_id": 525725,
"author_profile": "https://Stackoverflow.com/users/525725",
"pm_score": 5,
"selected": false,
"text": "<p>On Windows there is an alternative using <a href=\"https://github.com/twall/jna\" rel=\"noreferrer\">JNA</a>:</p>\n\n<pre><code>import com.sun.jna.Native;\nimport com.sun.jna.platform.win32.*;\nimport com.sun.jna.win32.W32APIOptions;\n\npublic class ProcessList {\n\n public static void main(String[] args) {\n WinNT winNT = (WinNT) Native.loadLibrary(WinNT.class, W32APIOptions.UNICODE_OPTIONS);\n\n WinNT.HANDLE snapshot = winNT.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));\n\n Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();\n\n while (winNT.Process32Next(snapshot, processEntry)) {\n System.out.println(processEntry.th32ProcessID + \"\\t\" + Native.toString(processEntry.szExeFile));\n }\n\n winNT.CloseHandle(snapshot);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10638518,
"author": "James Oravec",
"author_id": 1190934,
"author_profile": "https://Stackoverflow.com/users/1190934",
"pm_score": 2,
"selected": false,
"text": "<p>Using code to parse <code>ps aux</code> for linux and <code>tasklist</code> for windows are your best options, until something more general comes along.</p>\n\n<p>For windows, you can reference: <a href=\"http://www.rgagnon.com/javadetails/java-0593.html\" rel=\"nofollow\">http://www.rgagnon.com/javadetails/java-0593.html</a></p>\n\n<p>Linux can pipe the results of <code>ps aux</code> through <code>grep</code> too, which would make processing/searching quick and easy. I'm sure you can find something similar for windows too.</p>\n"
},
{
"answer_id": 16828521,
"author": "Panchotiya Vipul",
"author_id": 2114999,
"author_profile": "https://Stackoverflow.com/users/2114999",
"pm_score": 0,
"selected": false,
"text": "<pre><code>package com.vipul;\n\nimport java.applet.Applet;\nimport java.awt.Checkbox;\nimport java.awt.Choice;\nimport java.awt.Font;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class BatchExecuteService extends Applet {\n public Choice choice;\n\n public void init() \n {\n setFont(new Font(\"Helvetica\", Font.BOLD, 36));\n choice = new Choice();\n }\n\n public static void main(String[] args) {\n BatchExecuteService batchExecuteService = new BatchExecuteService();\n batchExecuteService.run();\n }\n\n List<String> processList = new ArrayList<String>();\n\n public void run() {\n try {\n Runtime runtime = Runtime.getRuntime();\n Process process = runtime.exec(\"D:\\\\server.bat\");\n process.getOutputStream().close();\n InputStream inputStream = process.getInputStream();\n InputStreamReader inputstreamreader = new InputStreamReader(\n inputStream);\n BufferedReader bufferedrReader = new BufferedReader(\n inputstreamreader);\n BufferedReader bufferedrReader1 = new BufferedReader(\n inputstreamreader);\n\n String strLine = \"\";\n String x[]=new String[100];\n int i=0;\n int t=0;\n while ((strLine = bufferedrReader.readLine()) != null) \n {\n // System.out.println(strLine);\n String[] a=strLine.split(\",\");\n x[i++]=a[0];\n }\n // System.out.println(\"Length : \"+i);\n\n for(int j=2;j<i;j++)\n {\n System.out.println(x[j]);\n }\n }\n catch (IOException ioException) \n {\n ioException.printStackTrace();\n }\n\n }\n}\n</code></pre>\n\n<blockquote>\n<pre><code> You can create batch file like \n</code></pre>\n \n <p>TASKLIST /v /FI \"STATUS eq running\" /FO \"CSV\" /FI \"Username eq LHPL002\\soft\" /FI \"MEMUSAGE gt 10000\" /FI \"Windowtitle ne N/A\" /NH</p>\n</blockquote>\n"
},
{
"answer_id": 35390242,
"author": "profesor_falken",
"author_id": 1774614,
"author_profile": "https://Stackoverflow.com/users/1774614",
"pm_score": 3,
"selected": false,
"text": "<p>You can easily retrieve the list of running processes using <a href=\"https://github.com/profesorfalken/jProcesses\" rel=\"nofollow noreferrer\">jProcesses</a></p>\n\n<pre><code>List<ProcessInfo> processesList = JProcesses.getProcessList();\n\nfor (final ProcessInfo processInfo : processesList) {\n System.out.println(\"Process PID: \" + processInfo.getPid());\n System.out.println(\"Process Name: \" + processInfo.getName());\n System.out.println(\"Process Used Time: \" + processInfo.getTime());\n System.out.println(\"Full command: \" + processInfo.getCommand());\n System.out.println(\"------------------\");\n}\n</code></pre>\n"
},
{
"answer_id": 41634959,
"author": "Stepan Yakovenko",
"author_id": 517073,
"author_profile": "https://Stackoverflow.com/users/517073",
"pm_score": 2,
"selected": false,
"text": "<p>For windows I use following:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Process process = new ProcessBuilder(\"tasklist.exe\", \"/fo\", \"csv\", \"/nh\").start();\nnew Thread(() -> {\n Scanner sc = new Scanner(process.getInputStream());\n if (sc.hasNextLine()) sc.nextLine();\n while (sc.hasNextLine()) {\n String line = sc.nextLine();\n String[] parts = line.split(\",\");\n String unq = parts[0].substring(1).replaceFirst(\".$\", \"\");\n String pid = parts[1].substring(1).replaceFirst(\".$\", \"\");\n System.out.println(unq + \" \" + pid);\n }\n}).start();\nprocess.waitFor();\nSystem.out.println(\"Done\");\n</code></pre>\n"
},
{
"answer_id": 45068036,
"author": "Hugues M.",
"author_id": 6730571,
"author_profile": "https://Stackoverflow.com/users/6730571",
"pm_score": 7,
"selected": true,
"text": "<p>Finally, with Java 9+ it is possible with <a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html\" rel=\"noreferrer\"><code>ProcessHandle</code></a>:</p>\n\n<pre><code>public static void main(String[] args) {\n ProcessHandle.allProcesses()\n .forEach(process -> System.out.println(processDetails(process)));\n}\n\nprivate static String processDetails(ProcessHandle process) {\n return String.format(\"%8d %8s %10s %26s %-40s\",\n process.pid(),\n text(process.parent().map(ProcessHandle::pid)),\n text(process.info().user()),\n text(process.info().startInstant()),\n text(process.info().commandLine()));\n}\n\nprivate static String text(Optional<?> optional) {\n return optional.map(Object::toString).orElse(\"-\");\n}\n</code></pre>\n\n<p>Output:\n</p>\n\n<pre><code> 1 - root 2017-11-19T18:01:13.100Z /sbin/init\n ...\n 639 1325 www-data 2018-12-04T06:35:58.680Z /usr/sbin/apache2 -k start\n ...\n23082 11054 huguesm 2018-12-04T10:24:22.100Z /.../java ProcessListDemo\n</code></pre>\n"
},
{
"answer_id": 51379205,
"author": "wax_lyrical",
"author_id": 3987353,
"author_profile": "https://Stackoverflow.com/users/3987353",
"pm_score": 2,
"selected": false,
"text": "<p>This might be useful for apps with a bundled JRE: I scan for the folder name that i'm running the application from: so if you're application is executing from:</p>\n\n<pre><code>C:\\Dev\\build\\SomeJavaApp\\jre-9.0.1\\bin\\javaw.exe\n</code></pre>\n\n<p>then you can find if it's already running in J9, by:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n AtomicBoolean isRunning = new AtomicBoolean(false);\n ProcessHandle.allProcesses()\n .filter(ph -> ph.info().command().isPresent() && ph.info().command().get().contains(\"SomeJavaApp\"))\n .forEach((process) -> {\n isRunning.set(true);\n });\n if (isRunning.get()) System.out.println(\"SomeJavaApp is running already\");\n}\n</code></pre>\n"
},
{
"answer_id": 53966059,
"author": "Dylan Wedman",
"author_id": 10844972,
"author_profile": "https://Stackoverflow.com/users/10844972",
"pm_score": 0,
"selected": false,
"text": "<p>This is my code for a function that gets the tasks and gets their names, also adding them into a list to be accessed from a list. It creates temp files with the data, reads the files and gets the task name with the .exe suffix, and arranges the files to be deleted when the program has exited with System.exit(0), it also hides the processes being used to get the tasks and also java.exe so that the user can't accidentally kill the process that runs the program all together.</p>\n\n<pre><code>private static final DefaultListModel tasks = new DefaultListModel();\n\npublic static void getTasks()\n{\n new Thread()\n {\n @Override\n public void run()\n {\n try \n {\n File batchFile = File.createTempFile(\"batchFile\", \".bat\");\n File logFile = File.createTempFile(\"log\", \".txt\");\n String logFilePath = logFile.getAbsolutePath();\n try (PrintWriter fileCreator = new PrintWriter(batchFile)) \n {\n String[] linesToPrint = {\"@echo off\", \"tasklist.exe >>\" + logFilePath, \"exit\"};\n for(String string:linesToPrint)\n {\n fileCreator.println(string);\n }\n fileCreator.close();\n }\n int task = Runtime.getRuntime().exec(batchFile.getAbsolutePath()).waitFor();\n if(task == 0)\n {\n FileReader fileOpener = new FileReader(logFile);\n try (BufferedReader reader = new BufferedReader(fileOpener))\n {\n String line;\n while(true)\n {\n line = reader.readLine();\n if(line != null)\n {\n if(line.endsWith(\"K\"))\n {\n if(line.contains(\".exe\"))\n {\n int index = line.lastIndexOf(\".exe\", line.length());\n String taskName = line.substring(0, index + 4);\n if(! taskName.equals(\"tasklist.exe\") && ! taskName.equals(\"cmd.exe\") && ! taskName.equals(\"java.exe\"))\n {\n tasks.addElement(taskName);\n }\n }\n }\n }\n else\n {\n reader.close();\n break;\n }\n }\n }\n }\n batchFile.deleteOnExit();\n logFile.deleteOnExit();\n } \n catch (FileNotFoundException ex) \n {\n Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);\n } \n catch (IOException | InterruptedException ex) \n {\n Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);\n }\n catch (NullPointerException ex)\n {\n // This stops errors from being thrown on an empty line\n }\n }\n }.start();\n}\n\npublic static void killTask(String taskName)\n{\n new Thread()\n {\n @Override\n public void run()\n {\n try \n {\n Runtime.getRuntime().exec(\"taskkill.exe /IM \" + taskName);\n } \n catch (IOException ex) \n {\n Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n }.start();\n}\n</code></pre>\n"
},
{
"answer_id": 58663666,
"author": "Nallamachu",
"author_id": 2159525,
"author_profile": "https://Stackoverflow.com/users/2159525",
"pm_score": 2,
"selected": false,
"text": "<p>The below program will be compatible with <strong>Java 9+</strong> version only...</p>\n\n<p>To get the CurrentProcess information,</p>\n\n<pre><code>public class CurrentProcess {\n public static void main(String[] args) {\n ProcessHandle handle = ProcessHandle.current();\n System.out.println(\"Current Running Process Id: \"+handle.pid());\n ProcessHandle.Info info = handle.info();\n System.out.println(\"ProcessHandle.Info : \"+info);\n }\n}\n</code></pre>\n\n<p>For all running processes,</p>\n\n<pre><code>import java.util.List;\nimport java.util.stream.Collectors;\n\npublic class AllProcesses {\n public static void main(String[] args) {\n ProcessHandle.allProcesses().forEach(processHandle -> {\n System.out.println(processHandle.pid()+\" \"+processHandle.info());\n });\n }\n}\n</code></pre>\n"
},
{
"answer_id": 60378892,
"author": "Jijo Joy",
"author_id": 12954467,
"author_profile": "https://Stackoverflow.com/users/12954467",
"pm_score": 2,
"selected": false,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> String line;\r\n Process process = Runtime.getRuntime().exec(\"ps -e\");\r\n process.getOutputStream().close();\r\n BufferedReader input =\r\n new BufferedReader(new InputStreamReader(process.getInputStream()));\r\n while ((line = input.readLine()) != null) {\r\n System.out.println(line); //<-- Parse data here.\r\n }\r\n input.close();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>We have to use <code>process.getOutputStream.close()</code> otherwise it will get locked in while loop.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4358/"
] | Does any one know how do I get the current open windows or process of a local machine using Java?
What I'm trying to do is: list the current open task, windows or process open, like in Windows Taskmanager, but using a multi-platform approach - using only Java if it's possible. | Finally, with Java 9+ it is possible with [`ProcessHandle`](https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html):
```
public static void main(String[] args) {
ProcessHandle.allProcesses()
.forEach(process -> System.out.println(processDetails(process)));
}
private static String processDetails(ProcessHandle process) {
return String.format("%8d %8s %10s %26s %-40s",
process.pid(),
text(process.parent().map(ProcessHandle::pid)),
text(process.info().user()),
text(process.info().startInstant()),
text(process.info().commandLine()));
}
private static String text(Optional<?> optional) {
return optional.map(Object::toString).orElse("-");
}
```
Output:
```
1 - root 2017-11-19T18:01:13.100Z /sbin/init
...
639 1325 www-data 2018-12-04T06:35:58.680Z /usr/sbin/apache2 -k start
...
23082 11054 huguesm 2018-12-04T10:24:22.100Z /.../java ProcessListDemo
``` |
54,708 | <p>This is an ASP.Net 2.0 web app. The Item template looks like this, for reference:</p>
<pre><code><ItemTemplate>
<tr>
<td class="class1" align=center><a href='url'><img src="img.gif"></a></td>
<td class="class1"><%# DataBinder.Eval(Container.DataItem,"field1") %></td>
<td class="class1"><%# DataBinder.Eval(Container.DataItem,"field2") %></td>
<td class="class1"><%# DataBinder.Eval(Container.DataItem,"field3") %></td>
<td class="class1"><%# DataBinder.Eval(Container.DataItem,"field4") %></td>
</tr>
</ItemTemplate>
</code></pre>
<p>Using this in codebehind:</p>
<pre><code>foreach (RepeaterItem item in rptrFollowupSummary.Items)
{
string val = ((DataBoundLiteralControl)item.Controls[0]).Text;
Trace.Write(val);
}
</code></pre>
<p>I produce this:</p>
<pre><code><tr>
<td class="class1" align=center><a href='url'><img src="img.gif"></a></td>
<td class="class1">23</td>
<td class="class1">1/1/2000</td>
<td class="class1">-2</td>
<td class="class1">11</td>
</tr>
</code></pre>
<p>What I need is the data from Field1 and Field4</p>
<p>I can't seem to get at the data the way I would in say a DataList or a GridView, and I can't seem to come up with anything else on Google or quickly leverage this one to do what I want. The only way I can see to get at the data is going to be using a regex to go and get it (Because a man takes what he wants. He takes it all. And I'm a man, aren't I? Aren't I?). </p>
<p>Am I on the right track (not looking for the specific regex to do this; forging that might be a followup question ;) ), or am I missing something?</p>
<hr>
<p>The Repeater in this case is set in stone so I can't switch to something more elegant. Once upon a time I did something similar to what Alison Zhou suggested using DataLists, but it's been some time (2+ years) and I just completely forgot about doing it this way. Yeesh, talk about overlooking something obvious. . .</p>
<p>So I did as Alison suggested and it works fine. I don't think the viewstate is an issue here, even though this repeater can get dozens of rows. I can't really speak to the question if doing it that way versus using the instead (but that seems like a fine solution to me otherwise). Obviously the latter is less of a viewstate footprint, but I'm not experienced enough to say when one approach might be preferrable to another without an extreme example in front of me. Alison, one question: why literals and not labels?</p>
<p>Euro Micelli, I was trying to avoid a return trip to the database. Since I'm still a little green relative to the rest of the development world, I admit I don't necessarily have a good grasp of how many database trips is "just right". There wouldn't be a performance issue here (I know the app's load enough to know this), but I suppose I was trying to avoid it out of habit, since my boss tends to emphasize fewer trips where possible.</p>
| [
{
"answer_id": 54738,
"author": "ern",
"author_id": 5609,
"author_profile": "https://Stackoverflow.com/users/5609",
"pm_score": 2,
"selected": false,
"text": "<p>Since you are working with tabular data, I'd recommend using the GridView control. Then you'll be able to access individual cells.</p>\n\n<p>Otherwise, you can set the td's for Field1 and Field4 to <code>runat=\"server\"</code> and give them ID's. Then in the codebehind, access the <code>InnerText</code> property for each td.</p>\n"
},
{
"answer_id": 54743,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 0,
"selected": false,
"text": "<p>If you can afford a smidge more overhead in the generation, go for DataList and use the DataKeys property, which will save the data fields you need.</p>\n\n<p>You could also use labels in each of your table cells and be able to reference items with e.Item.FindControl(\"LabelID\").</p>\n"
},
{
"answer_id": 54745,
"author": "NakedBrunch",
"author_id": 3742,
"author_profile": "https://Stackoverflow.com/users/3742",
"pm_score": 4,
"selected": true,
"text": "<p>Off the top of my head, you can try something like this:</p>\n\n<pre><code><ItemTemplate>\n <tr>\n <td \"class1\"><asp:Literal ID=\"litField1\" runat=\"server\" Text='<%# Bind(\"Field1\") %>'/></td>\n <td \"class1\"><asp:Literal ID=\"litField2\" runat=\"server\" Text='<%# Bind(\"Field2\") %>'/></td>\n <td \"class1\"><asp:Literal ID=\"litField3\" runat=\"server\" Text='<%# Bind(\"Field3\") %>'/></td>\n <td \"class1\"><asp:Literal ID=\"litField4\" runat=\"server\" Text='<%# Bind(\"Field4\") %>'/></td>\n </tr>\n</ItemTemplate>\n</code></pre>\n\n<p>Then, in your code behind, you can access each Literal control as follows:</p>\n\n<pre><code>foreach (RepeaterItem item in rptrFollowupSummary.Items)\n{ \n Literal lit1 = (Literal)item.FindControl(\"litField1\");\n string value1 = lit1.Text;\n Literal lit4 = (Literal)item.FindControl(\"litField4\");\n string value4 = lit4.Text;\n}\n</code></pre>\n\n<p>This will add to your ViewState but it makes it easy to find your controls.</p>\n"
},
{
"answer_id": 54805,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 0,
"selected": false,
"text": "<p>The <%#DataBinder.Eval(...) %> mechanism is not Data Binding in a \"strict\" sense. It is a one-way technique to put text in specific places in the template.</p>\n\n<p>If you need to get the data back out, you have to either:</p>\n\n<ol>\n<li>Get it from your source data</li>\n<li>Populate the repeater with a different mechanism</li>\n</ol>\n\n<p>Note that the Repeater doesn't save the DataSource between postbacks, You can't just ask it to give you the data later.</p>\n\n<p>The first method is usually easier to work with. Don't assume that it's too expensive to reacquire your data from the source, unless you prove it to yourself by measuring; it's usually pretty fast. The biggest problem with this technique is if the source data can change between calls.</p>\n\n<p>For the second method, a common technique is to use a Literal control. See <a href=\"https://stackoverflow.com/questions/54708/programmatically-accessing-data-in-an-aspnet-20-repeater#54745\">Alison Zhou</a>'s post for an example of how to do it. I usually personally prefer to fill the Literal controls inside of the OnItemDataBound instead</p>\n"
},
{
"answer_id": 54935,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/54708/programmatically-accessing-data-in-an-aspnet-20-repeater#54860\">@peacedog</a>: </p>\n\n<p>Correct; Alison's method is perfectly acceptable.</p>\n\n<p>The trick with the database roundtrips: they are not free, obviously, but web servers tend to be very \"close\" (fast, low-latency connection) to the database, while your users are probably \"far\" (slow, high-latency connection).</p>\n\n<p>Because of that, sending data to/from the browser via cookies, ViewState, hidden fields or any other method can actually be \"worse\" than reading it again from your database. There are also security implications to keep in mind (Can an \"evil\" user fake the data coming back from the browser? Would it matter if they do?).</p>\n\n<p>But quite often it doesn't make any difference in performance. That's why you should do what works more naturally for your particular problem and worry about it only <strong>if</strong> performance starts to be a real-world issue.</p>\n\n<p>Good luck!</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1734/"
] | This is an ASP.Net 2.0 web app. The Item template looks like this, for reference:
```
<ItemTemplate>
<tr>
<td class="class1" align=center><a href='url'><img src="img.gif"></a></td>
<td class="class1"><%# DataBinder.Eval(Container.DataItem,"field1") %></td>
<td class="class1"><%# DataBinder.Eval(Container.DataItem,"field2") %></td>
<td class="class1"><%# DataBinder.Eval(Container.DataItem,"field3") %></td>
<td class="class1"><%# DataBinder.Eval(Container.DataItem,"field4") %></td>
</tr>
</ItemTemplate>
```
Using this in codebehind:
```
foreach (RepeaterItem item in rptrFollowupSummary.Items)
{
string val = ((DataBoundLiteralControl)item.Controls[0]).Text;
Trace.Write(val);
}
```
I produce this:
```
<tr>
<td class="class1" align=center><a href='url'><img src="img.gif"></a></td>
<td class="class1">23</td>
<td class="class1">1/1/2000</td>
<td class="class1">-2</td>
<td class="class1">11</td>
</tr>
```
What I need is the data from Field1 and Field4
I can't seem to get at the data the way I would in say a DataList or a GridView, and I can't seem to come up with anything else on Google or quickly leverage this one to do what I want. The only way I can see to get at the data is going to be using a regex to go and get it (Because a man takes what he wants. He takes it all. And I'm a man, aren't I? Aren't I?).
Am I on the right track (not looking for the specific regex to do this; forging that might be a followup question ;) ), or am I missing something?
---
The Repeater in this case is set in stone so I can't switch to something more elegant. Once upon a time I did something similar to what Alison Zhou suggested using DataLists, but it's been some time (2+ years) and I just completely forgot about doing it this way. Yeesh, talk about overlooking something obvious. . .
So I did as Alison suggested and it works fine. I don't think the viewstate is an issue here, even though this repeater can get dozens of rows. I can't really speak to the question if doing it that way versus using the instead (but that seems like a fine solution to me otherwise). Obviously the latter is less of a viewstate footprint, but I'm not experienced enough to say when one approach might be preferrable to another without an extreme example in front of me. Alison, one question: why literals and not labels?
Euro Micelli, I was trying to avoid a return trip to the database. Since I'm still a little green relative to the rest of the development world, I admit I don't necessarily have a good grasp of how many database trips is "just right". There wouldn't be a performance issue here (I know the app's load enough to know this), but I suppose I was trying to avoid it out of habit, since my boss tends to emphasize fewer trips where possible. | Off the top of my head, you can try something like this:
```
<ItemTemplate>
<tr>
<td "class1"><asp:Literal ID="litField1" runat="server" Text='<%# Bind("Field1") %>'/></td>
<td "class1"><asp:Literal ID="litField2" runat="server" Text='<%# Bind("Field2") %>'/></td>
<td "class1"><asp:Literal ID="litField3" runat="server" Text='<%# Bind("Field3") %>'/></td>
<td "class1"><asp:Literal ID="litField4" runat="server" Text='<%# Bind("Field4") %>'/></td>
</tr>
</ItemTemplate>
```
Then, in your code behind, you can access each Literal control as follows:
```
foreach (RepeaterItem item in rptrFollowupSummary.Items)
{
Literal lit1 = (Literal)item.FindControl("litField1");
string value1 = lit1.Text;
Literal lit4 = (Literal)item.FindControl("litField4");
string value4 = lit4.Text;
}
```
This will add to your ViewState but it makes it easy to find your controls. |
54,709 | <p>Multiple approaches exist to write your unit tests when using Rhino Mocks:</p>
<ul>
<li>The Standard Syntax</li>
<li>Record/Replay Syntax</li>
<li>The Fluent Syntax</li>
</ul>
<p>What is the ideal and most frictionless way?</p>
| [
{
"answer_id": 54819,
"author": "alastairs",
"author_id": 5296,
"author_profile": "https://Stackoverflow.com/users/5296",
"pm_score": 0,
"selected": false,
"text": "<p>Interesting question! My own preference is the for the reflection-based syntax (what I guess you mean by the Standard Syntax). I would argue that this is the most frictionless, as it does not add much extra code: you reference the stubs directly on your interfaces as though they were properly implemented. </p>\n\n<p>I do also quite like the Fluent syntax, although this is quite cumbersome. The Record/Replay syntax is as cumbersome as the Fluent syntax (if not more so, seemingly), but less intuitive (to me at least). I've only used NMock2, so the Record/Replay syntax is a bit alien to me, whilst the Fluent syntax is quite familiar. </p>\n\n<p>However, as <a href=\"https://yellowduckguy.wordpress.com/2007/10/06/rhino-mocks-v3-2-new-syntax/\" rel=\"nofollow noreferrer\">this post</a> suggests, if you prefer separating your expectations from your verifications/assertions, you should opt for the Fluent syntax. It's all a matter of style and personal preference, ultimately :-)</p>\n"
},
{
"answer_id": 54893,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 1,
"selected": false,
"text": "<p>For .NET 2.0, I recommend the record/playback model. We like this because it separates clearly your expectations from your verifications.</p>\n\n<pre><code>using(mocks.Record())\n{\n Expect.Call(foo.Bar());\n}\nusing(mocks.Playback())\n{\n MakeItAllHappen();\n}\n</code></pre>\n\n<p>If you're using .NET 3.5 and C# 3, then I'd recommend the fluent syntax.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | Multiple approaches exist to write your unit tests when using Rhino Mocks:
* The Standard Syntax
* Record/Replay Syntax
* The Fluent Syntax
What is the ideal and most frictionless way? | For .NET 2.0, I recommend the record/playback model. We like this because it separates clearly your expectations from your verifications.
```
using(mocks.Record())
{
Expect.Call(foo.Bar());
}
using(mocks.Playback())
{
MakeItAllHappen();
}
```
If you're using .NET 3.5 and C# 3, then I'd recommend the fluent syntax. |
54,725 | <p>Sending a message from the Unix command line using <code>mail TO_ADDR</code> results in an email from <code>$USER@$HOSTNAME</code>. Is there a way to change the "From:" address inserted by <code>mail</code>?</p>
<p>For the record, I'm using GNU Mailutils 1.1/1.2 on Ubuntu (but I've seen the same behavior with Fedora and RHEL).</p>
<p>[EDIT]</p>
<pre>
$ mail -s Testing chris@example.org
Cc:
From: foo@bar.org
Testing
.
</pre>
<p>yields</p>
<pre>
Subject: Testing
To: <chris@example.org>
X-Mailer: mail (GNU Mailutils 1.1)
Message-Id: <E1KdTJj-00025z-RK@localhost>
From: <chris@localhost>
Date: Wed, 10 Sep 2008 13:17:23 -0400
From: foo@bar.org
Testing
</pre>
<p>The "From: foo@bar.org" line is part of the message body, not part of the header.</p>
| [
{
"answer_id": 54752,
"author": "Thomas Kammeyer",
"author_id": 4410,
"author_profile": "https://Stackoverflow.com/users/4410",
"pm_score": 2,
"selected": false,
"text": "<p>Here are some options:</p>\n\n<ul>\n<li><p>If you have privelige enough, configure sendmail to do rewrites with the generics table</p></li>\n<li><p>Write the entire header yourself (or mail it to yourself, save the entire message with all headers, and re-edit, and send it with rmail from the command line</p></li>\n<li><p>Send directly with sendmail, use the \"-f\" command line flag and don't include your \"From:\" line in your message</p></li>\n</ul>\n\n<p>These aren't all exactly the same, but I'll leave it to you look into it further.</p>\n\n<p>On my portable, I have sendmail authenticating as a client to an outgoing mail server and I use generics to make returning mail come to another account. It works like a charm.\nI aggregate incoming mail with fetchmail.</p>\n"
},
{
"answer_id": 380573,
"author": "cms",
"author_id": 28532,
"author_profile": "https://Stackoverflow.com/users/28532",
"pm_score": 8,
"selected": true,
"text": "<p>In my version of mail ( Debian linux 4.0 ) the following options work for controlling the source / reply addresses</p>\n\n<ul>\n<li>the <strong>-a</strong> switch, for additional headers to apply, supplying a From: header on the command line that will be appended to the outgoing mail header</li>\n<li>the <strong>$REPLYTO</strong> environment variable specifies a Reply-To: header</li>\n</ul>\n\n<p>so the following sequence</p>\n\n<pre><code>export REPLYTO=cms-replies@example.com\nmail -aFrom:cms-sends@example.com -s 'Testing'\n</code></pre>\n\n<p>The result, in my mail clients, is a mail from cms-sends@example.com, which any replies to will default to cms-replies@example.com</p>\n\n<p><em>NB:</em> Mac OS users: you don't have -a , but you do have <strong>$REPLYTO</strong></p>\n\n<p><em>NB(2):</em> CentOS users, many commenters have added that you need to use <code>-r</code> not <code>-a</code></p>\n\n<p><em>NB(3):</em> This answer is at least ten years old(1), please bear that in mind when you're coming in from Google. </p>\n"
},
{
"answer_id": 1353352,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>this worked for me </p>\n\n<pre><code>echo \"hi root\"|mail -rsawrub@testingdomain.org -s'testinggg' root\n</code></pre>\n"
},
{
"answer_id": 2059055,
"author": "Beau",
"author_id": 60371,
"author_profile": "https://Stackoverflow.com/users/60371",
"pm_score": 5,
"selected": false,
"text": "<p>On Centos 5.3 I'm able to do:</p>\n\n<pre><code>mail -s \"Subject\" user@address.com -- -f from@address.com < body\n</code></pre>\n\n<p>The double dash stops mail from parsing the -f argument and passes it along to sendmail itself.</p>\n"
},
{
"answer_id": 4519341,
"author": "ubuntu-fanboy",
"author_id": 552429,
"author_profile": "https://Stackoverflow.com/users/552429",
"pm_score": 5,
"selected": false,
"text": "<p>GNU mailutils's 'mail' command doesn't let you do this (easily at least). But If you install 'heirloom-mailx', its mail command (mailx) has the '-r' option to override the default '$USER@$HOSTNAME' from field.</p>\n\n<pre><code>echo \"Hello there\" | mail -s \"testing\" -r sender@company.com recipient@company.com\n</code></pre>\n\n<p>Works for 'mailx' but not 'mail'.</p>\n\n<pre>\n$ ls -l /usr/bin/mail\nlrwxrwxrwx 1 root root 22 2010-12-23 08:33 /usr/bin/mail -> /etc/alternatives/mail\n$ ls -l /etc/alternatives/mail\nlrwxrwxrwx 1 root root 23 2010-12-23 08:33 /etc/alternatives/mail -> /usr/bin/heirloom-mailx\n</pre>\n"
},
{
"answer_id": 6118894,
"author": "gbla",
"author_id": 768791,
"author_profile": "https://Stackoverflow.com/users/768791",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks BEAU</p>\n\n<pre><code>mail -s \"Subject\" user@address.com -- -f from@address.com\n</code></pre>\n\n<p>I just found this and it works for me. The man pages for mail 8.1 on CentOS 5 doesn't mention this. For <code>-f</code> option, the man page says:</p>\n\n<blockquote>\n <p>-f Read messages from the file named by the file operand instead of the system mailbox. (See also folder.) If no file operand is specified, read messages from mbox instead of the system mailbox.</p>\n</blockquote>\n\n<p>So anyway this is great to find, thanks.</p>\n"
},
{
"answer_id": 6124477,
"author": "Ryan Barong",
"author_id": 769550,
"author_profile": "https://Stackoverflow.com/users/769550",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know if it's the same with other OS, but in OpenBSD, the mail command has this syntax:</p>\n\n<pre><code>mail to-addr ... -sendmail-options ...\n</code></pre>\n\n<p>sendmail has -f option where you indicate the email address for the FROM: field. The following command works for me.</p>\n\n<pre><code>mail recepient@example.com -f from@example.com\n</code></pre>\n"
},
{
"answer_id": 8087751,
"author": "papsy",
"author_id": 1040755,
"author_profile": "https://Stackoverflow.com/users/1040755",
"pm_score": 0,
"selected": false,
"text": "<p>On CentOS 5.5, the easiest way I've found to set the default from domain is to modify the hosts file. If your hosts file contains your WAN/public IP address, simply modify the first hostname listed for it. For example, your hosts file may look like:</p>\n\n<blockquote>\n <p>... <br>\n 11.22.33.44 localhost default-domain <strong>whatever-else.com</strong><br >\n ... <br></p>\n</blockquote>\n\n<p>To make it send from whatever-else.com, simply modify it so that whatever-else.com is listed first, for example:</p>\n\n<blockquote>\n <p>... <br>\n 11.22.33.44 <strong>whatever-else.com</strong> localhost default-domain <br>\n ... <br></p>\n</blockquote>\n\n<p>I can't speak for any other distro (or even version of CentOS) but in my particular case, the above works perfectly. </p>\n"
},
{
"answer_id": 8483239,
"author": "artickl",
"author_id": 1094841,
"author_profile": "https://Stackoverflow.com/users/1094841",
"pm_score": 3,
"selected": false,
"text": "<p>Plus it's good to use <code>-F option</code> to specify Name of sender.</p>\n\n<p>Something like this:</p>\n\n<pre><code>mail -s \"$SUBJECT\" $MAILTO -- -F $MAILFROM -f ${MAILFROM}@somedomain.com\n</code></pre>\n\n<p>Or just look at available options:\n<a href=\"http://www.courier-mta.org/sendmail.html\" rel=\"nofollow noreferrer\">http://www.courier-mta.org/sendmail.html</a></p>\n"
},
{
"answer_id": 11656356,
"author": "MoSs",
"author_id": 1552560,
"author_profile": "https://Stackoverflow.com/users/1552560",
"pm_score": 4,
"selected": false,
"text": "<pre><code>mail -s \"$(echo -e \"This is the subject\\nFrom: Paula <johny@paula.com>\\n\nReply-to: 1232564@yourserver.com\\nContent-Type: text/html\\n\")\" \nmilas.josh@gmail.com < htmlFileMessage.txt\n</code></pre>\n\n<p>the above is my solution....any extra headers can be added just after the from and before the reply to...just make sure you know your headers syntax before adding them....this worked perfectly for me.</p>\n"
},
{
"answer_id": 19007441,
"author": "Alcanzar",
"author_id": 2785358,
"author_profile": "https://Stackoverflow.com/users/2785358",
"pm_score": 3,
"selected": false,
"text": "<p>It's also possible to set both the From name and from address using something like:</p>\n\n<pre><code> echo test | mail -s \"test\" example@example.com -- -F'Some Name<example2@example.com>' -t\n</code></pre>\n\n<p>For some reason passing <code>-F'Some Name'</code> and <code>-fexample2@example.com</code> doesn't work, but passing in the <code>-t</code> to sendmail works and is \"easy\".</p>\n"
},
{
"answer_id": 21856390,
"author": "Céline Aussourd",
"author_id": 2339082,
"author_profile": "https://Stackoverflow.com/users/2339082",
"pm_score": 2,
"selected": false,
"text": "<p>On CentOS this worked for me: </p>\n\n<pre><code>echo \"email body\" | mail -s \"Subject here\" -r from_email_address email_address_to\n</code></pre>\n"
},
{
"answer_id": 24032988,
"author": "keypress",
"author_id": 1961303,
"author_profile": "https://Stackoverflow.com/users/1961303",
"pm_score": -1,
"selected": false,
"text": "<p>The answers provided before didn't work for me on CentOS5. I installed mutt. It has a lot of options. With mutt you do this this way:</p>\n\n<pre><code>export EMAIL=myfrom@example.com\nexport REPLYTO=myreplyto@example.com\nmutt -s Testing chris@example.org\n</code></pre>\n"
},
{
"answer_id": 26114710,
"author": "deepak.prathapani",
"author_id": 2165897,
"author_profile": "https://Stackoverflow.com/users/2165897",
"pm_score": 2,
"selected": false,
"text": "<p>I derived this from all the above answers. Nothing worked for me when I tried each one of them. I did lot of trail and error by combining all the above answers and concluded on this. I am not sure if this works for you but it worked for me on Ununtu 12.04 and RHEL 5.4.</p>\n\n<pre><code>echo \"This is the body of the mail\" | mail -s 'This is the subject' '<receiver-id1@email.com>,<receiver-id2@email.com>' -- -F '<SenderName>' -f '<from-id@email.com>'\n</code></pre>\n\n<p>One can send the mail to any number of people by adding any number of receiver id's and the mail is sent by <strong>SenderName</strong> from <strong>from-id@email.com</strong></p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 28788959,
"author": "jelloir",
"author_id": 837163,
"author_profile": "https://Stackoverflow.com/users/837163",
"pm_score": 2,
"selected": false,
"text": "<p>On Debian 7 I was still unable to correctly set the sender address using answers from this question, (would always be the hostname of the server) but resolved it this way.</p>\n\n<p>Install <strong>heirloom-mailx</strong></p>\n\n<pre><code>apt-get install heirloom-mailx\n</code></pre>\n\n<p>ensure it's the default.</p>\n\n<pre><code>update-alternatives --config mailx\n</code></pre>\n\n<p>Compose a message.</p>\n\n<pre><code>mail -s \"Testing from & replyto\" -r \"sender <sender@example.com>\" -S replyto=\"sender@example.com\" recipient@example.net < <(echo \"Test message\")\n</code></pre>\n"
},
{
"answer_id": 36642906,
"author": "Andrew Backeby",
"author_id": 6208343,
"author_profile": "https://Stackoverflow.com/users/6208343",
"pm_score": 1,
"selected": false,
"text": "<p><code>echo \"body\" | mail -S from=address@foo.com \"Hello\"</code></p>\n\n<p>-S lets you specify lots of string options, by far the easiest way to modify headers and such.</p>\n"
},
{
"answer_id": 38483319,
"author": "J. Ceron",
"author_id": 1797498,
"author_profile": "https://Stackoverflow.com/users/1797498",
"pm_score": 1,
"selected": false,
"text": "<p>echo \"test\" | mailx -r fake@example.com -s 'test' email@example.com </p>\n\n<p>It works in OpenBSD.</p>\n"
},
{
"answer_id": 44888449,
"author": "Stephane",
"author_id": 958373,
"author_profile": "https://Stackoverflow.com/users/958373",
"pm_score": 0,
"selected": false,
"text": "<p>What allowed me to have a custom reply-to address on an <code>Ubuntu 16.04</code> with <code>UTF-8</code> encoding and a file attachment:</p>\n\n<p>Install the mail client:</p>\n\n<pre><code>sudo apt-get install heirloom-mailx\n</code></pre>\n\n<p>Edit the SMTP configuration:</p>\n\n<pre><code>sudo vim /etc/ssmtp/ssmtp.conf\nmailhub=smtp.gmail.com:587\nFromLineOverride=YES\nAuthUser=???@gmail.com\nAuthPass=???\nUseSTARTTLS=YES\n</code></pre>\n\n<p>Send the mail:</p>\n\n<pre><code>sender='send@domain.com'\nrecipient='recipient@domain.com'\nzipfile=\"results/file.zip\"\ntoday=`date +\\%d-\\%m-\\%Y`\nmailSubject='My subject on the '$today\nread -r -d '' mailBody << EOM\nFind attached the zip file.\n\nRegards,\nEOM\nmail -s \"$mailSubject\" -r \"Name <$sender>\" -S replyto=\"$sender\" -a $zipfile $recipient < <(echo $mailBody)\n</code></pre>\n"
},
{
"answer_id": 54215803,
"author": "JazzCat",
"author_id": 972966,
"author_profile": "https://Stackoverflow.com/users/972966",
"pm_score": 0,
"selected": false,
"text": "<p>None of the above solutions are working for me...</p>\n\n<pre><code>#!/bin/bash\n\n# Message\necho \"My message\" > message.txt\n\n# Mail\nsubject=\"Test\"\nmail_header=\"From: John Smith <john.smith@example.com>\"\nrecipients=\"recipient@example.com\"\n\n#######################################################################\ncat message.txt | mail -s \"$subject\" -a \"$mail_header\" -t \"$recipients\"\n</code></pre>\n"
},
{
"answer_id": 67505477,
"author": "bluenote10",
"author_id": 1804173,
"author_profile": "https://Stackoverflow.com/users/1804173",
"pm_score": 0,
"selected": false,
"text": "<p>I recent versions of <a href=\"https://mailutils.org/manual/html_section/mail.html\" rel=\"nofollow noreferrer\">GNU mailutils <code>mail</code></a> it is simply <code>mail -r foo@bar.com</code>.</p>\n<p>Looking at the raw sent mail, it seems to set both <code>Return-Path: <foo@bar.com></code> and <code>From: foo@bar.com</code>.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] | Sending a message from the Unix command line using `mail TO_ADDR` results in an email from `$USER@$HOSTNAME`. Is there a way to change the "From:" address inserted by `mail`?
For the record, I'm using GNU Mailutils 1.1/1.2 on Ubuntu (but I've seen the same behavior with Fedora and RHEL).
[EDIT]
```
$ mail -s Testing chris@example.org
Cc:
From: foo@bar.org
Testing
.
```
yields
```
Subject: Testing
To: <chris@example.org>
X-Mailer: mail (GNU Mailutils 1.1)
Message-Id: <E1KdTJj-00025z-RK@localhost>
From: <chris@localhost>
Date: Wed, 10 Sep 2008 13:17:23 -0400
From: foo@bar.org
Testing
```
The "From: foo@bar.org" line is part of the message body, not part of the header. | In my version of mail ( Debian linux 4.0 ) the following options work for controlling the source / reply addresses
* the **-a** switch, for additional headers to apply, supplying a From: header on the command line that will be appended to the outgoing mail header
* the **$REPLYTO** environment variable specifies a Reply-To: header
so the following sequence
```
export REPLYTO=cms-replies@example.com
mail -aFrom:cms-sends@example.com -s 'Testing'
```
The result, in my mail clients, is a mail from cms-sends@example.com, which any replies to will default to cms-replies@example.com
*NB:* Mac OS users: you don't have -a , but you do have **$REPLYTO**
*NB(2):* CentOS users, many commenters have added that you need to use `-r` not `-a`
*NB(3):* This answer is at least ten years old(1), please bear that in mind when you're coming in from Google. |
54,754 | <p>For example, I want to populate a gridview control in an ASP.NET web page with only the data necessary for the # of rows displayed. How can NHibernate support this?</p>
| [
{
"answer_id": 54773,
"author": "NotMyself",
"author_id": 303,
"author_profile": "https://Stackoverflow.com/users/303",
"pm_score": 5,
"selected": false,
"text": "<p>How about using Linq to NHibernate as discussed in <a href=\"http://www.ayende.com/Blog/archive/2007/03/20/Linq-For-NHibernate-Orderring-and-Paging.aspx\" rel=\"noreferrer\">this blog post</a> by Ayende?</p>\n\n<p>Code Sample:</p>\n\n<pre><code>(from c in nwnd.Customers select c.CustomerID)\n .Skip(10).Take(10).ToList(); \n</code></pre>\n\n<p>And here is a detailed post by the NHibernate team blog on <a href=\"http://www.nhforge.org/blogs/nhibernate/archive/2008/08/31/data-access-with-nhibernate.aspx\" rel=\"noreferrer\">Data Access With NHibernate</a> including implementing paging.</p>\n"
},
{
"answer_id": 54777,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 8,
"selected": true,
"text": "<p><code>ICriteria</code> has a <code>SetFirstResult(int i)</code> method, which indicates the index of the first item that you wish to get (basically the first data row in your page). </p>\n\n<p>It also has a <code>SetMaxResults(int i)</code> method, which indicates the number of rows you wish to get (i.e., your page size).</p>\n\n<p>For example, this criteria object gets the first 10 results of your data grid:</p>\n\n<pre><code>criteria.SetFirstResult(0).SetMaxResults(10);\n</code></pre>\n"
},
{
"answer_id": 54858,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 3,
"selected": false,
"text": "<p>I suggest that you create a specific structure to deal with pagination. Something like (I'm a Java programmer, but that should be easy to map):</p>\n\n<pre><code>public class Page {\n\n private List results;\n private int pageSize;\n private int page;\n\n public Page(Query query, int page, int pageSize) {\n\n this.page = page;\n this.pageSize = pageSize;\n results = query.setFirstResult(page * pageSize)\n .setMaxResults(pageSize+1)\n .list();\n\n }\n\n public List getNextPage()\n\n public List getPreviousPage()\n\n public int getPageCount()\n\n public int getCurrentPage()\n\n public void setPageSize()\n\n}\n</code></pre>\n\n<p>I didn't supply an implementation, but you could use the methods suggested by <a href=\"https://stackoverflow.com/questions/54754/how-can-you-do-paging-with-nhibernate#54777\">@Jon</a>. Here's a <a href=\"http://in.relation.to/Bloggers/PaginationInHibernateAndEJB3\" rel=\"nofollow noreferrer\">good discussion</a> for you to take a look.</p>\n"
},
{
"answer_id": 138024,
"author": "zadam",
"author_id": 410357,
"author_profile": "https://Stackoverflow.com/users/410357",
"pm_score": 4,
"selected": false,
"text": "<p>Most likely in a GridView you will want to show a slice of data plus the total number of rows (rowcount) of the total amount of data that matched your query.</p>\n\n<p>You should use a MultiQuery to send both the Select count(*) query and .SetFirstResult(n).SetMaxResult(m) queries to your database in a single call.</p>\n\n<p>Note the result will be a list that holds 2 lists, one for the data slice and one for the count.</p>\n\n<p>Example:</p>\n\n<pre><code>IMultiQuery multiQuery = s.CreateMultiQuery()\n .Add(s.CreateQuery(\"from Item i where i.Id > ?\")\n .SetInt32(0, 50).SetFirstResult(10))\n .Add(s.CreateQuery(\"select count(*) from Item i where i.Id > ?\")\n .SetInt32(0, 50));\nIList results = multiQuery.List();\nIList items = (IList)results[0];\nlong count = (long)((IList)results[1])[0];\n</code></pre>\n"
},
{
"answer_id": 433210,
"author": "Barbaros Alp",
"author_id": 51734,
"author_profile": "https://Stackoverflow.com/users/51734",
"pm_score": 5,
"selected": false,
"text": "<pre><code>public IList<Customer> GetPagedData(int page, int pageSize, out long count)\n {\n try\n {\n var all = new List<Customer>();\n\n ISession s = NHibernateHttpModule.CurrentSession;\n IList results = s.CreateMultiCriteria()\n .Add(s.CreateCriteria(typeof(Customer)).SetFirstResult(page * pageSize).SetMaxResults(pageSize))\n .Add(s.CreateCriteria(typeof(Customer)).SetProjection(Projections.RowCountInt64()))\n .List();\n\n foreach (var o in (IList)results[0])\n all.Add((Customer)o);\n\n count = (long)((IList)results[1])[0];\n return all;\n }\n catch (Exception ex) { throw new Exception(\"GetPagedData Customer da hata\", ex); }\n }\n</code></pre>\n\n<p>When paging data is there another way to get typed result from MultiCriteria or everyone does the same just like me ?</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 1329082,
"author": "Jeremy D",
"author_id": 2096983,
"author_profile": "https://Stackoverflow.com/users/2096983",
"pm_score": 6,
"selected": false,
"text": "<p>You can also take advantage of the Futures feature in NHibernate to execute the query to get the total record count as well as the actual results in a single query.</p>\n\n<p><strong>Example</strong></p>\n\n<pre><code> // Get the total row count in the database.\nvar rowCount = this.Session.CreateCriteria(typeof(EventLogEntry))\n .Add(Expression.Between(\"Timestamp\", startDate, endDate))\n .SetProjection(Projections.RowCount()).FutureValue<Int32>();\n\n// Get the actual log entries, respecting the paging.\nvar results = this.Session.CreateCriteria(typeof(EventLogEntry))\n .Add(Expression.Between(\"Timestamp\", startDate, endDate))\n .SetFirstResult(pageIndex * pageSize)\n .SetMaxResults(pageSize)\n .Future<EventLogEntry>();\n</code></pre>\n\n<p>To get the total record count, you do the following:</p>\n\n<pre><code>int iRowCount = rowCount.Value;\n</code></pre>\n\n<p>A good discussion of what Futures give you is <a href=\"http://ayende.com/Blog/archive/2009/04/27/nhibernate-futures.aspx\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 5073510,
"author": "Leandro de los Santos",
"author_id": 627627,
"author_profile": "https://Stackoverflow.com/users/627627",
"pm_score": 6,
"selected": false,
"text": "<p>From NHibernate 3 and above, you can use <code>QueryOver<T></code>:</p>\n\n<pre><code>var pageRecords = nhSession.QueryOver<TEntity>()\n .Skip((PageNumber - 1) * PageSize)\n .Take(PageSize)\n .List();\n</code></pre>\n\n<p>You may also want to explicitly order your results like this:</p>\n\n<pre><code>var pageRecords = nhSession.QueryOver<TEntity>()\n .OrderBy(t => t.AnOrderFieldLikeDate).Desc\n .Skip((PageNumber - 1) * PageSize)\n .Take(PageSize)\n .List();\n</code></pre>\n"
},
{
"answer_id": 61224560,
"author": "Marcin",
"author_id": 8537786,
"author_profile": "https://Stackoverflow.com/users/8537786",
"pm_score": 0,
"selected": false,
"text": "<p>You don't need to define 2 criterias, you can define one and clone it. \nTo clone nHibernate criteria you can use a simple code:</p>\n\n<pre><code>var criteria = ... (your criteria initializations)...;\nvar countCrit = (ICriteria)criteria.Clone();\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | For example, I want to populate a gridview control in an ASP.NET web page with only the data necessary for the # of rows displayed. How can NHibernate support this? | `ICriteria` has a `SetFirstResult(int i)` method, which indicates the index of the first item that you wish to get (basically the first data row in your page).
It also has a `SetMaxResults(int i)` method, which indicates the number of rows you wish to get (i.e., your page size).
For example, this criteria object gets the first 10 results of your data grid:
```
criteria.SetFirstResult(0).SetMaxResults(10);
``` |
54,760 | <p>Is there a way to unfilter an NSPasteboard for what the source application specifically declared it would provide?</p>
<p>I'm attempting to serialize pasteboard data in my application. When another application places an RTF file on a pasteboard and then I ask for the available types, I get eleven different flavors of said RTF, everything from the original RTF to plain strings to dyn.* values. </p>
<p>Saving off all that data into a plist or raw data on disk isn't usually a problem as it's pretty small, but when an image of any considerable size is placed on the pasteboard, the resulting output can be tens of times larger than the source data (with multiple flavors of TIFF and PICT data being made available via filtering).</p>
<p>I'd like to just be able to save off what the original app made available if possible.</p>
<hr>
<p>John, you are far more observant than myself or the gentleman I work with who's been doing Mac programming since dinosaurs roamed the earth. Neither of us ever noticed the text you highlighted... and I've not a clue why. Starting too long at the problem, apparently.</p>
<p>And while I accepted your answer as the correct answer, it doesn't exactly answer my original question. What I was looking for was a way to identify flavors that can become other flavors simply by placing them on the pasteboard <strong>AND</strong> to know which of these types were originally offered by the provider. While walking the types list will get me the preferred order for the application that provided them, it won't tell me which ones I can safely ignore as they'll be recreated when I refill the pasteboard later.</p>
<p>I've come to the conclusion that there isn't a "good" way to do this. <code>[NSPasteboard declaredTypesFromOwner]</code> would be fabulous, but it doesn't exist.</p>
| [
{
"answer_id": 57771,
"author": "John Calsbeek",
"author_id": 5696,
"author_profile": "https://Stackoverflow.com/users/5696",
"pm_score": 3,
"selected": true,
"text": "<p><code>-[NSPasteboard types]</code> will return all the available types for the data on the clipboard, but it should return them <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSPasteboard_Class/Reference/Reference.html#//apple_ref/occ/instm/NSPasteboard/types\" rel=\"nofollow noreferrer\">\"in the order they were declared.\"</a></p>\n\n<p>The documentation for <code>-[NSPasteboard declareTypes:owner:]</code> says that <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSPasteboard_Class/Reference/Reference.html#//apple_ref/occ/instm/NSPasteboard/declareTypes:owner:\" rel=\"nofollow noreferrer\">\"the types should be ordered according to the preference of the source application.\"</a></p>\n\n<p>A properly implemented pasteboard owner should, therefore, declare the richest representation of the content (probably the original content) as the first type; so a reasonable single representation should be:</p>\n\n<pre><code>[pb dataForType:[[pb types] objectAtIndex:0]]\n</code></pre>\n"
},
{
"answer_id": 59715,
"author": "John Calsbeek",
"author_id": 5696,
"author_profile": "https://Stackoverflow.com/users/5696",
"pm_score": 0,
"selected": false,
"text": "<p>You may be able to get some use out of <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSPasteboard_Class/Reference/Reference.html#//apple_ref/occ/clm/NSPasteboard/typesFilterableTo:\" rel=\"nofollow noreferrer\"><code>+[NSPasteboard typesFilterableTo:]</code></a>. I'm picturing a snippet like this:</p>\n\n<pre><code>NSArray *allTypes = [pb types];\nNSAssert([allTypes count] > 0, @\"expected at least one type\");\n\n// We always require the first declared type, as a starting point.\nNSMutableSet *requiredTypes = [NSMutableSet setWithObject:[allTypes objectAtIndex:0]];\n\nfor (NSUInteger index = 1; index < [allTypes count]; index++) {\n NSString *aType = [allTypes objectAtIndex:index];\n NSSet *filtersFrom = [NSSet setWithArray:[NSPasteboard typesFilterableTo:aType]];\n\n // If this type can't be re-created with a filter we already use, add it to the\n // set of required types.\n if (![requiredTypes intersectsSet:filtersFrom])\n [requiredTypes addObject:aType];\n}\n</code></pre>\n\n<p>I'm not sure how effective this would be at picking good types, however.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4233/"
] | Is there a way to unfilter an NSPasteboard for what the source application specifically declared it would provide?
I'm attempting to serialize pasteboard data in my application. When another application places an RTF file on a pasteboard and then I ask for the available types, I get eleven different flavors of said RTF, everything from the original RTF to plain strings to dyn.\* values.
Saving off all that data into a plist or raw data on disk isn't usually a problem as it's pretty small, but when an image of any considerable size is placed on the pasteboard, the resulting output can be tens of times larger than the source data (with multiple flavors of TIFF and PICT data being made available via filtering).
I'd like to just be able to save off what the original app made available if possible.
---
John, you are far more observant than myself or the gentleman I work with who's been doing Mac programming since dinosaurs roamed the earth. Neither of us ever noticed the text you highlighted... and I've not a clue why. Starting too long at the problem, apparently.
And while I accepted your answer as the correct answer, it doesn't exactly answer my original question. What I was looking for was a way to identify flavors that can become other flavors simply by placing them on the pasteboard **AND** to know which of these types were originally offered by the provider. While walking the types list will get me the preferred order for the application that provided them, it won't tell me which ones I can safely ignore as they'll be recreated when I refill the pasteboard later.
I've come to the conclusion that there isn't a "good" way to do this. `[NSPasteboard declaredTypesFromOwner]` would be fabulous, but it doesn't exist. | `-[NSPasteboard types]` will return all the available types for the data on the clipboard, but it should return them ["in the order they were declared."](http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSPasteboard_Class/Reference/Reference.html#//apple_ref/occ/instm/NSPasteboard/types)
The documentation for `-[NSPasteboard declareTypes:owner:]` says that ["the types should be ordered according to the preference of the source application."](http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSPasteboard_Class/Reference/Reference.html#//apple_ref/occ/instm/NSPasteboard/declareTypes:owner:)
A properly implemented pasteboard owner should, therefore, declare the richest representation of the content (probably the original content) as the first type; so a reasonable single representation should be:
```
[pb dataForType:[[pb types] objectAtIndex:0]]
``` |
54,833 | <p>I have the following webform:</p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="TestWebApp.Default" %>
<!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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtMultiLine" runat="server"
Width="400px" Height="300px" TextMode="MultiLine"></asp:TextBox>
<br />
<asp:Button ID="btnSubmit" runat="server"
Text="Do A Postback" OnClick="btnSubmitClick" />
</div>
</form>
</body>
</html>
</code></pre>
<p>and each time I post-back the leading line feeds in the textbox are being removed. Is there any way that I can prevent this behavior? </p>
<p>I was thinking of creating a custom-control that inherited from the textbox but I wanted to get a sanity check here first.</p>
| [
{
"answer_id": 54834,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Take my advice. Ditch PDF for XPS. I am working on two apps, both server based. One displays image-based documents as PDFs in a browser. The second uses FixedPage templates to construct XPS documents bound to data sources. </p>\n\n<p>My conclusion after working on both projects is that PDFs suck; XPS documents less so. You have to pay cash money for a decent PDF library, whereas XPS comes with the framework. PDF document generation is a memory hog, has lots of potholes and isn't very server friendly. XPS docs have a much smaller footprint and less chances of shooting yourself in the foot. </p>\n"
},
{
"answer_id": 54846,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 0,
"selected": false,
"text": "<p>I have had great success using Microsoft Word. The form is designed in Word and composited with XML data. The document is run through a PDF converter (Neevia in this case, but there are better) to generate the PDF.</p>\n\n<p>All of this is done in C#.</p>\n"
},
{
"answer_id": 55802,
"author": "Tony BenBrahim",
"author_id": 80075,
"author_profile": "https://Stackoverflow.com/users/80075",
"pm_score": 2,
"selected": true,
"text": "<p>can't help with VB6 solution, can help with .net or java solution on the server.<br>\nGet iText or iTextSharp from <a href=\"http://www.lowagie.com/iText/\" rel=\"nofollow noreferrer\">http://www.lowagie.com/iText/</a>.<br>\nIt has a PdfStamper class that can merge a PDF and FDF FDFReader/FDFWriter classes to generate FDF files, get field names out of PDF files, etc... </p>\n"
},
{
"answer_id": 69603,
"author": "Jeremy",
"author_id": 8557,
"author_profile": "https://Stackoverflow.com/users/8557",
"pm_score": 0,
"selected": false,
"text": "<p>Same boat. We're currently making pdfs this way: vb6 app drops a record into sql (with filename, create date, user, and final destination) and the xls (or doc) gets moved into a server directory (share) and the server has a vb.net service that has a filewatcher monitoring that directory. The file shows up, the service kicks off excel (word) to pdf the file via adobe, looks to sql to figure out what to do with the PDF when it is made, and logs the finish time. </p>\n\n<p>This was the cheap solution- it only took about a day to do the code and another day to debug both ends and roll the build out.</p>\n\n<p><strong>This is not the way to do it.</strong> Adobe crashes at random times when trying to make the pdfs. it will run for two weeks with no issues at all, and then (like today) it will crash every 5 minutes. or every other hour. or at 11:07, 2:43, 3:05, and 6:11. </p>\n\n<p>We're going to convert the stuff out of excel and word and drop the data directly into pdfs using PDFTron in the next revision. Yes, PDFTron costs money, (we bought the 1-kilobuck-per-processor license) but it will do the job, and nicely. XPS are <em>nice</em> but I, like you, have to provide PDFs. It is the way of things.</p>\n\n<p>Check out pdfTron (google it) and see if it will do what you want. Then you just got to figure out which license you need and how you gonna pay for it. If someone comes up with something better, hope they'll vote it to the top of the list!!!</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1980/"
] | I have the following webform:
```
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="TestWebApp.Default" %>
<!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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtMultiLine" runat="server"
Width="400px" Height="300px" TextMode="MultiLine"></asp:TextBox>
<br />
<asp:Button ID="btnSubmit" runat="server"
Text="Do A Postback" OnClick="btnSubmitClick" />
</div>
</form>
</body>
</html>
```
and each time I post-back the leading line feeds in the textbox are being removed. Is there any way that I can prevent this behavior?
I was thinking of creating a custom-control that inherited from the textbox but I wanted to get a sanity check here first. | can't help with VB6 solution, can help with .net or java solution on the server.
Get iText or iTextSharp from <http://www.lowagie.com/iText/>.
It has a PdfStamper class that can merge a PDF and FDF FDFReader/FDFWriter classes to generate FDF files, get field names out of PDF files, etc... |
54,861 | <p>I've been using the following code to open Office Documents, PDF, etc. on my windows machines using Java and it's working fine, except for some reason when a filename has embedded it within it multiple contiguous spaces like "File[SPACE][SPACE]Test.doc".</p>
<p>How can I make this work? I'm not averse to canning the whole piece of code... but I'd rather not replace it with a third party library that calls JNI.</p>
<pre><code>public static void openDocument(String path) throws IOException {
// Make forward slashes backslashes (for windows)
// Double quote any path segments with spaces in them
path = path.replace("/", "\\").replaceAll(
"\\\\([^\\\\\\\\\"]* [^\\\\\\\\\"]*)", "\\\\\\\"$1\"");
String command = "C:\\Windows\\System32\\cmd.exe /c start " + path + "";
Runtime.getRuntime().exec(command);
}
</code></pre>
<p><strong>EDIT:</strong> When I run it with the errant file windows complains about finding the file. But... when I run the command line directly from the command line it runs just fine.</p>
| [
{
"answer_id": 54967,
"author": "Dan Dyer",
"author_id": 5171,
"author_profile": "https://Stackoverflow.com/users/5171",
"pm_score": 4,
"selected": true,
"text": "<p>If you are using Java 6 you can just use the <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#open(java.io.File)\" rel=\"nofollow noreferrer\">open method of java.awt.Desktop</a> to launch the file using the default application for the current platform.</p>\n"
},
{
"answer_id": 55018,
"author": "Matt Cummings",
"author_id": 828,
"author_profile": "https://Stackoverflow.com/users/828",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if this will help you much... I use java 1.5+'s <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html\" rel=\"nofollow noreferrer\">ProcessBuilder</a> to launch external shell scripts in a java program. Basically I do the following: ( although this may not apply because you don't want to capture the commands output; you actually wanna fire up the document - but, maybe this will spark something that you can use )</p>\n\n<pre><code>List<String> command = new ArrayList<String>();\ncommand.add(someExecutable);\ncommand.add(someArguemnt0);\ncommand.add(someArgument1);\ncommand.add(someArgument2);\nProcessBuilder builder = new ProcessBuilder(command);\ntry {\nfinal Process process = builder.start();\n... \n} catch (IOException ioe) {}\n</code></pre>\n"
},
{
"answer_id": 55059,
"author": "KeithL",
"author_id": 5478,
"author_profile": "https://Stackoverflow.com/users/5478",
"pm_score": 0,
"selected": false,
"text": "<p>The issue may be the \"start\" command you are using, rather than your file name parsing. For example, this seems to work well on my WinXP machine (using JDK 1.5)</p>\n\n<pre><code>import java.io.IOException;\nimport java.io.File;\n\npublic class test {\n\n public static void openDocument(String path) throws IOException {\n path = \"\\\"\" + path + \"\\\"\";\n File f = new File( path );\n String command = \"C:\\\\Windows\\\\System32\\\\cmd.exe /c \" + f.getPath() + \"\";\n Runtime.getRuntime().exec(command); \n }\n\n public static void main( String[] argv ) {\n test thisApp = new test();\n try {\n thisApp.openDocument( \"c:\\\\so\\\\My Doc.doc\");\n }\n catch( IOException e ) {\n e.printStackTrace();\n }\n }\n}\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] | I've been using the following code to open Office Documents, PDF, etc. on my windows machines using Java and it's working fine, except for some reason when a filename has embedded it within it multiple contiguous spaces like "File[SPACE][SPACE]Test.doc".
How can I make this work? I'm not averse to canning the whole piece of code... but I'd rather not replace it with a third party library that calls JNI.
```
public static void openDocument(String path) throws IOException {
// Make forward slashes backslashes (for windows)
// Double quote any path segments with spaces in them
path = path.replace("/", "\\").replaceAll(
"\\\\([^\\\\\\\\\"]* [^\\\\\\\\\"]*)", "\\\\\\\"$1\"");
String command = "C:\\Windows\\System32\\cmd.exe /c start " + path + "";
Runtime.getRuntime().exec(command);
}
```
**EDIT:** When I run it with the errant file windows complains about finding the file. But... when I run the command line directly from the command line it runs just fine. | If you are using Java 6 you can just use the [open method of java.awt.Desktop](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#open(java.io.File)) to launch the file using the default application for the current platform. |
54,866 | <p>I have string like this</p>
<pre><code> /c SomeText\MoreText "Some Text\More Text\Lol" SomeText
</code></pre>
<p>I want to tokenize it, however I can't just split on the spaces. I've come up with somewhat ugly parser that works, but I'm wondering if anyone has a more elegant design.</p>
<p>This is in C# btw.</p>
<p><strong>EDIT:</strong> My ugly version, while ugly, is O(N) and may actually be faster than using a RegEx.</p>
<pre><code>private string[] tokenize(string input)
{
string[] tokens = input.Split(' ');
List<String> output = new List<String>();
for (int i = 0; i < tokens.Length; i++)
{
if (tokens[i].StartsWith("\""))
{
string temp = tokens[i];
int k = 0;
for (k = i + 1; k < tokens.Length; k++)
{
if (tokens[k].EndsWith("\""))
{
temp += " " + tokens[k];
break;
}
else
{
temp += " " + tokens[k];
}
}
output.Add(temp);
i = k + 1;
}
else
{
output.Add(tokens[i]);
}
}
return output.ToArray();
}
</code></pre>
| [
{
"answer_id": 54876,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>The Microsoft.VisualBasic.FileIO namespace (in Microsoft.VisualBasic.dll) has a TextFieldParser you can use to split on space delimeted text. It handles strings within quotes (i.e., \"this is one token\" thisistokentwo) well.</p>\n\n<p>Note, just because the DLL says VisualBasic doesn't mean you can only use it in a VB project. Its part of the entire Framework.</p>\n"
},
{
"answer_id": 54880,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 0,
"selected": false,
"text": "<p>You also might want to look into regular expressions. That might help you out. Here is a sample ripped off from MSDN...</p>\n\n<pre><code>using System;\nusing System.Text.RegularExpressions;\n\npublic class Test\n{\n\n public static void Main ()\n {\n\n // Define a regular expression for repeated words.\n Regex rx = new Regex(@\"\\b(?<word>\\w+)\\s+(\\k<word>)\\b\",\n RegexOptions.Compiled | RegexOptions.IgnoreCase);\n\n // Define a test string. \n string text = \"The the quick brown fox fox jumped over the lazy dog dog.\";\n\n // Find matches.\n MatchCollection matches = rx.Matches(text);\n\n // Report the number of matches found.\n Console.WriteLine(\"{0} matches found in:\\n {1}\", \n matches.Count, \n text);\n\n // Report on each match.\n foreach (Match match in matches)\n {\n GroupCollection groups = match.Groups;\n Console.WriteLine(\"'{0}' repeated at positions {1} and {2}\", \n groups[\"word\"].Value, \n groups[0].Index, \n groups[1].Index);\n }\n\n }\n\n}\n// The example produces the following output to the console:\n// 3 matches found in:\n// The the quick brown fox fox jumped over the lazy dog dog.\n// 'The' repeated at positions 0 and 4\n// 'fox' repeated at positions 20 and 25\n// 'dog' repeated at positions 50 and 54\n</code></pre>\n"
},
{
"answer_id": 54916,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/54866/best-way-to-parse-space-seperated-text#54880\">Craig</a> is right — use regular expressions. <a href=\"http://msdn.microsoft.com/en-us/library/8yttk7sy.aspx\" rel=\"nofollow noreferrer\">Regex.Split</a> may be more concise for your needs.</p>\n"
},
{
"answer_id": 54928,
"author": "Todd Myhre",
"author_id": 5626,
"author_profile": "https://Stackoverflow.com/users/5626",
"pm_score": 5,
"selected": true,
"text": "<p>The computer term for what you're doing is <a href=\"http://en.wikipedia.org/wiki/Lexical_analysis\" rel=\"nofollow noreferrer\">lexical analysis</a>; read that for a good summary of this common task.</p>\n\n<p>Based on your example, I'm guessing that you want whitespace to separate your words, but stuff in quotation marks should be treated as a \"word\" without the quotes.</p>\n\n<p>The simplest way to do this is to define a word as a regular expression:</p>\n\n<pre><code>([^\"^\\s]+)\\s*|\"([^\"]+)\"\\s*\n</code></pre>\n\n<p>This expression states that a \"word\" is either (1) non-quote, non-whitespace text surrounded by whitespace, or (2) non-quote text surrounded by quotes (followed by some whitespace). Note the use of capturing parentheses to highlight the desired text.</p>\n\n<p>Armed with that regex, your algorithm is simple: search your text for the next \"word\" as defined by the capturing parentheses, and return it. Repeat that until you run out of \"words\".</p>\n\n<p>Here's the simplest bit of working code I could come up with, in VB.NET. Note that we have to check <em>both</em> groups for data since there are two sets of capturing parentheses.</p>\n\n<pre><code>Dim token As String\nDim r As Regex = New Regex(\"([^\"\"^\\s]+)\\s*|\"\"([^\"\"]+)\"\"\\s*\")\nDim m As Match = r.Match(\"this is a \"\"test string\"\"\")\n\nWhile m.Success\n token = m.Groups(1).ToString\n If token.length = 0 And m.Groups.Count > 1 Then\n token = m.Groups(2).ToString\n End If\n m = m.NextMatch\nEnd While\n</code></pre>\n\n<p>Note 1: <a href=\"https://stackoverflow.com/users/1228/will\">Will's</a> answer, above, is the same idea as this one. Hopefully this answer explains the details behind the scene a little better :)</p>\n"
},
{
"answer_id": 55064,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>[^\\t]+\\t|\"[^\"]+\"\\t</p>\n</blockquote>\n\n<p>using the Regex definitely looks like the best bet, however this one just returns the whole string. I'm trying to tweak it, but not much luck so far.</p>\n\n<pre><code>string[] tokens = System.Text.RegularExpressions.Regex.Split(this.BuildArgs, @\"[^\\t]+\\t|\"\"[^\"\"]+\"\"\\t\");\n</code></pre>\n"
},
{
"answer_id": 55201,
"author": "fryguybob",
"author_id": 4592,
"author_profile": "https://Stackoverflow.com/users/4592",
"pm_score": 2,
"selected": false,
"text": "<p>There is the state machine approach.</p>\n\n<pre><code> private enum State\n {\n None = 0,\n InTokin,\n InQuote\n }\n\n private static IEnumerable<string> Tokinize(string input)\n {\n input += ' '; // ensure we end on whitespace\n State state = State.None;\n State? next = null; // setting the next state implies that we have found a tokin\n StringBuilder sb = new StringBuilder();\n foreach (char c in input)\n {\n switch (state)\n {\n default:\n case State.None:\n if (char.IsWhiteSpace(c))\n continue;\n else if (c == '\"')\n {\n state = State.InQuote;\n continue;\n }\n else\n state = State.InTokin;\n break;\n case State.InTokin:\n if (char.IsWhiteSpace(c))\n next = State.None;\n else if (c == '\"')\n next = State.InQuote;\n break;\n case State.InQuote:\n if (c == '\"')\n next = State.None;\n break;\n }\n if (next.HasValue)\n {\n yield return sb.ToString();\n sb = new StringBuilder();\n state = next.Value;\n next = null;\n }\n else\n sb.Append(c);\n }\n }\n</code></pre>\n\n<p>It can easily be extended for things like nested quotes and escaping. Returning as <code>IEnumerable<string></code> allows your code to only parse as much as you need. There aren't any real downsides to that kind of lazy approach as strings are immutable so you know that <code>input</code> isn't going to change before you have parsed the whole thing.</p>\n\n<p>See: <a href=\"http://en.wikipedia.org/wiki/Automata-Based_Programming\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Automata-Based_Programming</a></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | I have string like this
```
/c SomeText\MoreText "Some Text\More Text\Lol" SomeText
```
I want to tokenize it, however I can't just split on the spaces. I've come up with somewhat ugly parser that works, but I'm wondering if anyone has a more elegant design.
This is in C# btw.
**EDIT:** My ugly version, while ugly, is O(N) and may actually be faster than using a RegEx.
```
private string[] tokenize(string input)
{
string[] tokens = input.Split(' ');
List<String> output = new List<String>();
for (int i = 0; i < tokens.Length; i++)
{
if (tokens[i].StartsWith("\""))
{
string temp = tokens[i];
int k = 0;
for (k = i + 1; k < tokens.Length; k++)
{
if (tokens[k].EndsWith("\""))
{
temp += " " + tokens[k];
break;
}
else
{
temp += " " + tokens[k];
}
}
output.Add(temp);
i = k + 1;
}
else
{
output.Add(tokens[i]);
}
}
return output.ToArray();
}
``` | The computer term for what you're doing is [lexical analysis](http://en.wikipedia.org/wiki/Lexical_analysis); read that for a good summary of this common task.
Based on your example, I'm guessing that you want whitespace to separate your words, but stuff in quotation marks should be treated as a "word" without the quotes.
The simplest way to do this is to define a word as a regular expression:
```
([^"^\s]+)\s*|"([^"]+)"\s*
```
This expression states that a "word" is either (1) non-quote, non-whitespace text surrounded by whitespace, or (2) non-quote text surrounded by quotes (followed by some whitespace). Note the use of capturing parentheses to highlight the desired text.
Armed with that regex, your algorithm is simple: search your text for the next "word" as defined by the capturing parentheses, and return it. Repeat that until you run out of "words".
Here's the simplest bit of working code I could come up with, in VB.NET. Note that we have to check *both* groups for data since there are two sets of capturing parentheses.
```
Dim token As String
Dim r As Regex = New Regex("([^""^\s]+)\s*|""([^""]+)""\s*")
Dim m As Match = r.Match("this is a ""test string""")
While m.Success
token = m.Groups(1).ToString
If token.length = 0 And m.Groups.Count > 1 Then
token = m.Groups(2).ToString
End If
m = m.NextMatch
End While
```
Note 1: [Will's](https://stackoverflow.com/users/1228/will) answer, above, is the same idea as this one. Hopefully this answer explains the details behind the scene a little better :) |
54,877 | <p>I can't seem to figure out a good way to do this, but it seems like it should be simple. I have an element that I want to <code>append a div</code> to. Then I have another element that I want to clone and shove into that intermediate div. Here's what I was hoping to do:</p>
<pre><code>$("#somediv > ul").after("<div id='xxx'></div>").append($("#someotherdiv").clone());
</code></pre>
<p>This seems to be close, but not quite there. The problem with this is that the "append" seems to be operating on the original <code>#somediv > ul</code> selector. This sort of makes sense, but it's not what I wanted. How can I most efficiently select that intermediate div that I added with the <code>after</code> and put my <code>#someotherdiv</code> into it?</p>
| [
{
"answer_id": 54897,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>How can I most efficiently select that intermediate div that I added with the \"after\" and put my \"#someotherdiv\" into it?</p>\n</blockquote>\n\n<p>@Vincent's solution is probably the fastest way to get the same result. However if for whatever reason you need add the div with <code>after()</code> then need to select it and operate on it you can use </p>\n\n<blockquote>\n <p><code>.nextAll( [expr] )</code></p>\n \n <p><code>Find all sibling elements after the current element.<br>\n Use an optional expression to filter the matched set.</code></p>\n</blockquote>\n\n<p>So your js becomes:</p>\n\n<pre><code>$(\"#somediv > ul\")\n .after(\"<div id='xxx'></div>\")\n .nextAll('#xxx')\n .append($(\"#someotherdiv\").clone());\n</code></pre>\n"
},
{
"answer_id": 54949,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 3,
"selected": false,
"text": "<p>use insertAfter():</p>\n\n<pre><code>$(\"<div id='xxx'></div>\").insertAfter(\"#somediv > ul\").append($(\"#someotherdiv\").clone())\n</code></pre>\n"
},
{
"answer_id": 54970,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 4,
"selected": true,
"text": "<p>Go the other way around and use <code>insertAfter()</code>.</p>\n\n<pre><code>$(\"<div id='xxx'></div>\")\n .append($(\"#someotherdiv\").clone())\n .insertAfter(\"#somediv > ul\")\n</code></pre>\n\n<p>Try to add your generated DOM nodes to the document only after finishing your work.</p>\n\n<p>Once the nodes are added to the displayed document, the browser starts listening to any change to refresh the view. Doing all the work before adding the nodes to the displayed document does improve browser performance.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
] | I can't seem to figure out a good way to do this, but it seems like it should be simple. I have an element that I want to `append a div` to. Then I have another element that I want to clone and shove into that intermediate div. Here's what I was hoping to do:
```
$("#somediv > ul").after("<div id='xxx'></div>").append($("#someotherdiv").clone());
```
This seems to be close, but not quite there. The problem with this is that the "append" seems to be operating on the original `#somediv > ul` selector. This sort of makes sense, but it's not what I wanted. How can I most efficiently select that intermediate div that I added with the `after` and put my `#someotherdiv` into it? | Go the other way around and use `insertAfter()`.
```
$("<div id='xxx'></div>")
.append($("#someotherdiv").clone())
.insertAfter("#somediv > ul")
```
Try to add your generated DOM nodes to the document only after finishing your work.
Once the nodes are added to the displayed document, the browser starts listening to any change to refresh the view. Doing all the work before adding the nodes to the displayed document does improve browser performance. |
54,909 | <p>I have an <code>ArrayList<String></code> that I'd like to return a copy of. <code>ArrayList</code> has a clone method which has the following signature:</p>
<pre><code>public Object clone()
</code></pre>
<p>After I call this method, how do I cast the returned Object back to <code>ArrayList<String></code>?</p>
| [
{
"answer_id": 54911,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 1,
"selected": false,
"text": "<pre><code>ArrayList first = new ArrayList ();\nArrayList copy = (ArrayList) first.clone ();\n</code></pre>\n"
},
{
"answer_id": 54912,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 7,
"selected": true,
"text": "<pre><code>ArrayList newArrayList = (ArrayList) oldArrayList.clone();\n</code></pre>\n"
},
{
"answer_id": 54917,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 4,
"selected": false,
"text": "<p>I find using addAll works fine.</p>\n\n<pre><code>ArrayList<String> copy = new ArrayList<String>();\ncopy.addAll(original);\n</code></pre>\n\n<p>parentheses are used rather than the generics syntax</p>\n"
},
{
"answer_id": 54922,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 2,
"selected": false,
"text": "<p>This should also work:</p>\n\n<pre><code>ArrayList<String> orig = new ArrayList<String>();\nArrayList<String> copy = (ArrayList<String>) orig.clone()\n</code></pre>\n"
},
{
"answer_id": 55132,
"author": "Aaron",
"author_id": 2628,
"author_profile": "https://Stackoverflow.com/users/2628",
"pm_score": 4,
"selected": false,
"text": "<p>I think this should do the trick using the Collections API:</p>\n\n<p><strong>Note</strong>: the copy method runs in linear time. </p>\n\n<pre><code>//assume oldList exists and has data in it.\nList<String> newList = new ArrayList<String>();\nCollections.copy(newList, oldList);\n</code></pre>\n"
},
{
"answer_id": 56383,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 8,
"selected": false,
"text": "<p>Why would you want to clone? Creating a new list usually makes more sense.</p>\n\n<pre><code>List<String> strs;\n...\nList<String> newStrs = new ArrayList<>(strs);\n</code></pre>\n\n<p>Job done.</p>\n"
},
{
"answer_id": 350301,
"author": "Julien Chastang",
"author_id": 32174,
"author_profile": "https://Stackoverflow.com/users/32174",
"pm_score": 4,
"selected": false,
"text": "<p>Be advised that Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from \"<a href=\"http://java.sun.com/docs/books/effective/\" rel=\"noreferrer\">Effective Java</a>\" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.</p>\n"
},
{
"answer_id": 599155,
"author": "Juan Besa",
"author_id": 72369,
"author_profile": "https://Stackoverflow.com/users/72369",
"pm_score": 2,
"selected": false,
"text": "<p>Be very careful when cloning ArrayLists. Cloning in java is shallow. This means that it will only clone the Arraylist itself and not its members. So if you have an ArrayList X1 and clone it into X2 any change in X2 will also manifest in X1 and vice-versa. When you clone you will only generate a new ArrayList with pointers to the same elements in the original. </p>\n"
},
{
"answer_id": 8971483,
"author": "Petr",
"author_id": 1164753,
"author_profile": "https://Stackoverflow.com/users/1164753",
"pm_score": 1,
"selected": false,
"text": "<p>I am not a java professional, but I have the same problem and I tried to solve by this method. (It suppose that T has a copy constructor).</p>\n\n<pre><code> public static <T extends Object> List<T> clone(List<T> list) {\n try {\n List<T> c = list.getClass().newInstance();\n for(T t: list) {\n T copy = (T) t.getClass().getDeclaredConstructor(t.getclass()).newInstance(t);\n c.add(copy);\n }\n return c;\n } catch(Exception e) {\n throw new RuntimeException(\"List cloning unsupported\",e);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10251692,
"author": "GeRmAn",
"author_id": 1347278,
"author_profile": "https://Stackoverflow.com/users/1347278",
"pm_score": 4,
"selected": false,
"text": "<p>This is the code I use for that:</p>\n\n<pre><code>ArrayList copy = new ArrayList (original.size());\nCollections.copy(copy, original);\n</code></pre>\n\n<p>Hope is usefull for you</p>\n"
},
{
"answer_id": 25785306,
"author": "Ahmed Hamdy",
"author_id": 319876,
"author_profile": "https://Stackoverflow.com/users/319876",
"pm_score": 2,
"selected": false,
"text": "<p>To clone a generic interface like <code>java.util.List</code> you will just need to cast it. here you are an example:</p>\n\n<pre><code>List list = new ArrayList();\nList list2 = ((List) ( (ArrayList) list).clone());\n</code></pre>\n\n<p>It is a bit tricky, but it works, if you are limited to return a <code>List</code> interface, so anyone after you can implement your list whenever he wants.</p>\n\n<p>I know this answer is close to the final answer, but my answer answers how to do all of that while you are working with <code>List</code> -the generic parent- not <code>ArrayList</code></p>\n"
},
{
"answer_id": 35014446,
"author": "Simon Jenkins",
"author_id": 5763141,
"author_profile": "https://Stackoverflow.com/users/5763141",
"pm_score": 4,
"selected": false,
"text": "<p>With Java 8 it can be cloned with a stream.</p>\n\n<pre><code>import static java.util.stream.Collectors.toList;\n</code></pre>\n\n<p>...</p>\n\n<pre><code>List<AnObject> clone = myList.stream().collect(toList());\n</code></pre>\n"
},
{
"answer_id": 35430941,
"author": "Uri Shalit",
"author_id": 5019818,
"author_profile": "https://Stackoverflow.com/users/5019818",
"pm_score": 3,
"selected": false,
"text": "<p>If you want this in order to be able to return the List in a getter it would be better to do:</p>\n\n<pre><code>ImmutableList.copyOf(list);\n</code></pre>\n"
},
{
"answer_id": 54040913,
"author": "Robert",
"author_id": 6113110,
"author_profile": "https://Stackoverflow.com/users/6113110",
"pm_score": 3,
"selected": false,
"text": "<pre><code>List<String> shallowClonedList = new ArrayList<>(listOfStrings);\n</code></pre>\n\n<p>Keep in mind that this is only a shallow not a deep copy, ie. you get a new list, but the entries are the same. This is no problem for simply strings. Get's more tricky when the list entries are objects themself.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] | I have an `ArrayList<String>` that I'd like to return a copy of. `ArrayList` has a clone method which has the following signature:
```
public Object clone()
```
After I call this method, how do I cast the returned Object back to `ArrayList<String>`? | ```
ArrayList newArrayList = (ArrayList) oldArrayList.clone();
``` |
54,952 | <p>We try to use Java and UTF-8 on Windows. The application writes logs on the console, and we would like to use UTF-8 for the logs as our application has internationalized logs.</p>
<p>It is possible to configure the JVM so it generates UTF-8, using <code>-Dfile.encoding=UTF-8</code> as arguments to the JVM. It works fine, but the output on a Windows console is garbled.</p>
<p>Then, we can set the code page of the console to 65001 (<code>chcp 65001</code>), but in this case, the <code>.bat</code> files do not work. This means that when we try to launch our application through our script (named start.bat), absolutely nothing happens. The command simple returns:</p>
<pre><code>C:\Application> chcp 65001
Activated code page: 65001
C:\Application> start.bat
C:\Application>
</code></pre>
<p>But without <code>chcp 65001</code>, there is no problem, and the application can be launched.</p>
<p>Any hints about that?</p>
| [
{
"answer_id": 55262,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": -1,
"selected": false,
"text": "<p>Have you tried <a href=\"http://en.wikipedia.org/wiki/PowerShell\" rel=\"nofollow noreferrer\">PowerShell</a> rather than old cmd.exe.</p>\n"
},
{
"answer_id": 55307,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 4,
"selected": true,
"text": "<p>Try <code>chcp 65001 && start.bat</code></p>\n<p>The <code>chcp</code> command changes the code page, and 65001 is the Win32 code page identifier for UTF-8 under Windows 7 and up. A code page, or character encoding, specifies how to convert a Unicode code point to a sequence of bytes or back again.</p>\n"
},
{
"answer_id": 265734,
"author": "Renato Soffiatto",
"author_id": 30477,
"author_profile": "https://Stackoverflow.com/users/30477",
"pm_score": 0,
"selected": false,
"text": "<p>We had some similar problems in Linux. Our code was in ISO-8859-1 (mostly cp-1252 compatible) but the console was UTF-8, making the code to not compile. Simply changing the console to ISO-8859-1 would make the build script, in UTF-8, to break. We found a couple of choices:<br>\n1- define some standard encoding and sticky to it. That was our choice. We choose to keep all in ISO-8859-1, modifying the build scripts.<br>\n2- Setting the encoding before starting any task, even inside the build scripts. Some code like the erickson said. In Linux was like :</p>\n\n<pre><code>lang=pt_BR.ISO-8859-1 /usr/local/xxxx\n</code></pre>\n\n<p>My eclipse is still like this. Both do work well.</p>\n"
},
{
"answer_id": 7610736,
"author": "Roger F. Gay",
"author_id": 490484,
"author_profile": "https://Stackoverflow.com/users/490484",
"pm_score": 0,
"selected": false,
"text": "<p>Windows doesn't support the 65001 code page: <a href=\"http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/chcp.mspx?mfr=true\" rel=\"nofollow\">http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/chcp.mspx?mfr=true</a></p>\n"
},
{
"answer_id": 8921509,
"author": "YIN SHAN",
"author_id": 1157731,
"author_profile": "https://Stackoverflow.com/users/1157731",
"pm_score": 3,
"selected": false,
"text": "<p>Java on windows does NOT support unicode ouput by default. I have written a workaround method by calling Native API with JNA library.The method will call WriteConsoleW for unicode output on the console.</p>\n\n<pre><code>import com.sun.jna.Native;\nimport com.sun.jna.Pointer;\nimport com.sun.jna.ptr.IntByReference;\nimport com.sun.jna.win32.StdCallLibrary;\n\n/** For unicode output on windows platform\n * @author Sandy_Yin\n * \n */\npublic class Console {\n private static Kernel32 INSTANCE = null;\n\n public interface Kernel32 extends StdCallLibrary {\n public Pointer GetStdHandle(int nStdHandle);\n\n public boolean WriteConsoleW(Pointer hConsoleOutput, char[] lpBuffer,\n int nNumberOfCharsToWrite,\n IntByReference lpNumberOfCharsWritten, Pointer lpReserved);\n }\n\n static {\n String os = System.getProperty(\"os.name\").toLowerCase();\n if (os.startsWith(\"win\")) {\n INSTANCE = (Kernel32) Native\n .loadLibrary(\"kernel32\", Kernel32.class);\n }\n }\n\n public static void println(String message) {\n boolean successful = false;\n if (INSTANCE != null) {\n Pointer handle = INSTANCE.GetStdHandle(-11);\n char[] buffer = message.toCharArray();\n IntByReference lpNumberOfCharsWritten = new IntByReference();\n successful = INSTANCE.WriteConsoleW(handle, buffer, buffer.length,\n lpNumberOfCharsWritten, null);\n if(successful){\n System.out.println();\n }\n }\n if (!successful) {\n System.out.println(message);\n }\n }\n}\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1430323/"
] | We try to use Java and UTF-8 on Windows. The application writes logs on the console, and we would like to use UTF-8 for the logs as our application has internationalized logs.
It is possible to configure the JVM so it generates UTF-8, using `-Dfile.encoding=UTF-8` as arguments to the JVM. It works fine, but the output on a Windows console is garbled.
Then, we can set the code page of the console to 65001 (`chcp 65001`), but in this case, the `.bat` files do not work. This means that when we try to launch our application through our script (named start.bat), absolutely nothing happens. The command simple returns:
```
C:\Application> chcp 65001
Activated code page: 65001
C:\Application> start.bat
C:\Application>
```
But without `chcp 65001`, there is no problem, and the application can be launched.
Any hints about that? | Try `chcp 65001 && start.bat`
The `chcp` command changes the code page, and 65001 is the Win32 code page identifier for UTF-8 under Windows 7 and up. A code page, or character encoding, specifies how to convert a Unicode code point to a sequence of bytes or back again. |
54,963 | <p>I've got a lot of ugly code that looks like this:</p>
<pre><code>if (!string.IsNullOrEmpty(ddlFileName.SelectedItem.Text))
results = results.Where(x => x.FileName.Contains(ddlFileName.SelectedValue));
if (chkFileName.Checked)
results = results.Where(x => x.FileName == null);
if (!string.IsNullOrEmpty(ddlIPAddress.SelectedItem.Text))
results = results.Where(x => x.IpAddress.Contains(ddlIPAddress.SelectedValue));
if (chkIPAddress.Checked)
results = results.Where(x => x.IpAddress == null);
...etc.
</code></pre>
<p><code>results</code> is an <code>IQueryable<MyObject></code>.<br>
The idea is that for each of these innumerable dropdowns and checkboxes, if the dropdown has something selected, the user wants to match that item. If the checkbox is checked, the user wants specifically those records where that field is null or an empty string. (The UI doesn't let both be selected at the same time.) This all adds to the LINQ Expression which gets executed at the end, after we've added all the conditions.</p>
<p>It <em>seems</em> like there ought to be some way to pull out an <code>Expression<Func<MyObject, bool>></code> or two so that I can put the repeated parts in a method and just pass in what changes. I've done this in other places, but this set of code has me stymied. (Also, I'd like to avoid "Dynamic LINQ", because I want to keep things type-safe if possible.) Any ideas?</p>
| [
{
"answer_id": 54981,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 0,
"selected": false,
"text": "<pre><code>results = results.Where(x => \n (string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) || x.FileName.Contains(ddlFileName.SelectedValue))\n && (!chkFileName.Checked || string.IsNullOrEmpty(x.FileName))\n && ...);\n</code></pre>\n"
},
{
"answer_id": 55069,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<p>I'd convert it into a single Linq statement:</p>\n\n<pre><code>var results =\n //get your inital results\n from x in GetInitialResults()\n //either we don't need to check, or the check passes\n where string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) ||\n x.FileName.Contains(ddlFileName.SelectedValue)\n where !chkFileName.Checked ||\n string.IsNullOrEmpty(x.FileName)\n where string.IsNullOrEmpty(ddlIPAddress.SelectedItem.Text) ||\n x.FileName.Contains(ddlIPAddress.SelectedValue)\n where !chkIPAddress.Checked ||\n string.IsNullOrEmpty(x. IpAddress)\n select x;\n</code></pre>\n\n<p>It's no shorter, but I find this logic clearer.</p>\n"
},
{
"answer_id": 55443,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 0,
"selected": false,
"text": "<p>Neither of these answers so far is quite what I'm looking for. To give an example of what I'm aiming at (I don't regard this as a complete answer either), I took the above code and created a couple of extension methods:</p>\n\n<pre><code>static public IQueryable<Activity> AddCondition(\n this IQueryable<Activity> results,\n DropDownList ddl, \n Expression<Func<Activity, bool>> containsCondition)\n{\n if (!string.IsNullOrEmpty(ddl.SelectedItem.Text))\n results = results.Where(containsCondition);\n return results;\n}\nstatic public IQueryable<Activity> AddCondition(\n this IQueryable<Activity> results,\n CheckBox chk, \n Expression<Func<Activity, bool>> emptyCondition)\n{\n if (chk.Checked)\n results = results.Where(emptyCondition);\n return results;\n}\n</code></pre>\n\n<p>This allowed me to refactor the code above into this:</p>\n\n<pre><code>results = results.AddCondition(ddlFileName, x => x.FileName.Contains(ddlFileName.SelectedValue));\nresults = results.AddCondition(chkFileName, x => x.FileName == null || x.FileName.Equals(string.Empty));\n\nresults = results.AddCondition(ddlIPAddress, x => x.IpAddress.Contains(ddlIPAddress.SelectedValue));\nresults = results.AddCondition(chkIPAddress, x => x.IpAddress == null || x.IpAddress.Equals(string.Empty));\n</code></pre>\n\n<p>This isn't <em>quite</em> as ugly, but it's still longer than I'd prefer. The pairs of lambda expressions in each set are obviously very similar, but I can't figure out a way to condense them further...at least not without resorting to dynamic LINQ, which makes me sacrifice type safety.</p>\n\n<p>Any other ideas?</p>\n"
},
{
"answer_id": 55490,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>@Kyralessa,</p>\n\n<p>You can create extension method AddCondition for predicates that accepts parameter of type Control plus lambda expression and returns combined expression. Then you can combine conditions using fluent interface and reuse your predicates. To see example of how it can be implemented see my answer on this question:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/53597/how-do-i-compose-existing-linq-expressions\">How do I compose existing Linq Expressions</a></p>\n"
},
{
"answer_id": 55955,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "<p>In that case:</p>\n\n<pre><code>//list of predicate functions to check\nvar conditions = new List<Predicate<MyClass>> \n{\n x => string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) ||\n x.FileName.Contains(ddlFileName.SelectedValue),\n x => !chkFileName.Checked ||\n string.IsNullOrEmpty(x.FileName),\n x => string.IsNullOrEmpty(ddlIPAddress.SelectedItem.Text) ||\n x.IpAddress.Contains(ddlIPAddress.SelectedValue),\n x => !chkIPAddress.Checked ||\n string.IsNullOrEmpty(x.IpAddress)\n}\n\n//now get results\nvar results =\n from x in GetInitialResults()\n //all the condition functions need checking against x\n where conditions.All( cond => cond(x) )\n select x;\n</code></pre>\n\n<p>I've just explicitly declared the predicate list, but these could be generated, something like:</p>\n\n<pre><code>ListBoxControl lbc;\nCheckBoxControl cbc;\nforeach( Control c in this.Controls)\n if( (lbc = c as ListBoxControl ) != null )\n conditions.Add( ... );\n else if ( (cbc = c as CheckBoxControl ) != null )\n conditions.Add( ... );\n</code></pre>\n\n<p>You would need some way to check the property of MyClass that you needed to check, and for that you'd have to use reflection.</p>\n"
},
{
"answer_id": 56014,
"author": "Ant",
"author_id": 3709,
"author_profile": "https://Stackoverflow.com/users/3709",
"pm_score": 1,
"selected": false,
"text": "<p>Have you seen the <a href=\"http://www.albahari.com/nutshell/linqkit.html\" rel=\"nofollow noreferrer\">LINQKit</a>? The AsExpandable sounds like what you're after (though you may want to read the post <a href=\"http://tomasp.net/blog/linq-expand.aspx\" rel=\"nofollow noreferrer\">Calling functions in LINQ queries</a> at TomasP.NET for more depth).</p>\n"
},
{
"answer_id": 130791,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 0,
"selected": false,
"text": "<p>I'd be wary of the solutions of the form:</p>\n\n<pre><code>// from Keith\nfrom x in GetInitialResults()\n //either we don't need to check, or the check passes\n where string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) ||\n x.FileName.Contains(ddlFileName.SelectedValue)\n</code></pre>\n\n<p>My reasoning is variable capture. If you're immediately execute just the once you probably won't notice a difference. However, in linq, evaluation isn't immediate but happens each time iterated occurs. Delegates can capture variables and use them outside the scope you intended.</p>\n\n<p>It feels like you're querying too close to the UI. Querying is a layer down, and linq isn't the way for the UI to communicate down.</p>\n\n<p>You may be better off doing the following. Decouple the searching logic from the presentation - it's more flexible and reusable - fundamentals of OO. </p>\n\n<pre><code>// my search parameters encapsulate all valid ways of searching.\npublic class MySearchParameter\n{\n public string FileName { get; private set; }\n public bool FindNullFileNames { get; private set; }\n public void ConditionallySearchFileName(bool getNullFileNames, string fileName)\n {\n FindNullFileNames = getNullFileNames;\n FileName = null;\n\n // enforce either/or and disallow empty string\n if(!getNullFileNames && !string.IsNullOrEmpty(fileName) )\n {\n FileName = fileName;\n }\n }\n // ...\n}\n\n// search method in a business logic layer.\npublic IQueryable<MyClass> Search(MySearchParameter searchParameter)\n{\n IQueryable<MyClass> result = ...; // something to get the initial list.\n\n // search on Filename.\n if (searchParameter.FindNullFileNames)\n {\n result = result.Where(o => o.FileName == null);\n }\n else if( searchParameter.FileName != null )\n { // intermixing a different style, just to show an alternative.\n result = from o in result\n where o.FileName.Contains(searchParameter.FileName)\n select o;\n }\n // search on other stuff...\n\n return result;\n}\n\n// code in the UI ... \nMySearchParameter searchParameter = new MySearchParameter();\nsearchParameter.ConditionallySearchFileName(chkFileNames.Checked, drpFileNames.SelectedItem.Text);\nsearchParameter.ConditionallySearchIPAddress(chkIPAddress.Checked, drpIPAddress.SelectedItem.Text);\n\nIQueryable<MyClass> result = Search(searchParameter);\n\n// inform control to display results.\nsearchResults.Display( result );\n</code></pre>\n\n<p>Yes it's more typing, but you read code around 10x more than you write it. Your UI is clearer, the search parameters class takes care of itself and ensures mutually exclusive options don't collide, and the search code is abstracted away from any UI and doesn't even care if you use Linq at all.</p>\n"
},
{
"answer_id": 132157,
"author": "hurst",
"author_id": 10991,
"author_profile": "https://Stackoverflow.com/users/10991",
"pm_score": 0,
"selected": false,
"text": "<p>Since you are wanting to repeatedly reduce the original results query with innumerable filters, you can use <strong>Aggregate()</strong>, (which corresponds to reduce() in functional languages).</p>\n\n<p>The filters are of predictable form, consisting of two values for every member of MyObject - according to the information I gleaned from your post. If every member to be compared is a string, which may be null, then I recommend using an extension method, which allows for null references to be associated to an extension method of its intended type.</p>\n\n<pre><code>public static class MyObjectExtensions\n{\n public static bool IsMatchFor(this string property, string ddlText, bool chkValue)\n {\n if(ddlText!=null && ddlText!=\"\")\n {\n return property!=null && property.Contains(ddlText);\n }\n else if(chkValue==true)\n {\n return property==null || property==\"\";\n }\n // no filtering selected\n return true;\n }\n}\n</code></pre>\n\n<p>We now need to arrange the property filters in a collection, to allow for iterating over many. They are represented as Expressions for compatibility with IQueryable.</p>\n\n<pre><code>var filters = new List<Expression<Func<MyObject,bool>>>\n{\n x=>x.Filename.IsMatchFor(ddlFileName.SelectedItem.Text,chkFileName.Checked),\n x=>x.IPAddress.IsMatchFor(ddlIPAddress.SelectedItem.Text,chkIPAddress.Checked),\n x=>x.Other.IsMatchFor(ddlOther.SelectedItem.Text,chkOther.Checked),\n // ... innumerable associations\n};\n</code></pre>\n\n<p>Now we aggregate the innumerable filters onto the initial results query:</p>\n\n<pre><code>var filteredResults = filters.Aggregate(results, (r,f) => r.Where(f));\n</code></pre>\n\n<p>I ran this in a console app with simulated test values, and it worked as expected. I think this at least demonstrates the principle.</p>\n"
},
{
"answer_id": 142632,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 0,
"selected": false,
"text": "<p>One thing you might consider is simplifying your UI by eliminating the checkboxes and using an \"<code><empty></code>\" or \"<code><null></code>\" item in your drop down list instead. This would reduce the number of controls taking up space on your window, remove the need for complex \"enable X only if Y is not checked\" logic, and would enable a nice one-control-per-query-field.</p>\n\n<p><br/>\nMoving on to your result query logic, I would start by creating a simple object to represent a filter on your domain object:</p>\n\n<pre><code>interface IDomainObjectFilter {\n bool ShouldInclude( DomainObject o, string target );\n}\n</code></pre>\n\n<p>You can associate an appropriate instance of the filter with each of your UI controls, and then retrieve that when the user initiates a query:</p>\n\n<pre><code>sealed class FileNameFilter : IDomainObjectFilter {\n public bool ShouldInclude( DomainObject o, string target ) {\n return string.IsNullOrEmpty( target )\n || o.FileName.Contains( target );\n }\n}\n\n...\nddlFileName.Tag = new FileNameFilter( );\n</code></pre>\n\n<p>You can then generalize your result filtering by simply enumerating your controls and executing the associated filter (thanks to <a href=\"https://stackoverflow.com/questions/54963/how-would-you-refactor-this-linq-code#132157\">hurst</a> for the Aggregate idea):</p>\n\n<pre><code>var finalResults = ddlControls.Aggregate( initialResults, ( c, r ) => {\n var filter = c.Tag as IDomainObjectFilter;\n var target = c.SelectedValue;\n return r.Where( o => filter.ShouldInclude( o, target ) );\n} );\n</code></pre>\n\n<p><br/>\nSince your queries are so regular, you might be able to simplify the implementation even further by using a single filter class taking a member selector:</p>\n\n<pre><code>sealed class DomainObjectFilter {\n private readonly Func<DomainObject,string> memberSelector_;\n public DomainObjectFilter( Func<DomainObject,string> memberSelector ) {\n this.memberSelector_ = memberSelector;\n }\n\n public bool ShouldInclude( DomainObject o, string target ) {\n string member = this.memberSelector_( o );\n return string.IsNullOrEmpty( target )\n || member.Contains( target );\n }\n}\n\n...\nddlFileName.Tag = new DomainObjectFilter( o => o.FileName );\n</code></pre>\n"
},
{
"answer_id": 142688,
"author": "loudej",
"author_id": 6056,
"author_profile": "https://Stackoverflow.com/users/6056",
"pm_score": 1,
"selected": false,
"text": "<p>Don't use LINQ if it's impacting readability. Factor out the individual tests into boolean methods which can be used as your where expression.</p>\n\n<pre><code>IQueryable<MyObject> results = ...;\n\nresults = results\n .Where(TestFileNameText)\n .Where(TestFileNameChecked)\n .Where(TestIPAddressText)\n .Where(TestIPAddressChecked);\n</code></pre>\n\n<p>So the the individual tests are simple methods on the class. They're even individually unit testable. </p>\n\n<pre><code>bool TestFileNameText(MyObject x)\n{\n return string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) ||\n x.FileName.Contains(ddlFileName.SelectedValue);\n}\n\nbool TestIPAddressChecked(MyObject x)\n{\n return !chkIPAddress.Checked ||\n x.IpAddress == null;\n}\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5486/"
] | I've got a lot of ugly code that looks like this:
```
if (!string.IsNullOrEmpty(ddlFileName.SelectedItem.Text))
results = results.Where(x => x.FileName.Contains(ddlFileName.SelectedValue));
if (chkFileName.Checked)
results = results.Where(x => x.FileName == null);
if (!string.IsNullOrEmpty(ddlIPAddress.SelectedItem.Text))
results = results.Where(x => x.IpAddress.Contains(ddlIPAddress.SelectedValue));
if (chkIPAddress.Checked)
results = results.Where(x => x.IpAddress == null);
...etc.
```
`results` is an `IQueryable<MyObject>`.
The idea is that for each of these innumerable dropdowns and checkboxes, if the dropdown has something selected, the user wants to match that item. If the checkbox is checked, the user wants specifically those records where that field is null or an empty string. (The UI doesn't let both be selected at the same time.) This all adds to the LINQ Expression which gets executed at the end, after we've added all the conditions.
It *seems* like there ought to be some way to pull out an `Expression<Func<MyObject, bool>>` or two so that I can put the repeated parts in a method and just pass in what changes. I've done this in other places, but this set of code has me stymied. (Also, I'd like to avoid "Dynamic LINQ", because I want to keep things type-safe if possible.) Any ideas? | I'd convert it into a single Linq statement:
```
var results =
//get your inital results
from x in GetInitialResults()
//either we don't need to check, or the check passes
where string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) ||
x.FileName.Contains(ddlFileName.SelectedValue)
where !chkFileName.Checked ||
string.IsNullOrEmpty(x.FileName)
where string.IsNullOrEmpty(ddlIPAddress.SelectedItem.Text) ||
x.FileName.Contains(ddlIPAddress.SelectedValue)
where !chkIPAddress.Checked ||
string.IsNullOrEmpty(x. IpAddress)
select x;
```
It's no shorter, but I find this logic clearer. |
54,966 | <p>How would I go about replacing Windows Explorer with a third party tool such as TotalCommander, explorer++, etc?</p>
<p>I would like to have one of those load instead of win explorer when I type "C:\directoryName" into the run window. Is this possible?</p>
| [
{
"answer_id": 55021,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 3,
"selected": true,
"text": "<p>From a comment on the first LifeHacker link,</p>\n\n<h3>How to make x² your default folder application</h3>\n\n<p>As part of the installation process, x² adds \"open with xplorer2\" in the context menu for\nfilesystem folders.</p>\n\n<p>If you want to have this the default action (so that folders always open in x2 when you click on\nthem) then make sure this is the default verb, either using Folder Options (\"file folder\" type) or\nediting the registry:</p>\n\n<pre><code>[HKEY_CLASSES_ROOT\\Directory\\shell]\n@=\"open_x2\"\n</code></pre>\n\n<p>If you want some slightly different command line options, you can add any of the supported\noptions by editing the following registry key:</p>\n\n<pre><code>[HKEY_CLASSES_ROOT\\Directory\\shell\\open\\command]\n@=\"C:\\Program files\\zabkat\\xplorer2\\xplorer2_UC.exe\" /T /1 \"%1\"\n</code></pre>\n\n<p>Notes:</p>\n\n<ol>\n<li><p>Please check your installation folder first: Your installation path may be different.\nSecondly, your executable may be called <code>xplorer2.exe</code>, if it is the non-Unicode version.</p></li>\n<li><p>Note that <code>\"%1\"</code> is required (including the quotation marks), and is replaced by the folder path you are trying to open.</p></li>\n<li><p>The <code>/T</code> switch causes no tabs to be restored and the <code>/1</code> switch puts x² in single pane mode. (You do not have to use these switches, but they make sense).</p></li>\n</ol>\n\n<p><em>(The above are from xplorer2 user manual)</em></p>\n"
},
{
"answer_id": 55033,
"author": "Howler",
"author_id": 2871,
"author_profile": "https://Stackoverflow.com/users/2871",
"pm_score": 0,
"selected": false,
"text": "<p>If you go to Control Panel -> Folder Options And go to the File Types tab. You can go to the \"Folder\" file type (with \"(NONE)\" as the extension). Go to Advanced, create a new action that uses your program (I tried it with FreeCommander). Make sure you set it as default.</p>\n\n<p>That should do it.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385358/"
] | How would I go about replacing Windows Explorer with a third party tool such as TotalCommander, explorer++, etc?
I would like to have one of those load instead of win explorer when I type "C:\directoryName" into the run window. Is this possible? | From a comment on the first LifeHacker link,
### How to make x² your default folder application
As part of the installation process, x² adds "open with xplorer2" in the context menu for
filesystem folders.
If you want to have this the default action (so that folders always open in x2 when you click on
them) then make sure this is the default verb, either using Folder Options ("file folder" type) or
editing the registry:
```
[HKEY_CLASSES_ROOT\Directory\shell]
@="open_x2"
```
If you want some slightly different command line options, you can add any of the supported
options by editing the following registry key:
```
[HKEY_CLASSES_ROOT\Directory\shell\open\command]
@="C:\Program files\zabkat\xplorer2\xplorer2_UC.exe" /T /1 "%1"
```
Notes:
1. Please check your installation folder first: Your installation path may be different.
Secondly, your executable may be called `xplorer2.exe`, if it is the non-Unicode version.
2. Note that `"%1"` is required (including the quotation marks), and is replaced by the folder path you are trying to open.
3. The `/T` switch causes no tabs to be restored and the `/1` switch puts x² in single pane mode. (You do not have to use these switches, but they make sense).
*(The above are from xplorer2 user manual)* |
54,991 | <p>When a user on our site loses his password and heads off to the Lost Password page we need to give him a new temporary password. I don't really mind how random this is, or if it matches all the "needed" strong password rules, all I want to do is give them a password that they can change later.</p>
<p>The application is a Web application written in C#. so I was thinking of being mean and going for the easy route of using part of a Guid. i.e.</p>
<pre><code>Guid.NewGuid().ToString("d").Substring(1,8)
</code></pre>
<p>Suggesstions? thoughts?</p>
| [
{
"answer_id": 54994,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 5,
"selected": false,
"text": "<p>This is a lot larger, but I think it looks a little more comprehensive:\n<a href=\"http://www.obviex.com/Samples/Password.aspx\" rel=\"noreferrer\">http://www.obviex.com/Samples/Password.aspx</a></p>\n\n<pre><code>///////////////////////////////////////////////////////////////////////////////\n// SAMPLE: Generates random password, which complies with the strong password\n// rules and does not contain ambiguous characters.\n//\n// To run this sample, create a new Visual C# project using the Console\n// Application template and replace the contents of the Class1.cs file with\n// the code below.\n//\n// THIS CODE AND INFORMATION IS PROVIDED \"AS IS\" WITHOUT WARRANTY OF ANY KIND,\n// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED\n// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.\n// \n// Copyright (C) 2004 Obviex(TM). All rights reserved.\n// \nusing System;\nusing System.Security.Cryptography;\n\n/// <summary>\n/// This class can generate random passwords, which do not include ambiguous \n/// characters, such as I, l, and 1. The generated password will be made of\n/// 7-bit ASCII symbols. Every four characters will include one lower case\n/// character, one upper case character, one number, and one special symbol\n/// (such as '%') in a random order. The password will always start with an\n/// alpha-numeric character; it will not start with a special symbol (we do\n/// this because some back-end systems do not like certain special\n/// characters in the first position).\n/// </summary>\npublic class RandomPassword\n{\n // Define default min and max password lengths.\n private static int DEFAULT_MIN_PASSWORD_LENGTH = 8;\n private static int DEFAULT_MAX_PASSWORD_LENGTH = 10;\n\n // Define supported password characters divided into groups.\n // You can add (or remove) characters to (from) these groups.\n private static string PASSWORD_CHARS_LCASE = \"abcdefgijkmnopqrstwxyz\";\n private static string PASSWORD_CHARS_UCASE = \"ABCDEFGHJKLMNPQRSTWXYZ\";\n private static string PASSWORD_CHARS_NUMERIC= \"23456789\";\n private static string PASSWORD_CHARS_SPECIAL= \"*$-+?_&=!%{}/\";\n\n /// <summary>\n /// Generates a random password.\n /// </summary>\n /// <returns>\n /// Randomly generated password.\n /// </returns>\n /// <remarks>\n /// The length of the generated password will be determined at\n /// random. It will be no shorter than the minimum default and\n /// no longer than maximum default.\n /// </remarks>\n public static string Generate()\n {\n return Generate(DEFAULT_MIN_PASSWORD_LENGTH, \n DEFAULT_MAX_PASSWORD_LENGTH);\n }\n\n /// <summary>\n /// Generates a random password of the exact length.\n /// </summary>\n /// <param name=\"length\">\n /// Exact password length.\n /// </param>\n /// <returns>\n /// Randomly generated password.\n /// </returns>\n public static string Generate(int length)\n {\n return Generate(length, length);\n }\n\n /// <summary>\n /// Generates a random password.\n /// </summary>\n /// <param name=\"minLength\">\n /// Minimum password length.\n /// </param>\n /// <param name=\"maxLength\">\n /// Maximum password length.\n /// </param>\n /// <returns>\n /// Randomly generated password.\n /// </returns>\n /// <remarks>\n /// The length of the generated password will be determined at\n /// random and it will fall with the range determined by the\n /// function parameters.\n /// </remarks>\n public static string Generate(int minLength,\n int maxLength)\n {\n // Make sure that input parameters are valid.\n if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)\n return null;\n\n // Create a local array containing supported password characters\n // grouped by types. You can remove character groups from this\n // array, but doing so will weaken the password strength.\n char[][] charGroups = new char[][] \n {\n PASSWORD_CHARS_LCASE.ToCharArray(),\n PASSWORD_CHARS_UCASE.ToCharArray(),\n PASSWORD_CHARS_NUMERIC.ToCharArray(),\n PASSWORD_CHARS_SPECIAL.ToCharArray()\n };\n\n // Use this array to track the number of unused characters in each\n // character group.\n int[] charsLeftInGroup = new int[charGroups.Length];\n\n // Initially, all characters in each group are not used.\n for (int i=0; i<charsLeftInGroup.Length; i++)\n charsLeftInGroup[i] = charGroups[i].Length;\n\n // Use this array to track (iterate through) unused character groups.\n int[] leftGroupsOrder = new int[charGroups.Length];\n\n // Initially, all character groups are not used.\n for (int i=0; i<leftGroupsOrder.Length; i++)\n leftGroupsOrder[i] = i;\n\n // Because we cannot use the default randomizer, which is based on the\n // current time (it will produce the same \"random\" number within a\n // second), we will use a random number generator to seed the\n // randomizer.\n\n // Use a 4-byte array to fill it with random bytes and convert it then\n // to an integer value.\n byte[] randomBytes = new byte[4];\n\n // Generate 4 random bytes.\n RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();\n rng.GetBytes(randomBytes);\n\n // Convert 4 bytes into a 32-bit integer value.\n int seed = BitConverter.ToInt32(randomBytes, 0);\n\n // Now, this is real randomization.\n Random random = new Random(seed);\n\n // This array will hold password characters.\n char[] password = null;\n\n // Allocate appropriate memory for the password.\n if (minLength < maxLength)\n password = new char[random.Next(minLength, maxLength+1)];\n else\n password = new char[minLength];\n\n // Index of the next character to be added to password.\n int nextCharIdx;\n\n // Index of the next character group to be processed.\n int nextGroupIdx;\n\n // Index which will be used to track not processed character groups.\n int nextLeftGroupsOrderIdx;\n\n // Index of the last non-processed character in a group.\n int lastCharIdx;\n\n // Index of the last non-processed group.\n int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;\n\n // Generate password characters one at a time.\n for (int i=0; i<password.Length; i++)\n {\n // If only one character group remained unprocessed, process it;\n // otherwise, pick a random character group from the unprocessed\n // group list. To allow a special character to appear in the\n // first position, increment the second parameter of the Next\n // function call by one, i.e. lastLeftGroupsOrderIdx + 1.\n if (lastLeftGroupsOrderIdx == 0)\n nextLeftGroupsOrderIdx = 0;\n else\n nextLeftGroupsOrderIdx = random.Next(0, \n lastLeftGroupsOrderIdx);\n\n // Get the actual index of the character group, from which we will\n // pick the next character.\n nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];\n\n // Get the index of the last unprocessed characters in this group.\n lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;\n\n // If only one unprocessed character is left, pick it; otherwise,\n // get a random character from the unused character list.\n if (lastCharIdx == 0)\n nextCharIdx = 0;\n else\n nextCharIdx = random.Next(0, lastCharIdx+1);\n\n // Add this character to the password.\n password[i] = charGroups[nextGroupIdx][nextCharIdx];\n\n // If we processed the last character in this group, start over.\n if (lastCharIdx == 0)\n charsLeftInGroup[nextGroupIdx] = \n charGroups[nextGroupIdx].Length;\n // There are more unprocessed characters left.\n else\n {\n // Swap processed character with the last unprocessed character\n // so that we don't pick it until we process all characters in\n // this group.\n if (lastCharIdx != nextCharIdx)\n {\n char temp = charGroups[nextGroupIdx][lastCharIdx];\n charGroups[nextGroupIdx][lastCharIdx] = \n charGroups[nextGroupIdx][nextCharIdx];\n charGroups[nextGroupIdx][nextCharIdx] = temp;\n }\n // Decrement the number of unprocessed characters in\n // this group.\n charsLeftInGroup[nextGroupIdx]--;\n }\n\n // If we processed the last group, start all over.\n if (lastLeftGroupsOrderIdx == 0)\n lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;\n // There are more unprocessed groups left.\n else\n {\n // Swap processed group with the last unprocessed group\n // so that we don't pick it until we process all groups.\n if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)\n {\n int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];\n leftGroupsOrder[lastLeftGroupsOrderIdx] = \n leftGroupsOrder[nextLeftGroupsOrderIdx];\n leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;\n }\n // Decrement the number of unprocessed groups.\n lastLeftGroupsOrderIdx--;\n }\n }\n\n // Convert password characters into a string and return the result.\n return new string(password);\n }\n}\n\n/// <summary>\n/// Illustrates the use of the RandomPassword class.\n/// </summary>\npublic class RandomPasswordTest\n{\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main(string[] args)\n {\n // Print 100 randomly generated passwords (8-to-10 char long).\n for (int i=0; i<100; i++)\n Console.WriteLine(RandomPassword.Generate(8, 10));\n }\n}\n//\n// END OF FILE\n///////////////////////////////////////////////////////////////////////////////\n</code></pre>\n"
},
{
"answer_id": 54997,
"author": "Radu094",
"author_id": 3263,
"author_profile": "https://Stackoverflow.com/users/3263",
"pm_score": 7,
"selected": false,
"text": "<pre><code>public string CreatePassword(int length)\n{\n const string valid = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\";\n StringBuilder res = new StringBuilder();\n Random rnd = new Random();\n while (0 < length--)\n {\n res.Append(valid[rnd.Next(valid.Length)]);\n }\n return res.ToString();\n}\n</code></pre>\n\n<p>This has a good benefit of being able to choose from a list of available characters for the generated password (e.g. digits only, only uppercase or only lowercase etc.)</p>\n"
},
{
"answer_id": 55023,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 3,
"selected": false,
"text": "<p>For this sort of password, I tend to use a system that's likely to generate more easily \"used\" passwords. Short, often made up of pronouncable fragments and a few numbers, and with no intercharacter ambiguity (is that a 0 or an O? A 1 or an I?). Something like</p>\n\n<pre><code>string[] words = { 'bur', 'ler', 'meh', 'ree' };\nstring word = \"\";\n\nRandom rnd = new Random();\nfor (i = 0; i < 3; i++)\n word += words[rnd.Next(words.length)]\n\nint numbCount = rnd.Next(4);\nfor (i = 0; i < numbCount; i++)\n word += (2 + rnd.Next(7)).ToString();\n\nreturn word;\n</code></pre>\n\n<p>(Typed right into the browser, so use only as guidelines. Also, add more words).</p>\n"
},
{
"answer_id": 55028,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 1,
"selected": false,
"text": "<p>I like to look at generating passwords, just like generating software keys. You should choose from an array of characters that follow a good practice. Take what <a href=\"https://stackoverflow.com/questions/54991/generating-random-passwords#54997\">@Radu094 answered</a> with and modify it to follow good practice. Don't put every single letter in the character array. Some letters are harder to say or understand over the phone.</p>\n\n<p>You should also consider using a checksum on the password that was generated to make sure that it was generated by you. A good way of accomplishing this is to use the <a href=\"http://en.wikipedia.org/wiki/Luhn_algorithm\" rel=\"nofollow noreferrer\">LUHN algorithm</a>.</p>\n"
},
{
"answer_id": 55447,
"author": "Rik",
"author_id": 5409,
"author_profile": "https://Stackoverflow.com/users/5409",
"pm_score": 10,
"selected": true,
"text": "<p>There's always <a href=\"http://msdn.microsoft.com/en-us/library/system.web.security.membership.generatepassword.aspx\" rel=\"noreferrer\"><code>System.Web.Security.Membership.GeneratePassword(int length, int numberOfNonAlphanumericCharacters</code>)</a>.</p>\n"
},
{
"answer_id": 4757527,
"author": "Matt Frear",
"author_id": 32598,
"author_profile": "https://Stackoverflow.com/users/32598",
"pm_score": 3,
"selected": false,
"text": "<p>I don't like the passwords that Membership.GeneratePassword() creates, as they're too ugly and have too many special characters.</p>\n<p>This code generates a 10 digit not-too-ugly password.</p>\n<pre><code>string password = Guid.NewGuid().ToString("N").ToLower()\n .Replace("1", "").Replace("o", "").Replace("0","")\n .Substring(0,10);\n</code></pre>\n<p>Sure, I could use a Regex to do all the replaces but this is more readable and maintainable IMO.</p>\n"
},
{
"answer_id": 10600220,
"author": "Hugo",
"author_id": 1396093,
"author_profile": "https://Stackoverflow.com/users/1396093",
"pm_score": 2,
"selected": false,
"text": "<p>I created this method similar to the available in the membership provider. This is usefull if you don't want to add the web reference in some applications.</p>\n\n<p>It works great.</p>\n\n<pre><code>public static string GeneratePassword(int Length, int NonAlphaNumericChars)\n {\n string allowedChars = \"abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789\";\n string allowedNonAlphaNum = \"!@#$%^&*()_-+=[{]};:<>|./?\";\n Random rd = new Random();\n\n if (NonAlphaNumericChars > Length || Length <= 0 || NonAlphaNumericChars < 0)\n throw new ArgumentOutOfRangeException();\n\n char[] pass = new char[Length];\n int[] pos = new int[Length];\n int i = 0, j = 0, temp = 0;\n bool flag = false;\n\n //Random the position values of the pos array for the string Pass\n while (i < Length - 1)\n {\n j = 0;\n flag = false;\n temp = rd.Next(0, Length);\n for (j = 0; j < Length; j++)\n if (temp == pos[j])\n {\n flag = true;\n j = Length;\n }\n\n if (!flag)\n {\n pos[i] = temp;\n i++;\n }\n }\n\n //Random the AlphaNumericChars\n for (i = 0; i < Length - NonAlphaNumericChars; i++)\n pass[i] = allowedChars[rd.Next(0, allowedChars.Length)];\n\n //Random the NonAlphaNumericChars\n for (i = Length - NonAlphaNumericChars; i < Length; i++)\n pass[i] = allowedNonAlphaNum[rd.Next(0, allowedNonAlphaNum.Length)];\n\n //Set the sorted array values by the pos array for the rigth posistion\n char[] sorted = new char[Length];\n for (i = 0; i < Length; i++)\n sorted[i] = pass[pos[i]];\n\n string Pass = new String(sorted);\n\n return Pass;\n }\n</code></pre>\n"
},
{
"answer_id": 14287335,
"author": "Troy Alford",
"author_id": 1454806,
"author_profile": "https://Stackoverflow.com/users/1454806",
"pm_score": 3,
"selected": false,
"text": "<p>I know that this is an old thread, but I have what might be a fairly simple solution for someone to use. Easy to implement, easy to understand, and easy to validate.</p>\n\n<p>Consider the following requirement:</p>\n\n<blockquote>\n <p>I need a random password to be generated which has at least 2 lower-case letters, 2 upper-case letters and 2 numbers. The password must also be a minimum of 8 characters in length.</p>\n</blockquote>\n\n<p>The following regular expression can validate this case:</p>\n\n<pre><code>^(?=\\b\\w*[a-z].*[a-z]\\w*\\b)(?=\\b\\w*[A-Z].*[A-Z]\\w*\\b)(?=\\b\\w*[0-9].*[0-9]\\w*\\b)[a-zA-Z0-9]{8,}$\n</code></pre>\n\n<p>It's outside the scope of this question - but the regex is based on <a href=\"http://www.regular-expressions.info/lookaround.html\">lookahead/lookbehind</a> and <a href=\"http://www.regular-expressions.info/lookaround.html\">lookaround</a>.</p>\n\n<p>The following code will create a random set of characters which match this requirement:</p>\n\n<pre><code>public static string GeneratePassword(int lowercase, int uppercase, int numerics) {\n string lowers = \"abcdefghijklmnopqrstuvwxyz\";\n string uppers = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n string number = \"0123456789\";\n\n Random random = new Random();\n\n string generated = \"!\";\n for (int i = 1; i <= lowercase; i++)\n generated = generated.Insert(\n random.Next(generated.Length), \n lowers[random.Next(lowers.Length - 1)].ToString()\n );\n\n for (int i = 1; i <= uppercase; i++)\n generated = generated.Insert(\n random.Next(generated.Length), \n uppers[random.Next(uppers.Length - 1)].ToString()\n );\n\n for (int i = 1; i <= numerics; i++)\n generated = generated.Insert(\n random.Next(generated.Length), \n number[random.Next(number.Length - 1)].ToString()\n );\n\n return generated.Replace(\"!\", string.Empty);\n\n}\n</code></pre>\n\n<p>To meet the above requirement, simply call the following:</p>\n\n<pre><code>String randomPassword = GeneratePassword(3, 3, 3);\n</code></pre>\n\n<p>The code starts with an invalid character (<code>\"!\"</code>) - so that the string has a length into which new characters can be injected.</p>\n\n<p>It then loops from 1 to the # of lowercase characters required, and on each iteration, grabs a random item from the lowercase list, and injects it at a random location in the string.</p>\n\n<p>It then repeats the loop for uppercase letters and for numerics.</p>\n\n<p>This gives you back strings of length = <code>lowercase + uppercase + numerics</code> into which lowercase, uppercase and numeric characters of the count you want have been placed in a random order.</p>\n"
},
{
"answer_id": 19067818,
"author": "Joe",
"author_id": 2724942,
"author_profile": "https://Stackoverflow.com/users/2724942",
"pm_score": -1,
"selected": false,
"text": "<p>Insert a Timer: timer1, 2 buttons: button1, button2, 1 textBox: textBox1, and a comboBox: comboBox1. Make sure you declare:</p>\n\n<pre><code>int count = 0;\n</code></pre>\n\n<hr>\n\n<p>Source Code:</p>\n\n<pre><code> private void button1_Click(object sender, EventArgs e)\n {\n // This clears the textBox, resets the count, and starts the timer\n count = 0;\n textBox1.Clear();\n timer1.Start();\n }\n\n private void timer1_Tick(object sender, EventArgs e)\n {\n // This generates the password, and types it in the textBox\n count += 1;\n string possible = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890\";\n string psw = \"\";\n Random rnd = new Random { };\n psw += possible[rnd.Next(possible.Length)];\n textBox1.Text += psw;\n if (count == (comboBox1.SelectedIndex + 1))\n {\n timer1.Stop();\n }\n }\n private void Form1_Load(object sender, EventArgs e)\n {\n // This adds password lengths to the comboBox to choose from.\n comboBox1.Items.Add(\"1\");\n comboBox1.Items.Add(\"2\");\n comboBox1.Items.Add(\"3\");\n comboBox1.Items.Add(\"4\");\n comboBox1.Items.Add(\"5\");\n comboBox1.Items.Add(\"6\");\n comboBox1.Items.Add(\"7\");\n comboBox1.Items.Add(\"8\");\n comboBox1.Items.Add(\"9\");\n comboBox1.Items.Add(\"10\");\n comboBox1.Items.Add(\"11\");\n comboBox1.Items.Add(\"12\");\n }\n private void button2_click(object sender, EventArgs e)\n {\n // This encrypts the password\n tochar = textBox1.Text;\n textBox1.Clear();\n char[] carray = tochar.ToCharArray();\n for (int i = 0; i < carray.Length; i++)\n {\n int num = Convert.ToInt32(carray[i]) + 10;\n string cvrt = Convert.ToChar(num).ToString();\n textBox1.Text += cvrt;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 19068116,
"author": "CodesInChaos",
"author_id": 445517,
"author_profile": "https://Stackoverflow.com/users/445517",
"pm_score": 6,
"selected": false,
"text": "<p>The main goals of my code are:</p>\n\n<ol>\n<li>The distribution of strings is almost uniform (don't care about minor deviations, as long as they're small)</li>\n<li>It outputs more than a few billion strings for each argument set. Generating an 8 character string (~47 bits of entropy) is meaningless if your PRNG only generates 2 billion (31 bits of entropy) different values.</li>\n<li>It's secure, since I expect people to use this for passwords or other security tokens.</li>\n</ol>\n\n<p>The first property is achieved by taking a 64 bit value modulo the alphabet size. For small alphabets (such as the 62 characters from the question) this leads to negligible bias. The second and third property are achieved by using <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx\" rel=\"noreferrer\"><code>RNGCryptoServiceProvider</code></a> instead of <a href=\"http://msdn.microsoft.com/en-us/library/system.random.aspx\" rel=\"noreferrer\"><code>System.Random</code></a>.</p>\n\n<pre><code>using System;\nusing System.Security.Cryptography;\n\npublic static string GetRandomAlphanumericString(int length)\n{\n const string alphanumericCharacters =\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\" +\n \"abcdefghijklmnopqrstuvwxyz\" +\n \"0123456789\";\n return GetRandomString(length, alphanumericCharacters);\n}\n\npublic static string GetRandomString(int length, IEnumerable<char> characterSet)\n{\n if (length < 0)\n throw new ArgumentException(\"length must not be negative\", \"length\");\n if (length > int.MaxValue / 8) // 250 million chars ought to be enough for anybody\n throw new ArgumentException(\"length is too big\", \"length\");\n if (characterSet == null)\n throw new ArgumentNullException(\"characterSet\");\n var characterArray = characterSet.Distinct().ToArray();\n if (characterArray.Length == 0)\n throw new ArgumentException(\"characterSet must not be empty\", \"characterSet\");\n\n var bytes = new byte[length * 8];\n new RNGCryptoServiceProvider().GetBytes(bytes);\n var result = new char[length];\n for (int i = 0; i < length; i++)\n {\n ulong value = BitConverter.ToUInt64(bytes, i * 8);\n result[i] = characterArray[value % (uint)characterArray.Length];\n }\n return new string(result);\n}\n</code></pre>\n\n<p><em>(This is a copy of my answer to <a href=\"https://stackoverflow.com/questions/1344221/how-can-i-generate-random-8-character-alphanumeric-strings-in-c/13416143#13416143\">How can I generate random 8 character, alphanumeric strings in C#?</a>)</em></p>\n"
},
{
"answer_id": 19613574,
"author": "user1058637",
"author_id": 1058637,
"author_profile": "https://Stackoverflow.com/users/1058637",
"pm_score": -1,
"selected": false,
"text": "<p>This is short and it works great for me.</p>\n\n<pre><code>public static string GenerateRandomCode(int length)\n{\n Random rdm = new Random();\n StringBuilder sb = new StringBuilder();\n\n for(int i = 0; i < length; i++)\n sb.Append(Convert.ToChar(rdm.Next(101,132)));\n\n return sb.ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 23973810,
"author": "Alex Siepman",
"author_id": 1333374,
"author_profile": "https://Stackoverflow.com/users/1333374",
"pm_score": 3,
"selected": false,
"text": "<p>I created <a href=\"https://www.siepman.nl/blog/random-password-generator-with-numbers-and-special-characters\" rel=\"nofollow noreferrer\">this class</a> that uses RNGCryptoServiceProvider and it is flexible. Example:</p>\n\n<pre><code>var generator = new PasswordGenerator(minimumLengthPassword: 8,\n maximumLengthPassword: 15,\n minimumUpperCaseChars: 2,\n minimumNumericChars: 3,\n minimumSpecialChars: 2);\nstring password = generator.Generate();\n</code></pre>\n"
},
{
"answer_id": 24711536,
"author": "anaximander",
"author_id": 1448943,
"author_profile": "https://Stackoverflow.com/users/1448943",
"pm_score": 5,
"selected": false,
"text": "<pre><code>public string GenerateToken(int length)\n{\n using (RNGCryptoServiceProvider cryptRNG = new RNGCryptoServiceProvider())\n {\n byte[] tokenBuffer = new byte[length];\n cryptRNG.GetBytes(tokenBuffer);\n return Convert.ToBase64String(tokenBuffer);\n }\n}\n</code></pre>\n\n<p><em>(You could also have the class where this method lives implement IDisposable, hold a reference to the <code>RNGCryptoServiceProvider</code>, and dispose of it properly, to avoid repeatedly instantiating it.)</em></p>\n\n<p>It's been noted that as this returns a base-64 string, the output length is always a multiple of 4, with the extra space using <code>=</code> as a padding character. The <code>length</code> parameter specifies the length of the byte buffer, not the output string (and is therefore perhaps not the best name for that parameter, now I think about it). This controls how many bytes of <a href=\"http://en.wikipedia.org/wiki/Password_strength#Entropy_as_a_measure_of_password_strength\" rel=\"noreferrer\">entropy</a> the password will have. However, because base-64 uses a 4-character block to encode each 3 bytes of input, if you ask for a length that's not a multiple of 3, there will be some extra \"space\", and it'll use <code>=</code> to fill the extra.</p>\n\n<p>If you don't like using base-64 strings for any reason, you can replace the <code>Convert.ToBase64String()</code> call with either a conversion to regular string, or with any of the <code>Encoding</code> methods; eg. <code>Encoding.UTF8.GetString(tokenBuffer)</code> - just make sure you pick a character set that can represent the full range of values coming out of the RNG, and that produces characters that are compatible with wherever you're sending or storing this. Using Unicode, for example, tends to give a lot of Chinese characters. Using base-64 guarantees a widely-compatible set of characters, and the characteristics of such a string shouldn't make it any less secure as long as you use a decent hashing algorithm.</p>\n"
},
{
"answer_id": 29334830,
"author": "GRUNGER",
"author_id": 4727475,
"author_profile": "https://Stackoverflow.com/users/4727475",
"pm_score": -1,
"selected": false,
"text": "<p>On my website I use this method:</p>\n\n<pre><code> //Symb array\n private const string _SymbolsAll = \"~`!@#$%^&*()_+=-\\\\|[{]}'\\\";:/?.>,<\";\n\n //Random symb\n public string GetSymbol(int Length)\n {\n Random Rand = new Random(DateTime.Now.Millisecond);\n StringBuilder result = new StringBuilder();\n for (int i = 0; i < Length; i++)\n result.Append(_SymbolsAll[Rand.Next(0, _SymbolsAll.Length)]);\n return result.ToString();\n }\n</code></pre>\n\n<p>Edit string <code>_SymbolsAll</code> for your array list. </p>\n"
},
{
"answer_id": 30830874,
"author": "Peter",
"author_id": 328968,
"author_profile": "https://Stackoverflow.com/users/328968",
"pm_score": 2,
"selected": false,
"text": "<p>I've always been very happy with the password generator built-in to KeePass. Since KeePass is a .Net program, and open source, I decided to dig around the code a bit. I ended up just referncing KeePass.exe, the copy provided in the standard application install, as a reference in my project and writing the code below. You can see how flexible it is thanks to KeePass. You can specify length, which characters to include/not include, etc...</p>\n\n<pre><code>using KeePassLib.Cryptography.PasswordGenerator;\nusing KeePassLib.Security;\n\n\npublic static string GeneratePassword(int passwordLength, bool lowerCase, bool upperCase, bool digits,\n bool punctuation, bool brackets, bool specialAscii, bool excludeLookAlike)\n {\n var ps = new ProtectedString();\n var profile = new PwProfile();\n profile.CharSet = new PwCharSet();\n profile.CharSet.Clear();\n\n if (lowerCase)\n profile.CharSet.AddCharSet('l');\n if(upperCase)\n profile.CharSet.AddCharSet('u');\n if(digits)\n profile.CharSet.AddCharSet('d');\n if (punctuation)\n profile.CharSet.AddCharSet('p');\n if (brackets)\n profile.CharSet.AddCharSet('b');\n if (specialAscii)\n profile.CharSet.AddCharSet('s');\n\n profile.ExcludeLookAlike = excludeLookAlike;\n profile.Length = (uint)passwordLength;\n profile.NoRepeatingCharacters = true;\n\n KeePassLib.Cryptography.PasswordGenerator.PwGenerator.Generate(out ps, profile, null, _pool);\n\n return ps.ReadString();\n }\n</code></pre>\n"
},
{
"answer_id": 34060765,
"author": "Skyler Campbell",
"author_id": 2465875,
"author_profile": "https://Stackoverflow.com/users/2465875",
"pm_score": -1,
"selected": false,
"text": "<p>Here Is what i put together quickly. </p>\n\n<pre><code> public string GeneratePassword(int len)\n {\n string res = \"\";\n Random rnd = new Random();\n while (res.Length < len) res += (new Func<Random, string>((r) => {\n char c = (char)((r.Next(123) * DateTime.Now.Millisecond % 123)); \n return (Char.IsLetterOrDigit(c)) ? c.ToString() : \"\"; \n }))(rnd);\n return res;\n }\n</code></pre>\n"
},
{
"answer_id": 35722429,
"author": "Ercan ILIK",
"author_id": 5166814,
"author_profile": "https://Stackoverflow.com/users/5166814",
"pm_score": -1,
"selected": false,
"text": "<pre><code>public string Sifre_Uret(int boy, int noalfa)\n{\n\n // 01.03.2016 \n // Genel amaçlı şifre üretme fonksiyonu\n\n\n //Fonskiyon 128 den büyük olmasına izin vermiyor.\n if (boy > 128 ) { boy = 128; }\n if (noalfa > 128) { noalfa = 128; }\n if (noalfa > boy) { noalfa = boy; }\n\n\n string passch = System.Web.Security.Membership.GeneratePassword(boy, noalfa);\n\n //URL encoding ve Url Pass + json sorunu yaratabilecekler pass ediliyor.\n //Microsoft Garanti etmiyor. Alfa Sayısallar Olabiliyorimiş . !@#$%^&*()_-+=[{]};:<>|./?.\n //https://msdn.microsoft.com/tr-tr/library/system.web.security.membership.generatepassword(v=vs.110).aspx\n\n\n //URL ve Json ajax lar için filtreleme\n passch = passch.Replace(\":\", \"z\");\n passch = passch.Replace(\";\", \"W\");\n passch = passch.Replace(\"'\", \"t\");\n passch = passch.Replace(\"\\\"\", \"r\");\n passch = passch.Replace(\"/\", \"+\");\n passch = passch.Replace(\"\\\\\", \"e\");\n\n passch = passch.Replace(\"?\", \"9\");\n passch = passch.Replace(\"&\", \"8\");\n passch = passch.Replace(\"#\", \"D\");\n passch = passch.Replace(\"%\", \"u\");\n passch = passch.Replace(\"=\", \"4\");\n passch = passch.Replace(\"~\", \"1\");\n\n passch = passch.Replace(\"[\", \"2\");\n passch = passch.Replace(\"]\", \"3\");\n passch = passch.Replace(\"{\", \"g\");\n passch = passch.Replace(\"}\", \"J\");\n\n\n //passch = passch.Replace(\"(\", \"6\");\n //passch = passch.Replace(\")\", \"0\");\n //passch = passch.Replace(\"|\", \"p\");\n //passch = passch.Replace(\"@\", \"4\");\n //passch = passch.Replace(\"!\", \"u\");\n //passch = passch.Replace(\"$\", \"Z\");\n //passch = passch.Replace(\"*\", \"5\");\n //passch = passch.Replace(\"_\", \"a\");\n\n passch = passch.Replace(\",\", \"V\");\n passch = passch.Replace(\".\", \"N\");\n passch = passch.Replace(\"+\", \"w\");\n passch = passch.Replace(\"-\", \"7\");\n\n\n\n\n\n return passch;\n\n\n\n}\n</code></pre>\n"
},
{
"answer_id": 41449547,
"author": "Matt",
"author_id": 2157661,
"author_profile": "https://Stackoverflow.com/users/2157661",
"pm_score": -1,
"selected": false,
"text": "<p>Added some supplemental code to the accepted answer. It improves upon answers just using Random and allows for some password options. I also liked some of the options from the KeePass answer but did not want to include the executable in my solution.</p>\n\n<pre><code>private string RandomPassword(int length, bool includeCharacters, bool includeNumbers, bool includeUppercase, bool includeNonAlphaNumericCharacters, bool includeLookAlikes)\n{\n if (length < 8 || length > 128) throw new ArgumentOutOfRangeException(\"length\");\n if (!includeCharacters && !includeNumbers && !includeNonAlphaNumericCharacters) throw new ArgumentException(\"RandomPassword-Key arguments all false, no values would be returned\");\n\n string pw = \"\";\n do\n {\n pw += System.Web.Security.Membership.GeneratePassword(128, 25);\n pw = RemoveCharacters(pw, includeCharacters, includeNumbers, includeUppercase, includeNonAlphaNumericCharacters, includeLookAlikes);\n } while (pw.Length < length);\n\n return pw.Substring(0, length);\n}\n\nprivate string RemoveCharacters(string passwordString, bool includeCharacters, bool includeNumbers, bool includeUppercase, bool includeNonAlphaNumericCharacters, bool includeLookAlikes)\n{\n if (!includeCharacters)\n {\n var remove = new string[] { \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\" };\n foreach (string r in remove)\n {\n passwordString = passwordString.Replace(r, string.Empty);\n passwordString = passwordString.Replace(r.ToUpper(), string.Empty);\n }\n }\n\n if (!includeNumbers)\n {\n var remove = new string[] { \"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\" };\n foreach (string r in remove)\n passwordString = passwordString.Replace(r, string.Empty);\n }\n\n if (!includeUppercase)\n passwordString = passwordString.ToLower();\n\n if (!includeNonAlphaNumericCharacters)\n {\n var remove = new string[] { \"!\", \"@\", \"#\", \"$\", \"%\", \"^\", \"&\", \"*\", \"(\", \")\", \"-\", \"_\", \"+\", \"=\", \"{\", \"}\", \"[\", \"]\", \"|\", \"\\\\\", \":\", \";\", \"<\", \">\", \"/\", \"?\", \".\" };\n foreach (string r in remove)\n passwordString = passwordString.Replace(r, string.Empty);\n }\n\n if (!includeLookAlikes)\n {\n var remove = new string[] { \"(\", \")\", \"0\", \"O\", \"o\", \"1\", \"i\", \"I\", \"l\", \"|\", \"!\", \":\", \";\" };\n foreach (string r in remove)\n passwordString = passwordString.Replace(r, string.Empty);\n }\n\n return passwordString;\n}\n</code></pre>\n\n<p>This was the first link when I searched for generating random passwords and the following is out of scope for the current question but might be important to consider. </p>\n\n<ul>\n<li>Based upon the assumption that <code>System.Web.Security.Membership.GeneratePassword</code> is cryptographically secure with a minimum of 20% of the characters being Non-Alphanumeric.</li>\n<li>Not sure if removing characters and appending strings is considered good practice in this case and provides enough entropy.</li>\n<li>Might want to consider implementing in some way with <a href=\"https://msdn.microsoft.com/en-us/library/system.security.securestring(v=vs.110).aspx\" rel=\"nofollow noreferrer\">SecureString</a> for secure password storage in memory.</li>\n</ul>\n"
},
{
"answer_id": 46550870,
"author": "Sean",
"author_id": 6114538,
"author_profile": "https://Stackoverflow.com/users/6114538",
"pm_score": -1,
"selected": false,
"text": "<p>validChars can be any construct, but I decided to select based on ascii code ranges removing control chars. In this example, it is a 12 character string. </p>\n\n<pre><code>string validChars = String.Join(\"\", Enumerable.Range(33, (126 - 33)).Where(i => !(new int[] { 34, 38, 39, 44, 60, 62, 96 }).Contains(i)).Select(i => { return (char)i; }));\nstring.Join(\"\", Enumerable.Range(1, 12).Select(i => { return validChars[(new Random(Guid.NewGuid().GetHashCode())).Next(0, validChars.Length - 1)]; }))\n</code></pre>\n"
},
{
"answer_id": 48701757,
"author": "akshay tilekar",
"author_id": 8152379,
"author_profile": "https://Stackoverflow.com/users/8152379",
"pm_score": -1,
"selected": false,
"text": "<pre><code> Generate random password of specified length with \n - Special characters \n - Number\n - Lowecase\n - Uppercase\n\n public static string CreatePassword(int length = 12)\n {\n const string lower = \"abcdefghijklmnopqrstuvwxyz\";\n const string upper = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n const string number = \"1234567890\";\n const string special = \"!@#$%^&*\";\n\n var middle = length / 2;\n StringBuilder res = new StringBuilder();\n Random rnd = new Random();\n while (0 < length--)\n {\n if (middle == length)\n {\n res.Append(number[rnd.Next(number.Length)]);\n }\n else if (middle - 1 == length)\n {\n res.Append(special[rnd.Next(special.Length)]);\n }\n else\n {\n if (length % 2 == 0)\n {\n res.Append(lower[rnd.Next(lower.Length)]);\n }\n else\n {\n res.Append(upper[rnd.Next(upper.Length)]);\n }\n }\n }\n return res.ToString();\n }\n</code></pre>\n"
},
{
"answer_id": 51023300,
"author": "Saeed Ahmad",
"author_id": 7351330,
"author_profile": "https://Stackoverflow.com/users/7351330",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public static string GeneratePassword(int passLength) {\n var chars = \"abcdefghijklmnopqrstuvwxyz@#$&ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n var random = new Random();\n var result = new string(\n Enumerable.Repeat(chars, passLength)\n .Select(s => s[random.Next(s.Length)])\n .ToArray());\n return result;\n }\n</code></pre>\n"
},
{
"answer_id": 55130798,
"author": "kitsu.eb",
"author_id": 770443,
"author_profile": "https://Stackoverflow.com/users/770443",
"pm_score": 3,
"selected": false,
"text": "<p>I'll add another ill-advised answer to the pot.</p>\n\n<p>I have a use case where I need random passwords for machine-machine communication, so I don't have any requirement for human readability. I also don't have access to <code>Membership.GeneratePassword</code> in my project, and don't want to add the dependency.</p>\n\n<p>I am fairly certain <code>Membership.GeneratePassword</code> is doing something similar to this, but here you can tune the pools of characters to draw from.</p>\n\n<pre><code>public static class PasswordGenerator\n{\n private readonly static Random _rand = new Random();\n\n public static string Generate(int length = 24)\n {\n const string lower = \"abcdefghijklmnopqrstuvwxyz\";\n const string upper = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n const string number = \"1234567890\";\n const string special = \"!@#$%^&*_-=+\";\n\n // Get cryptographically random sequence of bytes\n var bytes = new byte[length];\n new RNGCryptoServiceProvider().GetBytes(bytes);\n\n // Build up a string using random bytes and character classes\n var res = new StringBuilder();\n foreach(byte b in bytes)\n {\n // Randomly select a character class for each byte\n switch (_rand.Next(4))\n {\n // In each case use mod to project byte b to the correct range\n case 0:\n res.Append(lower[b % lower.Count()]);\n break;\n case 1:\n res.Append(upper[b % upper.Count()]);\n break;\n case 2:\n res.Append(number[b % number.Count()]);\n break;\n case 3:\n res.Append(special[b % special.Count()]);\n break;\n }\n }\n return res.ToString();\n }\n}\n</code></pre>\n\n<p>And some example output:</p>\n\n<pre><code>PasswordGenerator.Generate(12)\n\"pzY=64@-ChS$\"\n\"BG0OsyLbYnI_\"\n\"l9#5^2&adj_i\"\n\"#++Ws9d$%O%X\"\n\"IWhdIN-#&O^s\"\n</code></pre>\n\n<p>To preempt complaints about the use of <code>Random</code>: The primary source of randomness is still the crypto RNG. Even if you could deterministically preordain the sequence coming out of <code>Random</code> (say it only produced <code>1</code>) you still wouldn't know the next char that would be picked (though that <em>would</em> limit the range of possibilities).</p>\n\n<p>One simple extension would be to add weighting to the different character sets, which could be as simple as upping the max value and adding fall-through cases to increase weight.</p>\n\n<pre><code>switch (_rand.Next(6))\n{\n // Prefer letters 2:1\n case 0:\n case 1:\n res.Append(lower[b % lower.Count()]);\n break;\n case 2:\n case 3:\n res.Append(upper[b % upper.Count()]);\n break;\n case 4:\n res.Append(number[b % number.Count()]);\n break;\n case 5:\n res.Append(special[b % special.Count()]);\n break;\n}\n</code></pre>\n\n<p>For a more humanistic random password generator I once implemented a prompt system using <a href=\"https://www.eff.org/deeplinks/2016/07/new-wordlists-random-passphrases\" rel=\"noreferrer\">the EFF dice-word list</a>.</p>\n"
},
{
"answer_id": 57331316,
"author": "Roohi Ali",
"author_id": 3706939,
"author_profile": "https://Stackoverflow.com/users/3706939",
"pm_score": -1,
"selected": false,
"text": "<p>I use this code for generate password with balance composition of alphabet, numeric and non_alpha_numeric chars. </p>\n\n<pre><code>public static string GeneratePassword(int Length, int NonAlphaNumericChars)\n {\n string allowedChars = \"abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789\";\n string allowedNonAlphaNum = \"!@#$%^&*()_-+=[{]};:<>|./?\";\n string pass = \"\";\n Random rd = new Random(DateTime.Now.Millisecond);\n for (int i = 0; i < Length; i++)\n {\n if (rd.Next(1) > 0 && NonAlphaNumericChars > 0)\n {\n pass += allowedNonAlphaNum[rd.Next(allowedNonAlphaNum.Length)];\n NonAlphaNumericChars--;\n }\n else\n {\n pass += allowedChars[rd.Next(allowedChars.Length)];\n }\n }\n return pass;\n }\n</code></pre>\n"
},
{
"answer_id": 59933028,
"author": "Johan Maes",
"author_id": 9266796,
"author_profile": "https://Stackoverflow.com/users/9266796",
"pm_score": 0,
"selected": false,
"text": "<p>This package allows you to generate a random password while fluently indicating which characters it should contain (if needed):</p>\n\n<p><a href=\"https://github.com/prjseal/PasswordGenerator/\" rel=\"nofollow noreferrer\">https://github.com/prjseal/PasswordGenerator/</a></p>\n\n<p>Example:</p>\n\n<pre><code>var pwd = new Password().IncludeLowercase().IncludeUppercase().IncludeSpecial();\nvar password = pwd.Next();\n</code></pre>\n"
},
{
"answer_id": 60382377,
"author": "samgak",
"author_id": 696391,
"author_profile": "https://Stackoverflow.com/users/696391",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to make use of the cryptographically secure random number generation used by System.Web.Security.Membership.GeneratePassword but also want to restrict the character set to alphanumeric characters, you can filter the result with a regex:</p>\n\n<pre><code>static string GeneratePassword(int characterCount)\n{\n string password = String.Empty;\n while(password.Length < characterCount)\n password += Regex.Replace(System.Web.Security.Membership.GeneratePassword(128, 0), \"[^a-zA-Z0-9]\", string.Empty);\n return password.Substring(0, characterCount);\n}\n</code></pre>\n"
},
{
"answer_id": 66334368,
"author": "RD07 Dz",
"author_id": 13557184,
"author_profile": "https://Stackoverflow.com/users/13557184",
"pm_score": 0,
"selected": false,
"text": "<p>check this code...\nI added the .remove(length) to improve <a href=\"https://stackoverflow.com/users/1448943/anaximander\">anaximander</a>'s response</p>\n<pre><code> public string GeneratePassword(int length)\n {\n using(RNGCryptoServiceProvider cryptRNG = new RNGCryptoServiceProvider();)\n {\n byte[] tokenBuffer = new byte[length];\n cryptRNG.GetBytes(tokenBuffer);\n return Convert.ToBase64String(tokenBuffer).Remove(length);\n }\n \n }\n</code></pre>\n"
},
{
"answer_id": 67102548,
"author": "Vijay Kumavat",
"author_id": 12376492,
"author_profile": "https://Stackoverflow.com/users/12376492",
"pm_score": 0,
"selected": false,
"text": "<p>How to Generate the Random Password in C#.<br />\nOutput : (<a href=\"https://prnt.sc/11fac8v\" rel=\"nofollow noreferrer\">https://prnt.sc/11fac8v</a>)<br />\nRun : <a href=\"https://onlinegdb.com/HJe5OHBLu\" rel=\"nofollow noreferrer\">https://onlinegdb.com/HJe5OHBLu</a></p>\n<pre><code> private static Random random = new Random();\n public static void Main()\n {\n Console.WriteLine("Random password with length of 8 character.");\n Console.WriteLine("===========================================");\n Console.WriteLine("Capital latters : 2");\n Console.WriteLine("Number latters : 2");\n Console.WriteLine("Special latters : 2");\n Console.WriteLine("Small latters : 2");\n Console.WriteLine("===========================================");\n Console.Write("The Random Password : ");\n Console.WriteLine(RandomStringCap(2) + RandomStringNum(2) + RandomStringSpe(2) + RandomStringSml(2));\n Console.WriteLine("===========================================");\n }\n public static string RandomStringCap(int length)\n {\n const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n return new string(Enumerable.Repeat(chars, length)\n .Select(s => s[random.Next(s.Length)]).ToArray());\n }\n public static string RandomStringNum(int length)\n {\n const string chars = "0123456789";\n return new string(Enumerable.Repeat(chars, length)\n .Select(s => s[random.Next(s.Length)]).ToArray());\n }\n public static string RandomStringSml(int length)\n {\n const string chars = "abcdefghijklmnopqrstuvwxyz";\n return new string(Enumerable.Repeat(chars, length)\n .Select(s => s[random.Next(s.Length)]).ToArray());\n }\n public static string RandomStringSpe(int length)\n {\n const string chars = "!@#$%^&*_-=+";\n return new string(Enumerable.Repeat(chars, length)\n .Select(s => s[random.Next(s.Length)]).ToArray());\n }\n</code></pre>\n"
},
{
"answer_id": 73316960,
"author": "Shane",
"author_id": 5564257,
"author_profile": "https://Stackoverflow.com/users/5564257",
"pm_score": 0,
"selected": false,
"text": "<p>Inspired by the answer from @kitsu.eb, but using <code>RandomNumberGenerator</code> instead of <code>Random</code> or <code>RNGCryptoServiceProvider</code> (deprecated in .NET 6), and added a few more special characters.</p>\n<p>Optional parameter to exclude characters that will be escaped when using <code>System.Text.Json.JsonSerializer.Serialize</code> - for example <code>&</code> which is escaped as <code>\\u0026</code> - so that you can guarantee the length of the serialized string will match the length of the password.</p>\n<p>For .NET Core 3.0 and above.</p>\n<pre><code>public static class PasswordGenerator\n{\n const string lower = "abcdefghijklmnopqrstuvwxyz";\n const string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n const string number = "1234567890";\n const string special = "!@#$%^&*()[]{},.:`~_-=+"; // excludes problematic characters like ;'"/\\\n const string specialJsonSafe = "!@#$%^*()[]{},.:~_-="; // excludes problematic characters like ;'"/\\ and &`+\n\n const int lowerLength = 26; // lower.Length\n const int upperLength = 26; // upper.Length;\n const int numberLength = 10; // number.Length;\n const int specialLength = 23; // special.Length;\n const int specialJsonSafeLength = 20; // specialJsonSafe.Length;\n\n public static string Generate(int length = 96, bool jsonSafeSpecialCharactersOnly = false)\n {\n Span<char> result = length < 1024 ? stackalloc char[length] : new char[length].AsSpan();\n\n for (int i = 0; i < length; ++i)\n {\n switch (RandomNumberGenerator.GetInt32(4))\n {\n case 0:\n result[i] = lower[RandomNumberGenerator.GetInt32(0, lowerLength)];\n break;\n case 1:\n result[i] = upper[RandomNumberGenerator.GetInt32(0, upperLength)];\n break;\n case 2:\n result[i] = number[RandomNumberGenerator.GetInt32(0, numberLength)];\n break;\n case 3:\n if (jsonSafeSpecialCharactersOnly)\n {\n result[i] = specialJsonSafe[RandomNumberGenerator.GetInt32(0, specialJsonSafeLength)];\n }\n else\n {\n result[i] = special[RandomNumberGenerator.GetInt32(0, specialLength)];\n }\n break;\n }\n }\n\n return result.ToString();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 73913189,
"author": "clamchoda",
"author_id": 591285,
"author_profile": "https://Stackoverflow.com/users/591285",
"pm_score": 0,
"selected": false,
"text": "<p>Pretty easy way to require one from each group using <code>Random</code> and linq-to-objects.</p>\n<ul>\n<li>Randomize each group</li>\n<li>Select random amount from first group</li>\n<li>Select remaining random amounts from following groups</li>\n</ul>\n<p> </p>\n<pre><code>Random rand = new Random();\nint min = 8;\nint max = 16;\nint totalLen = rand.Next(min, max);\nint remainingGroups = 4;\n \nstring[] allowedLowerChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z".Split(','); \nstring [] allowedUpperChars = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".Split(',');\nstring [] allowedNumbers = "1,2,3,4,5,6,7,8,9,0".Split(',');\nstring [] allowedSpecialChars = "!,@,#,$,%,&,?".Split(',');\n\n\nvar password = allowedLowerChars.OrderBy(c => rand.Next()).Take(rand.Next(1, totalLen-remainingGroups--)).ToList();\npassword.AddRange(allowedUpperChars.OrderBy(c => rand.Next()).Take(rand.Next(1, totalLen-password.Count-remainingGroups--)).ToList());\npassword.AddRange(allowedNumbers.OrderBy(c => rand.Next()).Take(rand.Next(1, totalLen-password.Count-remainingGroups--)).ToList());\npassword.AddRange(allowedSpecialChars.OrderBy(c => rand.Next()).Take(totalLen-password.Count).ToList());\npassword = password.OrderBy(c => rand.Next()).ToList(); // randomize groups\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/54991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231/"
] | When a user on our site loses his password and heads off to the Lost Password page we need to give him a new temporary password. I don't really mind how random this is, or if it matches all the "needed" strong password rules, all I want to do is give them a password that they can change later.
The application is a Web application written in C#. so I was thinking of being mean and going for the easy route of using part of a Guid. i.e.
```
Guid.NewGuid().ToString("d").Substring(1,8)
```
Suggesstions? thoughts? | There's always [`System.Web.Security.Membership.GeneratePassword(int length, int numberOfNonAlphanumericCharacters`)](http://msdn.microsoft.com/en-us/library/system.web.security.membership.generatepassword.aspx). |
55,042 | <p>I want to build a bot that asks someone a few simple questions and branches based on the answer. I realize parsing meaning from the human responses will be challenging, but how do you setup the program to deal with the "state" of the conversation?</p>
<p>It will be a one-to-one conversation between a human and the bot.</p>
| [
{
"answer_id": 55049,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 0,
"selected": false,
"text": "<p>I would suggest looking at Bayesian probabilities. Then just monitor the chat room for a period of time to create your probability tree.</p>\n"
},
{
"answer_id": 55053,
"author": "argv0",
"author_id": 5595,
"author_profile": "https://Stackoverflow.com/users/5595",
"pm_score": 6,
"selected": true,
"text": "<p>You probably want to look into <a href=\"http://en.wikipedia.org/wiki/Markov_chain\" rel=\"noreferrer\">Markov Chains</a> as the basics for the bot AI. I wrote something a long time ago (the code to which I'm not proud of at all, and needs some mods to run on Python > 1.5) that may be a useful starting place for you: <a href=\"http://sourceforge.net/projects/benzo/\" rel=\"noreferrer\"><a href=\"http://sourceforge.net/projects/benzo/\" rel=\"noreferrer\">http://sourceforge.net/projects/benzo/</a></a></p>\n\n<p>EDIT: Here's a minimal example in Python of a Markov Chain that accepts input from stdin and outputs text based on the probabilities of words succeeding one another in the input. It's optimized for IRC-style chat logs, but running any decent-sized text through it should demonstrate the concepts:</p>\n\n<pre><code>import random, sys\n\nNONWORD = \"\\n\"\nSTARTKEY = NONWORD, NONWORD\nMAXGEN=1000\n\nclass MarkovChainer(object):\n def __init__(self):\n self.state = dict()\n\n def input(self, input):\n word1, word2 = STARTKEY\n for word3 in input.split():\n self.state.setdefault((word1, word2), list()).append(word3)\n word1, word2 = word2, word3 \n self.state.setdefault((word1, word2), list()).append(NONWORD)\n\n def output(self):\n output = list()\n word1, word2 = STARTKEY\n for i in range(MAXGEN):\n word3 = random.choice(self.state[(word1,word2)])\n if word3 == NONWORD: break\n output.append(word3)\n word1, word2 = word2, word3\n return \" \".join(output)\n\nif __name__ == \"__main__\":\n c = MarkovChainer()\n c.input(sys.stdin.read())\n print c.output()\n</code></pre>\n\n<p>It's pretty easy from here to plug in persistence and an IRC library and have the basis of the type of bot you're talking about.</p>\n"
},
{
"answer_id": 55055,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>I think you can look at the code for <a href=\"http://kookybot.org/\" rel=\"nofollow noreferrer\">Kooky</a>, and IIRC it also uses Markov Chains.</p>\n\n<p>Also check out the <a href=\"http://quotes.kookybot.org/top\" rel=\"nofollow noreferrer\">kooky quotes</a>, they were featured on Coding Horror not long ago and some are hilarious.</p>\n"
},
{
"answer_id": 55062,
"author": "nutario",
"author_id": 5334,
"author_profile": "https://Stackoverflow.com/users/5334",
"pm_score": 2,
"selected": false,
"text": "<p>I think to start this project, it would be good to have a database with questions (organized as a tree. In every node one or more questions).\nThese questions sould be answered with \"yes \" or \"no\".</p>\n\n<p>If the bot starts to question, it can start with any question from yuor database of questions marked as a start-question. The answer is the way to the next node in the tree.</p>\n\n<p>Edit: Here is a somple one written in ruby you can start with: <a href=\"http://snippets.dzone.com/posts/show/1785\" rel=\"nofollow noreferrer\">rubyBOT</a></p>\n"
},
{
"answer_id": 55464,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure this is what you're looking for, but there's an old program called <a href=\"http://en.wikipedia.org/wiki/ELIZA\" rel=\"nofollow noreferrer\">ELIZA</a> which could hold a conversation by taking what you said and spitting it back at you after performing some simple textual transformations.</p>\n\n<p>If I remember correctly, many people were convinced that they were \"talking\" to a real person and had long elaborate conversations with it.</p>\n"
},
{
"answer_id": 94936,
"author": "Josh Millard",
"author_id": 13600,
"author_profile": "https://Stackoverflow.com/users/13600",
"pm_score": 4,
"selected": false,
"text": "<p>Folks have mentioned already that statefulness isn't a big component of typical chatbots:</p>\n\n<ul>\n<li><p>a pure Markov implementations may express a very loose sort of state if it is growing its lexicon and table in real time—earlier utterances by the human interlocutor may get regurgitated by chance later in the conversation—but the Markov model doesn't have any inherent mechanism for selecting or producing such responses.</p></li>\n<li><p>a parsing-based bot (e.g. ELIZA) generally attempts to respond to (some of the) semantic content of the most recent input from the user without significant regard for prior exchanges.</p></li>\n</ul>\n\n<p>That said, you certainly <i>can</i> add some amount of state to a chatbot, regardless of the input-parsing and statement-synthesis model you're using. How to do that depends a lot on what you want to accomplish with your statefulness, and that's not really clear from your question. A couple general ideas, however:</p>\n\n<ul>\n<li><p>Create a keyword stack. As your human offers input, parse out keywords from their statements/questions and throw those keywords onto a stack of some sort. When your chatbot fails to come up with something compelling to respond to in the most recent input—or, perhaps, just at random, to mix things up—go back to your stack, grab a previous keyword, and use that to seed your next synthesis. For bonus points, have the bot explicitly acknowledge that it's going back to a previous subject, e.g. \"Wait, HUMAN, earlier you mentioned foo. [Sentence seeded by foo]\".</p></li>\n<li><p>Build RPG-like dialogue logic into the bot. As your parsing human input, toggle flags for specific conversational prompts or content from the user and conditionally alter what the chatbot can talk about, or how it communicates. For example, a chatbot bristling (or scolding, or laughing) at foul language is fairly common; a chatbot that will get het up, and conditionally <i>remain so until apologized to</i>, would be an interesting stateful variation on this. Switch output to ALL CAPS, throw in confrontational rhetoric or demands or sobbing, etc.</p></li>\n</ul>\n\n<p>Can you clarify a little what you want the state to help you accomplish?</p>\n"
},
{
"answer_id": 217861,
"author": "Ralph M. Rickenbach",
"author_id": 4549416,
"author_profile": "https://Stackoverflow.com/users/4549416",
"pm_score": 3,
"selected": false,
"text": "<p>Imagine a neural network with parsing capabilities in each node or neuron. Depending on rules and parsing results, neurons fire. If certain neurons fire, you get a good idea about topic and semantic of the question and therefore can give a good answer.</p>\n\n<p>Memory is done by keeping topics talked about in a session, adding to the firing for the next question, and therefore guiding the selection process of possible answers at the end.</p>\n\n<p>Keep your rules and patterns in a knowledge base, but compile them into memory at start time, with a neuron per rule. You can engineer synapses using something like listeners or event functions.</p>\n"
},
{
"answer_id": 1235616,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 0,
"selected": false,
"text": "<p>If you're just dabbling, I believe <a href=\"http://pidgin.im/\" rel=\"nofollow noreferrer\">Pidgin</a> allows you to script chat style behavior. Part of the framework probably tacks the state of who sent the message when, and you'd want to keep a log of your bot's internal state for each of the last N messages. Future state decisions could be hardcoded based on inspection of previous states and the content of the most recent few messages. Or you could do something like the Markov chains discussed and use it both for parsing and generating.</p>\n"
},
{
"answer_id": 12791406,
"author": "Erk",
"author_id": 386587,
"author_profile": "https://Stackoverflow.com/users/386587",
"pm_score": 0,
"selected": false,
"text": "<p>If you do not require a learning bot, using AIML (<a href=\"http://www.aiml.net/\" rel=\"nofollow\">http://www.aiml.net/</a>) will most likely produce the result you want, at least with respect to the bot parsing input and answering based on it.</p>\n\n<p>You would reuse or create \"brains\" made of XML (in the AIML-format) and parse/run them in a program (parser). There are parsers made in several different languages to choose from, and as far as I can tell the code seems to be open source in most cases.</p>\n"
},
{
"answer_id": 23901502,
"author": "user3513316",
"author_id": 3513316,
"author_profile": "https://Stackoverflow.com/users/3513316",
"pm_score": 1,
"selected": false,
"text": "<p>naive chatbot program. No parsing, no cleverness, just a training file and output.</p>\n\n<p>It first trains itself on a text and then later uses the data from that training to generate responses to the interlocutor’s input. The training process creates a dictionary where each key is a word and the value is a list of all the words that follow that word sequentially anywhere in the training text. If a word features more than once in this list then that reflects and it is more likely to be chosen by the bot, no need for probabilistic stuff just do it with a list.</p>\n\n<p>The bot chooses a random word from your input and generates a response by choosing another random word that has been seen to be a successor to its held word. It then repeats the process by finding a successor to that word in turn and carrying on iteratively until it thinks it’s said enough. It reaches that conclusion by stopping at a word that was prior to a punctuation mark in the training text. It then returns to input mode again to let you respond, and so on.</p>\n\n<p>It isn’t very realistic but I hereby challenge anyone to do better in 71 lines of code !! This is a great challenge for any budding Pythonists, and I just wish I could open the challenge to a wider audience than the small number of visitors I get to this blog. To code a bot that is always guaranteed to be grammatical must surely be closer to several hundred lines, I simplified hugely by just trying to think of the simplest rule to give the computer a mere stab at having something to say.</p>\n\n<p>Its responses are rather impressionistic to say the least ! Also you have to put what you say in single quotes.</p>\n\n<p>I used War and Peace for my “corpus” which took a couple of hours for the training run, use a shorter file if you are impatient…</p>\n\n<p>here is the trainer</p>\n\n<pre><code>#lukebot-trainer.py\nimport pickle\nb=open('war&peace.txt')\ntext=[]\nfor line in b:\n for word in line.split():\n text.append (word)\nb.close()\ntextset=list(set(text))\nfollow={}\nfor l in range(len(textset)):\n working=[]\n check=textset[l]\n for w in range(len(text)-1):\n if check==text[w] and text[w][-1] not in '(),.?!':\n working.append(str(text[w+1]))\n follow[check]=working\na=open('lexicon-luke','wb')\npickle.dump(follow,a,2)\na.close()\n</code></pre>\n\n<p>here is the bot</p>\n\n<pre><code>#lukebot.py\nimport pickle,random\na=open('lexicon-luke','rb')\nsuccessorlist=pickle.load(a)\na.close()\ndef nextword(a):\n if a in successorlist:\n return random.choice(successorlist[a])\n else:\n return 'the'\nspeech=''\nwhile speech!='quit':\n speech=raw_input('>')\n s=random.choice(speech.split())\n response=''\n while True:\n neword=nextword(s)\n response+=' '+neword\n s=neword\n if neword[-1] in ',?!.':\n break\n print response\n</code></pre>\n\n<p>You tend to get an uncanny feeling when it says something that seems partially to make sense. </p>\n"
},
{
"answer_id": 51896174,
"author": "Ratnakar Chinchkar",
"author_id": 3723257,
"author_profile": "https://Stackoverflow.com/users/3723257",
"pm_score": 0,
"selected": false,
"text": "<p>You can use \"ChatterBot\", and host it locally using - 'flask-chatterbot-master\" </p>\n\n<p><strong>Links:</strong> </p>\n\n<ol>\n<li>[ChatterBot Installation] \n<a href=\"https://chatterbot.readthedocs.io/en/stable/setup.html\" rel=\"nofollow noreferrer\">https://chatterbot.readthedocs.io/en/stable/setup.html</a> </li>\n<li>[Host Locally using - flask-chatterbot-master]: <a href=\"https://github.com/chamkank/flask-chatterbot\" rel=\"nofollow noreferrer\">https://github.com/chamkank/flask-chatterbot</a> </li>\n</ol>\n\n<p>Cheers, </p>\n\n<p>Ratnakar</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] | I want to build a bot that asks someone a few simple questions and branches based on the answer. I realize parsing meaning from the human responses will be challenging, but how do you setup the program to deal with the "state" of the conversation?
It will be a one-to-one conversation between a human and the bot. | You probably want to look into [Markov Chains](http://en.wikipedia.org/wiki/Markov_chain) as the basics for the bot AI. I wrote something a long time ago (the code to which I'm not proud of at all, and needs some mods to run on Python > 1.5) that may be a useful starting place for you: [<http://sourceforge.net/projects/benzo/>](http://sourceforge.net/projects/benzo/)
EDIT: Here's a minimal example in Python of a Markov Chain that accepts input from stdin and outputs text based on the probabilities of words succeeding one another in the input. It's optimized for IRC-style chat logs, but running any decent-sized text through it should demonstrate the concepts:
```
import random, sys
NONWORD = "\n"
STARTKEY = NONWORD, NONWORD
MAXGEN=1000
class MarkovChainer(object):
def __init__(self):
self.state = dict()
def input(self, input):
word1, word2 = STARTKEY
for word3 in input.split():
self.state.setdefault((word1, word2), list()).append(word3)
word1, word2 = word2, word3
self.state.setdefault((word1, word2), list()).append(NONWORD)
def output(self):
output = list()
word1, word2 = STARTKEY
for i in range(MAXGEN):
word3 = random.choice(self.state[(word1,word2)])
if word3 == NONWORD: break
output.append(word3)
word1, word2 = word2, word3
return " ".join(output)
if __name__ == "__main__":
c = MarkovChainer()
c.input(sys.stdin.read())
print c.output()
```
It's pretty easy from here to plug in persistence and an IRC library and have the basis of the type of bot you're talking about. |
55,054 | <p>What’s the best way to capitalize the first letter of each word in a string in SQL Server.</p>
| [
{
"answer_id": 55057,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 7,
"selected": true,
"text": "<p>From <a href=\"http://www.sql-server-helper.com/functions/initcap.aspx\" rel=\"noreferrer\">http://www.sql-server-helper.com/functions/initcap.aspx</a></p>\n\n<pre><code>CREATE FUNCTION [dbo].[InitCap] ( @InputString varchar(4000) ) \nRETURNS VARCHAR(4000)\nAS\nBEGIN\n\nDECLARE @Index INT\nDECLARE @Char CHAR(1)\nDECLARE @PrevChar CHAR(1)\nDECLARE @OutputString VARCHAR(255)\n\nSET @OutputString = LOWER(@InputString)\nSET @Index = 1\n\nWHILE @Index <= LEN(@InputString)\nBEGIN\n SET @Char = SUBSTRING(@InputString, @Index, 1)\n SET @PrevChar = CASE WHEN @Index = 1 THEN ' '\n ELSE SUBSTRING(@InputString, @Index - 1, 1)\n END\n\n IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(')\n BEGIN\n IF @PrevChar != '''' OR UPPER(@Char) != 'S'\n SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char))\n END\n\n SET @Index = @Index + 1\nEND\n\nRETURN @OutputString\n\nEND\nGO\n</code></pre>\n\n<p>There is a simpler/smaller one here (but doesn't work if any row doesn't have spaces, \"Invalid length parameter passed to the RIGHT function.\"): </p>\n\n<p><a href=\"http://www.devx.com/tips/Tip/17608\" rel=\"noreferrer\">http://www.devx.com/tips/Tip/17608</a></p>\n"
},
{
"answer_id": 55153,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 2,
"selected": false,
"text": "<p>A variation of the one I've been using for quite some time is:</p>\n\n<pre><code>CREATE FUNCTION [widget].[properCase](@string varchar(8000)) RETURNS varchar(8000) AS\nBEGIN \n SET @string = LOWER(@string)\n DECLARE @i INT\n SET @i = ASCII('a')\n WHILE @i <= ASCII('z')\n BEGIN\n SET @string = REPLACE( @string, ' ' + CHAR(@i), ' ' + CHAR(@i-32))\n SET @i = @i + 1\n END\n SET @string = CHAR(ASCII(LEFT(@string, 1))-32) + RIGHT(@string, LEN(@string)-1)\n RETURN @string\nEND\n</code></pre>\n\n<p>You can easily modify to handle characters after items other than spaces if you wanted to.</p>\n"
},
{
"answer_id": 27742913,
"author": "Andrey Morozov",
"author_id": 483408,
"author_profile": "https://Stackoverflow.com/users/483408",
"pm_score": 2,
"selected": false,
"text": "<p>Another solution without using the loop - pure set-based approach with recursive CTE</p>\n\n<pre><code>create function [dbo].InitCap (@value varchar(max))\nreturns varchar(max) as\nbegin\n\n declare\n @separator char(1) = ' ',\n @result varchar(max) = '';\n\n with r as (\n select value, cast(null as varchar(max)) [x], cast('' as varchar(max)) [char], 0 [no] from (select rtrim(cast(@value as varchar(max))) [value]) as j\n union all\n select right(value, len(value)-case charindex(@separator, value) when 0 then len(value) else charindex(@separator, value) end) [value]\n , left(r.[value], case charindex(@separator, r.value) when 0 then len(r.value) else abs(charindex(@separator, r.[value])-1) end ) [x]\n , left(r.[value], 1)\n , [no] + 1 [no]\n from r where value > '')\n\n select @result = @result +\n case\n when ascii([char]) between 97 and 122 \n then stuff(x, 1, 1, char(ascii([char])-32))\n else x\n end + @separator\n from r where x is not null;\n\n set @result = rtrim(@result);\n\n return @result;\nend\n</code></pre>\n"
},
{
"answer_id": 31574024,
"author": "Amrik",
"author_id": 1783751,
"author_profile": "https://Stackoverflow.com/users/1783751",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the simplest one-liner to do this:</p>\n<pre><code>SELECT LEFT(column, 1)+ lower(RIGHT(column, len(column)-1) ) FROM [tablename]\n</code></pre>\n"
},
{
"answer_id": 46344989,
"author": "Kristofer",
"author_id": 1398417,
"author_profile": "https://Stackoverflow.com/users/1398417",
"pm_score": 3,
"selected": false,
"text": "<p>As a table-valued function:</p>\n<pre><code>CREATE FUNCTION dbo.InitCap(@v AS VARCHAR(MAX))\nRETURNS TABLE\nAS\nRETURN \nWITH a AS (\n SELECT (\n SELECT UPPER(LEFT(value, 1)) + LOWER(SUBSTRING(value, 2, LEN(value))) AS 'data()'\n FROM string_split(@v, ' ')\n ORDER BY CHARINDEX(value,@v)\n FOR XML PATH (''), TYPE) ret)\n\nSELECT CAST(a.ret AS varchar(MAX)) ret from a\nGO\n</code></pre>\n<p>Note that <code>string_split</code> requires <code>COMPATIBILITY_LEVEL</code> 130.</p>\n"
},
{
"answer_id": 47754555,
"author": "Vignesh Sonaiya",
"author_id": 8294507,
"author_profile": "https://Stackoverflow.com/users/8294507",
"pm_score": 1,
"selected": false,
"text": "<pre><code>BEGIN\nDECLARE @string varchar(100) = 'asdsadsd asdad asd'\nDECLARE @ResultString varchar(200) = ''\nDECLARE @index int = 1\nDECLARE @flag bit = 0\nDECLARE @temp varchar(2) = ''\nWHILE (@Index <LEN(@string)+1)\n BEGIN\n SET @temp = SUBSTRING(@string, @Index-1, 1)\n --select @temp\n IF @temp = ' ' OR @index = 1\n BEGIN\n SET @ResultString = @ResultString + UPPER(SUBSTRING(@string, @Index, 1))\n END\n ELSE\n BEGIN\n \n SET @ResultString = @ResultString + LOWER(SUBSTRING(@string, @Index, 1)) \n END \n\n SET @Index = @Index+ 1--increase the index\n END\nSELECT @ResultString\nEND\n</code></pre>\n"
},
{
"answer_id": 52286176,
"author": "Rene",
"author_id": 1739704,
"author_profile": "https://Stackoverflow.com/users/1739704",
"pm_score": 0,
"selected": false,
"text": "<p>I was looking for the best way to capitalize and i recreate simple sql script</p>\n<p>how to use SELECT dbo.Capitalyze('this is a test with multiple spaces')</p>\n<p>result "This Is A Test With Multiple Spaces"</p>\n<pre><code>CREATE FUNCTION Capitalyze(@input varchar(100) )\n returns varchar(100)\nas\nbegin\n \n declare @index int=0\n declare @char as varchar(1)=' '\n declare @prevCharIsSpace as bit=1\n declare @Result as varchar(100)=''\n\n set @input=UPPER(LEFT(@input,1))+LOWER(SUBSTRING(@input, 2, LEN(@input)))\n set @index=PATINDEX('% _%',@input)\n if @index=0\n set @index=len(@input)\n set @Result=substring(@input,0,@index+1)\n\n WHILE (@index < len(@input))\n BEGIN\n SET @index = @index + 1\n SET @char=substring(@input,@index,1)\n if (@prevCharIsSpace=1)\n begin\n set @char=UPPER(@char)\n if (@char=' ')\n set @char=''\n end\n\n if (@char=' ')\n set @prevCharIsSpace=1\n else\n set @prevCharIsSpace=0\n\n set @Result=@Result+@char\n --print @Result\n END\n --print @Result\n return @Result\nend\n</code></pre>\n"
},
{
"answer_id": 52621398,
"author": "Akhil Singh",
"author_id": 7528842,
"author_profile": "https://Stackoverflow.com/users/7528842",
"pm_score": 0,
"selected": false,
"text": "<p>fname is column name if fname value is akhil then UPPER(left(fname,1)) provide capital First letter(A) and substring function SUBSTRING(fname,2,LEN(fname)) provide(khil) concate both using + then result is (Akhil) </p>\n\n<pre><code>select UPPER(left(fname,1))+SUBSTRING(fname,2,LEN(fname)) as fname\nFROM [dbo].[akhil]\n</code></pre>\n"
},
{
"answer_id": 53025811,
"author": "Shashank Gupta",
"author_id": 10155755,
"author_profile": "https://Stackoverflow.com/users/10155755",
"pm_score": 2,
"selected": false,
"text": "<p>If you are looking for the answer to the same question in Oracle/PLSQL then you may use the function INITCAP. Below is an example for the attribute <strong>dname</strong> from a table <strong>department</strong> which has the values ('sales', 'management', 'production', 'development').</p>\n\n<pre><code>SQL> select INITCAP(dname) from department;\n\nINITCAP(DNAME)\n--------------------------------------------------\nSales\nManagement\nProduction\nDevelopment\n</code></pre>\n"
},
{
"answer_id": 56481595,
"author": "Andrew Solomonik",
"author_id": 11610118,
"author_profile": "https://Stackoverflow.com/users/11610118",
"pm_score": -1,
"selected": false,
"text": "<pre><code>IF OBJECT_ID ('dbo.fnCapitalizeFirstLetterAndChangeDelimiter') IS NOT NULL\n DROP FUNCTION dbo.fnCapitalizeFirstLetterAndChangeDelimiter\nGO\n\nCREATE FUNCTION [dbo].[fnCapitalizeFirstLetterAndChangeDelimiter] (@string NVARCHAR(MAX), @delimiter NCHAR(1), @new_delimeter NCHAR(1))\nRETURNS NVARCHAR(MAX)\nAS \nBEGIN\n DECLARE @result NVARCHAR(MAX)\n SELECT @result = '';\n IF (LEN(@string) > 0)\n DECLARE @curr INT\n DECLARE @next INT\n BEGIN\n SELECT @curr = 1\n SELECT @next = CHARINDEX(@delimiter, @string)\n WHILE (LEN(@string) > 0)\n BEGIN\n SELECT @result = \n @result + \n CASE WHEN LEN(@result) > 0 THEN @new_delimeter ELSE '' END +\n UPPER(SUBSTRING(@string, @curr, 1)) + \n CASE \n WHEN @next <> 0 \n THEN LOWER(SUBSTRING(@string, @curr+1, @next-2))\n ELSE LOWER(SUBSTRING(@string, @curr+1, LEN(@string)-@curr))\n END\n IF (@next > 0)\n BEGIN\n SELECT @string = SUBSTRING(@string, @next+1, LEN(@string)-@next)\n SELECT @next = CHARINDEX(@delimiter, @string)\n END\n ELSE\n SELECT @string = ''\n END\n END\n RETURN @result\nEND\nGO\n</code></pre>\n"
},
{
"answer_id": 58296137,
"author": "Vitaly Borisov",
"author_id": 4119599,
"author_profile": "https://Stackoverflow.com/users/4119599",
"pm_score": 0,
"selected": false,
"text": "<p>On <strong>SQL Server 2016+</strong> using JSON which gives guaranteed order of the words:</p>\n\n<pre><code>CREATE FUNCTION [dbo].[InitCap](@Text NVARCHAR(MAX))\nRETURNS NVARCHAR(MAX)\nAS\nBEGIN\n RETURN STUFF((\n SELECT ' ' + UPPER(LEFT(s.value,1)) + LOWER(SUBSTRING(s.value,2,LEN(s.value)))\n FROM OPENJSON('[\"' + REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Text,'\\','\\\\'),'\"','\\\"'),CHAR(9),'\\t'),CHAR(10),'\\n'),' ','\",\"') + '\"]') s\n ORDER BY s.[key]\n FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)'),1,1,'');\nEND\n</code></pre>\n"
},
{
"answer_id": 61159787,
"author": "Glen",
"author_id": 1828277,
"author_profile": "https://Stackoverflow.com/users/1828277",
"pm_score": 2,
"selected": false,
"text": "<pre><code>;WITH StudentList(Name) AS (\n SELECT CONVERT(varchar(50), 'Carl-VAN')\nUNION SELECT 'Dean o''brian'\nUNION SELECT 'Andrew-le-Smith'\nUNION SELECT 'Eddy thompson'\nUNION SELECT 'BOBs-your-Uncle'\n), Student AS (\n SELECT CONVERT(varchar(50), UPPER(LEFT(Name, 1)) + LOWER(SUBSTRING(Name, 2, LEN(Name)))) Name, \n pos = PATINDEX('%[-'' ]%', Name)\n FROM StudentList\n UNION ALL\n SELECT CONVERT(varchar(50), LEFT(Name, pos) + UPPER(SUBSTRING(Name, pos + 1, 1)) + SUBSTRING(Name, pos + 2, LEN(Name))) Name, \n pos = CASE WHEN PATINDEX('%[-'' ]%', RIGHT(Name, LEN(Name) - pos)) = 0 THEN 0 ELSE pos + PATINDEX('%[-'' ]%', RIGHT(Name, LEN(Name) - pos)) END\n FROM Student\n WHERE pos > 0\n)\nSELECT Name\nFROM Student \nWHERE pos = 0\nORDER BY Name \n</code></pre>\n\n<p>This will result in:</p>\n\n<ul>\n<li>Andrew-Le-Smith</li>\n<li>Bobs-Your-Uncle</li>\n<li>Carl-Van</li>\n<li>Dean O'Brian</li>\n<li>Eddy Thompson</li>\n</ul>\n\n<p>Using a recursive CTE set based query should out perform a procedural while loop query.\nHere I also have made my separate to be 3 different characters [-' ] instead of 1 for a more advanced example. Using PATINDEX as I have done allows me to look for many characters. You could also use CHARINDEX on a single character and this function excepts a third parameter StartFromPosition so I could further simply my 2nd part of the recursion of the pos formula to (assuming a space): pos = CHARINDEX(' ', Name, pos + 1).</p>\n"
},
{
"answer_id": 64925176,
"author": "KodFun",
"author_id": 8783782,
"author_profile": "https://Stackoverflow.com/users/8783782",
"pm_score": 0,
"selected": false,
"text": "<pre><code>GO\nCREATE FUNCTION [dbo].[Capitalize](@text NVARCHAR(MAX)) RETURNS NVARCHAR(MAX) AS\nBEGIN\n DECLARE @result NVARCHAR(MAX) = '';\n DECLARE @c NVARCHAR(1);\n DECLARE @i INT = 1;\n DECLARE @isPrevSpace BIT = 1;\n\n WHILE @i <= LEN(@text)\n BEGIN\n SET @c = SUBSTRING(@text, @i, 1);\n SET @result += IIF(@isPrevSpace = 1, UPPER(@c), LOWER(@c));\n SET @isPrevSpace = IIF(@c LIKE '[ -]', 1, 0);\n SET @i += 1;\n END\n RETURN @result;\nEND\nGO\n\nDECLARE @sentence NVARCHAR(100) = N'i-thINK-this soLUTION-works-LiKe-a charm';\nPRINT dbo.Capitalize(@sentence);\n-- I-Think-This Solution-Works-Like-A Charm\n</code></pre>\n"
},
{
"answer_id": 67810946,
"author": "Merin Nakarmi",
"author_id": 717955,
"author_profile": "https://Stackoverflow.com/users/717955",
"pm_score": 1,
"selected": false,
"text": "<p>It can be as simple as this:</p>\n<pre><code>DECLARE @Name VARCHAR(500) = 'Roger';\n\nSELECT @Name AS Name, UPPER(LEFT(@Name, 1)) + SUBSTRING(@Name, 2, LEN(@Name)) AS CapitalizedName;\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/dm87c.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dm87c.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 67998634,
"author": "Ashraf Ali",
"author_id": 16241030,
"author_profile": "https://Stackoverflow.com/users/16241030",
"pm_score": 1,
"selected": false,
"text": "<p>The suggested function works fine, however, if you do not want to create any function this is how I do it:</p>\n<pre><code>select ID,Name\n,string_agg(concat(upper(substring(value,1,1)),lower(substring(value,2,len(value)-1))),' ') as ModifiedName \nfrom Table_Customer \ncross apply String_Split(replace(trim(Name),' ',' '),' ')\nwhere Name is not null\ngroup by ID,Name;\n</code></pre>\n<p>The above query split the words by space (' ') and create different rows of each having one substring, then convert the first letter of each substring to upper and keep remaining as lower. The final step is to string aggregate based on the key.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5170/"
] | What’s the best way to capitalize the first letter of each word in a string in SQL Server. | From <http://www.sql-server-helper.com/functions/initcap.aspx>
```
CREATE FUNCTION [dbo].[InitCap] ( @InputString varchar(4000) )
RETURNS VARCHAR(4000)
AS
BEGIN
DECLARE @Index INT
DECLARE @Char CHAR(1)
DECLARE @PrevChar CHAR(1)
DECLARE @OutputString VARCHAR(255)
SET @OutputString = LOWER(@InputString)
SET @Index = 1
WHILE @Index <= LEN(@InputString)
BEGIN
SET @Char = SUBSTRING(@InputString, @Index, 1)
SET @PrevChar = CASE WHEN @Index = 1 THEN ' '
ELSE SUBSTRING(@InputString, @Index - 1, 1)
END
IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(')
BEGIN
IF @PrevChar != '''' OR UPPER(@Char) != 'S'
SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char))
END
SET @Index = @Index + 1
END
RETURN @OutputString
END
GO
```
There is a simpler/smaller one here (but doesn't work if any row doesn't have spaces, "Invalid length parameter passed to the RIGHT function."):
<http://www.devx.com/tips/Tip/17608> |
55,060 | <p>I'm pretty sure the answer to this question is no, but in case there's some PHP guru</p>
<p>is it possible to write a function in a way where invalid arguments or non existent variables can be passed in and php will not error without the use of <code>'@'</code></p>
<p>Much like empty and isset do. You can pass in a variable you just made up and it won't error.</p>
<pre><code>ex:
empty($someBogusVar); // no error
myHappyFunction($someBogusVar); // Php warning / notice
</code></pre>
| [
{
"answer_id": 55065,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 1,
"selected": false,
"text": "<p>No, because this isn't really anything to do with the function; the error is coming from attempting to de-reference a non-existent array key. You can change the warning level of your PHP setup to surpress these errors, but you're better off just not doing this.</p>\n\n<p>Having said that, you <em>could</em> do something like</p>\n\n<pre><code>function safeLookup($array, $key)\n{\n if (isset($array, $key))\n return $array[$key];\n\n return 0;\n}\n</code></pre>\n\n<p>And use it in place of array key lookup</p>\n\n<pre><code>defaultValue(safeLookup($foo, \"bar\"), \"baz);\n</code></pre>\n\n<p>Now I need to take a shower :)</p>\n"
},
{
"answer_id": 55079,
"author": "SeanDowney",
"author_id": 5261,
"author_profile": "https://Stackoverflow.com/users/5261",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>@Brian: I use a trinary operation to do the check for me:</p>\n</blockquote>\n\n<pre><code>return $value ? $value : $default;\n</code></pre>\n\n<p>this returns either $value OR $default. Depending upon the value of $value. If it is 0, false, empty or anything similar the value in $default will be returned.</p>\n\n<p>I'm more going for the challenge to emulate functions like empty() and isset() </p>\n"
},
{
"answer_id": 55090,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": -1,
"selected": false,
"text": "<p>And going further up the abstraction tree, what are you using this for?</p>\n\n<p>You could either initialize those values in each class as appropriate or create a specific class containing all the default values and attributes, like:</p>\n\n<pre><code>class Configuration {\n\n private var $configValues = array( 'cool' => 'Defaultcoolval' ,\n 'uncool' => 'Defuncoolval' );\n\n public setCool($val) {\n $this->configValues['cool'] = $val;\n }\n\n public getCool() {\n return $this->configValues['cool'];\n }\n\n}\n</code></pre>\n\n<p>The idea being that, when using defaultValue function everywhere up and down in your code, it will become a maintenance nightmare whenever you have to change a value, looking for all the places where you've put a defaultValue call. And it'll also probably lead you to repeat yourself, violating DRY.</p>\n\n<p>Whereas this is a single place to store all those default values. You might be tempted to avoid creating those setters and getters, but they also help in maintenance, in case it becomse pertinent to do some modification of outputs or validation of inputs.</p>\n"
},
{
"answer_id": 55100,
"author": "SeanDowney",
"author_id": 5261,
"author_profile": "https://Stackoverflow.com/users/5261",
"pm_score": 0,
"selected": false,
"text": "<p>I'm sure there could be a great discussion on ternary operators vrs function calls. But the point of this question was to see if we can create a function that won't throw an error if a non existent value is passed in without using the '@'</p>\n"
},
{
"answer_id": 55127,
"author": "reefnet_alex",
"author_id": 2745,
"author_profile": "https://Stackoverflow.com/users/2745",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this using func_get_args like so:</p>\n\n<pre><code>error_reporting(E_ALL);\nini_set('display_errors', 1);\n\nfunction defaultValue() {\n $args = func_get_args();\n\n foreach($args as $arg) {\n if (!is_array($arg)) {\n $arg = array($arg);\n }\n foreach($arg as $a) {\n if(!empty($a)) {\n return $a;\n }\n }\n }\n\n return false;\n}\n\n$var = 'bob';\n\necho defaultValue(compact('var'), 'alpha') . \"\\n\"; //returns 'bob'\necho defaultValue(compact('var2'), 'alpha') . \"\\n\"; //returns 'alpha'\necho defaultValue('alpha') . \"\\n\"; //return\necho defaultValue() . \"\\n\";\n</code></pre>\n\n<p>This func goes one step further and would give you the first non empty value of any number of args (you could always force it to only take up to two args but this look more useful to me like this).</p>\n\n<p>EDIT: original version didn't use compact to try and make an array of args and STILL gave an error. Error reporting bumped up a notch and this new version with compact is a little less tidy, but still does the same thing and allows you to provide a default value for non existent vars. </p>\n"
},
{
"answer_id": 55128,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "<p>@Sean That was already answered by Brian</p>\n\n<pre><code>return isset($input) ? $input : $default;\n</code></pre>\n"
},
{
"answer_id": 55133,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 0,
"selected": false,
"text": "<p>Sean, you could do:</p>\n\n<pre><code>$result = ($func_result = doLargeIntenseFunction()) ? $func_result : 'no result';\n</code></pre>\n\n<p>EDIT:</p>\n\n<blockquote>\n <p>I'm sure there could be a great\n discussion on ternary operators vrs\n function calls. But the point of this\n question was to see if we can create a\n function that won't throw an error if\n a non existent value is passed in\n without using the '@'</p>\n</blockquote>\n\n<p>And I told you, check it with <code>isset()</code>. A ternary conditional's first part doesn't check null or not null, it checks <code>true</code> or <code>false</code>. If you try to check <code>true</code> or <code>false</code> on a null value in PHP, you get these warnings. <code>isset()</code> checks whether a variable or expression returns a null value or not, and it returns a boolean, which can be evaluated by the first part of your ternary without any errors.</p>\n"
},
{
"answer_id": 55191,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": true,
"text": "<p>Summing up, the proper answer is <strong>no, you shouldn't</strong> (see caveat below). </p>\n\n<p>There are workarounds already mentioned by many people in this thread, like using reference variables or isset() or empty() in conditions and suppressing notices in PHP configuration. That in addition to the obvious workaround, using @, which you don't want.</p>\n\n<p>Summarizing an interesting comment discussion with <a href=\"https://stackoverflow.com/users/109561/gerry\">Gerry</a>: Passing the variable by reference is indeed valid if you <strong>check for the value of the variable inside the function</strong> and handle undefined or null cases properly. Just don't use reference passing as a way of shutting PHP up (this is where my original shouldn't points to).</p>\n"
},
{
"answer_id": 311954,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 4,
"selected": false,
"text": "<p>You don't get any error when a variable is passed by reference (PHP will create a new variable silently):</p>\n\n<pre><code> function myHappyFunction(&$var)\n { \n }\n</code></pre>\n\n<p>But I recommend against abusing this for hiding programming errors.</p>\n"
},
{
"answer_id": 504472,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>While the answer to the original question is \"no\", there is an options no one has mentioned.</p>\n\n<p>When you use the @ sign, all PHP is doing is overriding the <code>error_reporting</code> level and temporarily setting it to zero. You can use \"<code>ini_restore('error_reporting');</code>\" to set it back to whatever it was before the @ was used.</p>\n\n<p>This was useful to me in the situation where I wanted to write a convenience function to check and see if a variable was set, and had some other properties as well, otherwise, return a default value. But, sending an unset variable through caused a PHP notice, so I used the @ to suppress that, but then set <code>error_reporting</code> back to the original value inside the function.</p>\n\n<p>Something like:</p>\n\n<pre><code>$var = @foo($bar);\n\nfunction foo($test_var)\n{\n ini_restore('error_reporting');\n\n if(is_set($test_var) && strlen($test_var))\n {\n return $test_var;\n }\n else\n {\n return -1;\n }\n}\n</code></pre>\n\n<p>So, in the case above, if <code>$bar</code> is not set, I won't get an error when I call <code>foo()</code> with a non-existent variable. However, I will get an error from within the function where I mistakenly typed <code>is_set</code> instead of <code>isset</code>.</p>\n\n<p>This could be a useful option covering what the original question was asking in spirit, if not in actual fact.</p>\n"
},
{
"answer_id": 884770,
"author": "Gerry",
"author_id": 109561,
"author_profile": "https://Stackoverflow.com/users/109561",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>is it possible to write a function in a way where invalid arguments or non existent variables can be passed in and php will not error without the use of '@'</p>\n</blockquote>\n\n<p><strong>Yes you can!</strong></p>\n\n<p>porneL is correct [edit:I don't have enough points to link to his answer or vote it up, but it's on this page]</p>\n\n<p>He is also correct when he cautions \"But I recommend against abusing this for hiding programming errors.\" however error suppression via the Error Control Operator (@) should also be avoided for this same reason.</p>\n\n<p>I'm new to Stack Overflow, but I hope it's not common for an incorrect answer to be ranked the highest on a page while the correct answer receives no votes. :(</p>\n"
},
{
"answer_id": 931565,
"author": "BraedenP",
"author_id": 95764,
"author_profile": "https://Stackoverflow.com/users/95764",
"pm_score": 0,
"selected": false,
"text": "<p>If you simply add a default value to the parameter, you can skip it when calling the function. For example:</p>\n\n<pre><code>function empty($paramName = \"\"){\n if(isset($paramName){\n //Code here\n }\n else if(empty($paramName)){\n //Code here\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1867434,
"author": "Bob Fanger",
"author_id": 19165,
"author_profile": "https://Stackoverflow.com/users/19165",
"pm_score": 2,
"selected": false,
"text": "<p>There are valid cases where checking becomes cumbersome and unnessesary.<br>\nTherfore i've written this little magic function: </p>\n\n<pre><code>/**\n * Shortcut for getting a value from a possibly unset variable.\n * Normal:\n * if (isset($_GET['foo']) && $_GET['foo'] == 'bar') {\n * Short:\n * if (value($_GET['foo']) == 'bar') {\n *\n * @param mixed $variable \n * @return mixed Returns null if not set\n */\nfunction value(&$variable) {\n if (isset($variable)) {\n return $variable;\n }\n}\n</code></pre>\n\n<p>It doesn't require any changes to myHappyFunction().<br>\nYou'll have to change</p>\n\n<pre><code>myHappyFunction($someBogusVar);\n</code></pre>\n\n<p>to</p>\n\n<pre><code>myHappyFunction(value($someBogusVar));\n</code></pre>\n\n<p>Stating your intent explicitly. which makes it <strong>good practice</strong> in my book.</p>\n"
},
{
"answer_id": 10890296,
"author": "Omar",
"author_id": 931377,
"author_profile": "https://Stackoverflow.com/users/931377",
"pm_score": 0,
"selected": false,
"text": "<p>With a single line, you can acomplish it: <code>myHappyFunction($someBogusVar=\"\");</code></p>\n\n<p>I hope this is what you are looking for. If you read the php documentation, under <a href=\"http://php.net/manual/en/functions.arguments.php\" rel=\"nofollow\">default argument values</a>, you can see that assigning a default value to an function's argument helps you prevent an error message when using functions.</p>\n\n<p>In this example you can see the difference of using a default argument and it's advantages:</p>\n\n<p><strong>PHP code:</strong></p>\n\n<pre><code><?php\nfunction test1($argument)\n{\n echo $argument;\n echo \"\\n\";\n}\n\nfunction test2($argument=\"\")\n{\n echo $argument;\n echo \"\\n\";\n}\n\ntest1();\ntest1(\"Hello\");\ntest1($argument);\n$argument = \"Hello world\";\ntest1($argument);\n\ntest2();\ntest2(\"Hello\");\ntest2($argument);\n$argument = \"Hello world\";\ntest2($argument);\n?>\n</code></pre>\n\n<p><strong>Output for <code>test1()</code> lines:</strong></p>\n\n<blockquote>\n <p><b>Warning</b>: Missing argument 1 for test1() .<br/>\n Hello. <br/>\n . <br/>\n Hello world.</p>\n</blockquote>\n\n<p><strong>Output for <code>test2()</code> lines:</strong></p>\n\n<blockquote>\n <p>. <br/>\n Hello. <br/>\n <br/>\n Hello world.</p>\n</blockquote>\n\n<p>This can also be used in combination to <code>isset()</code> and other functions to accomplish what you want.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5261/"
] | I'm pretty sure the answer to this question is no, but in case there's some PHP guru
is it possible to write a function in a way where invalid arguments or non existent variables can be passed in and php will not error without the use of `'@'`
Much like empty and isset do. You can pass in a variable you just made up and it won't error.
```
ex:
empty($someBogusVar); // no error
myHappyFunction($someBogusVar); // Php warning / notice
``` | Summing up, the proper answer is **no, you shouldn't** (see caveat below).
There are workarounds already mentioned by many people in this thread, like using reference variables or isset() or empty() in conditions and suppressing notices in PHP configuration. That in addition to the obvious workaround, using @, which you don't want.
Summarizing an interesting comment discussion with [Gerry](https://stackoverflow.com/users/109561/gerry): Passing the variable by reference is indeed valid if you **check for the value of the variable inside the function** and handle undefined or null cases properly. Just don't use reference passing as a way of shutting PHP up (this is where my original shouldn't points to). |
55,083 | <p>Any ideas how to display a PDF file in a WPF Windows Application? </p>
<hr>
<p>I am using the following code to run the browser but the <code>Browser.Navigate</code> method does not do anything!</p>
<pre><code>WebBrowser browser = new WebBrowser();
browser.Navigate("http://www.google.com");
this.AddChild(browser); // this is the System.Windows.Window
</code></pre>
| [
{
"answer_id": 55085,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": -1,
"selected": false,
"text": "<p>Check this out: <a href=\"http://itextsharp.sourceforge.net/\" rel=\"nofollow noreferrer\">http://itextsharp.sourceforge.net/</a>\nYou may have to use a WindowsFormsHost, but since it is open source, you might be able to make it a little more elegant in WPF.</p>\n"
},
{
"answer_id": 55087,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 4,
"selected": false,
"text": "<p>You could simply host a Web Browser control on the form and use it to open the PDF.</p>\n\n<p>There's a new native WPF \"WebBrowser\" control in .NET 3.51, or you could host the Windows.Forms browser in your WPF app.</p>\n"
},
{
"answer_id": 55177,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 4,
"selected": true,
"text": "<p>Oops. this is for a winforms app. Not for WPF. I will post this anyway.</p>\n\n<p>try this</p>\n\n<pre><code>private AxAcroPDFLib.AxAcroPDF axAcroPDF1;\nthis.axAcroPDF1 = new AxAcroPDFLib.AxAcroPDF();\nthis.axAcroPDF1.Dock = System.Windows.Forms.DockStyle.Fill;\nthis.axAcroPDF1.Enabled = true;\nthis.axAcroPDF1.Name = \"axAcroPDF1\";\nthis.axAcroPDF1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject(\"axAcroPDF1.OcxState\")));\naxAcroPDF1.LoadFile(DownloadedFullFileName);\naxAcroPDF1.Visible = true;\n</code></pre>\n"
},
{
"answer_id": 581997,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>The following code expects Adobe Reader to be installed and the Pdf extension to be connected to this.\nIt simply runs it:</p>\n\n<pre><code>String fileName = \"FileName.pdf\";\nSystem.Diagnostics.Process process = new System.Diagnostics.Process(); \nprocess.StartInfo.FileName = fileName;\nprocess.Start();\nprocess.WaitForExit();\n</code></pre>\n"
},
{
"answer_id": 720372,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>You can get the Acrobat Reader control working in a WPF app by using the WindowsFormHost control. I have a blog post about it here:</p>\n\n<p><a href=\"http://hugeonion.com/2009/04/06/displaying-a-pdf-file-within-a-wpf-application/\" rel=\"noreferrer\">http://hugeonion.com/2009/04/06/displaying-a-pdf-file-within-a-wpf-application/</a></p>\n\n<p>I also have a 5 minute screencast of how I made it here:</p>\n\n<p><a href=\"http://www.screencast.com/t/JXRhGvzvB\" rel=\"noreferrer\">http://www.screencast.com/t/JXRhGvzvB</a></p>\n"
},
{
"answer_id": 5759095,
"author": "odyth",
"author_id": 86524,
"author_profile": "https://Stackoverflow.com/users/86524",
"pm_score": 3,
"selected": false,
"text": "<p>Just use a frame and a webbrowser like so</p>\n\n<pre><code>Frame frame = new Frame();\nWebBrowserbrowser = new WebBrowser();\nbrowser.Navigate(new Uri(filename));\nframe.Content = browser;\n</code></pre>\n\n<p>Then when you don't need it anymore do this to clean it up:</p>\n\n<pre><code>WebBrowser browser = frame.Content as WebBrowser;\nbrowser.Dispose();\nframe.Content = null;\n</code></pre>\n\n<p>If you don't clean it up then you might have memory leak problems depending on the version of .NET your using. I saw bad memory leaks in .NET 3.5 if I didn't clean up.</p>\n"
},
{
"answer_id": 14174843,
"author": "Mohammad",
"author_id": 633495,
"author_profile": "https://Stackoverflow.com/users/633495",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use FoxitReader. It's free and comes with an ActiveX control that registers in the web browsers (IE and others) after you install the FoxitReader application.\nSo after you install FoxitReader on the system put a WebBrowser Control and set its Source property to point to the file path of your PDF file.</p>\n"
},
{
"answer_id": 17381626,
"author": "VahidN",
"author_id": 298573,
"author_profile": "https://Stackoverflow.com/users/298573",
"pm_score": 3,
"selected": false,
"text": "<p>Try <code>MoonPdfPanel - A WPF-based PDF viewer control</code>\n<a href=\"http://www.codeproject.com/Articles/579878/MoonPdfPanel-A-WPF-based-PDF-viewer-control\" rel=\"noreferrer\">http://www.codeproject.com/Articles/579878/MoonPdfPanel-A-WPF-based-PDF-viewer-control</a></p>\n\n<p>GitHub: <a href=\"https://github.com/reliak/moonpdf\" rel=\"noreferrer\">https://github.com/reliak/moonpdf</a></p>\n"
},
{
"answer_id": 19423956,
"author": "Frank Rem",
"author_id": 450467,
"author_profile": "https://Stackoverflow.com/users/450467",
"pm_score": 1,
"selected": false,
"text": "<p>Disclosure: Here is a commercial one and I work for this company. </p>\n\n<p>I realize that an answer has already been accepted but the following does not require Adobe Reader/Acrobat and it is a WPF solution - as opposed to Winforms. I also realize this is an old question but it has just been updated so I guess it is still actual.</p>\n\n<p><a href=\"https://www.tallcomponents.com/pdfrasterizer3.aspx\" rel=\"nofollow\">PDFRasterizer.NET 3.0</a> allows you to render to a WPF FixedDocument. It preserves all vector graphics (PDF graphics are converted to more or less equivalent WPF elements. This is probably closest to what you need.</p>\n\n<pre><code>using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))\n{\n pdfDoc = new Document(file);\n\n ConvertToWpfOptions convertOptions = new ConvertToWpfOptions();\n RenderSettings renderSettings = new RenderSettings();\n ...\n\n FixedDocument wpfDoc = pdfDoc.ConvertToWpf(renderSettings, convertOptions, 0, 9, summary);\n}\n</code></pre>\n\n<p>You can pass the wpfDoc to e.g. the WPF DocumentViewer to quickly implement a viewer.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3797/"
] | Any ideas how to display a PDF file in a WPF Windows Application?
---
I am using the following code to run the browser but the `Browser.Navigate` method does not do anything!
```
WebBrowser browser = new WebBrowser();
browser.Navigate("http://www.google.com");
this.AddChild(browser); // this is the System.Windows.Window
``` | Oops. this is for a winforms app. Not for WPF. I will post this anyway.
try this
```
private AxAcroPDFLib.AxAcroPDF axAcroPDF1;
this.axAcroPDF1 = new AxAcroPDFLib.AxAcroPDF();
this.axAcroPDF1.Dock = System.Windows.Forms.DockStyle.Fill;
this.axAcroPDF1.Enabled = true;
this.axAcroPDF1.Name = "axAcroPDF1";
this.axAcroPDF1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axAcroPDF1.OcxState")));
axAcroPDF1.LoadFile(DownloadedFullFileName);
axAcroPDF1.Visible = true;
``` |
55,093 | <p>I have a class to parse a matrix that keeps the result in an array member:</p>
<pre><code>class Parser
{
...
double matrix_[4][4];
};
</code></pre>
<p>The user of this class needs to call an API function (as in, a function I have no control over, so I can't just change its interface to make things work more easily) that looks like this:</p>
<pre><code>void api_func(const double matrix[4][4]);
</code></pre>
<p>The only way I have come up with for the caller to pass the array result to the function is by making the member public:</p>
<pre><code>void myfunc()
{
Parser parser;
...
api_func(parser.matrix_);
}
</code></pre>
<p>Is this the only way to do things? I'm astounded by how inflexible multidimensional arrays declared like this are. I thought <code>matrix_</code> would essentially be the same as a <code>double**</code> and I could cast (safely) between the two. As it turns out, I can't even find an <em>unsafe</em> way to cast between the things. Say I add an accessor to the <code>Parser</code> class:</p>
<pre><code>void* Parser::getMatrix()
{
return (void*)matrix_;
}
</code></pre>
<p>This will compile, but I can't use it, because there doesn't seem to be a way to cast back to the weirdo array type:</p>
<pre><code> // A smorgasbord of syntax errors...
api_func((double[][])parser.getMatrix());
api_func((double[4][4])parser.getMatrix());
api_func((double**)parser.getMatrix()); // cast works but it's to the wrong type
</code></pre>
<p>The error is:</p>
<blockquote>
<p>error C2440: 'type cast' : cannot convert from 'void *' to 'const double [4][4]'</p>
</blockquote>
<p>...with an intriguing addendum:</p>
<blockquote>
<p>There are no conversions to array types, although there are conversions to references or pointers to arrays</p>
</blockquote>
<p>I can't determine how to cast to a reference or pointer to array either, albeit that it probably won't help me here.</p>
<p>To be sure, at this point the matter is purely academic, as the <code>void*</code> casts are hardly cleaner than a single class member left public!</p>
| [
{
"answer_id": 55118,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 2,
"selected": false,
"text": "<p>I've used a union like this to pass around matrices in the past:</p>\n\n<pre><code>union matrix {\n double dflat[16];\n double dmatr[4][4];\n};\n</code></pre>\n\n<p>Then pass a pointer in to your setter and copy the data into the matrix in your class.</p>\n\n<p>There are ways of handling this otherwise (that are more generic), but this solution tends to be the cleanest in the end, in my experience.</p>\n"
},
{
"answer_id": 55149,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 5,
"selected": true,
"text": "<p>Here's a nice, clean way:</p>\n\n<pre><code>class Parser\n{\npublic:\n typedef double matrix[4][4];\n\n // ...\n\n const matrix& getMatrix() const\n {\n return matrix_;\n }\n\n // ...\n\nprivate:\n matrix matrix_;\n};\n</code></pre>\n\n<p>Now you're working with a descriptive type name rather than an array, but since it's a <code>typedef</code> the compiler will still allow passing it to the unchangeable API function that takes the base type.</p>\n"
},
{
"answer_id": 55167,
"author": "Andrew",
"author_id": 826,
"author_profile": "https://Stackoverflow.com/users/826",
"pm_score": 3,
"selected": false,
"text": "<p>Try this. It compiles cleanly on gcc 4.1.3:</p>\n\n<pre><code>typedef double FourSquare[4][4];\n\nclass Parser\n{\n private:\n double matrix_[4][4];\n\n public:\n Parser()\n {\n for(int i=0; i<4; i++)\n for(int j=0; j<4; j++)\n matrix_[i][j] = i*j;\n }\n\n public:\n const FourSquare& GetMatrix()\n {\n return matrix_;\n }\n};\n\nvoid api_func( const double matrix[4][4] )\n{\n}\n\nint main( int argc, char** argv )\n{\n Parser parser;\n api_func( parser.GetMatrix() );\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 55183,
"author": "Pete Kirkham",
"author_id": 1527,
"author_profile": "https://Stackoverflow.com/users/1527",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I thought matrix_ would essentially be the same as a double**</p>\n</blockquote>\n\n<p>In C there are true multi-dimensional arrays, not arrays of pointers to arrays, so a double[4][4] is a contiguous array of four double[4] arrays, equivalent to a double[16], not a (double*)[4]. </p>\n\n<blockquote>\n <p>There are no conversions to array types, although there are conversions to references or pointers to arrays\n Casting a value to a double[4][4] would attempt to construct one on the stack - equivalent to std::string(parser.getMatrix()) - except that the array doesn't supply a suitable constructor. You probably did't want to do that, even if you could.</p>\n</blockquote>\n\n<p>Since the type encodes the stride, you need a full type (double[][] won't do). You can reinterpret cast the void* to ((double[4][4])*), and then take the reference. But it's easiest to typedef the matrix and return a reference of the correct type in the first place:</p>\n\n<pre><code>typedef double matrix_t[4][4];\n\nclass Parser\n{\n double matrix_[4][4];\npublic:\n void* get_matrix () { return static_cast<void*>(matrix_); }\n\n const matrix_t& get_matrix_ref () const { return matrix_; }\n};\n\nint main ()\n{\n Parser p;\n\n matrix_t& data1 = *reinterpret_cast<matrix_t*>(p.get_matrix());\n\n const matrix_t& data2 = p.get_matrix_ref();\n}\n</code></pre>\n"
},
{
"answer_id": 55341,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "<p>To elaborate on the selected answer, observe this line</p>\n\n<pre><code>const matrix& getMatrix() const\n</code></pre>\n\n<p>This is great, you don't have to worry about pointers and casting. You're returning a <em>reference</em> to the underlying matrix object. IMHO references are one of the best features of C++, which I miss when coding in straight C.</p>\n\n<p>If you're not familiar with the difference between references and pointers in C++, <a href=\"https://isocpp.org/wiki/faq/references\" rel=\"nofollow noreferrer\">read this</a></p>\n\n<p>At any rate, you do have to be aware that if the <code>Parser</code> object which actually owns the underlying matrix object goes out of scope, any code which tries to access the matrix via that reference will now be referencing an out-of-scope object, and you'll crash.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
] | I have a class to parse a matrix that keeps the result in an array member:
```
class Parser
{
...
double matrix_[4][4];
};
```
The user of this class needs to call an API function (as in, a function I have no control over, so I can't just change its interface to make things work more easily) that looks like this:
```
void api_func(const double matrix[4][4]);
```
The only way I have come up with for the caller to pass the array result to the function is by making the member public:
```
void myfunc()
{
Parser parser;
...
api_func(parser.matrix_);
}
```
Is this the only way to do things? I'm astounded by how inflexible multidimensional arrays declared like this are. I thought `matrix_` would essentially be the same as a `double**` and I could cast (safely) between the two. As it turns out, I can't even find an *unsafe* way to cast between the things. Say I add an accessor to the `Parser` class:
```
void* Parser::getMatrix()
{
return (void*)matrix_;
}
```
This will compile, but I can't use it, because there doesn't seem to be a way to cast back to the weirdo array type:
```
// A smorgasbord of syntax errors...
api_func((double[][])parser.getMatrix());
api_func((double[4][4])parser.getMatrix());
api_func((double**)parser.getMatrix()); // cast works but it's to the wrong type
```
The error is:
>
> error C2440: 'type cast' : cannot convert from 'void \*' to 'const double [4][4]'
>
>
>
...with an intriguing addendum:
>
> There are no conversions to array types, although there are conversions to references or pointers to arrays
>
>
>
I can't determine how to cast to a reference or pointer to array either, albeit that it probably won't help me here.
To be sure, at this point the matter is purely academic, as the `void*` casts are hardly cleaner than a single class member left public! | Here's a nice, clean way:
```
class Parser
{
public:
typedef double matrix[4][4];
// ...
const matrix& getMatrix() const
{
return matrix_;
}
// ...
private:
matrix matrix_;
};
```
Now you're working with a descriptive type name rather than an array, but since it's a `typedef` the compiler will still allow passing it to the unchangeable API function that takes the base type. |
55,101 | <p>I have a Linq query that I want to call from multiple places:</p>
<pre><code>var myData = from a in db.MyTable
where a.MyValue == "A"
select new {
a.Key,
a.MyValue
};
</code></pre>
<p>How can I create a method, put this code in it, and then call it?</p>
<pre><code>public ??? GetSomeData()
{
// my Linq query
}
</code></pre>
| [
{
"answer_id": 55110,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.linq.iqueryable.aspx\" rel=\"nofollow noreferrer\"><code>IQueryable</code></a></p>\n\n<p>So your method declaration would look like</p>\n\n<pre><code>public IQueryable GetSomeData()\n</code></pre>\n"
},
{
"answer_id": 55120,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to return, you need a type.</p>\n\n<p>Instead of <code>var</code>, declare using <code>IEnumerable<></code> and return that variable. Iterating through it actually executes the query.</p>\n"
},
{
"answer_id": 55254,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 4,
"selected": true,
"text": "<p>IQueryable and IEnumerable both work. But you want to use a type specific version, IQueryable<code><</code>T<code>></code> or IEnumerable <code><</code>T<code>></code>.</p>\n\n<p>So you'll want to create a type to keep the data.</p>\n\n<pre><code>var myData = from a in db.MyTable\n where a.MyValue == \"A\"\n select new MyType\n {\n Key = a.Key,\n Value = a.MyValue\n };\n</code></pre>\n"
},
{
"answer_id": 55278,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>A generic method should give you intellisense:</p>\n\n<pre><code>public class MyType {Key{get;set;} Value{get;set}}\n\npublic IQueryable<T> GetSomeData<T>() where T : MyType, new() \n { return from a in db.MyTable\n where a.MyValue == \"A\" \n select new T {Key=a.Key,Value=a.MyValue};\n }\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] | I have a Linq query that I want to call from multiple places:
```
var myData = from a in db.MyTable
where a.MyValue == "A"
select new {
a.Key,
a.MyValue
};
```
How can I create a method, put this code in it, and then call it?
```
public ??? GetSomeData()
{
// my Linq query
}
``` | IQueryable and IEnumerable both work. But you want to use a type specific version, IQueryable`<`T`>` or IEnumerable `<`T`>`.
So you'll want to create a type to keep the data.
```
var myData = from a in db.MyTable
where a.MyValue == "A"
select new MyType
{
Key = a.Key,
Value = a.MyValue
};
``` |
55,114 | <p>Ok, so I'm an idiot. </p>
<p>So I was working on a regex that took way to long to craft. After perfecting it, I upgraded my work machine with a blazing fast hard drive and realized that I never saved the regex anywhere and simply used RegexBuddy's autosave to store it. Dumb dumb dumb. </p>
<p>I sent a copy of the regex to a coworker but now he can't find it (or the record of our communication). My best hope of finding the regex is to find it in RegexBuddy on the old hard drive. RegexBuddy automatically saves whatever you were working on each time you close it. I've done some preliminary searches to try to determine where it actually saves that working data but I'm having no success. </p>
<p>This question is the result of my dumb behavior but I thought it was a good chance to finally ask a question here. </p>
| [
{
"answer_id": 55168,
"author": "Morten Christiansen",
"author_id": 4055,
"author_profile": "https://Stackoverflow.com/users/4055",
"pm_score": 0,
"selected": false,
"text": "<p>It depends on the OS, of cause, but on Windows I would guess the application data directory. I can't remember the path on xp but on vista it's something like this:</p>\n\n<p>C:\\Users\\ <em>user name</em> \\AppData\\</p>\n\n<p>And then it would probably be here:</p>\n\n<p>C:\\Users\\ <em>user name</em> \\AppData\\roaming</p>\n"
},
{
"answer_id": 55182,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": true,
"text": "<p>On my XP box, it was in the registry here:</p>\n\n<pre><code>HKEY_CURRENT_USER\\Software\\JGsoft\\RegexBuddy3\\History\n</code></pre>\n\n<p>There were two REG_BINARY keys called <strong>Action0</strong> and <strong>Action1</strong> that had hex data containing my two regexes from the history.</p>\n\n<p><img src=\"https://i.stack.imgur.com/0k0b0.png\" alt=\"Screenshot of the Action registry key\"></p>\n\n<p>The test data that I was testing the regex against was here:</p>\n\n<pre><code>C:\\Documents and Settings\\<username>\\Application Data\\JGsoft\\RegexBuddy 3\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1116922/"
] | Ok, so I'm an idiot.
So I was working on a regex that took way to long to craft. After perfecting it, I upgraded my work machine with a blazing fast hard drive and realized that I never saved the regex anywhere and simply used RegexBuddy's autosave to store it. Dumb dumb dumb.
I sent a copy of the regex to a coworker but now he can't find it (or the record of our communication). My best hope of finding the regex is to find it in RegexBuddy on the old hard drive. RegexBuddy automatically saves whatever you were working on each time you close it. I've done some preliminary searches to try to determine where it actually saves that working data but I'm having no success.
This question is the result of my dumb behavior but I thought it was a good chance to finally ask a question here. | On my XP box, it was in the registry here:
```
HKEY_CURRENT_USER\Software\JGsoft\RegexBuddy3\History
```
There were two REG\_BINARY keys called **Action0** and **Action1** that had hex data containing my two regexes from the history.

The test data that I was testing the regex against was here:
```
C:\Documents and Settings\<username>\Application Data\JGsoft\RegexBuddy 3
``` |
55,130 | <p>This is a segment of code from an app I've inherited, a user got a Yellow screen of death:</p>
<blockquote>
<p>Object reference not set to an instance of an object</p>
</blockquote>
<p>on the line: </p>
<pre><code>bool l_Success ...
</code></pre>
<p>Now I'm 95% sure the faulty argument is <code>ref l_Monitor</code> which is very weird considering the object is instantiated a few lines before. Anyone have a clue why it would happen? Note that I have seen the same issue pop up in other places in the code.</p>
<pre><code>IDMS.Monitor l_Monitor = new IDMS.Monitor();
l_Monitor.LogFile.Product_ID = "SE_WEB_APP";
if (m_PermType_RadioButtonList.SelectedIndex == -1) {
l_Monitor.LogFile.Log(
Nortel.IS.IDMS.LogFile.MessageTypes.ERROR,
"No permission type selected"
);
return;
}
bool l_Success = SE.UI.Utilities.GetPermissionList(
ref l_Monitor,
ref m_CPermissions_ListBox,
(int)this.ViewState["m_Account_Share_ID"],
(m_PermFolders_DropDownList.Enabled)
? m_PermFolders_DropDownList.SelectedItem.Value
: "-1",
(SE.Types.PermissionType)m_PermType_RadioButtonList.SelectedIndex,
(SE.Types.PermissionResource)m_PermResource_RadioButtonList.SelectedIndex);
</code></pre>
| [
{
"answer_id": 55138,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "<p>You sure that one of the properties trying to be accessed on the l_Monitor instance isn't null?</p>\n"
},
{
"answer_id": 55144,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 0,
"selected": false,
"text": "<p>Sprinkle in a few variables for all the property-queries on that (loooooongg) line temporarily. Run the debugger, Check values and Corner the little bug.</p>\n"
},
{
"answer_id": 55158,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 0,
"selected": false,
"text": "<p>I'm inclined to agree with the others; it sounds like one of the parameters you are passing SE.UI.Utilities.GetPermissionList is null which is causing the exception. Your best bet is to fire up the debugger and check was the variables are before that code is called.</p>\n"
},
{
"answer_id": 84541,
"author": "Beriadan",
"author_id": 1983,
"author_profile": "https://Stackoverflow.com/users/1983",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>NullReferenceException</code> was actually thrown within a catch block so the stack trace couldn't display that line of code so instead it stopped at the caller. </p>\n\n<p>It was indeed one of the properties of the <code>l_Monitor</code> instance.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1983/"
] | This is a segment of code from an app I've inherited, a user got a Yellow screen of death:
>
> Object reference not set to an instance of an object
>
>
>
on the line:
```
bool l_Success ...
```
Now I'm 95% sure the faulty argument is `ref l_Monitor` which is very weird considering the object is instantiated a few lines before. Anyone have a clue why it would happen? Note that I have seen the same issue pop up in other places in the code.
```
IDMS.Monitor l_Monitor = new IDMS.Monitor();
l_Monitor.LogFile.Product_ID = "SE_WEB_APP";
if (m_PermType_RadioButtonList.SelectedIndex == -1) {
l_Monitor.LogFile.Log(
Nortel.IS.IDMS.LogFile.MessageTypes.ERROR,
"No permission type selected"
);
return;
}
bool l_Success = SE.UI.Utilities.GetPermissionList(
ref l_Monitor,
ref m_CPermissions_ListBox,
(int)this.ViewState["m_Account_Share_ID"],
(m_PermFolders_DropDownList.Enabled)
? m_PermFolders_DropDownList.SelectedItem.Value
: "-1",
(SE.Types.PermissionType)m_PermType_RadioButtonList.SelectedIndex,
(SE.Types.PermissionResource)m_PermResource_RadioButtonList.SelectedIndex);
``` | You sure that one of the properties trying to be accessed on the l\_Monitor instance isn't null? |
55,159 | <p>In SQL Server 2005 I have an "id" field in a table that has the "Is Identity" property set to 'Yes'. So, when an Insert is executed on that table the "id" gets set automatically to the next incrementing integer. Is there an easy way when the Insert is executed to get what the "id" was set to without having to do a Select statement right after the Insert?</p>
<blockquote>
<p>duplicate of:<br>
<a href="https://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row">Best way to get identity of inserted row?</a></p>
</blockquote>
| [
{
"answer_id": 55164,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>You have to select the scope_identity() function. </p>\n\n<p>To do this from application code, I normally encapsulate this process in a stored procedure so it still looks like one query to my application.</p>\n"
},
{
"answer_id": 55170,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": false,
"text": "<p>Scope_identity() is the preferred way, see: <a href=\"http://wiki.lessthandot.com/index.php/6_Different_Ways_To_Get_The_Current_Identity_Value\" rel=\"nofollow noreferrer\">6 Different Ways To Get The Current Identity Value</a></p>\n"
},
{
"answer_id": 55172,
"author": "Josh Hinman",
"author_id": 2527,
"author_profile": "https://Stackoverflow.com/users/2527",
"pm_score": 6,
"selected": true,
"text": "<p>In .Net at least, you can send multiple queries to the server in one go. I do this in my app:</p>\n\n<pre><code>command.CommandText = \"INSERT INTO [Employee] (Name) VALUES (@Name); SELECT SCOPE_IDENTITY()\";\nint id = (int)command.ExecuteScalar();\n</code></pre>\n\n<p>Works like a charm.</p>\n"
},
{
"answer_id": 55190,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 2,
"selected": false,
"text": "<p>SCOPE_IDENTITY(); is your best bet. And if you are using .NET just pass an our parameter and check the value after the procedure is run.</p>\n\n<pre><code>CREATE PROCEDURE [dbo].[InsertProducts]\n @id INT = NULL OUT,\n @name VARCHAR(150) = NULL,\n @desc VARCHAR(250) = NULL\n\nAS\n\n INSERT INTO dbo.Products\n (Name,\n Description)\n VALUES\n (@name,\n @desc)\n\n SET @id = SCOPE_IDENTITY();\n</code></pre>\n"
},
{
"answer_id": 55299,
"author": "kamajo",
"author_id": 5415,
"author_profile": "https://Stackoverflow.com/users/5415",
"pm_score": 4,
"selected": false,
"text": "<p>If you're inserting multiple rows, the use of the <code>OUTPUT</code> and <code>INSERTED.columnname</code> clause on the <code>insert</code> statement is a simple way of getting all the ids into a temp table. </p>\n\n<pre><code>DECLARE @MyTableVar table( ID int, \n Name varchar(50), \n ModifiedDate datetime); \nINSERT MyTable \n OUTPUT INSERTED.ID, INSERTED.Name, INSERTED.ModifiedDate INTO @MyTableVar \nSELECT someName, GetDate() from SomeTable \n</code></pre>\n"
},
{
"answer_id": 55329,
"author": "callingshotgun",
"author_id": 2876,
"author_profile": "https://Stackoverflow.com/users/2876",
"pm_score": 1,
"selected": false,
"text": "<p>I tend to prefer attaching a trigger to the table using enterprise manager. That way you don't need to worry about writing out extra sql statements in your code. Mine look something like this:</p>\n\n<p>Create Trigger tblName\nOn dbo.tblName\nFor Insert\nAs\nselect new_id = @@IDENTITY</p>\n\n<p>Then, from within your code, treat your insert statements like select statements- Just execute and evaluate the results. the \"newID\" column will contain the identity of the row you just created.</p>\n"
},
{
"answer_id": 27740695,
"author": "Udit Narayan",
"author_id": 2267783,
"author_profile": "https://Stackoverflow.com/users/2267783",
"pm_score": 0,
"selected": false,
"text": "<p>This is probably the best working solution I found for SQL Server..\n<a href=\"https://stackoverflow.com/questions/17993606/sql-server-return-the-value-of-identity-column-after-insert-statement\">Sql Server return the value of identity column after insert statement</a></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1096640/"
] | In SQL Server 2005 I have an "id" field in a table that has the "Is Identity" property set to 'Yes'. So, when an Insert is executed on that table the "id" gets set automatically to the next incrementing integer. Is there an easy way when the Insert is executed to get what the "id" was set to without having to do a Select statement right after the Insert?
>
> duplicate of:
>
> [Best way to get identity of inserted row?](https://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row)
>
>
> | In .Net at least, you can send multiple queries to the server in one go. I do this in my app:
```
command.CommandText = "INSERT INTO [Employee] (Name) VALUES (@Name); SELECT SCOPE_IDENTITY()";
int id = (int)command.ExecuteScalar();
```
Works like a charm. |
55,180 | <p>Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added. </p>
<p>What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?</p>
<p>For example, you had this:</p>
<pre><code>d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
</code></pre>
<p>I want to print the associated values in the following sequence sorted by key:</p>
<pre><code>this is a
this is b
this is c
</code></pre>
| [
{
"answer_id": 55188,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 2,
"selected": false,
"text": "<p>This snippet will do it. If you're going to do it frequently, you might want to make a 'sortkeys' method to make it easier on the eyes.</p>\n<pre><code>keys = list(d.keys())\nkeys.sort()\nfor key in keys:\n print d[key]\n</code></pre>\n<p>Edit: <a href=\"https://stackoverflow.com/a/55193/2745495\">dF's solution</a> is better -- I forgot all about <code>sorted()</code>.</p>\n"
},
{
"answer_id": 55193,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 4,
"selected": false,
"text": "<p>Do you mean that you need the values sorted by the value of the key?\nIn that case, this should do it:</p>\n\n<pre><code>for key in sorted(d):\n print d[key]\n</code></pre>\n\n<p><strong>EDIT:</strong> changed to use sorted(d) instead of sorted(d.keys()), thanks <a href=\"https://stackoverflow.com/users/1694/eli-courtwright\">Eli</a>!</p>\n"
},
{
"answer_id": 55194,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "<p>Or shorter,</p>\n\n<pre><code>for key, value in sorted(d.items()):\n print value\n</code></pre>\n"
},
{
"answer_id": 55197,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 0,
"selected": false,
"text": "<pre><code>>>> d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}\n>>> for k,v in sorted(d.items()):\n... print v, k\n... \nthis is a a\nthis is b b\nthis is c c\n</code></pre>\n"
},
{
"answer_id": 55202,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 0,
"selected": false,
"text": "<pre><code>d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}\nks = d.keys()\nks.sort()\nfor k in ks:\n print \"this is \" + k\n</code></pre>\n"
},
{
"answer_id": 56134,
"author": "Will Boyce",
"author_id": 5757,
"author_profile": "https://Stackoverflow.com/users/5757",
"pm_score": 0,
"selected": false,
"text": "<pre><code>for key in sorted(d):\n print d[key]\n</code></pre>\n"
},
{
"answer_id": 59235,
"author": "Peter C",
"author_id": 1952,
"author_profile": "https://Stackoverflow.com/users/1952",
"pm_score": 2,
"selected": false,
"text": "<p>You can also sort a dictionary by value and control the sort order:</p>\n\n<pre><code>import operator\n\nd = {'b' : 'this is 3', 'a': 'this is 2' , 'c' : 'this is 1'}\n\nfor key, value in sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True):\n print key, \" \", value\n</code></pre>\n\n<p>Output:<br>\nb this is 3<br>\na this is 2<br>\nc this is 1</p>\n"
},
{
"answer_id": 40301443,
"author": "Ukimiku",
"author_id": 6804704,
"author_profile": "https://Stackoverflow.com/users/6804704",
"pm_score": 0,
"selected": false,
"text": "<p>Do you mean \"sorted\" instead of \"ordered\"? It seems your question aims at sorting a dictionary and not at ordering it. If you do mean \"ordered\", you can use an OrderedDict from the collections module. Those dictionaries remember the order in which the key/value pairs were entered:</p>\n\n<pre><code>from collections import OrderedDict\n</code></pre>\n\n<p>Reference information: <a href=\"https://docs.python.org/2/library/collections.html#collections.OrderedDict\" rel=\"nofollow\">https://docs.python.org/2/library/collections.html#collections.OrderedDict</a></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added.
What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?
For example, you had this:
```
d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}
```
I want to print the associated values in the following sequence sorted by key:
```
this is a
this is b
this is c
``` | Do you mean that you need the values sorted by the value of the key?
In that case, this should do it:
```
for key in sorted(d):
print d[key]
```
**EDIT:** changed to use sorted(d) instead of sorted(d.keys()), thanks [Eli](https://stackoverflow.com/users/1694/eli-courtwright)! |
55,203 | <p>I have an asp.net web page written in C#.<br>
Using some javascript I popup another .aspx page which has a few controls that are filled in and from which I create a small snippet of text.<br>
When the user clicks OK on that dialog box I want to insert that piece of text into a textbox on the page that initial "popped up" the dialog/popup page. </p>
<p>I'm guessing that this will involve javascript which is not a strong point of mine.</p>
<p>How do I do this?</p>
| [
{
"answer_id": 55222,
"author": "Dale Marshall",
"author_id": 1491425,
"author_profile": "https://Stackoverflow.com/users/1491425",
"pm_score": 2,
"selected": false,
"text": "<p>What you could do is create an ajax modal pop-up instead of a new window. The semantic and aesthetic value is greater not to mention the data-passing is much easier.</p>\n\n<p><a href=\"http://www.asp.net/ajax/ajaxcontroltoolkit/samples/modalpopup/modalpopup.aspx\" rel=\"nofollow noreferrer\">http://www.asp.net/ajax/ajaxcontroltoolkit/samples/modalpopup/modalpopup.aspx</a></p>\n"
},
{
"answer_id": 55242,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 4,
"selected": true,
"text": "<p>You will have to do something like:</p>\n\n<pre><code>parent.opener.document.getElemenyById('ParentTextBox').value = \"New Text\";\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | I have an asp.net web page written in C#.
Using some javascript I popup another .aspx page which has a few controls that are filled in and from which I create a small snippet of text.
When the user clicks OK on that dialog box I want to insert that piece of text into a textbox on the page that initial "popped up" the dialog/popup page.
I'm guessing that this will involve javascript which is not a strong point of mine.
How do I do this? | You will have to do something like:
```
parent.opener.document.getElemenyById('ParentTextBox').value = "New Text";
``` |
55,210 | <p>What would be the best strategy to generate anagrams.</p>
<blockquote>
<pre><code>An anagram is a type of word play, the result of rearranging the letters
of a word or phrase to produce a new word or phrase, using all the original
letters exactly once;
ex.
</code></pre>
<ul>
<li><strong>Eleven plus two</strong> is anagram of <strong><em>Twelve plus one</em></strong> </li>
<li><strong>A decimal point</strong> is anagram of <strong><em>I'm a dot in place</em></strong></li>
<li><strong>Astronomers</strong> is anagram of <strong><em>Moon starers</em></strong></li>
</ul>
</blockquote>
<p>At first it looks straightforwardly simple, just to jumble the letters and generate all possible combinations. But what would be the efficient approach to generate only the words in dictionary.</p>
<p>I came across this page, <a href="http://lojic.com/blog/2007/10/22/solving-anagrams-in-ruby/" rel="noreferrer">Solving anagrams in Ruby</a>. </p>
<p>But what are your ideas?</p>
| [
{
"answer_id": 55239,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 0,
"selected": false,
"text": "<p>Off the top of my head, the solution that makes the most sense would be to pick a letter out of the input string randomly and filter the dictionary based on words that start with that. Then pick another, filter on the second letter, etc. In addition, filter out words that can't be made with the remaining text. Then when you hit the end of a word, insert a space and start it over with the remaining letters. You might also restrict words based on word type (e.g. you wouldn't have two verbs next to each other, you wouldn't have two articles next to each other, etc).</p>\n"
},
{
"answer_id": 55250,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 4,
"selected": false,
"text": "<p>For each word in the dictionary, sort the letters alphabetically. So \"foobar\" becomes \"abfoor.\"</p>\n\n<p>Then when the input anagram comes in, sort its letters too, then look it up. <strong>It's as fast as a hashtable lookup!</strong></p>\n\n<p>For multiple words, you could do combinations of the sorted letters, sorting as you go. Still <em>much</em> faster than generating all combinations.</p>\n\n<p><em>(see comments for more optimizations and details)</em></p>\n"
},
{
"answer_id": 55255,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 1,
"selected": false,
"text": "<p>How I see it: </p>\n\n<p>you'd want to build a table that maps unordered sets of letters to lists words i.e. go through the dictionary so you'd wind up with, say</p>\n\n<pre><code>lettermap[set(a,e,d,f)] = { \"deaf\", \"fade\" }\n</code></pre>\n\n<p>then from your starting word, you find the set of letters:</p>\n\n<pre><code> astronomers => (a,e,m,n,o,o,r,r,s,s,t)\n</code></pre>\n\n<p>then loop through all the partitions of that set ( this might be the most technical part, just generating all the possible partitions), and look up the words for that set of letters.</p>\n\n<p>edit: hmmm, this is pretty much what Jason Cohen posted.</p>\n\n<p>edit: furthermore, the comments on the question mention generating \"good\" anagrams, like the examples :). after you build your list of all possible anagrams, run them through WordNet and find ones that are semantically close to the original phrase :)</p>\n"
},
{
"answer_id": 55339,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 0,
"selected": false,
"text": "<ol>\n<li>As Jason suggested, prepare a dictionary making hashtable with key being word sorted alphabetically, and value word itself (you may have multiple values per key). </li>\n<li>Remove whitespace and sort your query before looking it up. </li>\n</ol>\n\n<p>After this, you'd need to do some sort of a recursive, exhaustive search. Pseudo code is very roughly:</p>\n\n<pre><code>function FindWords(solutionList, wordsSoFar, sortedQuery)\n // base case\n if sortedQuery is empty\n solutionList.Add(wordsSoFar)\n return\n\n // recursive case\n\n // InitialStrings(\"abc\") is {\"a\",\"ab\",\"abc\"}\n foreach initialStr in InitalStrings(sortedQuery)\n // Remaining letters after initialStr\n sortedQueryRec := sortedQuery.Substring(initialStr.Length)\n words := words matching initialStr in the dictionary\n // Note that sometimes words list will be empty\n foreach word in words\n // Append should return a new list, not change wordSoFar\n wordsSoFarRec := Append(wordSoFar, word) \n FindWords(solutionList, wordSoFarRec, sortedQueryRec)\n</code></pre>\n\n<p>In the end, you need to iterate through the solutionList, and print the words in each sublist with spaces between them. You might need to print all orderings for these cases (e.g. \"I am Sam\" and \"Sam I am\" are both solutions).</p>\n\n<p>Of course, I didn't test this, and it's a brute force approach.</p>\n"
},
{
"answer_id": 55422,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 3,
"selected": false,
"text": "<p>See this <a href=\"http://www.cs.washington.edu/education/courses/cse143/08sp/handouts/23.html\" rel=\"noreferrer\">assignment</a> from the University of Washington CSE department.</p>\n\n<p>Basically, you have a data structure that just has the counts of each letter in a word (an array works for ascii, upgrade to a map if you want unicode support). You can subtract two of these letter sets; if a count is negative, you know one word can't be an anagram of another.</p>\n"
},
{
"answer_id": 55999,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 3,
"selected": false,
"text": "<p>Pre-process:</p>\n\n<p>Build a trie with each leaf as a known word, keyed in alphabetical order.</p>\n\n<p>At search time:</p>\n\n<p>Consider the input string as a multiset. Find the first sub-word by traversing the index trie as in a depth-first search. At each branch you can ask, is letter x in the remainder of my input? If you have a good multiset representation, this should be a constant time query (basically).</p>\n\n<p>Once you have the first sub-word, you can keep the remainder multiset and treat it as a new input to find the rest of that anagram (if any exists).</p>\n\n<p>Augment this procedure with memoization for faster look-ups on common remainder multisets.</p>\n\n<p>This is pretty fast - each trie traversal is guaranteed to give an actual subword, and each traversal takes linear time in the length of the subword (and subwords are usually pretty darn small, by coding standards). However, if you <em>really</em> want something even faster, you could include all n-grams in your pre-process, where an n-gram is any string of n words in a row. Of course, if W = #words, then you'll jump from index size O(W) to O(W^n). Maybe n = 2 is realistic, depending on the size of your dictionary.</p>\n"
},
{
"answer_id": 60586,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I've used the following way of computing anagrams a couple of month ago: </p>\n\n<ul>\n<li><p>Compute a \"code\" for each word in your dictionary: Create a lookup-table from letters in the alphabet to prime numbers, e.g. starting with ['a', 2] and ending with ['z', 101]. As a pre-processing step compute the code for each word in your dictionary by looking up the prime number for each letter it consists of in the lookup-table and multiply them together. For later lookup create a multimap of codes to words.</p></li>\n<li><p>Compute the code of your input word as outlined above.</p></li>\n<li><p>Compute codeInDictionary % inputCode for each code in the multimap. If the result is 0, you've found an anagram and you can lookup the appropriate word. This also works for 2- or more-word anagrams as well.</p></li>\n</ul>\n\n<p>Hope that was helpful.</p>\n"
},
{
"answer_id": 65464,
"author": "user9282",
"author_id": 9282,
"author_profile": "https://Stackoverflow.com/users/9282",
"pm_score": 2,
"selected": false,
"text": "<p>The book <em>Programming Pearls</em> by Jon Bentley covers this kind of stuff quite nicely. A must-read.</p>\n"
},
{
"answer_id": 395596,
"author": "martinus",
"author_id": 48181,
"author_profile": "https://Stackoverflow.com/users/48181",
"pm_score": 1,
"selected": false,
"text": "<p>A while ago I have written a blog post about how to quickly find two word anagrams. It works really fast: finding all 44 two-word anagrams for a word with a textfile of more than 300,000 words (4 Megabyte) takes only 0.6 seconds in a Ruby program.</p>\n\n<p><a href=\"http://martin.ankerl.com/2008/08/09/two-word-anagram-finder-algorithm/\" rel=\"nofollow noreferrer\">Two Word Anagram Finder Algorithm (in Ruby)</a></p>\n\n<p>It is possible to make the application faster when it is allowed to preprocess the wordlist into a large hash mapping from words sorted by letters to a list of words using these letters. This preprocessed data can be serialized and used from then on.</p>\n"
},
{
"answer_id": 395639,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 2,
"selected": false,
"text": "<p>One of the seminal works on programmatic anagrams was by Michael Morton (Mr. Machine Tool), using a tool called Ars Magna. Here is <a href=\"http://query.nytimes.com/gst/fullpage.html?res=9B06E6DB133EF93BA2575BC0A9639C8B63\" rel=\"nofollow noreferrer\">a light article</a> based on his work.</p>\n"
},
{
"answer_id": 1924561,
"author": "FogleBird",
"author_id": 90308,
"author_profile": "https://Stackoverflow.com/users/90308",
"pm_score": 6,
"selected": false,
"text": "<p>Most of these answers are horribly inefficient and/or will only give one-word solutions (no spaces). My solution will handle any number of words and is very efficient.</p>\n\n<p>What you want is a trie data structure. Here's a <strong>complete</strong> Python implementation. You just need a word list saved in a file named <code>words.txt</code> You can try the Scrabble dictionary word list here:</p>\n\n<p><a href=\"http://www.isc.ro/lists/twl06.zip\" rel=\"noreferrer\">http://www.isc.ro/lists/twl06.zip</a></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>MIN_WORD_SIZE = 4 # min size of a word in the output\n\nclass Node(object):\n def __init__(self, letter='', final=False, depth=0):\n self.letter = letter\n self.final = final\n self.depth = depth\n self.children = {}\n def add(self, letters):\n node = self\n for index, letter in enumerate(letters):\n if letter not in node.children:\n node.children[letter] = Node(letter, index==len(letters)-1, index+1)\n node = node.children[letter]\n def anagram(self, letters):\n tiles = {}\n for letter in letters:\n tiles[letter] = tiles.get(letter, 0) + 1\n min_length = len(letters)\n return self._anagram(tiles, [], self, min_length)\n def _anagram(self, tiles, path, root, min_length):\n if self.final and self.depth >= MIN_WORD_SIZE:\n word = ''.join(path)\n length = len(word.replace(' ', ''))\n if length >= min_length:\n yield word\n path.append(' ')\n for word in root._anagram(tiles, path, root, min_length):\n yield word\n path.pop()\n for letter, node in self.children.iteritems():\n count = tiles.get(letter, 0)\n if count == 0:\n continue\n tiles[letter] = count - 1\n path.append(letter)\n for word in node._anagram(tiles, path, root, min_length):\n yield word\n path.pop()\n tiles[letter] = count\n\ndef load_dictionary(path):\n result = Node()\n for line in open(path, 'r'):\n word = line.strip().lower()\n result.add(word)\n return result\n\ndef main():\n print 'Loading word list.'\n words = load_dictionary('words.txt')\n while True:\n letters = raw_input('Enter letters: ')\n letters = letters.lower()\n letters = letters.replace(' ', '')\n if not letters:\n break\n count = 0\n for word in words.anagram(letters):\n print word\n count += 1\n print '%d results.' % count\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>When you run the program, the words are loaded into a trie in memory. After that, just type in the letters you want to search with and it will print the results. It will only show results that use all of the input letters, nothing shorter.</p>\n\n<p>It filters short words from the output, otherwise the number of results is huge. Feel free to tweak the <code>MIN_WORD_SIZE</code> setting. Keep in mind, just using \"astronomers\" as input gives 233,549 results if <code>MIN_WORD_SIZE</code> is 1. Perhaps you can find a shorter word list that only contains more common English words.</p>\n\n<p>Also, the contraction \"I'm\" (from one of your examples) won't show up in the results unless you add \"im\" to the dictionary and set <code>MIN_WORD_SIZE</code> to 2.</p>\n\n<p>The trick to getting multiple words is to jump back to the root node in the trie whenever you encounter a complete word in the search. Then you keep traversing the trie until all letters have been used.</p>\n"
},
{
"answer_id": 7724784,
"author": "sanjiv",
"author_id": 989323,
"author_profile": "https://Stackoverflow.com/users/989323",
"pm_score": 1,
"selected": false,
"text": "<p>If I take a dictionary as a Hash Map as every word is unique and the Key is a binary(or Hex) representation of the word. Then if I have a word I can easily find the meaning of it with O(1) complexity.</p>\n\n<p>Now, if we have to generate all the valid anagrams, we need to verify if the generated anagram is in the dictionary, if it is present in dictionary, its a valid one else we need to ignore that.</p>\n\n<p>I will assume that there can be a word of max 100 characters(or more but there is a limit).</p>\n\n<p>So any word we take it as a sequence of indexes like a word \"hello\" can be represented like \n\"1234\".\nNow the anagrams of \"1234\" are \"1243\", \"1242\" ..etc </p>\n\n<p>The only thing we need to do is to store all such combinations of indexes for a particular number of characters. This is an one time task.\nAnd then words can be generated from the combinations by picking the characters from the index.Hence we get the anagrams. </p>\n\n<p>To verify if the anagrams are valid or not, just index into the dictionary and validate.</p>\n\n<p>The only thing need to be handled is the duplicates.That can be done easily. As an when we need to compare with the previous ones that has been searched in dictionary.</p>\n\n<p>The solution emphasizes on performance. </p>\n"
},
{
"answer_id": 14132957,
"author": "Parth",
"author_id": 1944006,
"author_profile": "https://Stackoverflow.com/users/1944006",
"pm_score": 2,
"selected": false,
"text": "<p>So <a href=\"https://github.com/parekhparth/AnagramSolver\" rel=\"nofollow\">here's</a> the working solution, in Java, that Jason Cohen suggested and it performs somewhat better than the one using trie. Below are some of the main points:</p>\n\n<ul>\n<li>Only load dictionary with the words that are subsets of given set of words</li>\n<li>Dictionary will be a hash of sorted words as key and set of actual words as values (as suggested by Jason)</li>\n<li>Iterate through each word from dictionary key and do a recursive forward lookup to see if any valid anagram is found for that key</li>\n<li>Only do forward lookup because, anagrams for all the words that have already been traversed, should have already been found</li>\n<li>Merge all the words associated to the keys for e.g. if 'enlist' is the word for which anagrams are to be found and one of the set of keys to merge are [ins] and [elt], and the actual words for key [ins] is [sin] and [ins], and for key [elt] is [let], then the final set of merge words would be [sin, let] and [ins, let] which will be part of our final anagrams list</li>\n<li>Also to note that, this logic will only list unique set of words i.e. \"eleven plus two\" and \"two plus eleven\" would be same and only one of them would be listed in the output</li>\n</ul>\n\n<p>Below is the main recursive code which finds the set of anagram keys:</p>\n\n<pre><code>// recursive function to find all the anagrams for charInventory characters\n// starting with the word at dictionaryIndex in dictionary keyList\nprivate Set<Set<String>> findAnagrams(int dictionaryIndex, char[] charInventory, List<String> keyList) {\n // terminating condition if no words are found\n if (dictionaryIndex >= keyList.size() || charInventory.length < minWordSize) {\n return null;\n }\n\n String searchWord = keyList.get(dictionaryIndex);\n char[] searchWordChars = searchWord.toCharArray();\n // this is where you find the anagrams for whole word\n if (AnagramSolverHelper.isEquivalent(searchWordChars, charInventory)) {\n Set<Set<String>> anagramsSet = new HashSet<Set<String>>();\n Set<String> anagramSet = new HashSet<String>();\n anagramSet.add(searchWord);\n anagramsSet.add(anagramSet);\n\n return anagramsSet;\n }\n\n // this is where you find the anagrams with multiple words\n if (AnagramSolverHelper.isSubset(searchWordChars, charInventory)) {\n // update charInventory by removing the characters of the search\n // word as it is subset of characters for the anagram search word\n char[] newCharInventory = AnagramSolverHelper.setDifference(charInventory, searchWordChars);\n if (newCharInventory.length >= minWordSize) {\n Set<Set<String>> anagramsSet = new HashSet<Set<String>>();\n for (int index = dictionaryIndex + 1; index < keyList.size(); index++) {\n Set<Set<String>> searchWordAnagramsKeysSet = findAnagrams(index, newCharInventory, keyList);\n if (searchWordAnagramsKeysSet != null) {\n Set<Set<String>> mergedSets = mergeWordToSets(searchWord, searchWordAnagramsKeysSet);\n anagramsSet.addAll(mergedSets);\n }\n }\n return anagramsSet.isEmpty() ? null : anagramsSet;\n }\n }\n\n // no anagrams found for current word\n return null;\n}\n</code></pre>\n\n<p>You can fork the repo from <a href=\"https://github.com/parekhparth/AnagramSolver\" rel=\"nofollow\">here</a> and play with it. There are many optimizations that I might have missed. But the code works and does find all the anagrams.</p>\n"
},
{
"answer_id": 41226791,
"author": "ACV",
"author_id": 912829,
"author_profile": "https://Stackoverflow.com/users/912829",
"pm_score": 2,
"selected": false,
"text": "<p>And <a href=\"http://dev.vvirlan.com/new-algorithm-anagram/\" rel=\"nofollow noreferrer\">here</a> is my novel solution.</p>\n\n<p>Jon Bentley’s book Programming Pearls contains a problem about finding anagrams of words.\nThe statement:</p>\n\n<blockquote>\n <p>Given a dictionary of english words, find all sets of anagrams. For\n instance, “pots”, “stop” and “tops” are all anagrams of one another\n because each can be formed by permuting the letters of the others.</p>\n</blockquote>\n\n<p>I thought a bit and it came to me that the solution would be to obtain the signature of the word you’re searching and comparing it with all the words in the dictionary. All anagrams of a word should have the same signature. But how to achieve this? My idea was to use the Fundamental Theorem of Arithmetic:</p>\n\n<p>The fundamental theorem of arithmetic states that</p>\n\n<blockquote>\n <p>every positive integer (except the number 1) can be represented in\n exactly one way apart from rearrangement as a product of one or more\n primes</p>\n</blockquote>\n\n<p>So the idea is to use an array of the first 26 prime numbers. Then for each letter in the word we get the corresponding prime number A = 2, B = 3, C = 5, D = 7 … and then we calculate the product of our input word. Next we do this for each word in the dictionary and if a word matches our input word, then we add it to the resulting list.</p>\n\n<p>The performance is more or less acceptable. For a dictionary of 479828 words, it takes 160 ms to get all anagrams. This is roughly 0.0003 ms / word, or 0.3 microsecond / word. Algorithm’s complexity seems to be O(mn) or ~O(m) where m is the size of the dictionary and n is the length of the input word.</p>\n\n<p>Here’s the code:</p>\n\n<pre><code>package com.vvirlan;\n\nimport java.io.BufferedReader;\nimport java.io.File;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.Scanner;\n\npublic class Words {\n private int[] PRIMES = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,\n 79, 83, 89, 97, 101, 103, 107, 109, 113 };\n\n public static void main(String[] args) {\n Scanner s = new Scanner(System.in);\n String word = \"hello\";\n System.out.println(\"Please type a word:\");\n if (s.hasNext()) {\n word = s.next();\n }\n Words w = new Words();\n w.start(word);\n }\n\n private void start(String word) {\n measureTime();\n char[] letters = word.toUpperCase().toCharArray();\n long searchProduct = calculateProduct(letters);\n System.out.println(searchProduct);\n try {\n findByProduct(searchProduct);\n } catch (Exception e) {\n e.printStackTrace();\n }\n measureTime();\n System.out.println(matchingWords);\n System.out.println(\"Total time: \" + time);\n }\n\n private List<String> matchingWords = new ArrayList<>();\n\n private void findByProduct(long searchProduct) throws IOException {\n File f = new File(\"/usr/share/dict/words\");\n FileReader fr = new FileReader(f);\n BufferedReader br = new BufferedReader(fr);\n String line = null;\n while ((line = br.readLine()) != null) {\n char[] letters = line.toUpperCase().toCharArray();\n long p = calculateProduct(letters);\n if (p == -1) {\n continue;\n }\n if (p == searchProduct) {\n matchingWords.add(line);\n }\n }\n br.close();\n }\n\n private long calculateProduct(char[] letters) {\n long result = 1L;\n for (char c : letters) {\n if (c < 65) {\n return -1;\n }\n int pos = c - 65;\n result *= PRIMES[pos];\n }\n return result;\n }\n\n private long time = 0L;\n\n private void measureTime() {\n long t = new Date().getTime();\n if (time == 0L) {\n time = t;\n } else {\n time = t - time;\n }\n }\n}\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123/"
] | What would be the best strategy to generate anagrams.
>
>
> ```
> An anagram is a type of word play, the result of rearranging the letters
> of a word or phrase to produce a new word or phrase, using all the original
> letters exactly once;
> ex.
>
> ```
>
> * **Eleven plus two** is anagram of ***Twelve plus one***
> * **A decimal point** is anagram of ***I'm a dot in place***
> * **Astronomers** is anagram of ***Moon starers***
>
>
>
At first it looks straightforwardly simple, just to jumble the letters and generate all possible combinations. But what would be the efficient approach to generate only the words in dictionary.
I came across this page, [Solving anagrams in Ruby](http://lojic.com/blog/2007/10/22/solving-anagrams-in-ruby/).
But what are your ideas? | Most of these answers are horribly inefficient and/or will only give one-word solutions (no spaces). My solution will handle any number of words and is very efficient.
What you want is a trie data structure. Here's a **complete** Python implementation. You just need a word list saved in a file named `words.txt` You can try the Scrabble dictionary word list here:
<http://www.isc.ro/lists/twl06.zip>
```py
MIN_WORD_SIZE = 4 # min size of a word in the output
class Node(object):
def __init__(self, letter='', final=False, depth=0):
self.letter = letter
self.final = final
self.depth = depth
self.children = {}
def add(self, letters):
node = self
for index, letter in enumerate(letters):
if letter not in node.children:
node.children[letter] = Node(letter, index==len(letters)-1, index+1)
node = node.children[letter]
def anagram(self, letters):
tiles = {}
for letter in letters:
tiles[letter] = tiles.get(letter, 0) + 1
min_length = len(letters)
return self._anagram(tiles, [], self, min_length)
def _anagram(self, tiles, path, root, min_length):
if self.final and self.depth >= MIN_WORD_SIZE:
word = ''.join(path)
length = len(word.replace(' ', ''))
if length >= min_length:
yield word
path.append(' ')
for word in root._anagram(tiles, path, root, min_length):
yield word
path.pop()
for letter, node in self.children.iteritems():
count = tiles.get(letter, 0)
if count == 0:
continue
tiles[letter] = count - 1
path.append(letter)
for word in node._anagram(tiles, path, root, min_length):
yield word
path.pop()
tiles[letter] = count
def load_dictionary(path):
result = Node()
for line in open(path, 'r'):
word = line.strip().lower()
result.add(word)
return result
def main():
print 'Loading word list.'
words = load_dictionary('words.txt')
while True:
letters = raw_input('Enter letters: ')
letters = letters.lower()
letters = letters.replace(' ', '')
if not letters:
break
count = 0
for word in words.anagram(letters):
print word
count += 1
print '%d results.' % count
if __name__ == '__main__':
main()
```
When you run the program, the words are loaded into a trie in memory. After that, just type in the letters you want to search with and it will print the results. It will only show results that use all of the input letters, nothing shorter.
It filters short words from the output, otherwise the number of results is huge. Feel free to tweak the `MIN_WORD_SIZE` setting. Keep in mind, just using "astronomers" as input gives 233,549 results if `MIN_WORD_SIZE` is 1. Perhaps you can find a shorter word list that only contains more common English words.
Also, the contraction "I'm" (from one of your examples) won't show up in the results unless you add "im" to the dictionary and set `MIN_WORD_SIZE` to 2.
The trick to getting multiple words is to jump back to the root node in the trie whenever you encounter a complete word in the search. Then you keep traversing the trie until all letters have been used. |
55,218 | <p>I looking for a way, specifically in PHP that I will be guaranteed to always get a unique key.</p>
<p>I have done the following:</p>
<pre><code>strtolower(substr(crypt(time()), 0, 7));
</code></pre>
<p>But I have found that once in a while I end up with a duplicate key (rarely, but often enough).</p>
<p>I have also thought of doing:</p>
<pre><code>strtolower(substr(crypt(uniqid(rand(), true)), 0, 7));
</code></pre>
<p>But according to the PHP website, uniqid() could, if uniqid() is called twice in the same microsecond, it could generate the same key. I'm thinking that the addition of rand() that it rarely would, but still possible.</p>
<p>After the lines mentioned above I am also remove characters such as L and O so it's less confusing for the user. This maybe part of the cause for the duplicates, but still necessary.</p>
<p>One option I have a thought of is creating a website that will generate the key, storing it in a database, ensuring it's completely unique.</p>
<p>Any other thoughts? Are there any websites out there that already do this that have some kind of API or just return the key. I found <a href="http://userident.com" rel="noreferrer">http://userident.com</a> but I'm not sure if the keys will be completely unique.</p>
<p>This needs to run in the background without any user input.</p>
| [
{
"answer_id": 55224,
"author": "Humpton",
"author_id": 1444,
"author_profile": "https://Stackoverflow.com/users/1444",
"pm_score": 0,
"selected": false,
"text": "<p>Without writing the code, my logic would be:</p>\n\n<p>Generate a random string from whatever acceptable characters you like.<br>\nThen add half the date stamp (partial seconds and all) to the front and the other half to the end (or somewhere in the middle if you prefer).</p>\n\n<p>Stay JOLLY!<br>\nH</p>\n"
},
{
"answer_id": 55226,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>If you use your original method, but add the username or emailaddress in front of the password, it will always be unique if each user only can have 1 password.</p>\n"
},
{
"answer_id": 55227,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 0,
"selected": false,
"text": "<p>You may be interested in this article which deals with the same issue: <a href=\"http://blogs.msdn.com/oldnewthing/archive/2008/06/27/8659071.aspx\" rel=\"nofollow noreferrer\">GUIDs are globally unique, but substrings of GUIDs aren't</a>.</p>\n\n<blockquote>\n <blockquote>\n <p>The goal of this algorithm is to use the combination of time and location (\"space-time coordinates\" for the relativity geeks out there) as the uniqueness key. However, timekeeping is not perfect, so there's a possibility that, for example, two GUIDs are generated in rapid succession from the same machine, so close to each other in time that the timestamp would be the same. That's where the uniquifier comes in.</p>\n </blockquote>\n</blockquote>\n"
},
{
"answer_id": 55233,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 0,
"selected": false,
"text": "<p>I usually do it like this:</p>\n\n<pre><code>$this->password = '';\n\nfor($i=0; $i<10; $i++)\n{\n if($i%2 == 0)\n $this->password .= chr(rand(65,90));\n if($i%3 == 0)\n $this->password .= chr(rand(97,122));\n if($i%4 == 0)\n $this->password .= chr(rand(48,57));\n}\n</code></pre>\n\n<p>I suppose there are some theoretical holes but I've never had an issue with duplication. I usually use it for temporary passwords (like after a password reset) and it works well enough for that.</p>\n"
},
{
"answer_id": 55241,
"author": "Adam Lerman",
"author_id": 673,
"author_profile": "https://Stackoverflow.com/users/673",
"pm_score": -1,
"selected": false,
"text": "<p>I usually do a random substring (randomize how many chars between 8 an 32, or less for user convenience) or the MD5 of some value I have gotten in, or the time, or some combination. For more randomness I do MD5 of come value (say last name) concatenate that with the time, MD5 it again, then take the random substring. Yes, you <em>could</em> get equal passwords, but its not very likely at all.</p>\n"
},
{
"answer_id": 55245,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 0,
"selected": false,
"text": "<p>You might be interested in Steve Gibson's over-the-top-secure implementation of a password generator (no source, but he has a detailed description of how it works) at <a href=\"https://www.grc.com/passwords.htm\" rel=\"nofollow noreferrer\">https://www.grc.com/passwords.htm</a>.</p>\n<p>The site creates huge 64-character passwords but, since they're completely random, you could easily take the first 8 (or however many) characters for a less secure but "as random as possible" password.</p>\n<p>EDIT: from your later answers I see you need something more like a GUID than a password, so this probably isn't what you want...</p>\n"
},
{
"answer_id": 55247,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Any algorithm will result in duplicates</strong>.</p>\n\n<p>Therefore, might I suggest that you use your existing algorithm* and simply check for duplicates?</p>\n\n<p>*Slight addition: If <code>uniqid()</code> can be non-unique based on time, also include a global counter that you increment after every invocation. That way something is different even in the same microsecond.</p>\n"
},
{
"answer_id": 55249,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 0,
"selected": false,
"text": "<p>As Frank Kreuger commented, go with a GUID generator.</p>\n\n<p>Like <a href=\"http://www.phpclasses.org/browse/package/1738.html\" rel=\"nofollow noreferrer\">this one</a></p>\n"
},
{
"answer_id": 55298,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 0,
"selected": false,
"text": "<p>I'm still not seeing why the passwords have to be unique? What's the downside if 2 of your users have the same password?</p>\n\n<p>This is assuming we're talking about passwords that are tied to userids, and not just unique identifiers. If <em>that's</em> what you're looking for, why not use GUIDs?</p>\n"
},
{
"answer_id": 55324,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 5,
"selected": true,
"text": "<p>There are only 3 ways to generate unique values, rather they be passwords, user IDs, etc.:</p>\n\n<ol>\n<li>Use an effective GUID generator - these are long and cannot be shrunk. If you only use part <strong>you FAIL</strong>. </li>\n<li>At least part of the number is sequentially generated off of a single sequence. You can add fluff or encoding to make it look less sequential. Advantage is they start short - disadvantage is they require a single source. The work around for the single source limitation is to have numbered sources, so you include the [source #] + [seq #] and then each source can generate its own sequence. </li>\n<li>Generate them via some other means and then check them against the single history of previously generated values.</li>\n</ol>\n\n<p>Any other method is not guaranteed. Keep in mind, fundamentally you are generating a binary number (it is a computer), but then you can encode it in Hexadecimal, Decimal, Base64, or a word list. Pick an encoding that fits your usage. Usually for user entered data you want some variation of Base32 (which you hinted at).</p>\n\n<p><strong>Note about GUIDS</strong>: They gain their strength of uniqueness from their length and the method used to generate them. <em>Anything less than 128-bits is not secure.</em> Beyond random number generation there are characteristics that go into a GUID to make it more unique. Keep in mind they are only practically unique, not completely unique. It is possible, although practically impossible to have a duplicate. </p>\n\n<p><strong>Updated Note about GUIDS</strong>: Since writing this I learned that many GUID generators use a cryptographically secure random number generator (difficult or impossible to predict the next number generated, and a not likely to repeat). There are actually 5 different <a href=\"http://en.wikipedia.org/wiki/Universally_Unique_Identifier#Definition\" rel=\"noreferrer\">UUID algorithms</a>. Algorithm 4 is what Microsoft currently uses for the Windows GUID generation API. A <a href=\"http://en.wikipedia.org/wiki/Globally_unique_identifier\" rel=\"noreferrer\">GUID</a> is Microsoft's implementation of the UUID standard.</p>\n\n<p><strong>Update</strong>: If you want 7 to 16 characters then you need to use either method 2 or 3.</p>\n\n<p><strong>Bottom line</strong>: Frankly there is no such thing as completely unique. Even if you went with a sequential generator you would eventually run out of storage using all the atoms in the universe, thus looping back on yourself and repeating. Your only hope would be the heat death of the universe before reaching that point.</p>\n\n<p>Even the best random number generator has a possibility of repeating equal to the total size of the random number you are generating. Take a quarter for example. It is a completely random bit generator, and its odds of repeating are 1 in 2. </p>\n\n<p>So it all comes down to your threshold of uniqueness. You can have 100% uniqueness in 8 digits for 1,099,511,627,776 numbers by using a sequence and then base32 encoding it. Any other method that does not involve checking against a list of past numbers only has odds equal to n/1,099,511,627,776 (where n=number of previous numbers generated) of not being unique.</p>\n"
},
{
"answer_id": 57672,
"author": "Laith",
"author_id": 5961,
"author_profile": "https://Stackoverflow.com/users/5961",
"pm_score": 0,
"selected": false,
"text": "<p>I do believe that part of your issue is that you are trying to us a singular function for two separate uses... passwords and transaction_id </p>\n\n<p>these really are two different problem areas and it really is not best to try to address them together.</p>\n"
},
{
"answer_id": 1426722,
"author": "Vince",
"author_id": 173661,
"author_profile": "https://Stackoverflow.com/users/173661",
"pm_score": 0,
"selected": false,
"text": "<p>I recently wanted a quick and simple random unique key so I did the following: </p>\n\n<pre><code>$ukey = dechex(time()) . crypt( time() . md5(microtime() + mt_rand(0, 100000)) ); \n</code></pre>\n\n<p>So, basically, I get the unix time in seconds and add a random md5 string generated from time + random number. It's not the best, but for low frequency requests it is pretty good. It's fast and works. </p>\n\n<p>I did a test where I'd generate thousands of keys and then look for repeats, and having about 800 keys per second there were no repetitions, so not bad. I guess it totally depends on mt_rand()</p>\n\n<p>I use it for a survey tracker where we get a submission rate of about 1000 surveys per minute... so for now (crosses fingers) there are no duplicates. Of course, the rate is not constant (we get the submissions at certain times of the day) so this is not fail proof nor the best solution... the tip is using an incremental value as part of the key (in my case, I used time(), but could be better). </p>\n"
},
{
"answer_id": 2472907,
"author": "Marco Demaio",
"author_id": 260080,
"author_profile": "https://Stackoverflow.com/users/260080",
"pm_score": 0,
"selected": false,
"text": "<p>Ingoring the crypting part that does not have much to do with creating a unique value I usually use this one:</p>\n\n<pre><code>function GetUniqueValue()\n{\n static $counter = 0; //initalized only 1st time function is called\n return strtr(microtime(), array('.' => '', ' ' => '')) . $counter++;\n}\n</code></pre>\n\n<p>When called in same process $counter is increased so value is always unique in same process.</p>\n\n<p>When called in different processes you must be really unlucky to get 2 microtime() call with the same values, think that microtime() calls usually have different values also when called in same script.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] | I looking for a way, specifically in PHP that I will be guaranteed to always get a unique key.
I have done the following:
```
strtolower(substr(crypt(time()), 0, 7));
```
But I have found that once in a while I end up with a duplicate key (rarely, but often enough).
I have also thought of doing:
```
strtolower(substr(crypt(uniqid(rand(), true)), 0, 7));
```
But according to the PHP website, uniqid() could, if uniqid() is called twice in the same microsecond, it could generate the same key. I'm thinking that the addition of rand() that it rarely would, but still possible.
After the lines mentioned above I am also remove characters such as L and O so it's less confusing for the user. This maybe part of the cause for the duplicates, but still necessary.
One option I have a thought of is creating a website that will generate the key, storing it in a database, ensuring it's completely unique.
Any other thoughts? Are there any websites out there that already do this that have some kind of API or just return the key. I found <http://userident.com> but I'm not sure if the keys will be completely unique.
This needs to run in the background without any user input. | There are only 3 ways to generate unique values, rather they be passwords, user IDs, etc.:
1. Use an effective GUID generator - these are long and cannot be shrunk. If you only use part **you FAIL**.
2. At least part of the number is sequentially generated off of a single sequence. You can add fluff or encoding to make it look less sequential. Advantage is they start short - disadvantage is they require a single source. The work around for the single source limitation is to have numbered sources, so you include the [source #] + [seq #] and then each source can generate its own sequence.
3. Generate them via some other means and then check them against the single history of previously generated values.
Any other method is not guaranteed. Keep in mind, fundamentally you are generating a binary number (it is a computer), but then you can encode it in Hexadecimal, Decimal, Base64, or a word list. Pick an encoding that fits your usage. Usually for user entered data you want some variation of Base32 (which you hinted at).
**Note about GUIDS**: They gain their strength of uniqueness from their length and the method used to generate them. *Anything less than 128-bits is not secure.* Beyond random number generation there are characteristics that go into a GUID to make it more unique. Keep in mind they are only practically unique, not completely unique. It is possible, although practically impossible to have a duplicate.
**Updated Note about GUIDS**: Since writing this I learned that many GUID generators use a cryptographically secure random number generator (difficult or impossible to predict the next number generated, and a not likely to repeat). There are actually 5 different [UUID algorithms](http://en.wikipedia.org/wiki/Universally_Unique_Identifier#Definition). Algorithm 4 is what Microsoft currently uses for the Windows GUID generation API. A [GUID](http://en.wikipedia.org/wiki/Globally_unique_identifier) is Microsoft's implementation of the UUID standard.
**Update**: If you want 7 to 16 characters then you need to use either method 2 or 3.
**Bottom line**: Frankly there is no such thing as completely unique. Even if you went with a sequential generator you would eventually run out of storage using all the atoms in the universe, thus looping back on yourself and repeating. Your only hope would be the heat death of the universe before reaching that point.
Even the best random number generator has a possibility of repeating equal to the total size of the random number you are generating. Take a quarter for example. It is a completely random bit generator, and its odds of repeating are 1 in 2.
So it all comes down to your threshold of uniqueness. You can have 100% uniqueness in 8 digits for 1,099,511,627,776 numbers by using a sequence and then base32 encoding it. Any other method that does not involve checking against a list of past numbers only has odds equal to n/1,099,511,627,776 (where n=number of previous numbers generated) of not being unique. |
55,270 | <p>I have some code that modifies a value that several controls in other update panels are bound to. When this event handler fires, I'd like it to force the other update panels to refresh as well, so they can rebind.</p>
<p>Is this possible?</p>
<p>Edit: </p>
<p>To clarify, I have an update panel in one user control, the other update panels are in other user controls, so they can't see each other unless I were to expose some custom properties and use findControl etc etc...</p>
<p>Edit Again:</p>
<p>Here is what I came up with:</p>
<pre><code>public void Update()
{
recursiveUpdate(this);
}
private void recursiveUpdate(Control control)
{
foreach (Control c in control.Controls)
{
if (c is UpdatePanel)
{
((UpdatePanel)c).Update();
}
if (c.HasControls())
{
recursiveUpdate(c);
}
}
}
</code></pre>
<p>I had 3 main user controls that were full of update panels, these controls were visible to the main page, so I added an Update method there that called Update on those three.</p>
<p>In my triggering control, I just cast this.Page into the currentpage and called Update.</p>
<p>Edit:</p>
<p>AARRGGGG!</p>
<p>While the update panels refresh, it does not call Page_Load within the subcontrols in them...What do I do now!</p>
| [
{
"answer_id": 55300,
"author": "Dale Marshall",
"author_id": 1491425,
"author_profile": "https://Stackoverflow.com/users/1491425",
"pm_score": 2,
"selected": false,
"text": "<p>You can set triggers on the events in the update panel you want updated or you can explicitly say updatepanel.update() in the code behind.</p>\n"
},
{
"answer_id": 55301,
"author": "Dr Zimmerman",
"author_id": 4605,
"author_profile": "https://Stackoverflow.com/users/4605",
"pm_score": 2,
"selected": false,
"text": "<p>What about registering a PostBackTrigger (instead of an AsyncPostBackTrigger) that will refresh every panel when a specific event fires. </p>\n\n<p>Or add the trigger that already refreshes some UpdatePanels to the other UpdatePanels as well.</p>\n"
},
{
"answer_id": 55304,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 0,
"selected": false,
"text": "<p>This is a good technique if you want to refresh updatepanel from <a href=\"http://encosia.com/2007/07/13/easily-refresh-an-updatepanel-using-javascript/\" rel=\"nofollow noreferrer\">client side Javascript</a>.</p>\n"
},
{
"answer_id": 55442,
"author": "Jacob Proffitt",
"author_id": 1336,
"author_profile": "https://Stackoverflow.com/users/1336",
"pm_score": 0,
"selected": false,
"text": "<p>Page.DataBind() kicks off a round of databind on all child controls. That'll cause Asp.Net to re-evaluate bind expressions on each control. If that's insufficient, you can add whatever logic you want to make sure gets kicked off to an OnDataBinding or OnDataBound override in your usercontrols. If you need to re-execute the Page_Load event, for example, you can simply call it in your overridden OnDataBound method.</p>\n"
},
{
"answer_id": 23698230,
"author": "ravenx30",
"author_id": 3515281,
"author_profile": "https://Stackoverflow.com/users/3515281",
"pm_score": 0,
"selected": false,
"text": "<p>instantuate both view panels to a third presenter class, Then let the presenter class control both views. for example:</p>\n\n<p>You could just pass over what you need the 'middle class' to do its job for example, in your main you could have;</p>\n\n<pre><code>PresenterClass.AttachInterface(mIOrder);\nPresenterClass.DoSomeCalulation();\nPresenterClass.drawPanel(1);\nPresenterClass.AttachInterface(mIOtherOrder);\nPresenterClass.DoSomeCalulation();\nPresenterClass.drawPanel(2);\n</code></pre>\n\n<p>each view will have its own controls. So many differant ways you could do this.. alternitivly you could use the middle class to instantuate both your panels then in each of your panels you could have 'get methods' to retrive the data for processing.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | I have some code that modifies a value that several controls in other update panels are bound to. When this event handler fires, I'd like it to force the other update panels to refresh as well, so they can rebind.
Is this possible?
Edit:
To clarify, I have an update panel in one user control, the other update panels are in other user controls, so they can't see each other unless I were to expose some custom properties and use findControl etc etc...
Edit Again:
Here is what I came up with:
```
public void Update()
{
recursiveUpdate(this);
}
private void recursiveUpdate(Control control)
{
foreach (Control c in control.Controls)
{
if (c is UpdatePanel)
{
((UpdatePanel)c).Update();
}
if (c.HasControls())
{
recursiveUpdate(c);
}
}
}
```
I had 3 main user controls that were full of update panels, these controls were visible to the main page, so I added an Update method there that called Update on those three.
In my triggering control, I just cast this.Page into the currentpage and called Update.
Edit:
AARRGGGG!
While the update panels refresh, it does not call Page\_Load within the subcontrols in them...What do I do now! | You can set triggers on the events in the update panel you want updated or you can explicitly say updatepanel.update() in the code behind. |
55,296 | <p>I'm looking to implement httpOnly in my legacy ASP classic sites.
Anyone knows how to do it?</p>
| [
{
"answer_id": 55318,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 1,
"selected": false,
"text": "<p>You need to append \";HttpOnly\" to the Response cookies collection.</p>\n"
},
{
"answer_id": 55389,
"author": "Aaron Wagner",
"author_id": 3909,
"author_profile": "https://Stackoverflow.com/users/3909",
"pm_score": 5,
"selected": true,
"text": "<pre><code>Response.AddHeader \"Set-Cookie\", \"mycookie=yo; HttpOnly\"\n</code></pre>\n\n<p>Other options like <code>expires</code>, <code>path</code> and <code>secure</code> can be also added in this way. I don't know of any magical way to change your whole cookies collection, but I could be wrong about that.</p>\n"
},
{
"answer_id": 57423,
"author": "tqbf",
"author_id": 5674,
"author_profile": "https://Stackoverflow.com/users/5674",
"pm_score": -1,
"selected": false,
"text": "<p>HttpOnly does very little to improve the security of web applications. For one thing, it only works in IE (Firefox \"supports\" it, but still discloses cookies to Javascript in some situations). For another thing, it only prevents a \"drive-by\" attack against your application; it does nothing to keep a cross-site scripting attack from resetting passwords, changing email addresses, or placing orders.</p>\n\n<p>Should you use it? Sure. It's not going to hurt you. But there are 10 things you should be sure you're doing before you start messing with HttpOnly. </p>\n"
},
{
"answer_id": 14818679,
"author": "Brian Clark",
"author_id": 1496402,
"author_profile": "https://Stackoverflow.com/users/1496402",
"pm_score": 4,
"selected": false,
"text": "<p>If you run your Classic ASP web pages on IIS 7/7.5, then you can use the IIS URL Rewrite module to write a rule to make your cookies HTTPOnly.</p>\n\n<p>Paste the following into the section of your web.config:</p>\n\n<pre><code><rewrite>\n <outboundRules>\n <rule name=\"Add HttpOnly\" preCondition=\"No HttpOnly\">\n <match serverVariable=\"RESPONSE_Set_Cookie\" pattern=\".*\" negate=\"false\" />\n <action type=\"Rewrite\" value=\"{R:0}; HttpOnly\" />\n <conditions>\n </conditions>\n </rule>\n <preConditions>\n <preCondition name=\"No HttpOnly\">\n <add input=\"{RESPONSE_Set_Cookie}\" pattern=\".\" />\n <add input=\"{RESPONSE_Set_Cookie}\" pattern=\"; HttpOnly\" negate=\"true\" />\n </preCondition>\n </preConditions>\n </outboundRules>\n</rewrite>\n</code></pre>\n\n<p>See here for the details: <a href=\"http://forums.iis.net/t/1168473.aspx/1/10\">http://forums.iis.net/t/1168473.aspx/1/10</a> </p>\n\n<p>For background, HTTPOnly cookies are required for PCI compliance reasons. The PCI standards folks (for credit card security) make you have HTTPOnly on your sessionID cookies at the very least in order to help prevent XSS attacks. </p>\n\n<p>Also, at the current time (2-11-2013), all major browser support the HTTPOnly restriction on cookies. This includes current versions of IE, Firefox, Chrome and Safari. </p>\n\n<p>See here for more info on how this works and support by various browser versions:\n<a href=\"https://www.owasp.org/index.php/HTTPOnly\">https://www.owasp.org/index.php/HTTPOnly</a> </p>\n"
},
{
"answer_id": 31680643,
"author": "Hernaldo Gonzalez",
"author_id": 1536197,
"author_profile": "https://Stackoverflow.com/users/1536197",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Response.AddHeader \"Set-Cookie\", \"\"&CStr(Request.ServerVariables(\"HTTP_COOKIE\"))&\";path=/;HttpOnly\"&\"\"\n</code></pre>\n"
},
{
"answer_id": 62751004,
"author": "Yvan Zhu",
"author_id": 13054805,
"author_profile": "https://Stackoverflow.com/users/13054805",
"pm_score": -1,
"selected": false,
"text": "<p>If you are using IIS7 or IIS7.5 and install the URL Rewriting add-in then you can do this. You can create a rewriting rule that adds "HttpOnly" to any out going "Set-Cookie" headers. Paste the following into the <system.webServer> section of your web.config. I then used Fiddler to prove the output.</p>\n<p>Regards, Jeremy</p>\n<pre><code> <rewrite>\n <outboundRules>\n <rule name="Add HttpOnly" preCondition="No HttpOnly">\n <match serverVariable="RESPONSE_Set_Cookie" pattern=".*" negate="false" />\n <action type="Rewrite" value="{R:0}; HttpOnly" />\n <conditions>\n </conditions>\n </rule>\n <preConditions>\n <preCondition name="No HttpOnly">\n <add input="{RESPONSE_Set_Cookie}" pattern="." />\n <add input="{RESPONSE_Set_Cookie}" pattern="; HttpOnly" negate="true" />\n </preCondition>\n </preConditions>\n </outboundRules>\n </rewrite>\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2385/"
] | I'm looking to implement httpOnly in my legacy ASP classic sites.
Anyone knows how to do it? | ```
Response.AddHeader "Set-Cookie", "mycookie=yo; HttpOnly"
```
Other options like `expires`, `path` and `secure` can be also added in this way. I don't know of any magical way to change your whole cookies collection, but I could be wrong about that. |
55,297 | <p>Currently I run an classic (old) ASP webpage with recordset object used directly in bad old spagethi code fasion.</p>
<p>I'm thinking of implementing a data layer in asp.net as web serivce to improve manageability. This is also a first step towards upgrading the website to asp.net.
The site itself remains ASP for the moment...</p>
<p>Can anybody recommend a good way of replacing the recordset object type with a web service compatible type (like an array or something)?
What do I replace below with?:</p>
<pre><code>set objRS = oConn.execute(SQL)
while not objRS.eof
...
name = Cstr(objRS(1))
...
wend
</code></pre>
<p>and also mutliple recordsets can be replaced with?
I'm talking :</p>
<pre><code> set objRS = objRs.nextRecordset
</code></pre>
<p>Anybody went through this and can recommend?</p>
<p><strong><em>@AdditionalInfo - you asked for it :-)</em></strong></p>
<p>Let me start at the beginning.
<strong>Existing Situation is</strong>:
I have an old ASP website with classical hierachical content (header, section, subsection, content) pulled out of database via stored procedures and content pages are in database also (a link to html file).</p>
<p>Now bad thing is, ASP code everywhere spread over many .asp files all doing their own database connections, reading, writing (u have to register for content). Recently we had problems with SQL injection attacks so I was called to fix it.</p>
<p>I <em>could</em> go change all the .asp pages to prevent sql injection but that would be madness. So I thought build a data layer - all pages using this layer to access database. Once place to fix and update db access code.</p>
<p>Coming to that decision I thought asp.net upgrade isn'f far away, why not start using asp.net for the data layer? This way it can be re-used when upgrading the site.</p>
<p>That brings me to the questions above!</p>
| [
{
"answer_id": 55358,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 2,
"selected": false,
"text": "<p>First my favorite advice of this week: do not treat your Web Service like it if was a local object or you are going to pay a very hefty performance price. Essentially, don't do things like this in your web application:</p>\n\n<pre><code>MyDataWebService ws = new MyDataWebService();\nforeach(DataItem item in myData)\n{\n ws.Insert(item);\n}\n</code></pre>\n\n<p>You should always prefer to minimize calls to your Web Service (and SQL):</p>\n\n<pre><code>MyDataWebService ws = new MyDataWebService();\nws.Insert(myData); // Let the web service process the whole set at once.\n</code></pre>\n\n<p>Now, as far as the data type to use for your web service calls, you basically have two choices:</p>\n\n<ul>\n<li>DataSet</li>\n<li>Everything else (Array)</li>\n</ul>\n\n<p>Most collections returned from a web service (like a List<MyData>) actually convert to an Array during the Web Service invocation. Remember that Web Services don't return objects (data + behavior) but just data structures (or a sequence of). Therefore, there is little distinction between a List and an Array.</p>\n\n<p>DataSets are more complex classes; they use their own custom serializer and pretty much get fully recreated in the calling application. There is a cost in performance to be paid for using DataSets like that, so I don't usually recommend it for most scenarios. Using arrays to pass data back and forth tends to be more efficient, and quite frankly it's easier to do.</p>\n\n<p>Your case is a bit different; because you are converting an existing site that already uses ADO, an ADO.NET DataSet might be your best updgrade path. ADO.NET and ADO are similar enough that a straight update might be easier that way. It kind of depends how your web site is built.</p>\n\n<p>For the last part of your question, DataSets do support multiple recordsets similar to ADO's Recordset. They are called DataTables. Every DataSet has at least one DataTable and you can read them in any order.</p>\n\n<p>Good luck.</p>\n"
},
{
"answer_id": 55378,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 1,
"selected": false,
"text": "<p>I'd suggest using the XmlHttp class in your ASP code.</p>\n\n<p>Assuming you have an ASMX web service similar to this, in MyService.asmx:</p>\n\n<pre><code>[WebMethod]\npublic string HelloWorld()\n{\n return \"Hello World\";\n}\n</code></pre>\n\n<p>You could call it in ASP something like this:</p>\n\n<pre><code>Dim xhr\n\nSet xhr = server.CreateObject(\"MSXML2.XMLHTTP\")\n\nxhr.Open \"POST\", \"/MyService.asmx/HelloWorld\", false\nxhr.SetRequestHeader \"content-type\", \"application/x-www-form-urlencoded\"\nxhr.Send\n\nResponse.Write(xhr.ResponseText)\n</code></pre>\n\n<p>ResponseText would be an XML response of:</p>\n\n<pre><code><string>Hello World</string>\n</code></pre>\n\n<p>Assuming your service returned a collection of data, you could iterate over it using XPath or any other XML processing technique/library.</p>\n\n<p>Googling around about MSXML2 will probably answer any specific questions you have, since it's specific to ASP classic.</p>\n"
},
{
"answer_id": 55588,
"author": "DancesWithBamboo",
"author_id": 1334,
"author_profile": "https://Stackoverflow.com/users/1334",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of thinking in layers, why not try taking vertical slices through the application and converting those to .net. That way you will get entire features coded in .net instead of disjoint parts. What is the business value in replacing perfectly working code without improving the user experience or adding features?</p>\n\n<p>You might also consider the trade-off of performance you are going to give up with a Web Service over direct ado calls. Web Services are a good solution to the problem of multiple disjoint applications/teams accessing a common schema; they do not make a single isolated application more maintainable, only slower and more complex.</p>\n"
},
{
"answer_id": 75703,
"author": "Skyhigh",
"author_id": 13387,
"author_profile": "https://Stackoverflow.com/users/13387",
"pm_score": 2,
"selected": true,
"text": "<p>If you wanted to stick with Classic ASP then I would suggest creating a Database handling object via ASP Classes then just use that object to do your recordset creations. This would centralize your database handling code and make it so that you only have to handle SQL Injection attacks in a single location.</p>\n\n<p>A simple example.</p>\n\n<pre><code>Class clsDatabase\n\n Private Sub Class_Initialize()\n If Session(\"Debug\") Then Response.Write \"Database Initialized<br />\"\n End Sub\n\n Private Sub Class_Terminate()\n If Session(\"Debug\") Then Response.Write \"Database Terminated<br />\"\n End Sub\n\n Public Function Run(SQL)\n Set RS = CreateObject(\"ADODB.Recordset\")\n RS.CursorLocation = adUseClient\n RS.Open SQLValidate(SQL), Application(\"Data\"), adOpenKeyset, adLockReadOnly, adCmdText\n Set Run = RS\n Set RS = nothing\n End Function\n\n Public Function SQLValidate(SQL)\n SQLValidate = SQL\n SQLValidate = Replace(SQLValidate, \"--\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \";\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \"SP_\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \"@@\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \" DECLARE\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \"EXEC\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \" DROP\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \" CREATE\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \" GRANT\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \" XP_\", \"\", 1, -1, 1)\n SQLValidate = Replace(SQLValidate, \"CHAR(124)\", \"\", 1, -1, 1)\n End Function\nEnd Class\n</code></pre>\n\n<p>Then to use this you would change your calls to:</p>\n\n<pre><code>Set oData = new clsDatabase\nSet Recordset = oData.Run(\"SELECT field FROM table WHERE something = another\")\nSet oData = nothing\n</code></pre>\n\n<p>Of course you can expand the basic class to handle parametrized stored procedures or what not and more validations etc. </p>\n"
},
{
"answer_id": 79876,
"author": "Mike Henry",
"author_id": 14934,
"author_profile": "https://Stackoverflow.com/users/14934",
"pm_score": 1,
"selected": false,
"text": "<p>Another alternative is to use COM Interop to create an assembly in .NET that is callable from classic ASP.</p>\n\n<p>To create a COM Interop assembly from Visual Studio (e.g. Microsoft Visual C# 2005 Express Edition):</p>\n\n<ul>\n<li>Create a new Class Library project</li>\n<li><p>Open the project properties</p>\n\n<ul>\n<li>Under Application select Assembly Information... and enable \"Make assembly COM-Visible\"</li>\n<li>Under Signing enable Sign the assembly and create or select an existing strong name key file</li>\n</ul></li>\n<li><p>Write and build the library</p>\n\n<ul>\n<li>COM Interop classes must have a default constructor and only non-static classes and methods are published</li>\n</ul></li>\n<li><p>Copy the .dll to the desired folder/machine</p></li>\n<li>Register the .dll for COM using RegAsm</li>\n</ul>\n\n<p>For example (adjust as necessary):</p>\n\n<pre><code>\"C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\RegAsm.exe\" \"C:\\path\\to\\assembly.dll\" /tlb /codebase\n</code></pre>\n\n<ul>\n<li>Call the assembly from ASP</li>\n</ul>\n\n<p>For example (adjust as necessary):</p>\n\n<pre><code>Dim obj, returnValue\nSet obj = Server.CreateObject(\"MyProject.MyClass\")\nreturnValue = obj.DoSomething(param1, param2)\n</code></pre>\n\n<p>Note:</p>\n\n<ul>\n<li>the assembly must be re-registered via RegAsm when it's updated</li>\n</ul>\n\n<p>See also:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/zsfww439(VS.71).aspx\" rel=\"nofollow noreferrer\">Exposing .NET Framework Components to COM (MSDN)</a></li>\n<li><a href=\"http://www.codeproject.com/KB/dotnet/dotnetcomponentandasp.aspx\" rel=\"nofollow noreferrer\">CodeProject: Call a .NET component from an ASP Page</a></li>\n</ul>\n"
},
{
"answer_id": 110377,
"author": "DancesWithBamboo",
"author_id": 1334,
"author_profile": "https://Stackoverflow.com/users/1334",
"pm_score": 1,
"selected": false,
"text": "<p>Sql injection should be handled by using parametrized sql queries. Not only will this eliminate the security risk but it will significantly speed up your database performance because it will be able to reuse an execution plan instead of recalcing it every time. The suggestion to handle it through string replacements is foolish. VB is terrible at handling strings and those \"replace\" statements will be extremely costly in performance and memory (also, you actually only need to handle the ' character anyway) </p>\n\n<p>Moving code to .net doesn't make it better. Having db code in your pages isn't bad; especially if id you are talking about a small site with only a couple devs. Thousands of sites use that technique to process bazillions of dollars in transactions. Now, unparameterized dynamic sql is bad and you should work to eliminate that, but that doesn't require a rewrite of the app or .net to do it. I'm always curious why people see .net as a defacto improvement to their app. Most of the bad code and bad habits that existed in the COM model just propagate forward during a conversion. </p>\n\n<p>You either need to make a commitment to creating a truly cohesive, minimally coupled, OO design; or just keep what you have going because it isn't all that bad.</p>\n"
},
{
"answer_id": 4768697,
"author": "alexsts",
"author_id": 552446,
"author_profile": "https://Stackoverflow.com/users/552446",
"pm_score": 1,
"selected": false,
"text": "<p>Too bad I did not see this question in 2008.\nFor me it looks like your site is using Justa framework.\nSimple way is to modify Justa code for submit of search and data inputs to urlencode.\nI did it and work perfectly for me.</p>\n\n<p>Rest of the code secure enough to prevent any type os SQL injections or other attempt to get into database.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925/"
] | Currently I run an classic (old) ASP webpage with recordset object used directly in bad old spagethi code fasion.
I'm thinking of implementing a data layer in asp.net as web serivce to improve manageability. This is also a first step towards upgrading the website to asp.net.
The site itself remains ASP for the moment...
Can anybody recommend a good way of replacing the recordset object type with a web service compatible type (like an array or something)?
What do I replace below with?:
```
set objRS = oConn.execute(SQL)
while not objRS.eof
...
name = Cstr(objRS(1))
...
wend
```
and also mutliple recordsets can be replaced with?
I'm talking :
```
set objRS = objRs.nextRecordset
```
Anybody went through this and can recommend?
***@AdditionalInfo - you asked for it :-)***
Let me start at the beginning.
**Existing Situation is**:
I have an old ASP website with classical hierachical content (header, section, subsection, content) pulled out of database via stored procedures and content pages are in database also (a link to html file).
Now bad thing is, ASP code everywhere spread over many .asp files all doing their own database connections, reading, writing (u have to register for content). Recently we had problems with SQL injection attacks so I was called to fix it.
I *could* go change all the .asp pages to prevent sql injection but that would be madness. So I thought build a data layer - all pages using this layer to access database. Once place to fix and update db access code.
Coming to that decision I thought asp.net upgrade isn'f far away, why not start using asp.net for the data layer? This way it can be re-used when upgrading the site.
That brings me to the questions above! | If you wanted to stick with Classic ASP then I would suggest creating a Database handling object via ASP Classes then just use that object to do your recordset creations. This would centralize your database handling code and make it so that you only have to handle SQL Injection attacks in a single location.
A simple example.
```
Class clsDatabase
Private Sub Class_Initialize()
If Session("Debug") Then Response.Write "Database Initialized<br />"
End Sub
Private Sub Class_Terminate()
If Session("Debug") Then Response.Write "Database Terminated<br />"
End Sub
Public Function Run(SQL)
Set RS = CreateObject("ADODB.Recordset")
RS.CursorLocation = adUseClient
RS.Open SQLValidate(SQL), Application("Data"), adOpenKeyset, adLockReadOnly, adCmdText
Set Run = RS
Set RS = nothing
End Function
Public Function SQLValidate(SQL)
SQLValidate = SQL
SQLValidate = Replace(SQLValidate, "--", "", 1, -1, 1)
SQLValidate = Replace(SQLValidate, ";", "", 1, -1, 1)
SQLValidate = Replace(SQLValidate, "SP_", "", 1, -1, 1)
SQLValidate = Replace(SQLValidate, "@@", "", 1, -1, 1)
SQLValidate = Replace(SQLValidate, " DECLARE", "", 1, -1, 1)
SQLValidate = Replace(SQLValidate, "EXEC", "", 1, -1, 1)
SQLValidate = Replace(SQLValidate, " DROP", "", 1, -1, 1)
SQLValidate = Replace(SQLValidate, " CREATE", "", 1, -1, 1)
SQLValidate = Replace(SQLValidate, " GRANT", "", 1, -1, 1)
SQLValidate = Replace(SQLValidate, " XP_", "", 1, -1, 1)
SQLValidate = Replace(SQLValidate, "CHAR(124)", "", 1, -1, 1)
End Function
End Class
```
Then to use this you would change your calls to:
```
Set oData = new clsDatabase
Set Recordset = oData.Run("SELECT field FROM table WHERE something = another")
Set oData = nothing
```
Of course you can expand the basic class to handle parametrized stored procedures or what not and more validations etc. |
55,330 | <p>I already found this article:</p>
<p><a href="http://www.dotnetcurry.com/ShowArticle.aspx?ID=181&AspxAutoDetectCookieSupport=1" rel="nofollow noreferrer">http://www.dotnetcurry.com/ShowArticle.aspx?ID=181&AspxAutoDetectCookieSupport=1</a></p>
<p>But I've got a different situation. I am embedding some hiddenFields inside of the master page and trying to store the position of the dragPanel in those. </p>
<p>I am using javascript to store the position of the dragPanel and then when the user clicks on a link, the new page is loaded, but the dragPanel is reset into the starting position.</p>
<p><strong>Is there any easy way to do this?</strong> </p>
<p>Pseudocode:</p>
<pre><code>**this is in MasterPage.master**
function pageLoad()
{
// call the savePanelPosition when the panel is moved
$find('DragP1').add_move(savePanelPosition);
var elem = $get("<%=HiddenField1.ClientID%>");
if(elem.value != "0")
{
var temp = new Array();
temp = elem.value.split(';');
// set the position of the panel manually with the retrieve value
$find('<%=Panel1_DragPanelExtender.BehaviorID%>').set_location(new
Sys.UI.Point(parseInt(temp[0]),parseInt(temp[1])));
}
}
function savePanelPosition()
{
var elem = $find('DragP1').get_element();
var loc = $common.getLocation(elem);
var elem1 = $get("<%=HiddenField1.ClientID%>");
// store the value in the hidden field
elem1.value = loc.x + ';' + loc.y;
}
<asp:Button ID="Button1" runat="server" Text="Button"/>
<asp:HiddenField ID="HiddenField1" runat="server" Value="0"
</code></pre>
<p>However, <strong>HiddenField</strong> is not visible in the redirected page, foo.aspx</p>
| [
{
"answer_id": 76281,
"author": "Colin Neller",
"author_id": 12571,
"author_profile": "https://Stackoverflow.com/users/12571",
"pm_score": 1,
"selected": false,
"text": "<p>Rather than storing the position information in a hidden field, store it in a cookie. The information is small, so it will have minimal effect on the page load performance.</p>\n"
},
{
"answer_id": 8195416,
"author": "Tim Maxey",
"author_id": 655576,
"author_profile": "https://Stackoverflow.com/users/655576",
"pm_score": 0,
"selected": false,
"text": "<p>ok so I got the drag stuff to work, saves in a database and all, brings up cool on my one monitor 1600X1050 all good, fine and dandy! BUT WAIT! I bring up the same page on my other monitor 1366x768 and the panels are all off.</p>\n\n<p>The save function saves in pixels, so when you move over to another \"resolution\" the panels are off. ya know?</p>\n\n<p>P.S. I could pop up a message stating the user to change their monitor settings, lol...</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/750/"
] | I already found this article:
<http://www.dotnetcurry.com/ShowArticle.aspx?ID=181&AspxAutoDetectCookieSupport=1>
But I've got a different situation. I am embedding some hiddenFields inside of the master page and trying to store the position of the dragPanel in those.
I am using javascript to store the position of the dragPanel and then when the user clicks on a link, the new page is loaded, but the dragPanel is reset into the starting position.
**Is there any easy way to do this?**
Pseudocode:
```
**this is in MasterPage.master**
function pageLoad()
{
// call the savePanelPosition when the panel is moved
$find('DragP1').add_move(savePanelPosition);
var elem = $get("<%=HiddenField1.ClientID%>");
if(elem.value != "0")
{
var temp = new Array();
temp = elem.value.split(';');
// set the position of the panel manually with the retrieve value
$find('<%=Panel1_DragPanelExtender.BehaviorID%>').set_location(new
Sys.UI.Point(parseInt(temp[0]),parseInt(temp[1])));
}
}
function savePanelPosition()
{
var elem = $find('DragP1').get_element();
var loc = $common.getLocation(elem);
var elem1 = $get("<%=HiddenField1.ClientID%>");
// store the value in the hidden field
elem1.value = loc.x + ';' + loc.y;
}
<asp:Button ID="Button1" runat="server" Text="Button"/>
<asp:HiddenField ID="HiddenField1" runat="server" Value="0"
```
However, **HiddenField** is not visible in the redirected page, foo.aspx | Rather than storing the position information in a hidden field, store it in a cookie. The information is small, so it will have minimal effect on the page load performance. |
55,340 | <p>I'm just wondering if there's a better way of doing this in SQL Server 2005.</p>
<p>Effectively, I'm taking an originator_id (a number between 0 and 99) and a 'next_element' (it's really just a sequential counter between 1 and 999,999).
We are trying to create a 6-character 'code' from them. </p>
<p>The originator_id is multiplied up by a million, and then the counter added in, giving us a number between 0 and 99,999,999.</p>
<p>Then we convert this into a 'base 32' string - a fake base 32, where we're really just using 0-9 and A-Z but with a few of the more confusing alphanums removed for clarity (I, O, S, Z).</p>
<p>To do this, we just divide the number up by powers of 32, at each stage using the result we get for each power as an index for a character from our array of selected character.</p>
<pre>
Thus, an originator ID of 61 and NextCodeElement of 9 gives a code of '1T5JA9'
(61 * 1,000,000) + 9 = 61,000,009
61,000,009 div (5^32 = 33,554,432) = 1 = '1'
27,445,577 div (4^32 = 1,048,576) = 26 = 'T'
182,601 div (3^32 = 32,768) = 5 = '5'
18,761 div (2^32 = 1,024) = 18 = 'J'
329 div (1^32 = 32) = 10 = 'A'
9 div (0^32 = 1) = 9 = '9'
so my code is 1T5JA9
</pre>
<p>Previously I've had this algorithm working (in Delphi) but now I really need to be able to recreate it in SQL Server 2005. Obviously I don't quite have the same functions to hand that I have in Delphi, but this is my take on the routine. It works, and I can generate codes (or reconstruct codes back into their components) just fine.</p>
<p>But it looks a bit long-winded, and I'm not sure that the trick of selecting the result of a division into an int (ie casting it, really) is necessarily 'right' - is there a better SQLS approach to this kind of thing?</p>
<pre>
CREATE procedure dummy_RP_CREATE_CODE @NextCodeElement int, @OriginatorID int,
@code varchar(6) output
as
begin
declare @raw_num int;
declare @bcelems char(32);
declare @chr int;
select @bcelems='0123456789ABCDEFGHJKLMNPQRTUVWXY';
select @code='';
-- add in the originator_id, scaled into place
select @raw_num = (@OriginatorID * 1000000) + @NextCodeElement;
-- now to convert this to a 6-char code
-- 5^32
select @chr = @raw_num / 33554432;
select @raw_num = @raw_num - (@chr * 33554432);
select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);
-- 4^32
select @chr = @raw_num / 1048576;
select @raw_num = @raw_num - (@chr * 1048576);
select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);
-- 3^32
select @chr = @raw_num / 32768;
select @raw_num = @raw_num - (@chr * 32768);
select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);
-- 2^32
select @chr = @raw_num / 1024;
select @raw_num = @raw_num - (@chr * 1024);
select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);
-- 1^32
select @chr = @raw_num / 32;
select @raw_num = @raw_num - (@chr * 32);
select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);
-- 0^32
select @code = @code + SUBSTRING(@bcelems, 1 + @raw_num, 1);
-- that's it!
end;
</pre>
<p>I'm not desperately concerned about optimisation unless this method is actually an order of magnitude (or so) worse than any alternative. </p>
<p>The code only ever gets executed in small bursts, maybe generating 20 or 30 codes every 10 minutes or so. Because of the large range of numbers I don't want to pre-calculate the codes into a huge table (only small pockets of the overall code range will be used in any given installation).</p>
<p>However, I'm sure there's probably a tidier way of achieving the same result - particularly those divisions and subtractions.</p>
<p>Any constructive criticism, observations or suggestions would be most welcome. </p>
| [
{
"answer_id": 55504,
"author": "nickd",
"author_id": 2373,
"author_profile": "https://Stackoverflow.com/users/2373",
"pm_score": 3,
"selected": true,
"text": "<p>Seeing as it's SQL Server 2005, any reason not to use a CLR stored procedure? You could use your CLR language of choice then and it'd probably be a relatively direct port of your existing Delphi code.</p>\n"
},
{
"answer_id": 56298,
"author": "robsoft",
"author_id": 3897,
"author_profile": "https://Stackoverflow.com/users/3897",
"pm_score": 0,
"selected": false,
"text": "<p>Although it can clearly be done in SQL Server 2005, I think that it's of sufficient 'non-database-ness' that some kind of precompiled, high-level language routine makese sense.</p>\n\n<p>I've written DLLs for Interbase/Firebird, and T-SQL sprocs for SQL Server, but never a CLR routine. It will be an interesting exercise!</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3897/"
] | I'm just wondering if there's a better way of doing this in SQL Server 2005.
Effectively, I'm taking an originator\_id (a number between 0 and 99) and a 'next\_element' (it's really just a sequential counter between 1 and 999,999).
We are trying to create a 6-character 'code' from them.
The originator\_id is multiplied up by a million, and then the counter added in, giving us a number between 0 and 99,999,999.
Then we convert this into a 'base 32' string - a fake base 32, where we're really just using 0-9 and A-Z but with a few of the more confusing alphanums removed for clarity (I, O, S, Z).
To do this, we just divide the number up by powers of 32, at each stage using the result we get for each power as an index for a character from our array of selected character.
```
Thus, an originator ID of 61 and NextCodeElement of 9 gives a code of '1T5JA9'
(61 * 1,000,000) + 9 = 61,000,009
61,000,009 div (5^32 = 33,554,432) = 1 = '1'
27,445,577 div (4^32 = 1,048,576) = 26 = 'T'
182,601 div (3^32 = 32,768) = 5 = '5'
18,761 div (2^32 = 1,024) = 18 = 'J'
329 div (1^32 = 32) = 10 = 'A'
9 div (0^32 = 1) = 9 = '9'
so my code is 1T5JA9
```
Previously I've had this algorithm working (in Delphi) but now I really need to be able to recreate it in SQL Server 2005. Obviously I don't quite have the same functions to hand that I have in Delphi, but this is my take on the routine. It works, and I can generate codes (or reconstruct codes back into their components) just fine.
But it looks a bit long-winded, and I'm not sure that the trick of selecting the result of a division into an int (ie casting it, really) is necessarily 'right' - is there a better SQLS approach to this kind of thing?
```
CREATE procedure dummy_RP_CREATE_CODE @NextCodeElement int, @OriginatorID int,
@code varchar(6) output
as
begin
declare @raw_num int;
declare @bcelems char(32);
declare @chr int;
select @bcelems='0123456789ABCDEFGHJKLMNPQRTUVWXY';
select @code='';
-- add in the originator_id, scaled into place
select @raw_num = (@OriginatorID * 1000000) + @NextCodeElement;
-- now to convert this to a 6-char code
-- 5^32
select @chr = @raw_num / 33554432;
select @raw_num = @raw_num - (@chr * 33554432);
select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);
-- 4^32
select @chr = @raw_num / 1048576;
select @raw_num = @raw_num - (@chr * 1048576);
select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);
-- 3^32
select @chr = @raw_num / 32768;
select @raw_num = @raw_num - (@chr * 32768);
select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);
-- 2^32
select @chr = @raw_num / 1024;
select @raw_num = @raw_num - (@chr * 1024);
select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);
-- 1^32
select @chr = @raw_num / 32;
select @raw_num = @raw_num - (@chr * 32);
select @code = @code + SUBSTRING(@bcelems, 1 + @chr, 1);
-- 0^32
select @code = @code + SUBSTRING(@bcelems, 1 + @raw_num, 1);
-- that's it!
end;
```
I'm not desperately concerned about optimisation unless this method is actually an order of magnitude (or so) worse than any alternative.
The code only ever gets executed in small bursts, maybe generating 20 or 30 codes every 10 minutes or so. Because of the large range of numbers I don't want to pre-calculate the codes into a huge table (only small pockets of the overall code range will be used in any given installation).
However, I'm sure there's probably a tidier way of achieving the same result - particularly those divisions and subtractions.
Any constructive criticism, observations or suggestions would be most welcome. | Seeing as it's SQL Server 2005, any reason not to use a CLR stored procedure? You could use your CLR language of choice then and it'd probably be a relatively direct port of your existing Delphi code. |
55,342 | <p>I need to quickly (and forcibly) kill off all external sessions connecting to my oracle database without the supervision of and administrator.</p>
<p>I don't want to just lock the database and let the users quit gracefully.</p>
<p>How would I script this?</p>
| [
{
"answer_id": 55359,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 7,
"selected": true,
"text": "<p>This answer is heavily influenced by a conversation here: <a href=\"http://www.tek-tips.com/viewthread.cfm?qid=1395151&page=3\" rel=\"noreferrer\">http://www.tek-tips.com/viewthread.cfm?qid=1395151&page=3</a></p>\n\n<pre><code>ALTER SYSTEM ENABLE RESTRICTED SESSION;\n\nbegin \n for x in ( \n select Sid, Serial#, machine, program \n from v$session \n where \n machine <> 'MyDatabaseServerName' \n ) loop \n execute immediate 'Alter System Kill Session '''|| x.Sid \n || ',' || x.Serial# || ''' IMMEDIATE'; \n end loop; \nend;\n</code></pre>\n\n<p>I skip killing sessions originating on the database server to avoid killing off Oracle's connections to itself.</p>\n"
},
{
"answer_id": 59580,
"author": "Grrey",
"author_id": 6155,
"author_profile": "https://Stackoverflow.com/users/6155",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Try trigger on logon</strong></p>\n\n<p>Insted of trying disconnect users you should not allow them to connect.</p>\n\n<p>There is and example of such trigger.</p>\n\n<pre><code>CREATE OR REPLACE TRIGGER rds_logon_trigger\nAFTER LOGON ON DATABASE\nBEGIN\n IF SYS_CONTEXT('USERENV','IP_ADDRESS') not in ('192.168.2.121','192.168.2.123','192.168.2.233') THEN\n RAISE_APPLICATION_ERROR(-20003,'You are not allowed to connect to the database');\n END IF;\n\n IF (to_number(to_char(sysdate,'HH24'))< 6) and (to_number(to_char(sysdate,'HH24')) >18) THEN\n RAISE_APPLICATION_ERROR(-20005,'Logon only allowed during business hours');\n END IF;\n\nEND;\n</code></pre>\n"
},
{
"answer_id": 60807,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Before killing sessions, if possible do</p>\n\n<pre><code>ALTER SYSTEM ENABLE RESTRICTED SESSION;\n</code></pre>\n\n<p>to stop new sessions from connecting.</p>\n"
},
{
"answer_id": 234184,
"author": "Gazmo",
"author_id": 31175,
"author_profile": "https://Stackoverflow.com/users/31175",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to stop new users from connecting, but allow current sessions to continue until they are inactive, you can put the database in QUIESCE mode:</p>\n\n<pre><code>ALTER SYSTEM QUIESCE RESTRICTED;\n</code></pre>\n\n<p>From the <a href=\"http://download.oracle.com/docs/cd/B28359_01/server.111/b28310/start004.htm\" rel=\"nofollow noreferrer\">Oracle Database Administrator's Guide</a>:</p>\n\n<blockquote>\n <p>Non-DBA active sessions will continue\n until they become inactive. An active\n session is one that is currently\n inside of a transaction, a query, a\n fetch, or a PL/SQL statement; or a\n session that is currently holding any\n shared resources (for example,\n enqueues). No inactive sessions are\n allowed to become active...Once all\n non-DBA sessions become inactive, the\n ALTER SYSTEM QUIESCE RESTRICTED\n statement completes, and the database\n is in a quiesced state</p>\n</blockquote>\n"
},
{
"answer_id": 939765,
"author": "jon077",
"author_id": 22801,
"author_profile": "https://Stackoverflow.com/users/22801",
"pm_score": 1,
"selected": false,
"text": "<p>I found the below snippet helpful. Taken from: <a href=\"http://jeromeblog-jerome.blogspot.com/2007/10/how-to-unlock-record-on-oracle.html\" rel=\"nofollow noreferrer\">http://jeromeblog-jerome.blogspot.com/2007/10/how-to-unlock-record-on-oracle.html</a></p>\n\n<pre><code>select\nowner||'.'||object_name obj ,\noracle_username||' ('||s.status||')' oruser ,\nos_user_name osuser ,\nmachine computer ,\nl.process unix ,\ns.sid||','||s.serial# ss ,\nr.name rs ,\nto_char(s.logon_time,'yyyy/mm/dd hh24:mi:ss') time\nfrom v$locked_object l ,\ndba_objects o ,\nv$session s ,\nv$transaction t ,\nv$rollname r\nwhere l.object_id = o.object_id\nand s.sid=l.session_id\nand s.taddr=t.addr\nand t.xidusn=r.usn\norder by osuser, ss, obj\n;\n</code></pre>\n\n<p>Then ran:</p>\n\n<pre><code>Alter System Kill Session '<value from ss above>'\n;\n</code></pre>\n\n<p>To kill individual sessions.</p>\n"
},
{
"answer_id": 3825265,
"author": "Gaius",
"author_id": 447514,
"author_profile": "https://Stackoverflow.com/users/447514",
"pm_score": 4,
"selected": false,
"text": "<p>As SYS:</p>\n\n<pre><code>startup force;\n</code></pre>\n\n<p>Brutal, yet elegant.</p>\n"
},
{
"answer_id": 6122593,
"author": "dovka",
"author_id": 555848,
"author_profile": "https://Stackoverflow.com/users/555848",
"pm_score": 1,
"selected": false,
"text": "<p>To answer the question asked,\nhere is the most accurate SQL to accomplish the job,\nyou can combine it with PL/SQL loop to actually run kill statements:</p>\n\n<pre><code>select ses.USERNAME,\n substr(MACHINE,1,10) as MACHINE, \n substr(module,1,25) as module,\n status, \n 'alter system kill session '''||SID||','||ses.SERIAL#||''';' as kill\nfrom v$session ses LEFT OUTER JOIN v$process p ON (ses.paddr=p.addr)\nwhere schemaname <> 'SYS'\n and not exists\n (select 1 \n from DBA_ROLE_PRIVS \n where GRANTED_ROLE='DBA' \n and schemaname=grantee)\n and machine!='yourlocalhostname' \norder by LAST_CALL_ET desc;\n</code></pre>\n"
},
{
"answer_id": 7806123,
"author": "Thomas Bratt",
"author_id": 15985,
"author_profile": "https://Stackoverflow.com/users/15985",
"pm_score": 3,
"selected": false,
"text": "<p>I've been using something like this for a while to kill my sessions on a shared server. The first line of the 'where' can be removed to kill all non 'sys' sessions:</p>\n\n<pre><code>BEGIN\n FOR c IN (\n SELECT s.sid, s.serial#\n FROM v$session s\n WHERE (s.Osuser = 'MyUser' or s.MACHINE = 'MyNtDomain\\MyMachineName')\n AND s.USERNAME <> 'SYS'\n AND s.STATUS <> 'KILLED'\n )\n LOOP\n EXECUTE IMMEDIATE 'alter system kill session ''' || c.sid || ',' || c.serial# || '''';\n END LOOP;\nEND;\n</code></pre>\n"
},
{
"answer_id": 9117640,
"author": "Vadzim",
"author_id": 603516,
"author_profile": "https://Stackoverflow.com/users/603516",
"pm_score": 2,
"selected": false,
"text": "<p>Additional info</p>\n\n<blockquote>\n <p>Important Oracle 11g changes to alter session kill session</p>\n \n <p>Oracle author Mladen Gogala notes that an @ sign is now required to\n kill a session when using the inst_id column:</p>\n</blockquote>\n\n<pre><code>alter system kill session '130,620,@1';\n</code></pre>\n\n<p><a href=\"http://www.dba-oracle.com/tips_killing_oracle_sessions.htm\" rel=\"nofollow\">http://www.dba-oracle.com/tips_killing_oracle_sessions.htm</a></p>\n"
},
{
"answer_id": 36299914,
"author": "Ramki",
"author_id": 4136306,
"author_profile": "https://Stackoverflow.com/users/4136306",
"pm_score": 0,
"selected": false,
"text": "<p>If Oracle is running in Unix /Linux then we can grep for all client connections and kill it </p>\n\n<p>grep all oracle client process:</p>\n\n<p>ps -ef | grep LOCAL=NO | grep -v grep | awk '{print $2}' | wc -l</p>\n\n<p>Kill all oracle client process :</p>\n\n<p>kill -9 <code>ps -ef | grep LOCAL=NO | grep -v grep | awk '{print $2}'</code></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/685/"
] | I need to quickly (and forcibly) kill off all external sessions connecting to my oracle database without the supervision of and administrator.
I don't want to just lock the database and let the users quit gracefully.
How would I script this? | This answer is heavily influenced by a conversation here: <http://www.tek-tips.com/viewthread.cfm?qid=1395151&page=3>
```
ALTER SYSTEM ENABLE RESTRICTED SESSION;
begin
for x in (
select Sid, Serial#, machine, program
from v$session
where
machine <> 'MyDatabaseServerName'
) loop
execute immediate 'Alter System Kill Session '''|| x.Sid
|| ',' || x.Serial# || ''' IMMEDIATE';
end loop;
end;
```
I skip killing sessions originating on the database server to avoid killing off Oracle's connections to itself. |
55,360 | <p>The __doPostBack is not working in firefox 3 (have not checked 2). Everything is working great in IE 6&7 and it even works in Chrome??</p>
<p>It's a simple asp:LinkButton with an OnClick event</p>
<pre><code><asp:LinkButton ID="DeleteAllPicturesLinkButton" Enabled="False" OnClientClick="javascript:return confirm('Are you sure you want to delete all pictures? \n This action cannot be undone.');" OnClick="DeletePictureLinkButton_Click" CommandName="DeleteAll" CssClass="button" runat="server">
</code></pre>
<p>The javascript confirm is firing so I know the javascript is working, it's specirically the __doPostBack event. There is a lot more going on on the page, just didn't know if it's work it to post the entire page.</p>
<p>I enable the control on the page load event.</p>
<p>Any ideas?</p>
<hr>
<p>I hope this is the correct way to do this, but I found the answer. I figured I'd put it up here rather then in a stackoverflow "answer"</p>
<p>Seems it had something to do with nesting ajax toolkit UpdatePanel. When I removed the top level panel it was fixed.</p>
<p>Hope this helps if anyone else has the same problem. I still don't know what specifically was causing the problem, but that was the solution for me.</p>
| [
{
"answer_id": 55367,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 1,
"selected": false,
"text": "<p>Is it because you are doing <strong>return</strong> confirm? seems like the return statement should prevent the rest of the code from firing. i would think an if statement would work</p>\n\n<pre><code>if (!confirm(...)) { return false; } _doPostBack(...);\n</code></pre>\n\n<p>Can you post all the js code in the OnClick of the link?</p>\n\n<p><strong>EDIT</strong>: aha, forgot that link button emits code like this </p>\n\n<pre><code><a href=\"javascript:__doPostBack()\" onclick=\"return confirm()\" />\n</code></pre>\n"
},
{
"answer_id": 55379,
"author": "Dan Williams",
"author_id": 4230,
"author_profile": "https://Stackoverflow.com/users/4230",
"pm_score": 0,
"selected": false,
"text": "<p>With or without the OnClientClick event it still doesn't work.</p>\n\n<p>The _doPostBack event is the auto generated javascript that .NET produces.</p>\n\n<pre><code>function __doPostBack(eventTarget, eventArgument) {\n\n if (!theForm.onsubmit || (theForm.onsubmit() != false)) {\n\n theForm.__EVENTTARGET.value = eventTarget;\n\n theForm.__EVENTARGUMENT.value = eventArgument;\n\n theForm.submit();\n\n }\n\n}\n</code></pre>\n\n<p>*The &95; are underscores, seems to be a problem with the stackoverflow code block format.</p>\n"
},
{
"answer_id": 55387,
"author": "Paulj",
"author_id": 5433,
"author_profile": "https://Stackoverflow.com/users/5433",
"pm_score": 1,
"selected": false,
"text": "<p>this might seem elemental, but did you verify that your firefox settings aren't set to interfere with the postback? Sometimes I encounter similar problems due to a odd browser configuration I had from a debugging session.</p>\n"
},
{
"answer_id": 55413,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>Now that i think about it, as noted in my last edit, you want to drop the javascript: in the on client click property. It's not needed, because the onclick event is javascript as it is. try that, see if that works.</p>\n"
},
{
"answer_id": 55420,
"author": "moza",
"author_id": 3465,
"author_profile": "https://Stackoverflow.com/users/3465",
"pm_score": 1,
"selected": false,
"text": "<p>Are you handling the PageLoad event? If so, try the following</p>\n\n<pre><code>if (!isPostBack)\n{\n //do something\n}\nelse if (Request.Form[\"__EVENTTARGET\"].ToLower().IndexOf(\"myevent\") >= 0)\n{\n //call appropriate function.\n}\n</code></pre>\n\n<p>Check if you are getting a call this way, if so then maybe the event is not wired and nedes to be explicitly called.</p>\n"
},
{
"answer_id": 55430,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 1,
"selected": false,
"text": "<p>what do you expect from \"Enabled = 'false'\" ?</p>\n"
},
{
"answer_id": 55478,
"author": "seanb",
"author_id": 3354,
"author_profile": "https://Stackoverflow.com/users/3354",
"pm_score": 1,
"selected": false,
"text": "<p>I have had problems with firebug on some web forms, something to do with the network analyser can screw with postbacks.</p>\n"
},
{
"answer_id": 57232,
"author": "Dan Williams",
"author_id": 4230,
"author_profile": "https://Stackoverflow.com/users/4230",
"pm_score": 0,
"selected": false,
"text": "<p>Seems it had something to do with nesting ajax toolkit UpdatePanel. When I removed the top level panel it was fixed.</p>\n\n<p>Hope this helps if anyone else has the same problem.</p>\n"
},
{
"answer_id": 87364,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 4,
"selected": true,
"text": "<p>Check your User Agent string. This same thing happened to me one time and I realized it was because I was testing out some pages as \"googlebot\". The JavaScript that is generated depends on knowing what the user agent is.</p>\n\n<p>From <a href=\"http://support.mozilla.com/tiki-view_forum_thread.php?locale=tr&comments_parentId=160492&forumId=1\" rel=\"noreferrer\">http://support.mozilla.com/tiki-view_forum_thread.php?locale=tr&comments_parentId=160492&forumId=1</a>:</p>\n\n<blockquote>\n <p>To reset your user agent string type about:config into the location bar and press enter. This brings up a list of preferences. Enter general.useragent into the filter box, this should show a few preferences (probably 4 of them). If any have the status user set, right-click on the preference and choose Reset</p>\n</blockquote>\n"
},
{
"answer_id": 394236,
"author": "pearcewg",
"author_id": 24126,
"author_profile": "https://Stackoverflow.com/users/24126",
"pm_score": 0,
"selected": false,
"text": "<p>I had this exact same issue in a web app I was working on, and I tried solving it for hours.</p>\n\n<p>Eventually, I did a NEW webform, dropped a linkbutton in it, and it worked perfectly!</p>\n\n<p>I then noticed the following issue:</p>\n\n...\n\n<p>I switch the order to the following, and it immediately was fixed:\n...</p>\n\n<p>IE had no issue either way (that I noticed anyway).</p>\n"
},
{
"answer_id": 1004304,
"author": "Todd",
"author_id": 54305,
"author_profile": "https://Stackoverflow.com/users/54305",
"pm_score": 2,
"selected": false,
"text": "<p>I had this same problem (__doPostBack not working) in Firefox- caused a solid hour of wasted time. The problem turned out to be the HTML. If you use HTML like this:</p>\n\n<pre><code><input type=\"button\" id=\"yourButton\" onclick=\"doSomethingThenPostBack();\" value=\"Post\" />\n</code></pre>\n\n<p>Where \"doSomethingThenPostBack\" is just a JavaScript method that calls __doPostBack, the form <strong><em>will not</em></strong> post in Firefox. It <strong><em>will</em></strong> PostBack in IE and Chrome. To solve the problem, make sure your HTML is:</p>\n\n<pre><code><input type=\"submit\" id=\"yourButton\" ...\n</code></pre>\n\n<p>The key is the <strong>type</strong> attribute. It must be \"<strong>submit</strong>\" in Firefox for __doPostBack to work. Other browsers don't seem to care. Hope this helps anyone else who hits this problem.</p>\n"
},
{
"answer_id": 3092596,
"author": "DotNetDevster",
"author_id": 373095,
"author_profile": "https://Stackoverflow.com/users/373095",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar issue. It turned out that Akamai was modifying the user-agent string because an setting was being applied that was not needed.</p>\n\n<p>This meant that some .NET controls did not render __doPostBack code properly. This issue has been blogged <a href=\"http://www.dotnetlite.com/2010/06/21/loss-of-__dopostback-code-after-protecting-a-site-with-akamai/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 3994067,
"author": "AlwaysLearning",
"author_id": 390122,
"author_profile": "https://Stackoverflow.com/users/390122",
"pm_score": 0,
"selected": false,
"text": "<p>@Terrapin: you got this exactly right (for me, anyways).</p>\n\n<p>I was running User Agent Switcher and had inadvertently left the Googlebot 2.1 agent selected.</p>\n\n<p>In Reporting Services 2008 it was causing the iframes that reports are actually rendered in to be about 300x200 px, and in Reporting Services 2008 R2 is was throwing \"__doPostBack undefined\" errors in the Error Console.</p>\n\n<p>Switching back to the Default User Agent fixed all my issues.</p>\n"
},
{
"answer_id": 24784827,
"author": "SSZero",
"author_id": 400323,
"author_profile": "https://Stackoverflow.com/users/400323",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem with Firefox. Instead of using <code>__doPostBack()</code> could you use the jQuery .trigger() method to trigger a click action on an element that has your postback event registered as the click action?</p>\n\n<p>For example, if you had this element in your aspx page:</p>\n\n<pre><code><asp:Button runat=\"server\" ID=\"btnMyPostback\" OnClick=\"btnMyPostback_Click\" CssClass=\"hide\" ToolTip=\"Click here to submit this transaction.\" />\n</code></pre>\n\n<p>And your postback event in your controller:</p>\n\n<pre><code> protected void btnMyPostback_Click(object sender, EventArgs e)\n {\n //do my postback stuff\n }\n</code></pre>\n\n<p>You could do the postback by calling:</p>\n\n<pre><code>$(\"#btnMyPostback\").trigger(\"click\");\n</code></pre>\n\n<p>This will cause the <code>Page_Load</code> event to fire if you need to do something on <code>Page_Load</code>.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4230/"
] | The \_\_doPostBack is not working in firefox 3 (have not checked 2). Everything is working great in IE 6&7 and it even works in Chrome??
It's a simple asp:LinkButton with an OnClick event
```
<asp:LinkButton ID="DeleteAllPicturesLinkButton" Enabled="False" OnClientClick="javascript:return confirm('Are you sure you want to delete all pictures? \n This action cannot be undone.');" OnClick="DeletePictureLinkButton_Click" CommandName="DeleteAll" CssClass="button" runat="server">
```
The javascript confirm is firing so I know the javascript is working, it's specirically the \_\_doPostBack event. There is a lot more going on on the page, just didn't know if it's work it to post the entire page.
I enable the control on the page load event.
Any ideas?
---
I hope this is the correct way to do this, but I found the answer. I figured I'd put it up here rather then in a stackoverflow "answer"
Seems it had something to do with nesting ajax toolkit UpdatePanel. When I removed the top level panel it was fixed.
Hope this helps if anyone else has the same problem. I still don't know what specifically was causing the problem, but that was the solution for me. | Check your User Agent string. This same thing happened to me one time and I realized it was because I was testing out some pages as "googlebot". The JavaScript that is generated depends on knowing what the user agent is.
From <http://support.mozilla.com/tiki-view_forum_thread.php?locale=tr&comments_parentId=160492&forumId=1>:
>
> To reset your user agent string type about:config into the location bar and press enter. This brings up a list of preferences. Enter general.useragent into the filter box, this should show a few preferences (probably 4 of them). If any have the status user set, right-click on the preference and choose Reset
>
>
> |
55,386 | <p>I'm using Windows and I'm trying to get ANT to work.</p>
<p>When I do an ant build from the command line, I get:
<code>C:\dev\Projects\springapp\${%ANT_HOME%}\lib not found.</code></p>
<p>I look into the <code>build.xml</code> file and I find:
<code>appserver.home=${user.home}/apache-tomcat-6.0.14</code> (which I just copied and pasted straight from a tutorial)</p>
<p>I changed it to:</p>
<p><code>appserver.home="C:\Program Files\Apache Software Foundation\Tomcat 6.0"</code></p>
<p>but now I get:</p>
<p><code>C:\dev\Projects\springapp\"C:Program FilesApache Software FoundationTomcat 6.0"\lib not found.</code></p>
<p>It seems like the white space in Program Files and Tomcat 6.0 are causing the build to fail. How do you deal with these in xml files without re-creating the directory with a path with no white space?</p>
| [
{
"answer_id": 55426,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "<p>Change it to </p>\n\n<pre><code>appserver.home=\"C:\\\\Program Files\\\\Apache Software Foundation\\\\Tomcat 6.0\"\n</code></pre>\n"
},
{
"answer_id": 55492,
"author": "Dominik Grabiec",
"author_id": 3719,
"author_profile": "https://Stackoverflow.com/users/3719",
"pm_score": 1,
"selected": false,
"text": "<p>In addition to escaping the windows directory separator also make sure that all paths that you type in should be with correct capitalisation, Windows is not case sensitive but case presrving, while Ant is case sensitive.</p>\n"
},
{
"answer_id": 56911,
"author": "Rob Spieldenner",
"author_id": 5118,
"author_profile": "https://Stackoverflow.com/users/5118",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like you have your properties setup incorrectly.</p>\n\n<p>I'm guessing your basedir property is pointing at C:\\dev\\Projects\\springapp and your properties are using value like:</p>\n\n<pre><code><property name=\"property.1\" value=\"directory\" />\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code><property name=\"property.1\" location=\"directory\" />\n</code></pre>\n\n<p>Using the location property then resolves links as relative to your basedir if the location is a relative path and to the absolute path if you enter one of those. If you could post parts of your Ant file specifically how you define appserver.home and how you use it in the task that's throwing the error I could be more specific.</p>\n"
},
{
"answer_id": 3667871,
"author": "Eugene",
"author_id": 442423,
"author_profile": "https://Stackoverflow.com/users/442423",
"pm_score": 3,
"selected": false,
"text": "<p>Variant with \"/\" instead \"\\\" works on my system. Just need to delete \" symbols before and after path structure. </p>\n"
},
{
"answer_id": 4327767,
"author": "caseyboardman",
"author_id": 807,
"author_profile": "https://Stackoverflow.com/users/807",
"pm_score": 1,
"selected": false,
"text": "<p>In the top of your build.xml, try adding\n<code><property environment=\"env\"/></code>\nand then using <code>${env.USER_HOME}</code> (or whatever you have in your environment). That did it for me (${env.JAVA_HOME} rather than <code>${java.home}</code>).</p>\n"
},
{
"answer_id": 6830626,
"author": "gliptak",
"author_id": 304690,
"author_profile": "https://Stackoverflow.com/users/304690",
"pm_score": 2,
"selected": false,
"text": "<p>Find the Windows short name for those directories using <code>dir /x</code> and use thme when setting <code>path</code> values.</p>\n\n<p>Some more discussion at <a href=\"https://stackoverflow.com/questions/324041/how-does-windows-determine-handle-the-dos-short-name-of-any-given-file\">How does Windows determine/handle the DOS short name of any given file?</a></p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm using Windows and I'm trying to get ANT to work.
When I do an ant build from the command line, I get:
`C:\dev\Projects\springapp\${%ANT_HOME%}\lib not found.`
I look into the `build.xml` file and I find:
`appserver.home=${user.home}/apache-tomcat-6.0.14` (which I just copied and pasted straight from a tutorial)
I changed it to:
`appserver.home="C:\Program Files\Apache Software Foundation\Tomcat 6.0"`
but now I get:
`C:\dev\Projects\springapp\"C:Program FilesApache Software FoundationTomcat 6.0"\lib not found.`
It seems like the white space in Program Files and Tomcat 6.0 are causing the build to fail. How do you deal with these in xml files without re-creating the directory with a path with no white space? | Change it to
```
appserver.home="C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0"
``` |
55,391 | <p>I want to grab the value of a hidden input field in HTML.</p>
<pre><code><input type="hidden" name="fooId" value="12-3456789-1111111111" />
</code></pre>
<p>I want to write a regular expression in Python that will return the value of <code>fooId</code>, given that I know the line in the HTML follows the format</p>
<pre><code><input type="hidden" name="fooId" value="**[id is here]**" />
</code></pre>
<p>Can someone provide an example in Python to parse the HTML for the value?</p>
| [
{
"answer_id": 55399,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 0,
"selected": false,
"text": "<pre><code>/<input type=\"hidden\" name=\"fooId\" value=\"([\\d-]+)\" \\/>/\n</code></pre>\n"
},
{
"answer_id": 55401,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": false,
"text": "<p>Parsing is one of those areas where you really don't want to roll your own if you can avoid it, as you'll be chasing down the edge-cases and bugs for years go come</p>\n\n<p>I'd recommend using <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"nofollow noreferrer\">BeautifulSoup</a>. It has a very good reputation and looks from the docs like it's pretty easy to use.</p>\n"
},
{
"answer_id": 55404,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import re\nreg = re.compile('<input type=\"hidden\" name=\"([^\"]*)\" value=\"<id>\" />')\nvalue = reg.search(inputHTML).group(1)\nprint 'Value is', value\n</code></pre>\n"
},
{
"answer_id": 55424,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 6,
"selected": true,
"text": "<p>For this particular case, BeautifulSoup is harder to write than a regex, but it is much more robust... I'm just contributing with the BeautifulSoup example, given that you already know which regexp to use :-)</p>\n\n<pre><code>from BeautifulSoup import BeautifulSoup\n\n#Or retrieve it from the web, etc. \nhtml_data = open('/yourwebsite/page.html','r').read()\n\n#Create the soup object from the HTML data\nsoup = BeautifulSoup(html_data)\nfooId = soup.find('input',name='fooId',type='hidden') #Find the proper tag\nvalue = fooId.attrs[2][1] #The value of the third attribute of the desired tag \n #or index it directly via fooId['value']\n</code></pre>\n"
},
{
"answer_id": 56144,
"author": "Will Boyce",
"author_id": 5757,
"author_profile": "https://Stackoverflow.com/users/5757",
"pm_score": 0,
"selected": false,
"text": "<pre><code>/<input\\s+type=\"hidden\"\\s+name=\"([A-Za-z0-9_]+)\"\\s+value=\"([A-Za-z0-9_\\-]*)\"\\s*/>/\n\n>>> import re\n>>> s = '<input type=\"hidden\" name=\"fooId\" value=\"12-3456789-1111111111\" />'\n>>> re.match('<input\\s+type=\"hidden\"\\s+name=\"([A-Za-z0-9_]+)\"\\s+value=\"([A-Za-z0-9_\\-]*)\"\\s*/>', s).groups()\n('fooId', '12-3456789-1111111111')\n</code></pre>\n"
},
{
"answer_id": 64983,
"author": "A Nony Mouse",
"author_id": 7182,
"author_profile": "https://Stackoverflow.com/users/7182",
"pm_score": 4,
"selected": false,
"text": "<p>I agree with Vinko <a href=\"http://www.crummy.com/software/BeautifulSoup/\" rel=\"noreferrer\">BeautifulSoup</a> is the way to go. However I suggest using <code>fooId['value']</code> to <a href=\"http://www.crummy.com/software/BeautifulSoup/documentation.html#The%20attributes%20of%20Tags\" rel=\"noreferrer\">get the attribute</a> rather than relying on value being the third attribute.</p>\n\n<pre><code>from BeautifulSoup import BeautifulSoup\n#Or retrieve it from the web, etc.\nhtml_data = open('/yourwebsite/page.html','r').read()\n#Create the soup object from the HTML data\nsoup = BeautifulSoup(html_data)\nfooId = soup.find('input',name='fooId',type='hidden') #Find the proper tag\nvalue = fooId['value'] #The value attribute\n</code></pre>\n"
},
{
"answer_id": 1421480,
"author": "PaulMcG",
"author_id": 165216,
"author_profile": "https://Stackoverflow.com/users/165216",
"pm_score": 1,
"selected": false,
"text": "<p>Pyparsing is a good interim step between BeautifulSoup and regex. It is more robust than just regexes, since its HTML tag parsing comprehends variations in case, whitespace, attribute presence/absence/order, but simpler to do this kind of basic tag extraction than using BS.</p>\n\n<p>Your example is especially simple, since everything you are looking for is in the attributes of the opening \"input\" tag. Here is a pyparsing example showing several variations on your input tag that would give regexes fits, and also shows how NOT to match a tag if it is within a comment:</p>\n\n<pre><code>html = \"\"\"<html><body>\n<input type=\"hidden\" name=\"fooId\" value=\"**[id is here]**\" />\n<blah>\n<input name=\"fooId\" type=\"hidden\" value=\"**[id is here too]**\" />\n<input NAME=\"fooId\" type=\"hidden\" value=\"**[id is HERE too]**\" />\n<INPUT NAME=\"fooId\" type=\"hidden\" value=\"**[and id is even here TOO]**\" />\n<!--\n<input type=\"hidden\" name=\"fooId\" value=\"**[don't report this id]**\" />\n-->\n<foo>\n</body></html>\"\"\"\n\nfrom pyparsing import makeHTMLTags, withAttribute, htmlComment\n\n# use makeHTMLTags to create tag expression - makeHTMLTags returns expressions for\n# opening and closing tags, we're only interested in the opening tag\ninputTag = makeHTMLTags(\"input\")[0]\n\n# only want input tags with special attributes\ninputTag.setParseAction(withAttribute(type=\"hidden\", name=\"fooId\"))\n\n# don't report tags that are commented out\ninputTag.ignore(htmlComment)\n\n# use searchString to skip through the input \nfoundTags = inputTag.searchString(html)\n\n# dump out first result to show all returned tags and attributes\nprint foundTags[0].dump()\nprint\n\n# print out the value attribute for all matched tags\nfor inpTag in foundTags:\n print inpTag.value\n</code></pre>\n\n<p>Prints:</p>\n\n<pre><code>['input', ['type', 'hidden'], ['name', 'fooId'], ['value', '**[id is here]**'], True]\n- empty: True\n- name: fooId\n- startInput: ['input', ['type', 'hidden'], ['name', 'fooId'], ['value', '**[id is here]**'], True]\n - empty: True\n - name: fooId\n - type: hidden\n - value: **[id is here]**\n- type: hidden\n- value: **[id is here]**\n\n**[id is here]**\n**[id is here too]**\n**[id is HERE too]**\n**[and id is even here TOO]**\n</code></pre>\n\n<p>You can see that not only does pyparsing match these unpredictable variations, it returns the data in an object that makes it easy to read out the individual tag attributes and their values.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5675/"
] | I want to grab the value of a hidden input field in HTML.
```
<input type="hidden" name="fooId" value="12-3456789-1111111111" />
```
I want to write a regular expression in Python that will return the value of `fooId`, given that I know the line in the HTML follows the format
```
<input type="hidden" name="fooId" value="**[id is here]**" />
```
Can someone provide an example in Python to parse the HTML for the value? | For this particular case, BeautifulSoup is harder to write than a regex, but it is much more robust... I'm just contributing with the BeautifulSoup example, given that you already know which regexp to use :-)
```
from BeautifulSoup import BeautifulSoup
#Or retrieve it from the web, etc.
html_data = open('/yourwebsite/page.html','r').read()
#Create the soup object from the HTML data
soup = BeautifulSoup(html_data)
fooId = soup.find('input',name='fooId',type='hidden') #Find the proper tag
value = fooId.attrs[2][1] #The value of the third attribute of the desired tag
#or index it directly via fooId['value']
``` |
55,411 | <p>Running into a problem where on certain servers we get an error that the directory name is invalid when using Path.GetTempFileName. Further investigation shows that it is trying to write a file to c:\Documents and Setting\computername\aspnet\local settings\temp (found by using Path.GetTempPath). This folder exists so I'm assuming this must be a permissions issue with respect to the asp.net account. </p>
<p>I've been told by some that Path.GetTempFileName should be pointing to C:\Windows\Microsoft.NET\Framework\v2.0.50727\temporaryasp.net files.</p>
<p>I've also been told that this problem may be due to the order in which IIS and .NET where installed on the server. I've done the typical 'aspnet_regiis -i' and checked security on the folders etc. At this point I'm stuck.</p>
<p>Can anyone shed some light on this?</p>
<p>**Update:**Turns out that providing 'IUSR_ComputerName' access to the folder does the trick. Is that the correct procedure? I don't seem to recall doing that in the past, and obviously, want to follow best practices to maintain security. This is, after all, part of a file upload process.</p>
| [
{
"answer_id": 55423,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <strong>Path.GetTempPath()</strong> to find out which directory to which it's trying to write.</p>\n"
},
{
"answer_id": 55425,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "<p>Could be because <a href=\"http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/3648346f-e4f5-474b-86c7-5a86e85fa1ff.mspx?mfr=true\" rel=\"nofollow noreferrer\">IIS_WPG</a> does not have access to a temp folder. If you think it is a permission issue, run a <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow noreferrer\">Procmon</a> on asp.net worker process and check for AccessDenied errors.</p>\n"
},
{
"answer_id": 60353,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 5,
"selected": true,
"text": "<p>This is probably a combination of impersonation and a mismatch of different authentication methods occurring.</p>\n\n<p>There are many pieces; I'll try to go over them one by one.</p>\n\n<p><strong>Impersonation</strong> is a technique to \"temporarily\" switch the user account under which a thread is running. Essentially, the thread briefly gains the same rights and access -- no more, no less -- as the account that is being impersonated. As soon as the thread is done creating the web page, it \"reverts\" back to the original account and gets ready for the next call. This technique is used to access resources that only the user logged into your web site has access to. Hold onto the concept for a minute.</p>\n\n<p>Now, by default ASP.NET runs a web site under a local account called <strong>ASPNET</strong>. Again, by default, only the ASPNET account and members of the Administrators group can write to that folder. Your temporary folder is under that account's purview. This is the second piece of the puzzle.</p>\n\n<p>Impersonation doesn't happen on its own. It needs to be turn on intentionally in your web.config.</p>\n\n<pre><code><identity impersonate=\"true\" />\n</code></pre>\n\n<p>If the setting is missing or set to false, your code will execute pure and simply under the ASPNET account mentioned above. Given your error message, I'm positive that you have impersonation=true. There is nothing wrong with that! Impersonation has advantages and disadvantages that go beyond this discussion.</p>\n\n<p>There is one question left: when you use impersonation, <em>which account gets impersonated</em>?</p>\n\n<p>Unless you specify the account in the web.config (<a href=\"http://msdn.microsoft.com/en-us/library/72wdk8cc.aspx\" rel=\"noreferrer\">full syntax of the identity element here</a>), the account impersonated is the one that the IIS handed over to ASP.NET. And that depends on how the user has authenticated (or not) into the site. That is your third and final piece.</p>\n\n<p>The IUSR_ComputerName account is a low-rights account created by IIS. By default, this account is the account under which a web call runs <strong>if the user could not be authenticated</strong>. That is, the user comes in as an \"anonymous\".</p>\n\n<p>In summary, this is what is happening to you:</p>\n\n<p>Your user is trying to access the web site, and IIS could not authenticate the person for some reason. Because Anonymous access is ON, (or you would not see IUSRComputerName accessing the temp folder), IIS allows the user in anyway, but as a generic user. Your ASP.NET code runs and impersonates this generic IUSR___ComputerName \"guest\" account; only now the code doesn't have access to the things that the ASPNET account had access to, including its own temporary folder.</p>\n\n<p>Granting IUSR_ComputerName WRITE access to the folder makes your symptoms go away.</p>\n\n<p>But that just the symptoms. You need to review <strong>why is the person coming as \"Anonymous/Guest\"?</strong></p>\n\n<p>There are two likely scenarios:</p>\n\n<p>a) You intended to use IIS for authentication, but the authentication settings in IIS for some of your servers are wrong.</p>\n\n<p>In that case, you need to disable Anonymous access on those servers so that the usual authentication mechanisms take place. Note that you might still need to grant to your users access to that temporary folder, or use another folder instead, one to which your users already have access.</p>\n\n<p>I have worked with this scenario many times, and quite frankly it gives you less headaches to forgo the Temp folder; create a dedicated folder in the server, set the proper permissions, and set its location in web.config. </p>\n\n<p>b) You didn't want to authenticate people anyway, or you wanted to use ASP.NET Forms Authentication (which uses IIS's Anonymous access to bypass checks in IIS and lets ASP.NET handle the authentication directly)</p>\n\n<p>This case is a bit more complicated.</p>\n\n<p>You should go to IIS and disable all forms of authentication other than \"Anonymous Access\". Note that you can't do that in the developer's box, because the debugger needs Integrated Authentication to be enabled. So your debugging box will behave a bit different than the real server; just be aware of that.</p>\n\n<p>Then, you need to decide whether you should turn impersonation OFF, or conversely, to specify the account to impersonate in the web.config. Do the first if your web server doesn't need outside resources (like a database). Do the latter if your web site does need to run under an account that has access to a database (or some other outside resource).</p>\n\n<p>You have two more alternatives to specify the account to impersonate. One, you could go to IIS and change the \"anonymous\" account to be one with access to the resource instead of the one IIS manages for you. The second alternative is to stash the account and password encrypted in the registry. That step is a bit complicated and also goes beyond the scope of this discussion.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 14747986,
"author": "Mike Gledhill",
"author_id": 391605,
"author_profile": "https://Stackoverflow.com/users/391605",
"pm_score": 1,
"selected": false,
"text": "<p>I was having the same problem with one of my ASP.Net applications. I was getting <strong>Path.GetTempPath()</strong> but it was throwing an exception of:</p>\n\n<p><em>\"Could not write to file \"C:\\Windows\\Temp\\somefilename\", exception: Access to the path \"C:\\Windows\\Temp\\somefilename\" is denied.\"</em></p>\n\n<p>I tried a few suggestions on this page, but nothing helped.</p>\n\n<p>In the end, I went onto the web server (IIS server) and changed permissions on the server's \"C:\\Windows\\Temp\" directory to give the \"Everyone\" user full read-write permissions.</p>\n\n<p>And then, finally, the exception went away, and my users could download files from the application. Phew!</p>\n"
},
{
"answer_id": 45310564,
"author": "Brian",
"author_id": 203190,
"author_profile": "https://Stackoverflow.com/users/203190",
"pm_score": 2,
"selected": false,
"text": "<p>I encountered this error while diagnosing a console app that was writing in temp files. In one of my test iterations I purged all the files/directories in temp for a 'clean-slate' run. I resolved this self inflicted issue by logging out and back in again.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5678/"
] | Running into a problem where on certain servers we get an error that the directory name is invalid when using Path.GetTempFileName. Further investigation shows that it is trying to write a file to c:\Documents and Setting\computername\aspnet\local settings\temp (found by using Path.GetTempPath). This folder exists so I'm assuming this must be a permissions issue with respect to the asp.net account.
I've been told by some that Path.GetTempFileName should be pointing to C:\Windows\Microsoft.NET\Framework\v2.0.50727\temporaryasp.net files.
I've also been told that this problem may be due to the order in which IIS and .NET where installed on the server. I've done the typical 'aspnet\_regiis -i' and checked security on the folders etc. At this point I'm stuck.
Can anyone shed some light on this?
\*\*Update:\*\*Turns out that providing 'IUSR\_ComputerName' access to the folder does the trick. Is that the correct procedure? I don't seem to recall doing that in the past, and obviously, want to follow best practices to maintain security. This is, after all, part of a file upload process. | This is probably a combination of impersonation and a mismatch of different authentication methods occurring.
There are many pieces; I'll try to go over them one by one.
**Impersonation** is a technique to "temporarily" switch the user account under which a thread is running. Essentially, the thread briefly gains the same rights and access -- no more, no less -- as the account that is being impersonated. As soon as the thread is done creating the web page, it "reverts" back to the original account and gets ready for the next call. This technique is used to access resources that only the user logged into your web site has access to. Hold onto the concept for a minute.
Now, by default ASP.NET runs a web site under a local account called **ASPNET**. Again, by default, only the ASPNET account and members of the Administrators group can write to that folder. Your temporary folder is under that account's purview. This is the second piece of the puzzle.
Impersonation doesn't happen on its own. It needs to be turn on intentionally in your web.config.
```
<identity impersonate="true" />
```
If the setting is missing or set to false, your code will execute pure and simply under the ASPNET account mentioned above. Given your error message, I'm positive that you have impersonation=true. There is nothing wrong with that! Impersonation has advantages and disadvantages that go beyond this discussion.
There is one question left: when you use impersonation, *which account gets impersonated*?
Unless you specify the account in the web.config ([full syntax of the identity element here](http://msdn.microsoft.com/en-us/library/72wdk8cc.aspx)), the account impersonated is the one that the IIS handed over to ASP.NET. And that depends on how the user has authenticated (or not) into the site. That is your third and final piece.
The IUSR\_ComputerName account is a low-rights account created by IIS. By default, this account is the account under which a web call runs **if the user could not be authenticated**. That is, the user comes in as an "anonymous".
In summary, this is what is happening to you:
Your user is trying to access the web site, and IIS could not authenticate the person for some reason. Because Anonymous access is ON, (or you would not see IUSRComputerName accessing the temp folder), IIS allows the user in anyway, but as a generic user. Your ASP.NET code runs and impersonates this generic IUSR\_\_\_ComputerName "guest" account; only now the code doesn't have access to the things that the ASPNET account had access to, including its own temporary folder.
Granting IUSR\_ComputerName WRITE access to the folder makes your symptoms go away.
But that just the symptoms. You need to review **why is the person coming as "Anonymous/Guest"?**
There are two likely scenarios:
a) You intended to use IIS for authentication, but the authentication settings in IIS for some of your servers are wrong.
In that case, you need to disable Anonymous access on those servers so that the usual authentication mechanisms take place. Note that you might still need to grant to your users access to that temporary folder, or use another folder instead, one to which your users already have access.
I have worked with this scenario many times, and quite frankly it gives you less headaches to forgo the Temp folder; create a dedicated folder in the server, set the proper permissions, and set its location in web.config.
b) You didn't want to authenticate people anyway, or you wanted to use ASP.NET Forms Authentication (which uses IIS's Anonymous access to bypass checks in IIS and lets ASP.NET handle the authentication directly)
This case is a bit more complicated.
You should go to IIS and disable all forms of authentication other than "Anonymous Access". Note that you can't do that in the developer's box, because the debugger needs Integrated Authentication to be enabled. So your debugging box will behave a bit different than the real server; just be aware of that.
Then, you need to decide whether you should turn impersonation OFF, or conversely, to specify the account to impersonate in the web.config. Do the first if your web server doesn't need outside resources (like a database). Do the latter if your web site does need to run under an account that has access to a database (or some other outside resource).
You have two more alternatives to specify the account to impersonate. One, you could go to IIS and change the "anonymous" account to be one with access to the resource instead of the one IIS manages for you. The second alternative is to stash the account and password encrypted in the registry. That step is a bit complicated and also goes beyond the scope of this discussion.
Good luck! |
55,440 | <p>I've a class which is a wrapper class(serves as a common interface) around another class implementing the functionality required. So my code looks like this.</p>
<pre><code>template<typename ImplemenationClass> class WrapperClass {
// the code goes here
}
</code></pre>
<p>Now, how do I make sure that <code>ImplementationClass</code> can be derived from a set of classes only, similar to java's generics</p>
<pre><code><? extends BaseClass>
</code></pre>
<p>syntax?</p>
| [
{
"answer_id": 55444,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 2,
"selected": false,
"text": "<p>In the current state of things, there is no good way other than by comments or a third-party solution. Boost provides a <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/concept_check/concept_check.htm\" rel=\"nofollow noreferrer\">concept check library</a> for this, and I think gcc also has an implementation. Concepts are on the list of C++0x improvements, but I'm not sure if you can specify subtypes - they are more for \"must support these operations\" which is (roughly) equivalent.</p>\n\n<p><strong>Edit:</strong> Wikipedia has this <a href=\"http://en.wikipedia.org/wiki/C%2B%2B0x#Concepts\" rel=\"nofollow noreferrer\">section</a> about concepts in C++0x, which is significantly easier to read than draft proposals.</p>\n"
},
{
"answer_id": 55446,
"author": "Daniel James",
"author_id": 2434,
"author_profile": "https://Stackoverflow.com/users/2434",
"pm_score": 4,
"selected": true,
"text": "<p>It's verbose, but you can do it like this:</p>\n\n<pre><code>#include <boost/utility/enable_if.hpp>\n#include <boost/type_traits/is_base_of.hpp>\n\nstruct base {};\n\ntemplate <typename ImplementationClass, class Enable = void>\nclass WrapperClass;\n\ntemplate <typename ImplementationClass>\nclass WrapperClass<ImplementationClass,\n typename boost::enable_if<\n boost::is_base_of<base,ImplementationClass> >::type>\n{};\n\nstruct derived : base {};\nstruct not_derived {};\n\nint main() {\n WrapperClass<derived> x;\n\n // Compile error here:\n WrapperClass<not_derived> y;\n}\n</code></pre>\n\n<p>This requires a compiler with good support for the standard (most recent compilers should be fine but old versions of Visual C++ won't be). For more information, see the <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/utility/enable_if.html\" rel=\"nofollow noreferrer\">Boost.Enable_If documentation</a>.</p>\n\n<p>As Ferruccio said, a simpler but less powerful implementation:</p>\n\n<pre><code>#include <boost/static_assert.hpp>\n#include <boost/type_traits/is_base_of.hpp>\n\nstruct base {};\n\ntemplate <typename ImplementationClass>\nclass WrapperClass\n{\n BOOST_STATIC_ASSERT((\n boost::is_base_of<base, ImplementationClass>::value));\n};\n</code></pre>\n"
},
{
"answer_id": 56551,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 0,
"selected": false,
"text": "<p>See <a href=\"http://www.research.att.com/~bs/bs_faq2.html#constraints\" rel=\"nofollow noreferrer\">Stoustrup's own words on the subject</a>.</p>\n\n<p>Basically a small class, that you instantiate somewhere, e.g. the templated classes constructor.</p>\n\n<pre><code>template<class T, class B> struct Derived_from {\n static void constraints(T* p) { B* pb = p; }\n Derived_from() { void(*p)(T*) = constraints; }\n};\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108465/"
] | I've a class which is a wrapper class(serves as a common interface) around another class implementing the functionality required. So my code looks like this.
```
template<typename ImplemenationClass> class WrapperClass {
// the code goes here
}
```
Now, how do I make sure that `ImplementationClass` can be derived from a set of classes only, similar to java's generics
```
<? extends BaseClass>
```
syntax? | It's verbose, but you can do it like this:
```
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_base_of.hpp>
struct base {};
template <typename ImplementationClass, class Enable = void>
class WrapperClass;
template <typename ImplementationClass>
class WrapperClass<ImplementationClass,
typename boost::enable_if<
boost::is_base_of<base,ImplementationClass> >::type>
{};
struct derived : base {};
struct not_derived {};
int main() {
WrapperClass<derived> x;
// Compile error here:
WrapperClass<not_derived> y;
}
```
This requires a compiler with good support for the standard (most recent compilers should be fine but old versions of Visual C++ won't be). For more information, see the [Boost.Enable\_If documentation](http://www.boost.org/doc/libs/1_36_0/libs/utility/enable_if.html).
As Ferruccio said, a simpler but less powerful implementation:
```
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_base_of.hpp>
struct base {};
template <typename ImplementationClass>
class WrapperClass
{
BOOST_STATIC_ASSERT((
boost::is_base_of<base, ImplementationClass>::value));
};
``` |
55,449 | <p>I sometimes use the feature 'Reconcile Offline Work...' found in Perforce's P4V IDE to sync up any files that I have been working on while disconnected from the P4 depot. It launches another window that performs a 'Folder Diff'.</p>
<p>I have files I never want to check in to source control (like ones found in bin folder such as DLLs, code generated output, etc.) Is there a way to filter those files/folders out from appearing as "new" that might be added. They tend to clutter up the list of files that I am actually interested in. Does P4 have the equivalent of Subversion's 'ignore file' feature? </p>
| [
{
"answer_id": 55509,
"author": "raven",
"author_id": 4228,
"author_profile": "https://Stackoverflow.com/users/4228",
"pm_score": 7,
"selected": true,
"text": "<p>As of version 2012.1, Perforce supports the <code>P4IGNORE</code> environment variable. I updated my answer to <a href=\"https://stackoverflow.com/a/3103898/4228\">this question about ignoring directories</a> with an explanation of how it works. Then I noticed this answer, which is now superfluous I guess.</p>\n\n<hr>\n\n<p>Assuming you have a client named \"CLIENT\", a directory named \"foo\" (located at your project root), and you wish to ignore all .dll files in that directory tree, you can add the following lines to your workspace view to accomplish this:</p>\n\n<pre>\n-//depot/foo/*.dll //CLIENT/foo/*.dll\n-//depot/foo/.../*.dll //CLIENT/foo/.../*.dll\n</pre>\n\n<p>The first line removes them from the directory \"foo\" and the second line removes them from all sub directories. Now, when you 'Reconcile Offline Work...', all the .dll files will be moved into \"Excluded Files\" folders at the bottom of the folder diff display. They will be out of your way, but can still view and manipulate them if you really need to.</p>\n\n<p>You can also do it another way, which will reduce your \"Excluded Files\" folder to just one, but you won't be able to manipulate any of the files it contains because the path will be corrupt (but if you just want them out of your way, it doesn't matter).</p>\n\n<pre>\n-//depot/foo.../*.dll //CLIENT/foo.../*.dll\n</pre>\n"
},
{
"answer_id": 56498,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 2,
"selected": false,
"text": "<p>Will's suggestion of using <code>.p4ignore</code> only seems to work with the WebSphere Studio (P4WSAD) plugin. I just tried it on my local windows box and any files and directories that I listed were <em>not</em> ignored. </p>\n\n<p>Raven's suggestion of modifying your client spec is the correct way under Perforce. Proper organization of your code/data/executables and generated output files will make the process of excluding files from being checked in much easier.</p>\n\n<p>As a more draconian approach, you can always write a submit trigger which will reject submission of change-lists if they contain a certain file or files with a certain extension, etc. </p>\n"
},
{
"answer_id": 2131347,
"author": "Deepak Sarda",
"author_id": 143438,
"author_profile": "https://Stackoverflow.com/users/143438",
"pm_score": -1,
"selected": false,
"text": "<p>If you are using the Eclipse Perforce plugin, then <a href=\"http://perforce.com/perforce/doc.091/manuals/p4wsad/topics/adding.html\" rel=\"nofollow noreferrer\">the plugin documentation</a> lists several ways to ignore files.</p>\n"
},
{
"answer_id": 3021154,
"author": "Mike Burrows",
"author_id": 171757,
"author_profile": "https://Stackoverflow.com/users/171757",
"pm_score": 3,
"selected": false,
"text": "<p>If you want a solution that will apply to all work-spaces without needing to be copied around, you (or your sysadmin) can refuse submission of those file-types through using lines like the below in the p4 protect table:</p>\n\n<pre><code>write user * * -//.../*.suo\nwrite user * * -//.../*.obj\nwrite user * * -//.../*.ccscc\n</code></pre>\n\n<p>I remember doing this before, but I don't have the necessary permissions to test this here. Check out <a href=\"http://www.perforce.com/perforce/doc.092/manuals/p4sag/p4sag.pdf\" rel=\"nofollow noreferrer\">Perforce's Sysadmin guide</a> and try it out</p>\n"
},
{
"answer_id": 3883647,
"author": "Warren P",
"author_id": 84704,
"author_profile": "https://Stackoverflow.com/users/84704",
"pm_score": 2,
"selected": false,
"text": "<p>HISTORICAL ANSWER - no longer correct. At the time this was written originally it was true;</p>\n\n<p>You can not write and check in a file that the server will use to make ignore rules; general glob or regexp file pattern ignore in perforce. </p>\n\n<p>Other answers have global server configurations that are global (and not per folder).\nThe other answers show things that might work for you, if you want one line in your view per folder times number of extensions you want to ignore in that single folder, or that provide this capability in WebSphere Studio plugins only, or provide capability for server administrators, but not available to users.</p>\n\n<p>In short, I find Perforce really weak in this area. While I appreciate that those who use the Eclipse Plugin can use <code>.p4ignore</code>, and I think that's great, it leaves those of us that don't, out in the dark.</p>\n\n<p>UPDATE: See accepted answer for new P4IGNORE capability added mid-2012.</p>\n"
},
{
"answer_id": 4973027,
"author": "kevin cline",
"author_id": 229810,
"author_profile": "https://Stackoverflow.com/users/229810",
"pm_score": 1,
"selected": false,
"text": "<p>I have found it easiest to reconcile offline work using a BASH script like this one:</p>\n\n<pre><code>#!/bin/bash\n# reconcile P4 offline work, assuming P4CLIENT is set\nif [ -z \"$P4CLIENT\" ] ; then echo \"P4CLIENT is not set\"; exit 1; fi\nunset PWD # confuses P4 on Windows/CYGWIN\n\n# delete filew that are no longer present\np4 diff -sd ... | p4 -x - delete\n\n# checkout files that have been changed. \n# I don't run this step. Instead I just checkout everything, \n# then revert unchanged files before committing.\np4 diff -se ... | pr -x - edit\n\n# Add new files, ignoring subversion info, EMACS backups, log files\n# Filter output to see only added files and real errors\nfind . -type f \\\n | grep -v -E '(\\.svn)|(/build.*/)|(/\\.settings)|~|#|(\\.log)' \\\n | p4 -x - add \\\n | grep -v -E '(currently opened for add)|(existing file)|(already opened for edit)'\n</code></pre>\n\n<p>I adapted this from <a href=\"http://kb.perforce.com/article/2\" rel=\"nofollow\">this Perforce Knowledge Base article</a>.</p>\n"
},
{
"answer_id": 6831195,
"author": "Derek Prior",
"author_id": 301059,
"author_profile": "https://Stackoverflow.com/users/301059",
"pm_score": 0,
"selected": false,
"text": "<p>I'm looking for a .p4ignore like solution as well (and not one tied to a particular IDE). Thus far, the closest thing I've found is p4delta. It sounds like it will do exactly what the original poster was asking, albeit through another layer of indirection.</p>\n\n<p><a href=\"http://p4delta.sourceforge.net\" rel=\"nofollow\">http://p4delta.sourceforge.net</a></p>\n\n<p>Unfortunately, while this does seem to produce the proper list of files, I can't get \"p4delta --execute\" to work (\"Can't modify a frozen string\") and the project has not been updated in year. Perhaps others will have better luck.</p>\n"
},
{
"answer_id": 9286380,
"author": "svec",
"author_id": 103,
"author_profile": "https://Stackoverflow.com/users/103",
"pm_score": 5,
"selected": false,
"text": "<p>This works as of Perforce 2013.1, the new P4IGNORE mechanism was first added in release, 2012.1, described on the Perforce blog here:</p>\n\n<blockquote>\n <p><a href=\"https://www.perforce.com/blog/new-20121-p4ignore\" rel=\"nofollow noreferrer\">https://www.perforce.com/blog/new-20121-p4ignore</a></p>\n</blockquote>\n\n<p>As it's currently described, you set an environment variable \"P4IGNORE\" to a filename which contains a list of the files to ignore.</p>\n\n<p>So you can check it out to see how you like it.</p>\n"
},
{
"answer_id": 9538265,
"author": "Chance",
"author_id": 382186,
"author_profile": "https://Stackoverflow.com/users/382186",
"pm_score": 3,
"selected": false,
"text": "<p>Perforce Streams makes ignoring files much easier, as of version 2011.1. According to the <a href=\"http://www.perforce.com/perforce/doc.current/manuals/cmdref/stream.html\" rel=\"nofollow\">documentation,</a> you can ignore certain extensions or certain paths in your directory. </p>\n\n<p>From <code>p4 help stream</code></p>\n\n<pre><code>Ignored: Optional; a list of file or directory names to be ignored in\n client views. For example:\n\n /tmp # ignores files named 'tmp'\n /tmp/... # ignores dirs named 'tmp'\n .tmp # ignores file names ending in '.tmp'\n\n Lines in the Ignored field may appear in any order. Ignored\n names are inherited by child stream client views.\n</code></pre>\n\n<p>This essentially does what @raven's answer specifies, but is done easier with streams, as it automatically propagates to every work-space using that stream. It also applies to any streams inheriting from the stream in which you specify the ignore types.</p>\n\n<p>You can edit the stream via <code>p4 stream //stream_depot/stream_name</code> or right-clicking the stream in p4v's stream view. </p>\n\n<p>And as @svec noted, the ability to specify ignore files per workspace is coming soon, and is in fact in <a href=\"http://www.perforce.com/blog/120130/new-20121-p4ignore\" rel=\"nofollow\">P4 2012.1 beta.</a></p>\n"
},
{
"answer_id": 13126496,
"author": "Colonel Panic",
"author_id": 284795,
"author_profile": "https://Stackoverflow.com/users/284795",
"pm_score": 6,
"selected": false,
"text": "<p>Yes, But.</p>\n\n<p>Perforce version 2012.1 added a feature known as <a href=\"http://www.perforce.com/blog/120130/new-20121-p4ignore\">p4ignore</a>, inspired by Git. However the Perforce developers made a change to the behaviour, without justification, that happens to make the feature a lot less useful.</p>\n\n<p>Whilst Git takes rules from all <a href=\"https://www.kernel.org/pub/software/scm/git/docs/gitignore.html\"><code>.gitignore</code></a> files, Perforce doesn't know where to look until you specify a filename in an environment variable <code>P4IGNORE</code>. This freedom is a curse. You can't hack on two repositories that use different names for their ignore files. </p>\n\n<p>Also, Perforce's ignore feature doesn't work out the box. You can set it up easily enough for yourself, but others don't benefit unless they explicitly opt-in. A contributor who hasn't may accidentally commit unwelcome files (eg. a <code>bin</code> folder created by a build script).</p>\n\n<p>Git's ignore feature is great because it works out the box. If the <code>.gitignore</code> files are added to the repository (<a href=\"https://github.com/search?q=extension%3A.gitignore\">everyone does this</a>), they'll work out the box for everyone. No-one will accidentally publish their private key.</p>\n\n<p>Amusingly, the <a href=\"http://www.perforce.com/perforce/doc.current/manuals/cmdref/env.P4IGNORE.html\">Perforce docs</a> shows '.p4ignore' as an example ignore rule, which is backwards! If the rules are useful, they should be shared as part of the repository. </p>\n\n<hr>\n\n<p>Perforce could still make good on the feature. Choose a convention for the file names, say <code>p4ignore.txt</code>, so the feature works out the box. Drop the <code>P4IGNORE</code> environment variable, it's counterproductive. Edit the docs, to encourage developers to share useful rules. Let users write personal rules in a file in their home folder, <a href=\"https://www.kernel.org/pub/software/scm/git/docs/gitignore.html\">as Git does</a>.</p>\n\n<p>If you know anyone at Perforce, please email them this post.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | I sometimes use the feature 'Reconcile Offline Work...' found in Perforce's P4V IDE to sync up any files that I have been working on while disconnected from the P4 depot. It launches another window that performs a 'Folder Diff'.
I have files I never want to check in to source control (like ones found in bin folder such as DLLs, code generated output, etc.) Is there a way to filter those files/folders out from appearing as "new" that might be added. They tend to clutter up the list of files that I am actually interested in. Does P4 have the equivalent of Subversion's 'ignore file' feature? | As of version 2012.1, Perforce supports the `P4IGNORE` environment variable. I updated my answer to [this question about ignoring directories](https://stackoverflow.com/a/3103898/4228) with an explanation of how it works. Then I noticed this answer, which is now superfluous I guess.
---
Assuming you have a client named "CLIENT", a directory named "foo" (located at your project root), and you wish to ignore all .dll files in that directory tree, you can add the following lines to your workspace view to accomplish this:
```
-//depot/foo/*.dll //CLIENT/foo/*.dll
-//depot/foo/.../*.dll //CLIENT/foo/.../*.dll
```
The first line removes them from the directory "foo" and the second line removes them from all sub directories. Now, when you 'Reconcile Offline Work...', all the .dll files will be moved into "Excluded Files" folders at the bottom of the folder diff display. They will be out of your way, but can still view and manipulate them if you really need to.
You can also do it another way, which will reduce your "Excluded Files" folder to just one, but you won't be able to manipulate any of the files it contains because the path will be corrupt (but if you just want them out of your way, it doesn't matter).
```
-//depot/foo.../*.dll //CLIENT/foo.../*.dll
``` |
55,482 | <p>I'm able to successfully uninstall a third-party application via the command line and via a custom Inno Setup installer. </p>
<p>Command line Execution:</p>
<pre><code>MSIEXEC.exe /x {14D74337-01C2-4F8F-B44B-67FC613E5B1F} /qn
</code></pre>
<p>Inno Setup Command:</p>
<pre><code>[Run]
Filename: msiexec.exe; Flags: runhidden waituntilterminated;
Parameters: "/x {{14D74337-01C2-4F8F-B44B-67FC613E5B1F} /qn";
StatusMsg: "Uninstalling Service...";
</code></pre>
<p>I am also able to uninstall the application programmatically when executing the following C# code in debug mode.</p>
<p>C# Code:</p>
<pre><code>string fileName = "MSIEXEC.exe";
string arguments = "/x {14D74337-01C2-4F8F-B44B-67FC613E5B1F} /qn";
ProcessStartInfo psi = new ProcessStartInfo(fileName, arguments)
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true
};
Process process = Process.Start(psi);
string errorMsg = process.StandardOutput.ReadToEnd();
process.WaitForExit();
</code></pre>
<p>The same C# code, however, produces the following failure output when run as a compiled, deployed Windows Service: </p>
<pre><code>"This action is only valid for products that are currently installed."
</code></pre>
<p>Additional Comments:</p>
<ul>
<li>The Windows Service which is issuing
the uninstall command is running on
the same machine as the code being
tested in Debug Mode. The Windows
Service is running/logged on as the
Local system account. </li>
<li>I have consulted my application logs
and I have validated that the
executed command arguments are thhe
same in both debug and release mode.</li>
<li>I have consulted the Event Viewer
but it doesn't offer any clues.</li>
</ul>
<p>Thoughts? Any help would be greatly appreciated. Thanks.</p>
| [
{
"answer_id": 55496,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Step 1:</strong> <a href=\"https://stackoverflow.com/questions/15109/visual-studio-2005-setup-project-install-crashes-over-terminal-server#15286\">Check the MSI error log files</a></p>\n\n<p>I'm suspicious that your problem is due to running as LocalSystem. </p>\n\n<p>The Local System account is not the same as a normal user account which happens to have admin rights. It has no access to the network, and its interaction with the registry and file system is quite different.</p>\n\n<p>From memory any requests to read/write to your 'home directory' or HKCU under the registry actually go into either the default user profile, or in the case of temp dirs, <code>c:\\windows\\temp</code></p>\n"
},
{
"answer_id": 55571,
"author": "saschabeaumont",
"author_id": 592,
"author_profile": "https://Stackoverflow.com/users/592",
"pm_score": 2,
"selected": false,
"text": "<p>I've come across similar problems in the past with installation, a customer was using the SYSTEM account to install and this was causing all sorts of permission problems for non-administrative users. </p>\n\n<p>MSI log files aren't really going to help if the application doesn't appear \"installed\", I'd suggest starting with capturing the output of <code>MSIINV.EXE</code> under the system account, that will get you an \"Inventory\" of the currently installed programs (or what that user sees installed) <a href=\"http://blogs.msdn.com/brada/archive/2005/06/24/432209.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/brada/archive/2005/06/24/432209.aspx</a></p>\n\n<p>I think you probably need to go back to the drawing board and see if you really need the windows service to do the uninstall. You'll probably come across all sorts of Vista UAC issues if you haven't already...</p>\n"
},
{
"answer_id": 57801,
"author": "Ben Griswold",
"author_id": 4115,
"author_profile": "https://Stackoverflow.com/users/4115",
"pm_score": 2,
"selected": true,
"text": "<p>Thanks to those offering help. This appears to be a permissions issue. I have updated my service to run under an Administrator account and it was able to successfully uninstall the third-party application. To Orion's point, though the Local System account is a powerful account that has full access to the system -- <a href=\"http://technet.microsoft.com/en-us/library/cc782435.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/library/cc782435.aspx</a> -- it doesn't seem to have the necessary rights to perform the uninstall.</p>\n\n<p>[See additional comments for full story regarding the LocalSystem being able to uninstall application for which it installed.]</p>\n"
},
{
"answer_id": 58197,
"author": "Paul Lalonde",
"author_id": 5782,
"author_profile": "https://Stackoverflow.com/users/5782",
"pm_score": 0,
"selected": false,
"text": "<p>This is bizarre. LocalSystem definitely has the privileges to install applications (that's how Windows Update and software deployment in Active Directory work), so it should be able to uninstall as well.</p>\n\n<p>Perhaps the application is initially installed per-user instead of per-machine?</p>\n"
},
{
"answer_id": 60079,
"author": "Ben Griswold",
"author_id": 4115,
"author_profile": "https://Stackoverflow.com/users/4115",
"pm_score": 0,
"selected": false,
"text": "<p>@Paul Lalonde</p>\n\n<p>The app's installer is wrapped within a custom InnoSetup Installer. The InnoSetup installer, in turn, is manually executed by the logged in user. That said, the uninstall is trigged by a service running under the Local System account. </p>\n\n<p>Apparently, you were on to something. I put together a quick test which had the service running under the LocalSystem account install as well as uninstall the application and everything worked flawlessly. You were correct. The LocalSystem account has required uninstall permissions for applications in which it installs. You saved the day. Thanks for the feedback! </p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4115/"
] | I'm able to successfully uninstall a third-party application via the command line and via a custom Inno Setup installer.
Command line Execution:
```
MSIEXEC.exe /x {14D74337-01C2-4F8F-B44B-67FC613E5B1F} /qn
```
Inno Setup Command:
```
[Run]
Filename: msiexec.exe; Flags: runhidden waituntilterminated;
Parameters: "/x {{14D74337-01C2-4F8F-B44B-67FC613E5B1F} /qn";
StatusMsg: "Uninstalling Service...";
```
I am also able to uninstall the application programmatically when executing the following C# code in debug mode.
C# Code:
```
string fileName = "MSIEXEC.exe";
string arguments = "/x {14D74337-01C2-4F8F-B44B-67FC613E5B1F} /qn";
ProcessStartInfo psi = new ProcessStartInfo(fileName, arguments)
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true
};
Process process = Process.Start(psi);
string errorMsg = process.StandardOutput.ReadToEnd();
process.WaitForExit();
```
The same C# code, however, produces the following failure output when run as a compiled, deployed Windows Service:
```
"This action is only valid for products that are currently installed."
```
Additional Comments:
* The Windows Service which is issuing
the uninstall command is running on
the same machine as the code being
tested in Debug Mode. The Windows
Service is running/logged on as the
Local system account.
* I have consulted my application logs
and I have validated that the
executed command arguments are thhe
same in both debug and release mode.
* I have consulted the Event Viewer
but it doesn't offer any clues.
Thoughts? Any help would be greatly appreciated. Thanks. | Thanks to those offering help. This appears to be a permissions issue. I have updated my service to run under an Administrator account and it was able to successfully uninstall the third-party application. To Orion's point, though the Local System account is a powerful account that has full access to the system -- <http://technet.microsoft.com/en-us/library/cc782435.aspx> -- it doesn't seem to have the necessary rights to perform the uninstall.
[See additional comments for full story regarding the LocalSystem being able to uninstall application for which it installed.] |
55,502 | <p>I have an object in a multi-threaded environment that maintains a collection of information, e.g.:</p>
<pre><code>public IList<string> Data
{
get
{
return data;
}
}
</code></pre>
<p>I currently have <code>return data;</code> wrapped by a <code>ReaderWriterLockSlim</code> to protect the collection from sharing violations. However, to be doubly sure, I'd like to return the collection as read-only, so that the calling code is unable to make changes to the collection, only view what's already there. Is this at all possible? </p>
| [
{
"answer_id": 55507,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 6,
"selected": true,
"text": "<p>If your underlying data is stored as list you can use <a href=\"http://msdn.microsoft.com/en-us/library/e78dcd75.aspx\" rel=\"noreferrer\">List(T).AsReadOnly</a> method.<br>\nIf your data can be enumerated, you can use <a href=\"http://msdn.microsoft.com/en-us/library/bb342261.aspx\" rel=\"noreferrer\">Enumerable.ToList</a> method to cast your collection to List and call AsReadOnly on it.</p>\n"
},
{
"answer_id": 55551,
"author": "Kris Erickson",
"author_id": 3798,
"author_profile": "https://Stackoverflow.com/users/3798",
"pm_score": 2,
"selected": false,
"text": "<p>One should note that <a href=\"https://stackoverflow.com/questions/55502/return-collection-as-read-only#55507\">aku</a>'s answer will only protect the list as being read only. Elements in the list are still very writable. I don't know if there is any way of protecting non-atomic elements without cloning them before placing them in the read only list. </p>\n"
},
{
"answer_id": 55661,
"author": "nedruod",
"author_id": 5504,
"author_profile": "https://Stackoverflow.com/users/5504",
"pm_score": 4,
"selected": false,
"text": "<p>If your only intent is to get calling code to not make a mistake, and modify the collection when it should only be reading all that is necessary is to return an interface which doesn't support Add, Remove, etc.. Why not return <code>IEnumerable<string></code>? Calling code would have to cast, which they are unlikely to do without knowing the internals of the property they are accessing.</p>\n\n<p>If however your intent is to prevent the calling code from observing updates from other threads you'll have to fall back to solutions already mentioned, to perform a deep or shallow copy depending on your need.</p>\n"
},
{
"answer_id": 59545,
"author": "Daniel Fortunov",
"author_id": 5975,
"author_profile": "https://Stackoverflow.com/users/5975",
"pm_score": 4,
"selected": false,
"text": "<p>I think you're confusing concepts here.</p>\n\n<p>The <code>ReadOnlyCollection</code> provides a read-only wrapper for an existing collection, allowing you (Class A) to pass out a reference to the collection safe in the knowledge that the caller (Class B) cannot modify the collection (i.e. cannot <strong>add</strong> or <strong>remove</strong> any elements from the collection.)</p>\n\n<p>There are absolutely no thread-safety guarantees.</p>\n\n<ul>\n<li>If you (Class A) continue to modify the underlying collection after you hand it out as a <code>ReadOnlyCollection</code> then class B will see these changes, have any iterators invalidated, etc. and generally be open to any of the usual concurrency issues with collections.</li>\n<li>Additionally, if the elements within the collection are mutable, both you (Class A) <strong>and</strong> the caller (Class B) will be able to change any mutable state of the objects within the collection.</li>\n</ul>\n\n<p>Your implementation depends on your needs:\n - If you don't care about the caller (Class B) from seeing any further changes to the collection then you can just clone the collection, hand it out, and stop caring.\n - If you definitely need the caller (Class B) to see changes that are made to the collection, and you want this to be thread-safe, then you have more of a problem on your hands. One possibility is to implement your own thread-safe variant of the ReadOnlyCollection to allow locked access, though this will be non-trivial and non-performant if you want to support IEnumerable, and it <em>still</em> won't protect you against mutable elements in the collection.</p>\n"
},
{
"answer_id": 110479,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a copy of the collection instead.</p>\n\n<pre><code>public IList<string> Data {\nget {\n return new List<T>(data);\n}}\n</code></pre>\n\n<p>That way it doesn't matter if it gets updated.</p>\n"
},
{
"answer_id": 110515,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 2,
"selected": false,
"text": "<p>You want to use the <a href=\"http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx\" rel=\"nofollow noreferrer\">yield</a> keyword. You loop through the IEnumerable list and return the results with yeild. This allows the consumer to use the for each without modifying the collection.</p>\n\n<p>It would look something like this:</p>\n\n<pre><code>List<string> _Data;\npublic IEnumerable<string> Data\n{\n get\n {\n foreach(string item in _Data)\n {\n return yield item;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1931338,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 4,
"selected": false,
"text": "<p>I voted for your accepted answer and agree with it--however might I give you something to consider?</p>\n\n<p>Don't return a collection directly. Make an accurately named business logic class that reflects the purpose of the collection.</p>\n\n<p>The main advantage of this comes in the fact that you can't add code to collections so whenever you have a native \"collection\" in your object model, you ALWAYS have non-OO support code spread throughout your project to access it.</p>\n\n<p>For instance, if your collection was invoices, you'd probably have 3 or 4 places in your code where you iterated over unpaid invoices. You could have a getUnpaidInvoices method. However, the real power comes in when you start to think of methods like \"payUnpaidInvoices(payer, account);\".</p>\n\n<p>When you pass around collections instead of writing an object model, entire classes of refactorings will never occur to you.</p>\n\n<p>Note also that this makes your problem particularly nice. If you don't want people changing the collections, your container need contain no mutators. If you decide later that in just one case you actually HAVE to modify it, you can create a safe mechanism to do so.</p>\n\n<p>How do you solve that problem when you are passing around a native collection?</p>\n\n<p>Also, native collections can't be enhanced with extra data. You'll recognize this next time you find that you pass in (Collection, Extra) to more than one or two methods. It indicates that \"Extra\" belongs with the object containing your collection.</p>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5296/"
] | I have an object in a multi-threaded environment that maintains a collection of information, e.g.:
```
public IList<string> Data
{
get
{
return data;
}
}
```
I currently have `return data;` wrapped by a `ReaderWriterLockSlim` to protect the collection from sharing violations. However, to be doubly sure, I'd like to return the collection as read-only, so that the calling code is unable to make changes to the collection, only view what's already there. Is this at all possible? | If your underlying data is stored as list you can use [List(T).AsReadOnly](http://msdn.microsoft.com/en-us/library/e78dcd75.aspx) method.
If your data can be enumerated, you can use [Enumerable.ToList](http://msdn.microsoft.com/en-us/library/bb342261.aspx) method to cast your collection to List and call AsReadOnly on it. |
55,503 | <p>I have a main asp.net app, which is written in asp.net 1.1. Runnning underneath the application are several 2.0 apps. To completely logout a user can I just logout of the 1.1 app with FormsAuthentication.SignOut or is it more complicated than that?</p>
| [
{
"answer_id": 55554,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 0,
"selected": false,
"text": "<p>It could be easier if you are having a central session store for all your applications. You can then set the session to null in one place.</p>\n"
},
{
"answer_id": 55575,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 4,
"selected": true,
"text": "<p>What you are looking to do is called Single Sign On and Single Sign Off. There are differences based on how you have the applications set up. I will try to clarify where those differences come into play.</p>\n\n<p>To implement single sign on and single sign off you need to make the cookie name, protection, and path attributes the same between all the applications.</p>\n\n<pre><code><authentication mode=\"Forms\">\n <forms name=\".cookiename\"\n loginUrl=\"~/Login.aspx\" \n timeout=\"30\" \n path=\"/\" />\n</authentication>\n</code></pre>\n\n<p>Next you need to add the machine keys and they need to be the same between all your applications.</p>\n\n<pre><code><machineKey validationKey=\"F9D1A2D3E1D3E2F7B3D9F90FF3965ABDAC304902\"\n encryptionKey=\"F9D1A2D3E1D3E2F7B3D9F90FF3965ABDAC304902F8D923AC\"\n validation=\"SHA1\" />\n</code></pre>\n\n<p>Are you using second or third level domains for the applications? If so you will need to do a little bit more by adding the domain to the cookie:</p>\n\n<pre><code>protected void Login(string userName, string password)\n{\n System.Web.HttpCookie cookie = FormsAuthentication.GetAuthCookie(userName, False);\n cookie.Domain = \"domain1.com\";\n cookie.Expires = DateTime.Now.AddDays(30);\n Response.AppendCookie(cookie);\n}\n</code></pre>\n\n<p>Now to do single sign off, calling FormsAuthentication.SignOut may not be enough. The next best thing is to set the cookie expiration to a past date. This will ensure that the cookie will not be used again for authentication.</p>\n\n<pre><code>protected void Logout(string userName)\n{\n System.Web.HttpCookie cookie = FormsAuthentication.GetAuthCookie(userName, False);\n cookie.Domain = \"domain1.com\";\n cookie.Expires = DateTime.Now.AddDays(-1);\n Response.AppendCookie(cookie);\n}\n</code></pre>\n\n<p>I am taking into consideration you are using the same database for all the applications. If the applications use a separate database for registration and authentication, then we will need to do some more. Just let me know if this is the case. Otherwise this should work for you.</p>\n"
},
{
"answer_id": 2280558,
"author": "Praveen",
"author_id": 269222,
"author_profile": "https://Stackoverflow.com/users/269222",
"pm_score": 0,
"selected": false,
"text": "<p>This worked for me:</p>\n\n<p>In the Logout event, instead of FormsAuthentication.GetAuthCookie method use Cookies collection in Request object as below:</p>\n\n<pre><code>HttpCookie cookie = Request.Cookies.Get(otherSiteCookieName);\ncookie.Expires = DateTime.Now.AddDays(-1);\nHttpContext.Current.Response.Cookies.Add(cookie);\n</code></pre>\n\n<p>Ofcourse, this requires u know the Cookie name of the site(s) you want the user to be logged out - which however won't be a problem if you are using the same cookie across all the web apps.</p>\n"
},
{
"answer_id": 3150917,
"author": "Daniel Steigerwald",
"author_id": 233902,
"author_profile": "https://Stackoverflow.com/users/233902",
"pm_score": 0,
"selected": false,
"text": "<p>I prefer to use web.config</p>\n\n<pre><code><authentication mode=\"Forms\">\n <forms domain=\".tv.loc\" loginUrl=\"~/signin\" timeout=\"2880\" name=\"auth\" />\n</authentication>\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4888/"
] | I have a main asp.net app, which is written in asp.net 1.1. Runnning underneath the application are several 2.0 apps. To completely logout a user can I just logout of the 1.1 app with FormsAuthentication.SignOut or is it more complicated than that? | What you are looking to do is called Single Sign On and Single Sign Off. There are differences based on how you have the applications set up. I will try to clarify where those differences come into play.
To implement single sign on and single sign off you need to make the cookie name, protection, and path attributes the same between all the applications.
```
<authentication mode="Forms">
<forms name=".cookiename"
loginUrl="~/Login.aspx"
timeout="30"
path="/" />
</authentication>
```
Next you need to add the machine keys and they need to be the same between all your applications.
```
<machineKey validationKey="F9D1A2D3E1D3E2F7B3D9F90FF3965ABDAC304902"
encryptionKey="F9D1A2D3E1D3E2F7B3D9F90FF3965ABDAC304902F8D923AC"
validation="SHA1" />
```
Are you using second or third level domains for the applications? If so you will need to do a little bit more by adding the domain to the cookie:
```
protected void Login(string userName, string password)
{
System.Web.HttpCookie cookie = FormsAuthentication.GetAuthCookie(userName, False);
cookie.Domain = "domain1.com";
cookie.Expires = DateTime.Now.AddDays(30);
Response.AppendCookie(cookie);
}
```
Now to do single sign off, calling FormsAuthentication.SignOut may not be enough. The next best thing is to set the cookie expiration to a past date. This will ensure that the cookie will not be used again for authentication.
```
protected void Logout(string userName)
{
System.Web.HttpCookie cookie = FormsAuthentication.GetAuthCookie(userName, False);
cookie.Domain = "domain1.com";
cookie.Expires = DateTime.Now.AddDays(-1);
Response.AppendCookie(cookie);
}
```
I am taking into consideration you are using the same database for all the applications. If the applications use a separate database for registration and authentication, then we will need to do some more. Just let me know if this is the case. Otherwise this should work for you. |
55,506 | <p>As part of my integration strategy, I have a few SQL scripts that run in order to update the database. The first thing all of these scripts do is check to see if they need to run, e.g.:</p>
<pre><code>if @version <> @expects
begin
declare @error varchar(100);
set @error = 'Invalid version. Your version is ' + convert(varchar, @version) + '. This script expects version ' + convert(varchar, @expects) + '.';
raiserror(@error, 10, 1);
end
else
begin
...sql statements here...
end
</code></pre>
<p>Works great! Except if I need to add a stored procedure. The "create proc" command must be the only command in a batch of sql commands. Putting a "create proc" in my IF statement causes this error:</p>
<pre>
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
</pre>
<p>Ouch! How do I put the CREATE PROC command in my script, and have it only execute if it needs to?</p>
| [
{
"answer_id": 55546,
"author": "Josh Hinman",
"author_id": 2527,
"author_profile": "https://Stackoverflow.com/users/2527",
"pm_score": 6,
"selected": true,
"text": "<p>Here's what I came up with:</p>\n\n<p>Wrap it in an EXEC(), like so:</p>\n\n<pre><code>if @version <> @expects\n begin\n ...snip...\n end\nelse\n begin\n exec('CREATE PROC MyProc AS SELECT ''Victory!''');\n end\n</code></pre>\n\n<p>Works like a charm!</p>\n"
},
{
"answer_id": 55773,
"author": "Anthony K",
"author_id": 1682,
"author_profile": "https://Stackoverflow.com/users/1682",
"pm_score": 3,
"selected": false,
"text": "<p>But watch out for single quotes within your Stored Procedure - they need to be \"escaped\" by adding a second one. The first answer has done this, but just in case you missed it. A trap for young players.</p>\n"
},
{
"answer_id": 55806,
"author": "Peter",
"author_id": 5189,
"author_profile": "https://Stackoverflow.com/users/5189",
"pm_score": 2,
"selected": false,
"text": "<p>Versioning your database is the way to go, but... Why conditionally create stored procedures. For Views, stored procedures, functions, just conditionally drop them and re-create them every time. If you conditionally create, then you will not clean-up databases that have a problem or a hack that got put in 2 years ago by another developer (you or I would never do this) who was sure he would remember to remove the one time emergency update.</p>\n"
},
{
"answer_id": 56002,
"author": "robsoft",
"author_id": 3897,
"author_profile": "https://Stackoverflow.com/users/3897",
"pm_score": 1,
"selected": false,
"text": "<p>I must admit, I would normally agree with @Peter - I conditionally drop and then unconditionally recreate every time. I've been caught out too many times in the past when trying to second-guess the schema differences between databases, with or without any form of version control.</p>\n\n<p>Having said that, your own suggestion @Josh is pretty cool. Certainly interesting. :-)</p>\n"
},
{
"answer_id": 350029,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Problem with dropping and creating is you lose any security grants that had previously been applied to the object being dropped. </p>\n"
},
{
"answer_id": 441970,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>IF NOT EXISTS(SELECT * FROM sys.procedures WHERE name = 'pr_MyStoredProc')\nBEGIN\n\n CREATE PROCEDURE pr_MyStoredProc AS .....\n SET NOCOUNT ON\nEND\n\nALTER PROC pr_MyStoredProc\nAS\nSELECT * FROM tb_MyTable\n</code></pre>\n"
},
{
"answer_id": 441972,
"author": "Jobo",
"author_id": 51915,
"author_profile": "https://Stackoverflow.com/users/51915",
"pm_score": 0,
"selected": false,
"text": "<p>use the 'Exists' command in T-SQL to see if the stored proc exists. If it does, use 'Alter', else use 'Create'</p>\n"
},
{
"answer_id": 9383336,
"author": "DWalker59",
"author_id": 1224123,
"author_profile": "https://Stackoverflow.com/users/1224123",
"pm_score": 2,
"selected": false,
"text": "<p>This is an old thread, but Jobo is incorrect: Create Procedure must be the first statement in a batch. Therefore, you can't use <code>Exists</code> to test for existence and then use either <code>Create</code> or <code>Alter</code>. Pity.</p>\n"
},
{
"answer_id": 36646576,
"author": "Proggear",
"author_id": 5247175,
"author_profile": "https://Stackoverflow.com/users/5247175",
"pm_score": 3,
"selected": false,
"text": "<p>SET NOEXEC ON is good way to switch off some part of code</p>\n\n<pre><code>IF NOT EXISTS (SELECT * FROM sys.assemblies WHERE name = 'SQL_CLR_Functions')\n SET NOEXEC ON\nGO\nCREATE FUNCTION dbo.CLR_CharList_Split(@list nvarchar(MAX), @delim nchar(1) = N',')\nRETURNS TABLE (str nvarchar(4000)) AS EXTERNAL NAME SQL_CLR_Functions.[Granite.SQL.CLR.Functions].CLR_CharList_Split\nGO\nSET NOEXEC OFF\n</code></pre>\n\n<p>Found here:\n<a href=\"https://codereview.stackexchange.com/questions/10490/conditional-create-must-be-the-only-statement-in-the-batch\">https://codereview.stackexchange.com/questions/10490/conditional-create-must-be-the-only-statement-in-the-batch</a></p>\n\n<p>P.S. Another way is SET PARSEONLY { ON | OFF }. </p>\n"
},
{
"answer_id": 49648591,
"author": "Dave Thompson",
"author_id": 1049108,
"author_profile": "https://Stackoverflow.com/users/1049108",
"pm_score": 1,
"selected": false,
"text": "<p>My solution is to check if the proc exists, if so then drop it, and then create the proc (same answer as @robsoft but with an example...)</p>\n\n<pre><code>IF EXISTS(SELECT * FROM sysobjects WHERE Name = 'PROC_NAME' AND xtype='P') \nBEGIN\n DROP PROCEDURE PROC_NAME\nEND\nGO\nCREATE PROCEDURE PROC_NAME\n @value int\nAS\nBEGIN\n UPDATE SomeTable\n SET SomeColumn = 1\n WHERE Value = @value\nEND\nGO\n</code></pre>\n"
},
{
"answer_id": 57115083,
"author": "Display name",
"author_id": 4501035,
"author_profile": "https://Stackoverflow.com/users/4501035",
"pm_score": 2,
"selected": false,
"text": "<p>It is much better to alter an existing stored proc because of the potential for properties and permissions that have been added AND which will be lost if the stored proc is dropped.</p>\n\n<p>So, test to see if it NOT EXISTS, if it does not then create a dummy proc. Then after that use an alter statement.</p>\n\n<pre><code>IF NOT EXISTS(SELECT * FROM sysobjects WHERE Name = 'YOUR_STORED_PROC_NAME' AND xtype='P')\nEXECUTE('CREATE PROC [dbo].[YOUR_STORED_PROC_NAME] as BEGIN select 0 END')\nGO\nALTER PROC [dbo].[YOUR_STORED_PROC_NAME]\n....\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527/"
] | As part of my integration strategy, I have a few SQL scripts that run in order to update the database. The first thing all of these scripts do is check to see if they need to run, e.g.:
```
if @version <> @expects
begin
declare @error varchar(100);
set @error = 'Invalid version. Your version is ' + convert(varchar, @version) + '. This script expects version ' + convert(varchar, @expects) + '.';
raiserror(@error, 10, 1);
end
else
begin
...sql statements here...
end
```
Works great! Except if I need to add a stored procedure. The "create proc" command must be the only command in a batch of sql commands. Putting a "create proc" in my IF statement causes this error:
```
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
```
Ouch! How do I put the CREATE PROC command in my script, and have it only execute if it needs to? | Here's what I came up with:
Wrap it in an EXEC(), like so:
```
if @version <> @expects
begin
...snip...
end
else
begin
exec('CREATE PROC MyProc AS SELECT ''Victory!''');
end
```
Works like a charm! |
55,510 | <p>I'm quite confident that globally declared variables get allocated (and initialized, if applicable) at program start time.</p>
<pre><code>int globalgarbage;
unsigned int anumber = 42;
</code></pre>
<p>But what about static ones defined within a function?</p>
<pre><code>void doSomething()
{
static bool globalish = true;
// ...
}
</code></pre>
<p>When is the space for <code>globalish</code> allocated? I'm guessing when the program starts. But does it get initialized then too? Or is it initialized when <code>doSomething()</code> is first called?</p>
| [
{
"answer_id": 55515,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>Static variables are allocated inside a code segment -- they are part of the executable image, and so are mapped in already initialized.</p>\n\n<p>Static variables within function scope are treated the same, the scoping is purely a language level construct.</p>\n\n<p>For this reason you are guaranteed that a static variable will be initialized to 0 (unless you specify something else) rather than an undefined value.</p>\n\n<p>There are some other facets to initialization you can take advantage off -- for example shared segments allow different instances of your executable running at once to access the same static variables.</p>\n\n<p>In C++ (globally scoped) static objects have their constructors called as part of the program start up, under the control of the C runtime library. Under Visual C++ at least the order that objects are initialized in can be controlled by the <a href=\"http://support.microsoft.com/kb/104248\" rel=\"nofollow noreferrer\">init_seg</a> pragma.</p>\n"
},
{
"answer_id": 55548,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 8,
"selected": true,
"text": "<p>I was curious about this so I wrote the following test program and compiled it with g++ version 4.1.2.</p>\n\n<pre><code>include <iostream>\n#include <string>\n\nusing namespace std;\n\nclass test\n{\npublic:\n test(const char *name)\n : _name(name)\n {\n cout << _name << \" created\" << endl;\n }\n\n ~test()\n {\n cout << _name << \" destroyed\" << endl;\n }\n\n string _name;\n};\n\ntest t(\"global variable\");\n\nvoid f()\n{\n static test t(\"static variable\");\n\n test t2(\"Local variable\");\n\n cout << \"Function executed\" << endl;\n}\n\n\nint main()\n{\n test t(\"local to main\");\n\n cout << \"Program start\" << endl;\n\n f();\n\n cout << \"Program end\" << endl;\n return 0;\n}\n</code></pre>\n\n<p>The results were not what I expected. The constructor for the static object was not called until the first time the function was called. Here is the output:</p>\n\n<pre><code>global variable created\nlocal to main created\nProgram start\nstatic variable created\nLocal variable created\nFunction executed\nLocal variable destroyed\nProgram end\nlocal to main destroyed\nstatic variable destroyed\nglobal variable destroyed\n</code></pre>\n"
},
{
"answer_id": 55570,
"author": "Eugene",
"author_id": 1155,
"author_profile": "https://Stackoverflow.com/users/1155",
"pm_score": 5,
"selected": false,
"text": "<p>The memory for all static variables is allocated at program load. But local static variables are created and initialized the first time they are used, not at program start up. There's some good reading about that, and statics in general, <a href=\"https://web.archive.org/web/20100328062506/http://www.acm.org/crossroads/xrds2-4/ovp.html\" rel=\"noreferrer\">here</a>. In general I think some of these issues depend on the implementation, especially if you want to know where in memory this stuff will be located.</p>\n"
},
{
"answer_id": 55592,
"author": "Henk",
"author_id": 4613,
"author_profile": "https://Stackoverflow.com/users/4613",
"pm_score": 3,
"selected": false,
"text": "<p>The compiler will allocate static variable(s) defined in a function <code>foo</code> at program load, however the compiler will also add some additional instructions (machine code) to your function <code>foo</code> so that the first time it is invoked this additional code will initialize the static variable (e.g. invoking the constructor, if applicable).</p>\n\n<p>@Adam: This behind the scenes injection of code by the compiler is the reason for the result you saw.</p>\n"
},
{
"answer_id": 55877,
"author": "dmityugov",
"author_id": 3232,
"author_profile": "https://Stackoverflow.com/users/3232",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Or is it initialized when doSomething() is first called?</p>\n</blockquote>\n\n<p>Yes, it is. This, among other things, lets you initialize globally-accessed data structures when it is appropriate, for example inside try/catch blocks. E.g. instead of</p>\n\n<pre><code>int foo = init(); // bad if init() throws something\n\nint main() {\n try {\n ...\n }\n catch(...){\n ...\n }\n}\n</code></pre>\n\n<p>you can write</p>\n\n<pre><code>int& foo() {\n static int myfoo = init();\n return myfoo;\n}\n</code></pre>\n\n<p>and use it inside the try/catch block. On the first call, the variable will be initialized. Then, on the first and next calls, its value will be returned (by reference).</p>\n"
},
{
"answer_id": 58804,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>Some relevant verbiage from C++ Standard:</p>\n\n<blockquote>\n <h2>3.6.2 Initialization of non-local objects [basic.start.init]</h2>\n \n <h3>1</h3>\n \n <p>The storage for objects with static storage \n duration (<em>basic.stc.static</em>) shall be zero-initialized (<em>dcl.init</em>)\n before any other initialization takes place. Objects of \n POD types (<em>basic.types</em>) with static storage duration\n initialized with constant expressions (<em>expr.const</em>) shall be \n initialized before any dynamic initialization takes place. \n Objects of namespace scope with static storage duration defined in\n the same translation unit and dynamically initialized shall be\n initialized in the order in which their definition appears in \n the translation unit. [Note: <em>dcl.init.aggr</em> describes the \n order in which aggregate members are initialized. The \n initialization of local static objects is described in <em>stmt.dcl</em>. ]</p>\n \n <p>[more text below adding more liberties for compiler writers]</p>\n \n <h2>6.7 Declaration statement [stmt.dcl]</h2>\n \n <p>...</p>\n \n <h3>4</h3>\n \n <p>The zero-initialization (<em>dcl.init</em>) of all local objects with \n static storage duration (<em>basic.stc.static</em>) is performed before\n any other initialization takes place. A local object of \n POD type (<em>basic.types</em>) with static storage duration\n initialized with constant-expressions is initialized before its\n block is first entered. An implementation is permitted to perform\n early initialization of other local objects with static storage\n duration under the same conditions that an implementation is\n permitted to statically initialize an object with static storage\n duration in namespace scope (<em>basic.start.init</em>). Otherwise such\n an object is initialized the first time control passes through its\n declaration; such an object is considered initialized upon the\n completion of its initialization. If the initialization exits by \n throwing an exception, the initialization is not complete, so it will\n be tried again the next time control enters the declaration. If control re-enters the declaration (recursively) while the object is being\n initialized, the behavior is undefined. [<em>Example:</em></p>\n\n<pre><code> int foo(int i)\n {\n static int s = foo(2*i); // recursive call - undefined\n return i+1;\n }\n</code></pre>\n \n <p>--<em>end example</em>]</p>\n \n <h3>5</h3>\n \n <p>The destructor for a local object with static storage duration will\n be executed if and only if the variable was constructed. \n [Note: <em>basic.start.term</em> describes the order in which local\n objects with static storage duration are destroyed. ]</p>\n</blockquote>\n"
},
{
"answer_id": 20355603,
"author": "Thang Le",
"author_id": 2103515,
"author_profile": "https://Stackoverflow.com/users/2103515",
"pm_score": 3,
"selected": false,
"text": "<p>I try to test again code from <strong>Adam Pierce</strong> and added two more cases: static variable in class and POD type. My compiler is g++ 4.8.1, in Windows OS(MinGW-32).\nResult is static variable in class is treated same with global variable. Its constructor will be called before enter main function.</p>\n<ul>\n<li>Conclusion (for g++, Windows environment):</li>\n</ul>\n<ol>\n<li><strong>Global variable</strong> and <strong>static member in class</strong>: constructor is called before enter <strong>main</strong> function <em><strong>(1)</strong></em>.</li>\n<li><strong>Local static variable</strong>: constructor is only called when execution reaches its declaration at first time.</li>\n<li>If <strong>Local static variable is POD type</strong>, then it is also initialized before enter <strong>main</strong> function <em><strong>(1)</strong></em>.\nExample for POD type: <em>static int number = 10;</em></li>\n</ol>\n<p><strong>(1)</strong>: The correct state should be: <em>"before any function from the same translation unit is called".</em> However, for simple, as in example below, then it is <em>main</em> function.</p>\n<pre><code>#include <iostream> \n#include <string>\n\nusing namespace std;\n\nclass test\n{\npublic:\n test(const char *name)\n : _name(name)\n {\n cout << _name << " created" << endl;\n }\n\n ~test()\n {\n cout << _name << " destroyed" << endl;\n }\n\n string _name;\n static test t; // static member\n };\ntest test::t("static in class");\n\ntest t("global variable");\n\nvoid f()\n{\n static test t("static variable");\n static int num = 10 ; // POD type, init before enter main function\n \n test t2("Local variable");\n cout << "Function executed" << endl;\n}\n\nint main()\n{\n test t("local to main");\n cout << "Program start" << endl;\n f();\n cout << "Program end" << endl;\n return 0;\n }\n</code></pre>\n<p><strong>result:</strong></p>\n<pre><code>static in class created\nglobal variable created\nlocal to main created\nProgram start\nstatic variable created\nLocal variable created\nFunction executed\nLocal variable destroyed\nProgram end\nlocal to main destroyed\nstatic variable destroyed\nglobal variable destroyed\nstatic in class destroyed\n</code></pre>\n<p>Anybody tested in Linux env ?</p>\n"
},
{
"answer_id": 70837256,
"author": "Sherif Beshr",
"author_id": 15441343,
"author_profile": "https://Stackoverflow.com/users/15441343",
"pm_score": -1,
"selected": false,
"text": "<p>In the following code it prints Initial = 4 which is the value of static_x as it is implemented in the compiling time.</p>\n<pre><code> int func(int x)\n {\n static int static_x = 4;\n static_x = x;\n printf ("Address = 0x%x",&static_x ); // prints 0x40a010\n return static_x;\n }\n int main()\n {\n int x = 8;\n uint32_t *ptr = (uint32_t *)(0x40a010); // static_x location\n printf ("Initial = %d\\n",*ptr);\n func(x);\n \n return 0;\n }\n</code></pre>\n"
}
] | 2008/09/10 | [
"https://Stackoverflow.com/questions/55510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
] | I'm quite confident that globally declared variables get allocated (and initialized, if applicable) at program start time.
```
int globalgarbage;
unsigned int anumber = 42;
```
But what about static ones defined within a function?
```
void doSomething()
{
static bool globalish = true;
// ...
}
```
When is the space for `globalish` allocated? I'm guessing when the program starts. But does it get initialized then too? Or is it initialized when `doSomething()` is first called? | I was curious about this so I wrote the following test program and compiled it with g++ version 4.1.2.
```
include <iostream>
#include <string>
using namespace std;
class test
{
public:
test(const char *name)
: _name(name)
{
cout << _name << " created" << endl;
}
~test()
{
cout << _name << " destroyed" << endl;
}
string _name;
};
test t("global variable");
void f()
{
static test t("static variable");
test t2("Local variable");
cout << "Function executed" << endl;
}
int main()
{
test t("local to main");
cout << "Program start" << endl;
f();
cout << "Program end" << endl;
return 0;
}
```
The results were not what I expected. The constructor for the static object was not called until the first time the function was called. Here is the output:
```
global variable created
local to main created
Program start
static variable created
Local variable created
Function executed
Local variable destroyed
Program end
local to main destroyed
static variable destroyed
global variable destroyed
``` |
55,532 | <p>This came up from <a href="https://stackoverflow.com/questions/55093/how-to-deal-with-arrays-declared-on-the-stack-in-c#55183">this answer to a previous question of mine</a>.
Is it guaranteed for the compiler to treat <code>array[4][4]</code> the same as <code>array[16]</code>?</p>
<p>For instance, would either of the below calls to <code>api_func()</code> be safe?</p>
<pre><code>void api_func(const double matrix[4][4]);
// ...
{
typedef double Matrix[4][4];
double* array1 = new double[16];
double array2[16];
// ...
api_func(reinterpret_cast<Matrix&>(array1));
api_func(reinterpret_cast<Matrix&>(array2));
}
</code></pre>
| [
{
"answer_id": 55539,
"author": "Josh Matthews",
"author_id": 3830,
"author_profile": "https://Stackoverflow.com/users/3830",
"pm_score": 0,
"selected": false,
"text": "<p>I would be worried about padding being added for things like Matrix[5][5] to make each row word aligned, but that could be simply my own superstition.</p>\n"
},
{
"answer_id": 55579,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think there is a problem with padding introduced by having a <strong>multi-dimensional</strong> array.</p>\n\n<p>Each element in an array must satisfy the padding requirements imposed by the architecture. An array [N][M] is always going to have the same in memory representation as one of [M*N].</p>\n"
},
{
"answer_id": 55580,
"author": "Henk",
"author_id": 4613,
"author_profile": "https://Stackoverflow.com/users/4613",
"pm_score": 1,
"selected": false,
"text": "<p>Each array element should be laid out sequentially in memory by the compiler. The two declarations whilst different types are the same underlying memory structure.</p>\n"
},
{
"answer_id": 55660,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 3,
"selected": true,
"text": "<p>From the C++ standard, referring to the <code>sizeof</code> operator:</p>\n\n<blockquote>\n <p>When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of <code>n</code> elements is <code>n</code> times the size of an element.</p>\n</blockquote>\n\n<p>From this, I'd say that <code>double[4][4]</code> and <code>double[16]</code> would have to have the same underlying representation. </p>\n\n<p>I.e., given </p>\n\n<pre><code>sizeof(double[4]) = 4*sizeof(double)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>sizeof(double[4][4]) = 4*sizeof(double[4])\n</code></pre>\n\n<p>then we have</p>\n\n<pre><code>sizeof(double[4][4]) = 4*4*sizeof(double) = 16*sizeof(double) = sizeof(double[16])\n</code></pre>\n\n<p>I think a standards-compliant compiler would have to implement these the same, and I think that this isn't something that a compiler would accidentally break. The standard way of implementing multi-dimensional arrays works as expected. Breaking the standard would require extra work, for likely no benefit.</p>\n\n<p>The C++ standard also states that an array consists of contiguously-allocated elements, which eliminates the possibility of doing anything strange using pointers and padding.</p>\n"
},
{
"answer_id": 55937,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 0,
"selected": false,
"text": "<p>A bigger question is: do you really need to perform such a cast?</p>\n\n<p>Although you <em>might</em> be able to get away with it, it would still be more readable and maintainable to avoid altogether. For example, you could consistently use double[m*n] as the actual type, and then work with a class that wraps this type, and perhaps overloads the [] operator for ease of use. In that case, you might also need an intermediate class to encapsulate a single row -- so that code like my_matrix[3][5] still works as expected.</p>\n"
},
{
"answer_id": 57934,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 1,
"selected": false,
"text": "<p>@Konrad Rudolph:</p>\n\n<p>I get those two (row major/column major) mixed up myself, but I do know this: It's well-defined.</p>\n\n<p>int x[3][5], for example, is an array of size 3, whose elements are int arrays of size 5. (§6.5.2.1) Adding all the rules from the standard about arrays, addressing, etc. you get that the second subscript references consecutive integers, wheras the first subscript will reference consecutive 5-int objects. (So 3 is the bigger number; you have 5 ints between <strong>x[1]</strong>[0] and <strong>x[2]</strong>[0].)</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4790/"
] | This came up from [this answer to a previous question of mine](https://stackoverflow.com/questions/55093/how-to-deal-with-arrays-declared-on-the-stack-in-c#55183).
Is it guaranteed for the compiler to treat `array[4][4]` the same as `array[16]`?
For instance, would either of the below calls to `api_func()` be safe?
```
void api_func(const double matrix[4][4]);
// ...
{
typedef double Matrix[4][4];
double* array1 = new double[16];
double array2[16];
// ...
api_func(reinterpret_cast<Matrix&>(array1));
api_func(reinterpret_cast<Matrix&>(array2));
}
``` | From the C++ standard, referring to the `sizeof` operator:
>
> When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of `n` elements is `n` times the size of an element.
>
>
>
From this, I'd say that `double[4][4]` and `double[16]` would have to have the same underlying representation.
I.e., given
```
sizeof(double[4]) = 4*sizeof(double)
```
and
```
sizeof(double[4][4]) = 4*sizeof(double[4])
```
then we have
```
sizeof(double[4][4]) = 4*4*sizeof(double) = 16*sizeof(double) = sizeof(double[16])
```
I think a standards-compliant compiler would have to implement these the same, and I think that this isn't something that a compiler would accidentally break. The standard way of implementing multi-dimensional arrays works as expected. Breaking the standard would require extra work, for likely no benefit.
The C++ standard also states that an array consists of contiguously-allocated elements, which eliminates the possibility of doing anything strange using pointers and padding. |
55,556 | <p>I need to generate some passwords, I want to avoid characters that can be confused for each other. Is there a definitive list of characters I should avoid? my current list is</p>
<p>il10o8B3Evu![]{}</p>
<p>Are there any other pairs of characters that are easy to confuse? for special characters I was going to limit myself to those under the number keys, though I know that this differs depending on your keyboards nationality!</p>
<p>As a rider question, I would like my passwords to be 'wordlike'do you have a favoured algorithm for that?</p>
<p>Thanks :)</p>
| [
{
"answer_id": 55568,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 3,
"selected": false,
"text": "<p>My preferred method is to get a word list of 3, 4 and 5 letter words. Then select at least 2 of those, and place a random 2 digit number or special symbol (%&*@#$) between each word. If you want to you can capitalize up to one character per word at random.</p>\n\n<p>Depending on your strength requirements you end up with easy-to-remember and communicate passwords like:</p>\n\n<ul>\n<li>lemon%desk</li>\n<li>paper&boy32hat</li>\n</ul>\n\n<p>Keep in mind you occasionally get interesting or inappropriate combinations of words (I'll let you use your imagination). I usually have a button allowing the generation of a new password if the one presented is disliked. </p>\n\n<p>As a rule, only use symbols that people commonly know the name for. On a US Standard keyboard I would avoid ~`'/\\^</p>\n\n<p>I guess this more answered your rider question than your main question . .. </p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 55619,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>To add to Jim's answer you could also use the word list and randomly replace certain characters with symbols (an @ for an A, a 0 (zero) for an O or a 5 for an S) and/or remove the vowels from the words.</p>\n\n<ul>\n<li>lmn%Desk</li>\n<li>p@per&b0y32H@t</li>\n</ul>\n\n<p>Still mostly human readable.</p>\n"
},
{
"answer_id": 55634,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 7,
"selected": true,
"text": "<p>Here are the character sets that Steve Gibson uses for his <a href=\"https://www.grc.com/ppp.htm\" rel=\"noreferrer\">\"Perfect Paper Password\"</a> system. They are \"characters to allow\" rather than \"characters to avoid\", but they seem pretty reasonable for what you want:</p>\n\n<p>A standard set of 64 characters</p>\n\n<pre><code>!#%+23456789:=?@ABCDEFGHJKLMNPRS\nTUVWXYZabcdefghijkmnopqrstuvwxyz\n</code></pre>\n\n<p>A larger set of 88 characters</p>\n\n<pre><code>!\"#$%&'()*+,-./23456789:;<=>?@ABCDEFGHJKLMNO\nPRSTUVWXYZ[\\]^_abcdefghijkmnopqrstuvwxyz{|}~\n</code></pre>\n\n<p>For pronounceable passwords, I'm not familiar with the algorithms but you might want to look at <a href=\"http://www.adel.nursat.kz/apg/\" rel=\"noreferrer\">APG</a> and <a href=\"http://sourceforge.net/projects/pwgen/\" rel=\"noreferrer\">pwgen</a> as a starting point.</p>\n"
},
{
"answer_id": 55689,
"author": "Dana the Sane",
"author_id": 2567,
"author_profile": "https://Stackoverflow.com/users/2567",
"pm_score": 2,
"selected": false,
"text": "<p>As another option, you could use a monospace/terminal font like courier for printing the passwords. Similar characters should be a lot more distinguishable that way.</p>\n"
},
{
"answer_id": 55798,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": false,
"text": "<p>Read <a href=\"http://www.schneier.com/blog/archives/2007/01/choosing_secure.html\" rel=\"noreferrer\">Choosing Secure Passwords</a>. </p>\n\n<p>One interesting tidbit from there: For more secure passwords, make sure some numbers and special characters appear in the middle. Cracking programs check for them at the beginning and ends sooner.</p>\n"
},
{
"answer_id": 57417,
"author": "tqbf",
"author_id": 5674,
"author_profile": "https://Stackoverflow.com/users/5674",
"pm_score": 1,
"selected": false,
"text": "<p>I don't love the wordlist approach. For example, in /usr/share/dict/words on OSX, there are 5110 4-character words. Using two of them with a seperator character produces ~600M combinations. But if you used the character set directly with a strong random number generator, you'd have 88^9 possible passwords, 3.16e+17 combinations. </p>\n\n<p>Either way, the likely attack against this system is going to be against the random number generator, so make sure you're using a cryptographically strong one. If you use PHP's standard rand function, it will be attacked by registering and resetting thousands of passwords to sample the RNG state and then predict the remaining RNG state, which will reduce the number of possible passwords an attacker needs to test. </p>\n"
},
{
"answer_id": 57452,
"author": "James B",
"author_id": 2951,
"author_profile": "https://Stackoverflow.com/users/2951",
"pm_score": 2,
"selected": false,
"text": "<p>For human-readable passwords, I recently used a PHP script very similar to the one below. It worked well. Granted, the passwords aren't going to be incredibly secure (as they're prone to dictionary attacks), but for memorisable, or at least readable, passwords it works well. However, this function shouldn't be used as-is, it's more for illustration than anything else.</p>\n\n<pre><code>function generatePassword($syllables = 2, $use_prefix = true)\n{\n\n // Define function unless it is already exists\n if (!function_exists('arr'))\n {\n // This function returns random array element\n function arr(&$arr)\n {\n return $arr[rand(0, sizeof($arr)-1)];\n }\n }\n\n // Random prefixes\n $prefix = array('aero', 'anti', 'auto', 'bi', 'bio',\n 'cine', 'deca', 'demo', 'dyna', 'eco',\n 'ergo', 'geo', 'gyno', 'hypo', 'kilo',\n 'mega', 'tera', 'mini', 'nano', 'duo',\n 'an', 'arch', 'auto', 'be', 'co',\n 'counter', 'de', 'dis', 'ex', 'fore',\n 'in', 'infra', 'inter', 'mal', \n 'mis', 'neo', 'non', 'out', 'pan',\n 'post', 'pre', 'pseudo', 'semi',\n 'super', 'trans', 'twi', 'vice');\n\n // Random suffixes\n $suffix = array('dom', 'ity', 'ment', 'sion', 'ness',\n 'ence', 'er', 'ist', 'tion', 'or',\n 'ance', 'ive', 'en', 'ic', 'al',\n 'able', 'y', 'ous', 'ful', 'less',\n 'ise', 'ize', 'ate', 'ify', 'fy', 'ly'); \n\n // Vowel sounds \n $vowels = array('a', 'o', 'e', 'i', 'y', 'u', 'ou', 'oo', 'ae', 'ea', 'ie'); \n\n // Consonants \n $consonants = array('w', 'r', 't', 'p', 's', 'd', 'f', 'g', 'h', 'j', \n 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'qu');\n\n $password = $use_prefix?arr($prefix):'';\n $password_suffix = arr($suffix);\n\n for($i=0; $i<$syllables; $i++)\n {\n // selecting random consonant\n $doubles = array('n', 'm', 't', 's');\n $c = arr($consonants);\n if (in_array($c, $doubles)&&($i!=0)) { // maybe double it\n if (rand(0, 2) == 1) // 33% probability\n $c .= $c;\n }\n $password .= $c;\n //\n\n // selecting random vowel\n $password .= arr($vowels);\n\n if ($i == $syllables - 1) // if suffix begin with vovel\n if (in_array($password_suffix[0], $vowels)) // add one more consonant \n $password .= arr($consonants);\n\n }\n\n // selecting random suffix\n $password .= $password_suffix;\n\n return $password;\n}\n</code></pre>\n"
},
{
"answer_id": 64836,
"author": "flamingLogos",
"author_id": 8161,
"author_profile": "https://Stackoverflow.com/users/8161",
"pm_score": 2,
"selected": false,
"text": "<p>For an international client several years ago, I had to generate random, secure passwords that were then mail-merged into documents by my client and sent by postal mail to recipients in 40 countries. Not knowing what typeface was to be used in the documents, I used a list of characters like the Steve Gibson <a href=\"https://www.grc.com/ppp.htm\" rel=\"nofollow noreferrer\">64-character</a> set to eliminate the confusion between similar glyphs.</p>\n\n<p>To make the resulting passwords pronounceable, and thus easier to remember, I paired consonants and vowels together, with some consonant digraphs (sh, th, wh, etc.) added to the mix. </p>\n\n<p>To reduce the chances of inappropriate or offensive words from being generated (in English or in the recipients’ languages), I limited runs of consecutive alpha characters to two, with numerals or punctuation characters betwee:</p>\n\n<pre><code>Es4tU$sA6\nwH@cY8Go2\n</code></pre>\n\n<p>Looking back over my method now, I realize that there was room for improvement in the inappropriateness algorithm. Using the just the rules above, some offensive words are possible now that some numerals and punctuation are substituted for letters.</p>\n"
},
{
"answer_id": 201599,
"author": "Paul Nathan",
"author_id": 26227,
"author_profile": "https://Stackoverflow.com/users/26227",
"pm_score": 1,
"selected": false,
"text": "<p>A starting approach might be to generate mostly valid english syllables, mix them, then throw in a text->l33t conversion. There's been work done on generational natural language grammars, so one of those might help.</p>\n\n<p>E.g. ah ul ing are all valid syllables or close to it... mix them -> Ingulah...l33t it -> 1ngu4h. Is it the best out there? Nah. But at least it is semipronouncable(if you speak l33t) and more computationally secure.</p>\n"
},
{
"answer_id": 242285,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 2,
"selected": false,
"text": "<p>In my (electrical engineering, techie) graduate school, all computer accounts were initialized with passwords that, I assume, were generated by a standard linux utility. They consisted of three random syllables, with three lowercase letters in each syllable. The result was reasonably secure (on the order of billions of possible combinations) yet so pronounce-able that I still use some of those passwords over a decade later. James' example is an excellent demonstration of this.</p>\n\n<p>A comment on passwords in general, from a network-security professional: they're terrible, for several reasons, including:</p>\n\n<ul>\n<li><p>Generally easily broken, either through social engineering or with attack software, especially if you know <em>anything</em> about your target. </p>\n\n<p><em>Example 1:</em> I recently needed to revise a password-protected technical document. Looking at the date, I knew who our Tech Writer in residence was at the time, typed the first word that entered my mind, and immediately unlocked the document. </p>\n\n<p><em>Example 2:</em> Standard password-cracking programs allow the cracker to specify a set of rules that operate on a user-supplied dictionary. It's trivial to replace certain letters with $ymb01$, or to translate into 1337, etc.</p></li>\n<li><p>\"Secure\" passwords aren't. Given the sheer number of passwords most people need to remember, the most common way to \"remember\" a \"strong\" password like \"a4$N!8_q\" is to write it on a piece of paper (or, worse, store it in a text file). 'Nuff said.</p></li>\n</ul>\n\n<p>If you need truly <em>secure</em> authentication, <em>multi-factor</em> (or <em>two-factor</em>) is the industry-accepted mechanism. The \"two factors\" are usually something you <em>have</em> (such as an access card) and something you <em>know</em> that enables it (such as a PIN). Neither one works without the other--you need both.</p>\n\n<p>On the other hand, consider the level of security you really need. What are you protecting? How badly do the \"bad guys\" want to get it, and what are the consequences if they do? Chances are, \"Its@Secret!\" is more than good enough. :-)</p>\n"
},
{
"answer_id": 9651123,
"author": "Anonym",
"author_id": 1261653,
"author_profile": "https://Stackoverflow.com/users/1261653",
"pm_score": 1,
"selected": false,
"text": "<pre><code>function random_readable_pwd($length=12){\n // special characters\n $sym=\"!\\\"§$%&/()={[]}\\,.-_:;@>|\";\n\n // read words from text file to array\n $filename=\"special.txt\";\n if (!file_exists($filename)) { die('File \"'.$filename.'\" is not exists!'); }\n $lines = file($filename);\n foreach ($lines as $line_num => $line) {\n $line=substr($line, 0, -2);\n $words[].=$line;\n }\n\n // Add words while password is smaller than the given length\n $pwd = '';\n $ran_date=date(\"s\");\n while (strlen($pwd) < $length){\n $r = mt_rand(0, count($words)-1);\n // randomly upercare word but not all in one time\n if ($ran_date % 3 == 0) $words[$r]=ucwords($words[$r]);\n $pwd .= $words[$r];\n //randomly add symbol\n if ($ran_date % 2 == 0) $pwd .= $sym{mt_rand(0,strlen($sym))};\n $ran_date++;\n }\n\n // append a number at the end if length > 2 and\n // reduce the password size to $length\n $num = mt_rand(1, 99);\n if ($length > 2){\n $pwd = substr($pwd,0,$length-strlen($num)).$num;\n } else { \n $pwd = substr($pwd, 0, $length);\n }\n\n return $pwd;\n\n}\n</code></pre>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5552/"
] | I need to generate some passwords, I want to avoid characters that can be confused for each other. Is there a definitive list of characters I should avoid? my current list is
il10o8B3Evu![]{}
Are there any other pairs of characters that are easy to confuse? for special characters I was going to limit myself to those under the number keys, though I know that this differs depending on your keyboards nationality!
As a rider question, I would like my passwords to be 'wordlike'do you have a favoured algorithm for that?
Thanks :) | Here are the character sets that Steve Gibson uses for his ["Perfect Paper Password"](https://www.grc.com/ppp.htm) system. They are "characters to allow" rather than "characters to avoid", but they seem pretty reasonable for what you want:
A standard set of 64 characters
```
!#%+23456789:=?@ABCDEFGHJKLMNPRS
TUVWXYZabcdefghijkmnopqrstuvwxyz
```
A larger set of 88 characters
```
!"#$%&'()*+,-./23456789:;<=>?@ABCDEFGHJKLMNO
PRSTUVWXYZ[\]^_abcdefghijkmnopqrstuvwxyz{|}~
```
For pronounceable passwords, I'm not familiar with the algorithms but you might want to look at [APG](http://www.adel.nursat.kz/apg/) and [pwgen](http://sourceforge.net/projects/pwgen/) as a starting point. |
55,577 | <p>I want to test the web pages I create in all the modern versions of Internet Explorer (6, 7 and 8 beta) but I work mainly on a Mac and often don't have direct access to a PC.</p>
| [
{
"answer_id": 55578,
"author": "georgebrock",
"author_id": 5168,
"author_profile": "https://Stackoverflow.com/users/5168",
"pm_score": 7,
"selected": true,
"text": "<p><strong>Update:</strong> Microsoft now provide virtual machine images for various versions of IE that are ready to use on all of the major OS X virtualisation platforms (<a href=\"https://www.virtualbox.org\" rel=\"nofollow noreferrer\">VirtualBox</a>, <a href=\"http://www.vmware.com/products/fusion/overview.html\" rel=\"nofollow noreferrer\">VMWare Fusion</a>, and <a href=\"http://www.parallels.com/\" rel=\"nofollow noreferrer\">Parallels</a>).</p>\n\n<p>Download the appropriate image from: <a href=\"https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/\" rel=\"nofollow noreferrer\">https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/</a></p>\n\n<hr>\n\n<p>On an Intel based Mac you can run Windows within a virtual machine. You will need one virtual machine for each version of IE you want to test against.</p>\n\n<p>The instructions below include free and legal virtualisation software and Windows disk images.</p>\n\n<ol>\n<li>Download some virtual machine software. The developer disk images we're going to use are will work with either <a href=\"http://www.vmware.com/products/fusion/\" rel=\"nofollow noreferrer\">VMWare Fusion</a> or <a href=\"http://www.virtualbox.org/\" rel=\"nofollow noreferrer\">Sun Virtual Box</a>. VMWare has more features but costs $80, Virtual Box on the other hand is more basic but is free for most users (see <a href=\"http://www.virtualbox.org/wiki/Licensing_FAQ\" rel=\"nofollow noreferrer\">Virtual Box licensing FAQ</a> for details).</li>\n<li>Download the IE developer disk images, which are free from Microsoft: <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=21EABB90-958F-4B64-B5F1-73D0A413C8EF&displaylang=en\" rel=\"nofollow noreferrer\">http://www.microsoft.com/downloads/...</a></li>\n<li>Extract the disk images using <a href=\"http://www.cabextract.org.uk/\" rel=\"nofollow noreferrer\">cabextract</a> which is available from <a href=\"http://www.macports.org\" rel=\"nofollow noreferrer\">MacPorts</a> or as source code (Thanks to <a href=\"https://stackoverflow.com/users/6262/clinton\">Clinton</a>).</li>\n<li>Download Q.app from <a href=\"http://www.kju-app.org/\" rel=\"nofollow noreferrer\">http://www.kju-app.org/</a> and put it in your /Applications folder (you will need it to convert the disk images into a format VMWare/Virtual Box can use)</li>\n</ol>\n\n<p>At this point, the process depends on which VM software you're using.</p>\n\n<p><strong>Virtual Box users</strong></p>\n\n<ol>\n<li><p>Open a Terminal.app on your Mac (you can find it in /Applications/Utilities) and run the following sequence of commands, replacing <em>input.vhd</em> with the name of the VHD file you're starting from and <em>output.vdi</em> with the name you want your final disk image to have:</p>\n\n<pre><code>/Applications/Q.app/Contents/MacOS/qemu-img convert -O raw -f vpc \"input.vhd\" temp.bin\nVBoxManage convertdd temp.bin \"output.vdi\"\nrm temp.bin\nmv \"output.vdi\" ~/Library/VirtualBox/VDI/\nVBoxManage modifyvdi \"output.vdi\" compact\n</code></pre></li>\n<li>Start Virtual Box and create a new virtual machine</li>\n<li>Select the new VDI file you've just created as the boot hard disk</li>\n</ol>\n\n<p><strong>VMWare fusion users</strong></p>\n\n<ol>\n<li><p>Open a Terminal.app on your Mac (you can find it in /Applications/Utilities) and run the following commands, replacing <em>input.vhd</em> and <em>output.vmdk</em> with the name of the VHD file you're working on and the name you want your resulting disk image to have:</p>\n\n<pre><code>/Applications/Q.app/Contents/MacOS/qemu-img convert -O vmdk -f vpc \"input.vhd\" \"output.vmdk\"\nmv \"output.vmdk\" ~/Documents/Virtual\\ Machines.localized/\n</code></pre>\n\n<p>This will probably take a while (It takes around 30 minutes per disk image on my 2.4GHz Core 2 Duo MacBook w/ 2Gb RAM).</p></li>\n<li>Start VMWare Fusion and create a new virtual machine</li>\n<li>In the advanced disk options select \"use and existing disk\" and find the VMDK file you just created</li>\n</ol>\n"
},
{
"answer_id": 55587,
"author": "Jason Navarrete",
"author_id": 3920,
"author_profile": "https://Stackoverflow.com/users/3920",
"pm_score": 3,
"selected": false,
"text": "<p>Once you've virtualized Windows on your Mac, you can also try the <strong>Mutiple IE</strong> installer to get a variety of flavors of Internet Explorer without having to create separate VM instances.</p>\n\n<ul>\n<li><a href=\"http://tredosoft.com/Multiple_IE\" rel=\"nofollow noreferrer\">Multiple IE Installer</a></li>\n</ul>\n\n<p>If you're just wanting to see a simple screenshot of how the page will render in various browsers, you can try the free service <strong>browsershots</strong> or there are a number of services that will automatically test your pages in multiple browsers.</p>\n\n<ul>\n<li><a href=\"http://browsershots.org/\" rel=\"nofollow noreferrer\">browsershots.org</a></li>\n</ul>\n"
},
{
"answer_id": 55593,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://browsershots.org/\" rel=\"nofollow noreferrer\">Browsershots</a> is another option if you just want to get screenshots..</p>\n"
},
{
"answer_id": 55600,
"author": "Eugene",
"author_id": 1155,
"author_profile": "https://Stackoverflow.com/users/1155",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't have a copy of Windows that you could run in a virtual machine (VMware also isn't free), you can try <a href=\"http://www.tatanka.com.br/ies4linux/page/Does_IEs_4_Linux_Work_with_Mac_OSX\" rel=\"nofollow noreferrer\">IEs4Linux</a>. It will require you configure some open source stuff on your Mac, but it is all free. You'll at least need fink, wine, and cabextract. See the link above for some specific command line directions. It's not that hard!</p>\n"
},
{
"answer_id": 55832,
"author": "Hagelin",
"author_id": 5156,
"author_profile": "https://Stackoverflow.com/users/5156",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://litmusapp.com/\" rel=\"nofollow noreferrer\" title=\"Litmus\">Litmus</a> is another web-based alternative.</p>\n"
},
{
"answer_id": 55971,
"author": "pauldunlop",
"author_id": 2152,
"author_profile": "https://Stackoverflow.com/users/2152",
"pm_score": 1,
"selected": false,
"text": "<p>I've used Codeweavers Crossover product for doing this from time to time. </p>\n\n<p><a href=\"http://www.codeweavers.com/products/cxmac/\" rel=\"nofollow noreferrer\">http://www.codeweavers.com/products/cxmac/</a></p>\n\n<p>It's a different option to virtualisation, and gives you a little more control than some of the hosted solutions. That said, it's based on WINE, and so you can potentially get all the problems and issues that come with doing it that way. That said, for basic testing without plugins, etc, it works great.</p>\n\n<p>I'm not 100% sure about support for IE8, you'd need to check that out, but it definitely gives you native support for 6 and 7.</p>\n"
},
{
"answer_id": 62377,
"author": "Kristian J.",
"author_id": 4588,
"author_profile": "https://Stackoverflow.com/users/4588",
"pm_score": 0,
"selected": false,
"text": "<p>There's a OSX distribution of IEs4 Linux called <a href=\"http://www.kronenberg.org/ies4osx/\" rel=\"nofollow noreferrer\">ies4osx</a>, which has worked fine for me without any configuration. </p>\n"
},
{
"answer_id": 65933,
"author": "Joe Strazzere",
"author_id": 120529,
"author_profile": "https://Stackoverflow.com/users/120529",
"pm_score": -1,
"selected": false,
"text": "<p>If this is a business web site (or a serious site where it is important that it actually works on IE), then don't take the cheap route - invest in a Windows machine or two. Your customers will thank you.</p>\n\n<p>Otherwise, virtualize.</p>\n"
},
{
"answer_id": 464080,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Browsershots is nice, but useless if you need to test functionality rather than just overall visual rendering.</p>\n\n<p>IEs4OSX and IEs4Linux have serious drawbacks. They have no real support for plugins and extensions like Flash and Silverlight. Rendering isn't precise and they're highly unstable. For testing you really need an actual version of IE running on Windows, but you don't need to have a dedicated box.</p>\n\n<p>IE images on VirtualBox is really the best, and easiest way to go.</p>\n\n<p>I have a <a href=\"http://www.10voltmedia.com/blog/2008/12/screencast-install-internet-explorer-on-osx-using-virtualbox/\" rel=\"nofollow noreferrer\">screencast here</a> if anyone's looking for a visual walk-through.</p>\n"
},
{
"answer_id": 466306,
"author": "gareth_bowles",
"author_id": 10715,
"author_profile": "https://Stackoverflow.com/users/10715",
"pm_score": 0,
"selected": false,
"text": "<p>Yet another Web based alternative (although as Jeff said, not much use for testing functionality) is <a href=\"http://www.browsercam.com\" rel=\"nofollow noreferrer\">http://www.browsercam.com</a></p>\n"
},
{
"answer_id": 1362080,
"author": "user113044",
"author_id": 113044,
"author_profile": "https://Stackoverflow.com/users/113044",
"pm_score": 2,
"selected": false,
"text": "<p>There is an issue with the latest release (January 2009) of the VHDs. The VHD sees there are hardware changes and prompts for a license key, evenutally locking users out. As yet there is no known workaround.</p>\n"
},
{
"answer_id": 4820088,
"author": "ma11hew28",
"author_id": 242933,
"author_profile": "https://Stackoverflow.com/users/242933",
"pm_score": 1,
"selected": false,
"text": "<p>You could use <a href=\"http://spoon.net/Browsers/\" rel=\"nofollow\">Spoon Browsers</a> (web-based) once it becomes available for Mac.</p>\n"
},
{
"answer_id": 9440667,
"author": "chadoh",
"author_id": 249801,
"author_profile": "https://Stackoverflow.com/users/249801",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://osxdaily.com/2011/09/04/internet-explorer-for-mac-ie7-ie8-ie-9-free/\" rel=\"nofollow\">OSX Daily explains how to install Windows VMs with a single terminal command</a> (assuming you already <a href=\"https://www.virtualbox.org/wiki/Downloads\" rel=\"nofollow\">have VirtualBox installed</a>). To summarize:</p>\n\n<p>IE 7:</p>\n\n<pre><code>curl -s https://raw.github.com/xdissent/ievms/master/ievms.sh | IEVMS_VERSIONS=\"7\" bash\n</code></pre>\n\n<p>IE 8:</p>\n\n<pre><code>curl -s https://raw.github.com/xdissent/ievms/master/ievms.sh | IEVMS_VERSIONS=\"8\" bash\n</code></pre>\n\n<p>IE 9:</p>\n\n<pre><code>curl -s https://raw.github.com/xdissent/ievms/master/ievms.sh | IEVMS_VERSIONS=\"9\" bash\n</code></pre>\n\n<p>ALL THE IEs!:</p>\n\n<pre><code>curl -s https://raw.github.com/xdissent/ievms/master/ievms.sh | bash\n</code></pre>\n"
},
{
"answer_id": 10387902,
"author": "Timo Tijhof",
"author_id": 319266,
"author_profile": "https://Stackoverflow.com/users/319266",
"pm_score": 3,
"selected": false,
"text": "<p>There's three different methods that I recommend:</p>\n\n<p><strong>Cloud-based interactive virtual machines</strong></p>\n\n<p>Use something like <a href=\"https://saucelabs.com/\" rel=\"nofollow noreferrer\">SauceLabs</a> or <a href=\"http://browserstack.com/\" rel=\"nofollow noreferrer\">BrowserStack</a>. You'll be able to pick a browser of choice, enter a url and use a real OS with the real browser and test and interact as much as you need. Both of these also support setting up a tunnel to/from your own machine so any local hostnames will work fine.</p>\n\n<p>There is also <a href=\"http://crossbrowsertesting.com/\" rel=\"nofollow noreferrer\">CrossBrowserTesting</a>, <a href=\"http://browserling.com/\" rel=\"nofollow noreferrer\">browserling</a>/<a href=\"http://testling.com/\" rel=\"nofollow noreferrer\">testling</a>, which seem to have similar services although I haven't used these myself.</p>\n\n<p><strong>Local virtualization</strong></p>\n\n<p>You can use <a href=\"http://www.virtualbox.org/\" rel=\"nofollow noreferrer\">VirtualBox</a> (free and open-source, similar to VMWare or Parallels) to create one or more virtual machines on your computer. You may or may not know this, but you do not need to get an official copy of Microsoft Windows for these virtual machines. Microsoft offers free VM images of simplified Windows installations for the purposes of testing Internet Explorer and Microsoft Edge (<strong><a href=\"https://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=11575\" rel=\"nofollow noreferrer\">download</a></strong>). Check one of these articles to get that up and running:</p>\n\n<ul>\n<li><a href=\"http://www.xairon.net/2011/06/testing-ie6-7-8-and-9-on-mac-os-x/\" rel=\"nofollow noreferrer\">Testing IE6, 7, 8 and 9 on Mac OS X</a>, 2011-06, xairon.net</li>\n<li><a href=\"http://osxdaily.com/2011/09/04/internet-explorer-for-mac-ie7-ie8-ie-9-free/\" rel=\"nofollow noreferrer\">Internet Explorer for Mac the Easy Way</a>, 2011-09, osxdaily.com</li>\n</ul>\n\n<p>In the past, there were also native Mac applications (such as <a href=\"http://www.kronenberg.org/ies4osx/\" rel=\"nofollow noreferrer\">ies4osx</a>), or as a Windows application which requires a VM if you don't have Windows (such as <a href=\"http://www.my-debugbar.com/wiki/IETester/HomePage\" rel=\"nofollow noreferrer\">IETester</a> or <a href=\"http://tredosoft.com/Multiple_IE\" rel=\"nofollow noreferrer\">MultipleIEs</a>). The downside is that these emulations are often less stable than the real client, and are even harder to debug with because they don't run in the natural environment of the browser. Sometimes causing errors that don't occur in the real browser, and maybe not having bugs that the real browser would have.</p>\n\n<p><strong>Cloud-based screenshots factory</strong></p>\n\n<p>If you don't need interactivity and or need a cheaper solution (note that this method may not always be cheaper, do a little research before making assumptions) there are also services online that, like the previous one, have access to real browser/OS environments. But contrary to the previous, don't grant interactive access to the actual machines but only to get screenshots. This has both an upside and a downside. The downside is that you can't interact with it. The upside however is that most of these allow easy summarizing of screenshots so you don't have to start session after another and get screenshots.</p>\n\n<p>Some I've used:</p>\n\n<ul>\n<li><a href=\"http://browsershots.org/\" rel=\"nofollow noreferrer\">BrowserShots</a> (free and used to be my favorite, although the slowness made alternatives more attractive)</li>\n<li><a href=\"https://browserlab.adobe.com/\" rel=\"nofollow noreferrer\">Adobe BrowserLab</a> (also free, requires an Adobe ID. Not as much options and coverage as BrowserShots, but: no delay, instant screenshots, compare views and ability to let the screenshot be taken after a given number of seconds instead of right away (to test asynchronous stuff).</li>\n<li><a href=\"http://crossbrowsertesting.com/\" rel=\"nofollow noreferrer\">CrossBrowserTesting</a> (not free, but also has an interactive environment (see previous method) and a screenshot factory that is like your own private \"BrowserShots\" site)</li>\n</ul>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168/"
] | I want to test the web pages I create in all the modern versions of Internet Explorer (6, 7 and 8 beta) but I work mainly on a Mac and often don't have direct access to a PC. | **Update:** Microsoft now provide virtual machine images for various versions of IE that are ready to use on all of the major OS X virtualisation platforms ([VirtualBox](https://www.virtualbox.org), [VMWare Fusion](http://www.vmware.com/products/fusion/overview.html), and [Parallels](http://www.parallels.com/)).
Download the appropriate image from: <https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/>
---
On an Intel based Mac you can run Windows within a virtual machine. You will need one virtual machine for each version of IE you want to test against.
The instructions below include free and legal virtualisation software and Windows disk images.
1. Download some virtual machine software. The developer disk images we're going to use are will work with either [VMWare Fusion](http://www.vmware.com/products/fusion/) or [Sun Virtual Box](http://www.virtualbox.org/). VMWare has more features but costs $80, Virtual Box on the other hand is more basic but is free for most users (see [Virtual Box licensing FAQ](http://www.virtualbox.org/wiki/Licensing_FAQ) for details).
2. Download the IE developer disk images, which are free from Microsoft: [http://www.microsoft.com/downloads/...](http://www.microsoft.com/downloads/details.aspx?FamilyId=21EABB90-958F-4B64-B5F1-73D0A413C8EF&displaylang=en)
3. Extract the disk images using [cabextract](http://www.cabextract.org.uk/) which is available from [MacPorts](http://www.macports.org) or as source code (Thanks to [Clinton](https://stackoverflow.com/users/6262/clinton)).
4. Download Q.app from <http://www.kju-app.org/> and put it in your /Applications folder (you will need it to convert the disk images into a format VMWare/Virtual Box can use)
At this point, the process depends on which VM software you're using.
**Virtual Box users**
1. Open a Terminal.app on your Mac (you can find it in /Applications/Utilities) and run the following sequence of commands, replacing *input.vhd* with the name of the VHD file you're starting from and *output.vdi* with the name you want your final disk image to have:
```
/Applications/Q.app/Contents/MacOS/qemu-img convert -O raw -f vpc "input.vhd" temp.bin
VBoxManage convertdd temp.bin "output.vdi"
rm temp.bin
mv "output.vdi" ~/Library/VirtualBox/VDI/
VBoxManage modifyvdi "output.vdi" compact
```
2. Start Virtual Box and create a new virtual machine
3. Select the new VDI file you've just created as the boot hard disk
**VMWare fusion users**
1. Open a Terminal.app on your Mac (you can find it in /Applications/Utilities) and run the following commands, replacing *input.vhd* and *output.vmdk* with the name of the VHD file you're working on and the name you want your resulting disk image to have:
```
/Applications/Q.app/Contents/MacOS/qemu-img convert -O vmdk -f vpc "input.vhd" "output.vmdk"
mv "output.vmdk" ~/Documents/Virtual\ Machines.localized/
```
This will probably take a while (It takes around 30 minutes per disk image on my 2.4GHz Core 2 Duo MacBook w/ 2Gb RAM).
2. Start VMWare Fusion and create a new virtual machine
3. In the advanced disk options select "use and existing disk" and find the VMDK file you just created |
55,607 | <p>What is the best way to use multiple EVAL fields in a GridView ItemTemplate?</p>
<p>Looking to have some control over formatting for appearance as well as setting up hyperlinks/javascript etc.</p>
| [
{
"answer_id": 55629,
"author": "Dhaust",
"author_id": 242,
"author_profile": "https://Stackoverflow.com/users/242",
"pm_score": 3,
"selected": false,
"text": "<p>I had previously used this (bad, I know): </p>\n\n<pre><code><%# Eval(\"Name1\", \"{0} - \")%> <%#Eval(\"Name2\")%>\n</code></pre>\n\n<p>Result = 'John - Smith'</p>\n\n<p>But just discovered that I can also put TWO (or more) Evals in the same data-bound group: </p>\n\n<pre><code><%#Eval(\"Name1\") & \" - \" & Eval(\"Name2\")%>\n</code></pre>\n\n<p>Result = 'John - Smith' </p>\n\n<p>Or </p>\n\n<pre><code><%# \"First Name - \" & Eval(\"Name1\") & \", Last Name - \" & Eval(\"Name2\")%> \n</code></pre>\n\n<p>Result = 'First Name - John, Last Name - Smith'</p>\n"
},
{
"answer_id": 55681,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 7,
"selected": true,
"text": "<p>Even clearer, IMO, is:</p>\n\n<pre><code><%# String.Format(\"{0} - {1}\", Eval(\"Name1\"), Eval(\"Name2\")) %>\n</code></pre>\n"
},
{
"answer_id": 55688,
"author": "Esteban Araya",
"author_id": 781,
"author_profile": "https://Stackoverflow.com/users/781",
"pm_score": 3,
"selected": false,
"text": "<p>Eval and Bind both suck.<br>\nWhy get the property through reflection? You can access it directly like this:</p>\n\n<pre>\n((MyObject)Container.DataItem).MyProperty\n</pre> \n\n<p>It's not like the object is unknown to you at runtime. That's my two cents, anyhow.</p>\n"
},
{
"answer_id": 36522821,
"author": "Durgesh Pandey",
"author_id": 5030579,
"author_profile": "https://Stackoverflow.com/users/5030579",
"pm_score": 2,
"selected": false,
"text": "<p>I have a easiest way to do this same thing...</p>\n\n<pre><code><asp:Label ID=\"lblName\" runat=\"server\" Text='<%#Eval(\"FirstName\").ToString() +\", \"+ Eval(\"LastName\").ToString() %>'></asp:Label>\n</code></pre>\n\n<p>.</p>\n\n<pre><code><%#Eval(\"FirstName\").ToString() +\", \"+ Eval(\"LastName\").ToString() %>\n</code></pre>\n\n<p>Here both objects are converted into string the concatenate them.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242/"
] | What is the best way to use multiple EVAL fields in a GridView ItemTemplate?
Looking to have some control over formatting for appearance as well as setting up hyperlinks/javascript etc. | Even clearer, IMO, is:
```
<%# String.Format("{0} - {1}", Eval("Name1"), Eval("Name2")) %>
``` |
55,611 | <p>To make a JavaScript class with a public method I'd do something like:</p>
<pre><code>function Restaurant() {}
Restaurant.prototype.buy_food = function(){
// something here
}
Restaurant.prototype.use_restroom = function(){
// something here
}
</code></pre>
<p>That way users of my class can:</p>
<pre><code>var restaurant = new Restaurant();
restaurant.buy_food();
restaurant.use_restroom();
</code></pre>
<p>How do I create a private method that can be called by the <code>buy_food</code> and <code>use_restroom</code> methods but not externally by users of the class?</p>
<p>In other words, I want my method implementation to be able to do:</p>
<pre><code>Restaurant.prototype.use_restroom = function() {
this.private_stuff();
}
</code></pre>
<p>But this shouldn't work:</p>
<pre><code>var r = new Restaurant();
r.private_stuff();
</code></pre>
<p>How do I define <code>private_stuff</code> as a private method so both of these hold true?</p>
<p>I've read <a href="http://javascript.crockford.com/private.html" rel="noreferrer">Doug Crockford's writeup</a> a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally.</p>
| [
{
"answer_id": 55637,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 10,
"selected": true,
"text": "<p>You can do it, but the downside is that it can't be part of the prototype:</p>\n\n<pre><code>function Restaurant() {\n var myPrivateVar;\n\n var private_stuff = function() { // Only visible inside Restaurant()\n myPrivateVar = \"I can set this here!\";\n }\n\n this.use_restroom = function() { // use_restroom is visible to all\n private_stuff();\n }\n\n this.buy_food = function() { // buy_food is visible to all\n private_stuff();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 55638,
"author": "georgebrock",
"author_id": 5168,
"author_profile": "https://Stackoverflow.com/users/5168",
"pm_score": 7,
"selected": false,
"text": "<p>You can simulate private methods like this:</p>\n\n<pre><code>function Restaurant() {\n}\n\nRestaurant.prototype = (function() {\n var private_stuff = function() {\n // Private code here\n };\n\n return {\n\n constructor:Restaurant,\n\n use_restroom:function() {\n private_stuff();\n }\n\n };\n})();\n\nvar r = new Restaurant();\n\n// This will work:\nr.use_restroom();\n\n// This will cause an error:\nr.private_stuff();\n</code></pre>\n\n<p>More information on this technique here: <a href=\"http://webreflection.blogspot.com/2008/04/natural-javascript-private-methods.html\" rel=\"noreferrer\">http://webreflection.blogspot.com/2008/04/natural-javascript-private-methods.html</a></p>\n"
},
{
"answer_id": 55696,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>In these situations when you have a public API, and you would like private and public methods/properties, I always use the Module Pattern. This pattern was made popular within the YUI library, and the details can be found here:</p>\n\n<p><a href=\"http://yuiblog.com/blog/2007/06/12/module-pattern/\" rel=\"noreferrer\">http://yuiblog.com/blog/2007/06/12/module-pattern/</a></p>\n\n<p>It is really straightforward, and easy for other developers to comprehend. For a simple example:</p>\n\n<pre><code>var MYLIB = function() { \n var aPrivateProperty = true;\n var aPrivateMethod = function() {\n // some code here...\n };\n return {\n aPublicMethod : function() {\n aPrivateMethod(); // okay\n // some code here...\n },\n aPublicProperty : true\n }; \n}();\n\nMYLIB.aPrivateMethod() // not okay\nMYLIB.aPublicMethod() // okay\n</code></pre>\n"
},
{
"answer_id": 55739,
"author": "Daniel Stockman",
"author_id": 5707,
"author_profile": "https://Stackoverflow.com/users/5707",
"pm_score": 2,
"selected": false,
"text": "<p>The apotheosis of the Module Pattern: <a href=\"http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/\" rel=\"nofollow noreferrer\" title=\"from Chris Heilemann, naturally\">The Revealing Module Pattern</a></p>\n\n<p>A neat little extension to a very robust pattern.</p>\n"
},
{
"answer_id": 63016,
"author": "Kelly",
"author_id": 7157,
"author_profile": "https://Stackoverflow.com/users/7157",
"pm_score": 3,
"selected": false,
"text": "<p>All of this closure will cost you. Make sure you test the speed implications especially in IE. You will find you are better off with a naming convention. There are still a lot of corporate web users out there that are forced to use IE6...</p>\n"
},
{
"answer_id": 148219,
"author": "domgblackwell",
"author_id": 16954,
"author_profile": "https://Stackoverflow.com/users/16954",
"pm_score": 2,
"selected": false,
"text": "<p>If you want the full range of public and private functions with the ability for public functions to access private functions, layout code for an object like this:</p>\n\n<pre><code>function MyObject(arg1, arg2, ...) {\n //constructor code using constructor arguments...\n //create/access public variables as \n // this.var1 = foo;\n\n //private variables\n\n var v1;\n var v2;\n\n //private functions\n function privateOne() {\n }\n\n function privateTwon() {\n }\n\n //public functions\n\n MyObject.prototype.publicOne = function () {\n };\n\n MyObject.prototype.publicTwo = function () {\n };\n}\n</code></pre>\n"
},
{
"answer_id": 1361654,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>I conjured up this: EDIT: Actually, someone has linked to a identical solution. Duh!</p>\n\n<pre><code>var Car = function() {\n}\n\nCar.prototype = (function() {\n var hotWire = function() {\n // Private code *with* access to public properties through 'this'\n alert( this.drive() ); // Alerts 'Vroom!'\n }\n\n return {\n steal: function() {\n hotWire.call( this ); // Call a private method\n },\n drive: function() {\n return 'Vroom!';\n }\n };\n})();\n\nvar getAwayVechile = new Car();\n\nhotWire(); // Not allowed\ngetAwayVechile.hotWire(); // Not allowed\ngetAwayVechile.steal(); // Alerts 'Vroom!'\n</code></pre>\n"
},
{
"answer_id": 5703989,
"author": "David",
"author_id": 713524,
"author_profile": "https://Stackoverflow.com/users/713524",
"pm_score": 2,
"selected": false,
"text": "<pre><code>var TestClass = function( ) {\n\n var privateProperty = 42;\n\n function privateMethod( ) {\n alert( \"privateMethod, \" + privateProperty );\n }\n\n this.public = {\n constructor: TestClass,\n\n publicProperty: 88,\n publicMethod: function( ) {\n alert( \"publicMethod\" );\n privateMethod( );\n }\n };\n};\nTestClass.prototype = new TestClass( ).public;\n\n\nvar myTestClass = new TestClass( );\n\nalert( myTestClass.publicProperty );\nmyTestClass.publicMethod( );\n\nalert( myTestClass.privateMethod || \"no privateMethod\" );\n</code></pre>\n\n<p>Similar to georgebrock but a little less verbose (IMHO)\nAny problems with doing it this way? (I haven't seen it anywhere)</p>\n\n<p>edit: I realised this is kinda useless since every independent instantiation has its own copy of the public methods, thus undermining the use of the prototype.</p>\n"
},
{
"answer_id": 6169955,
"author": "Dooma",
"author_id": 765125,
"author_profile": "https://Stackoverflow.com/users/765125",
"pm_score": 0,
"selected": false,
"text": "<p>Private functions cannot access the public variables using module pattern</p>\n"
},
{
"answer_id": 9288441,
"author": "Sarath",
"author_id": 353241,
"author_profile": "https://Stackoverflow.com/users/353241",
"pm_score": 4,
"selected": false,
"text": "<p>Here is the class which I created to understand what Douglas Crockford's has suggested in his site <a href=\"http://javascript.crockford.com/private.html\">Private Members in JavaScript</a></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function Employee(id, name) { //Constructor\n //Public member variables\n this.id = id;\n this.name = name;\n //Private member variables\n var fName;\n var lName;\n var that = this;\n //By convention, we create a private variable 'that'. This is used to \n //make the object available to the private methods. \n\n //Private function\n function setFName(pfname) {\n fName = pfname;\n alert('setFName called');\n }\n //Privileged function\n this.setLName = function (plName, pfname) {\n lName = plName; //Has access to private variables\n setFName(pfname); //Has access to private function\n alert('setLName called ' + this.id); //Has access to member variables\n }\n //Another privileged member has access to both member variables and private variables\n //Note access of this.dataOfBirth created by public member setDateOfBirth\n this.toString = function () {\n return 'toString called ' + this.id + ' ' + this.name + ' ' + fName + ' ' + lName + ' ' + this.dataOfBirth; \n }\n}\n//Public function has access to member variable and can create on too but does not have access to private variable\nEmployee.prototype.setDateOfBirth = function (dob) {\n alert('setDateOfBirth called ' + this.id);\n this.dataOfBirth = dob; //Creates new public member note this is accessed by toString\n //alert(fName); //Does not have access to private member\n}\n$(document).ready()\n{\n var employee = new Employee(5, 'Shyam'); //Create a new object and initialize it with constructor\n employee.setLName('Bhaskar', 'Ram'); //Call privileged function\n employee.setDateOfBirth('1/1/2000'); //Call public function\n employee.id = 9; //Set up member value\n //employee.setFName('Ram'); //can not call Private Privileged method\n alert(employee.toString()); //See the changed object\n\n}\n</code></pre>\n"
},
{
"answer_id": 13327997,
"author": "mark",
"author_id": 1753943,
"author_profile": "https://Stackoverflow.com/users/1753943",
"pm_score": 0,
"selected": false,
"text": "<p>Since everybody was posting here his own code, I'm gonna do that too...</p>\n\n<p>I like Crockford because he introduced real object oriented patterns in Javascript. But he also came up with a new misunderstanding, the \"that\" one.</p>\n\n<p>So why is he using \"that = this\"? It has nothing to do with private functions at all. It has to do with inner functions! </p>\n\n<p>Because according to Crockford this is buggy code: </p>\n\n<pre><code>Function Foo( ) {\n this.bar = 0; \n var foobar=function( ) {\n alert(this.bar);\n }\n} \n</code></pre>\n\n<p>So he suggested doing this:</p>\n\n<pre><code>Function Foo( ) {\n this.bar = 0;\n that = this; \n var foobar=function( ) {\n alert(that.bar);\n }\n}\n</code></pre>\n\n<p>So as I said, I'm quite sure that Crockford was wrong his explanation about that and this (but his code is certainly correct). Or was he just fooling the Javascript world, to know who is copying his code? I dunno...I'm no browser geek ;D</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Ah, that's what is all about: <a href=\"https://stackoverflow.com/questions/4886632/what-does-var-that-this-mean-in-javascript\">What does 'var that = this;' mean in JavaScript?</a></p>\n\n<p>So Crockie was really wrong with his explanation....but right with his code, so he's still a great guy. :))</p>\n"
},
{
"answer_id": 15721313,
"author": "Andreas Dyballa",
"author_id": 1636136,
"author_profile": "https://Stackoverflow.com/users/1636136",
"pm_score": 0,
"selected": false,
"text": "<p>In general I added the private Object _ temporarily to the object.\nYou have to open the privacy exlipcitly in the \"Power-constructor\" for the method.\nIf you call the method from the prototype, you will\nbe able to overwrite the prototype-method</p>\n\n<ul>\n<li><p>Make a public method accessible in the \"Power-constructor\": (ctx is the object context)</p>\n\n<pre><code>ctx.test = GD.Fabric.open('test', GD.Test.prototype, ctx, _); // is a private object\n</code></pre></li>\n<li><p>Now I have this openPrivacy:</p>\n\n<pre><code>GD.Fabric.openPrivacy = function(func, clss, ctx, _) {\n return function() {\n ctx._ = _;\n var res = clss[func].apply(ctx, arguments);\n ctx._ = null;\n return res;\n };\n};\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 16605660,
"author": "Flex Elektro Deimling",
"author_id": 530335,
"author_profile": "https://Stackoverflow.com/users/530335",
"pm_score": 0,
"selected": false,
"text": "<p>You have to put a closure around your actual constructor-function, where you can define your private methods.\nTo change data of the instances through these private methods, you have to give them \"this\" with them, either as an function argument or by calling this function with .apply(this) :</p>\n\n<pre><code>var Restaurant = (function(){\n var private_buy_food = function(that){\n that.data.soldFood = true;\n }\n var private_take_a_shit = function(){\n this.data.isdirty = true; \n }\n // New Closure\n function restaurant()\n {\n this.data = {\n isdirty : false,\n soldFood: false,\n };\n }\n\n restaurant.prototype.buy_food = function()\n {\n private_buy_food(this);\n }\n restaurant.prototype.use_restroom = function()\n {\n private_take_a_shit.call(this);\n }\n return restaurant;\n})()\n\n// TEST:\n\nvar McDonalds = new Restaurant();\nMcDonalds.buy_food();\nMcDonalds.use_restroom();\nconsole.log(McDonalds);\nconsole.log(McDonalds.__proto__);\n</code></pre>\n"
},
{
"answer_id": 18222581,
"author": "iimos",
"author_id": 502860,
"author_profile": "https://Stackoverflow.com/users/502860",
"pm_score": 4,
"selected": false,
"text": "<p>I think such questions come up again and again because of the lack of understanding of the closures. Сlosures is most important thing in JS. Every JS programmer have to feel the essence of it.</p>\n\n<p><strong>1.</strong> First of all we need to make separate scope (closure).</p>\n\n<pre><code>function () {\n\n}\n</code></pre>\n\n<p><strong>2.</strong> In this area, we can do whatever we want. And no one will know about it.</p>\n\n<pre><code>function () {\n var name,\n secretSkills = {\n pizza: function () { return new Pizza() },\n sushi: function () { return new Sushi() }\n }\n\n function Restaurant(_name) {\n name = _name\n }\n Restaurant.prototype.getFood = function (name) {\n return name in secretSkills ? secretSkills[name]() : null\n }\n}\n</code></pre>\n\n<p><strong>3.</strong> For the world to know about our restaurant class, \nwe have to return it from the closure.</p>\n\n<pre><code>var Restaurant = (function () {\n // Restaurant definition\n return Restaurant\n})()\n</code></pre>\n\n<p><strong>4.</strong> At the end, we have:</p>\n\n<pre><code>var Restaurant = (function () {\n var name,\n secretSkills = {\n pizza: function () { return new Pizza() },\n sushi: function () { return new Sushi() }\n }\n\n function Restaurant(_name) {\n name = _name\n }\n Restaurant.prototype.getFood = function (name) {\n return name in secretSkills ? secretSkills[name]() : null\n }\n return Restaurant\n})()\n</code></pre>\n\n<p><strong>5.</strong> Also, this approach has potential for inheritance and templating</p>\n\n<pre><code>// Abstract class\nfunction AbstractRestaurant(skills) {\n var name\n function Restaurant(_name) {\n name = _name\n }\n Restaurant.prototype.getFood = function (name) {\n return skills && name in skills ? skills[name]() : null\n }\n return Restaurant\n}\n\n// Concrete classes\nSushiRestaurant = AbstractRestaurant({ \n sushi: function() { return new Sushi() } \n})\n\nPizzaRestaurant = AbstractRestaurant({ \n pizza: function() { return new Pizza() } \n})\n\nvar r1 = new SushiRestaurant('Yo! Sushi'),\n r2 = new PizzaRestaurant('Dominos Pizza')\n\nr1.getFood('sushi')\nr2.getFood('pizza')\n</code></pre>\n\n<p>I hope this helps someone better understand this subject</p>\n"
},
{
"answer_id": 18239876,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This is what I worked out:</p>\n\n<p>Needs one class of sugar code that <a href=\"https://github.com/najamelan/TidBits_Javascript_OoJs\" rel=\"nofollow\">you can find here</a>. Also supports protected, inheritance, virtual, static stuff...</p>\n\n<pre><code>;( function class_Restaurant( namespace )\n{\n 'use strict';\n\n if( namespace[ \"Restaurant\" ] ) return // protect against double inclusions\n\n namespace.Restaurant = Restaurant\n var Static = TidBits.OoJs.setupClass( namespace, \"Restaurant\" )\n\n\n // constructor\n //\n function Restaurant()\n {\n this.toilets = 3\n\n this.Private( private_stuff )\n\n return this.Public( buy_food, use_restroom )\n }\n\n function private_stuff(){ console.log( \"There are\", this.toilets, \"toilets available\") }\n\n function buy_food (){ return \"food\" }\n function use_restroom (){ this.private_stuff() }\n\n})( window )\n\n\nvar chinese = new Restaurant\n\nconsole.log( chinese.buy_food() ); // output: food\nconsole.log( chinese.use_restroom() ); // output: There are 3 toilets available\nconsole.log( chinese.toilets ); // output: undefined\nconsole.log( chinese.private_stuff() ); // output: undefined\n\n// and throws: TypeError: Object #<Restaurant> has no method 'private_stuff'\n</code></pre>\n"
},
{
"answer_id": 19695554,
"author": "Evan Leis",
"author_id": 981337,
"author_profile": "https://Stackoverflow.com/users/981337",
"pm_score": 2,
"selected": false,
"text": "<p>What about this?</p>\n\n<pre><code>var Restaurant = (function() {\n\n var _id = 0;\n var privateVars = [];\n\n function Restaurant(name) {\n this.id = ++_id;\n this.name = name;\n privateVars[this.id] = {\n cooked: []\n };\n }\n\n Restaurant.prototype.cook = function (food) {\n privateVars[this.id].cooked.push(food);\n }\n\n return Restaurant;\n\n})();\n</code></pre>\n\n<p>Private variable lookup is impossible outside of the scope of the immediate function.\nThere is no duplication of functions, saving memory.</p>\n\n<p>The downside is that the lookup of private variables is clunky <code>privateVars[this.id].cooked</code> is ridiculous to type. There is also an extra \"id\" variable.</p>\n"
},
{
"answer_id": 20500648,
"author": "snowkid",
"author_id": 3087829,
"author_profile": "https://Stackoverflow.com/users/3087829",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Class({ \n Namespace:ABC, \n Name:\"ClassL2\", \n Bases:[ABC.ClassTop], \n Private:{ \n m_var:2 \n }, \n Protected:{ \n proval:2, \n fight:Property(function(){ \n this.m_var--; \n console.log(\"ClassL2::fight (m_var)\" +this.m_var); \n },[Property.Type.Virtual]) \n }, \n Public:{ \n Fight:function(){ \n console.log(\"ClassL2::Fight (m_var)\"+this.m_var); \n this.fight(); \n } \n } \n}); \n</code></pre>\n\n<p><a href=\"https://github.com/nooning/JSClass\" rel=\"nofollow\">https://github.com/nooning/JSClass</a></p>\n"
},
{
"answer_id": 21167136,
"author": "Trem",
"author_id": 732236,
"author_profile": "https://Stackoverflow.com/users/732236",
"pm_score": 0,
"selected": false,
"text": "<p>I have created a new tool to allow you to have true private methods on the prototype\n<a href=\"https://github.com/TremayneChrist/ProtectJS\" rel=\"nofollow\">https://github.com/TremayneChrist/ProtectJS</a></p>\n\n<p>Example:</p>\n\n<pre><code>var MyObject = (function () {\n\n // Create the object\n function MyObject() {}\n\n // Add methods to the prototype\n MyObject.prototype = {\n\n // This is our public method\n public: function () {\n console.log('PUBLIC method has been called');\n },\n\n // This is our private method, using (_)\n _private: function () {\n console.log('PRIVATE method has been called');\n }\n }\n\n return protect(MyObject);\n\n})();\n\n// Create an instance of the object\nvar mo = new MyObject();\n\n// Call its methods\nmo.public(); // Pass\nmo._private(); // Fail\n</code></pre>\n"
},
{
"answer_id": 25172901,
"author": "Yves M.",
"author_id": 1480391,
"author_profile": "https://Stackoverflow.com/users/1480391",
"pm_score": 8,
"selected": false,
"text": "<h1>Using self invoking function and call</h1>\n<p>JavaScript uses <a href=\"http://en.wikipedia.org/wiki/Prototype-based_programming\" rel=\"noreferrer\">prototypes</a> and does't have classes (or methods for that matter) like Object Oriented languages. A JavaScript developer need to think in JavaScript.</p>\n<p>Wikipedia quote:</p>\n<blockquote>\n<p>Unlike many object-oriented languages, there is no distinction between\na function definition and a method definition. Rather, the distinction\noccurs during function calling; when a function is called as a method\nof an object, the function's local this keyword is bound to that\nobject for that invocation.</p>\n</blockquote>\n<p>Solution using a <a href=\"http://en.wikipedia.org/wiki/Immediately-invoked_function_expression\" rel=\"noreferrer\">self invoking function</a> and the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call\" rel=\"noreferrer\">call function</a> to call the private "method" :</p>\n<pre class=\"lang-js prettyprint-override\"><code>var MyObject = (function () {\n \n // Constructor\n function MyObject(foo) {\n this._foo = foo;\n }\n\n function privateFun(prefix) {\n return prefix + this._foo;\n }\n \n MyObject.prototype.publicFun = function () {\n return privateFun.call(this, ">>");\n }\n \n return MyObject;\n\n}());\n</code></pre>\n<pre class=\"lang-js prettyprint-override\"><code>var myObject = new MyObject("bar");\nmyObject.publicFun(); // Returns ">>bar"\nmyObject.privateFun(">>"); // ReferenceError: private is not defined\n</code></pre>\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call\" rel=\"noreferrer\">call function</a> allows us to call the private function with the appropriate context (<code>this</code>).</p>\n<h1>Simpler with Node.js</h1>\n<p>If you are using <a href=\"http://nodejs.org/\" rel=\"noreferrer\">Node.js</a>, you don't need the <a href=\"http://en.wikipedia.org/wiki/Immediately-invoked_function_expression\" rel=\"noreferrer\">IIFE</a> because you can take advantage of the <a href=\"http://nodejs.org/api/modules.html\" rel=\"noreferrer\">module loading system</a>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function MyObject(foo) {\n this._foo = foo;\n}\n \nfunction privateFun(prefix) {\n return prefix + this._foo;\n}\n\nMyObject.prototype.publicFun = function () {\n return privateFun.call(this, ">>");\n}\n \nmodule.exports= MyObject;\n</code></pre>\n<p>Load the file:</p>\n<pre class=\"lang-js prettyprint-override\"><code>var MyObject = require("./MyObject");\n \nvar myObject = new MyObject("bar");\nmyObject.publicFun(); // Returns ">>bar"\nmyObject.privateFun(">>"); // ReferenceError: private is not defined\n</code></pre>\n<h1>(new!) Native private methods in future JavaScript versions</h1>\n<p>TC39 <a href=\"https://github.com/tc39/proposal-private-methods\" rel=\"noreferrer\">private methods and getter/setters for JavaScript classes</a> proposal is stage 3. That means any time soon, JavaScript will implement private methods natively!</p>\n<p>Note that <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields\" rel=\"noreferrer\">JavaScript private class fields</a> already exists in modern JavaScript versions.</p>\n<p>Here is an example of how it is used:</p>\n<pre class=\"lang-js prettyprint-override\"><code>class MyObject {\n\n // Private field\n #foo;\n \n constructor(foo) {\n this.#foo = foo;\n }\n\n #privateFun(prefix) {\n return prefix + this.#foo;\n }\n \n publicFun() {\n return this.#privateFun(">>");\n }\n\n}\n</code></pre>\n<p>You may need a <a href=\"https://babeljs.io\" rel=\"noreferrer\">JavaScript transpiler/compiler</a> to run this code on old JavaScript engines.</p>\n<p>PS: If you wonder why the <code>#</code> prefix, <a href=\"https://github.com/tc39/proposal-private-fields/issues/14\" rel=\"noreferrer\">read this</a>.</p>\n<h1>(deprecated) ES7 with the Bind Operator</h1>\n<p>Warning: The bind operator TC39 proposition is near dead <a href=\"https://github.com/tc39/proposal-bind-operator/issues/53#issuecomment-374271822\" rel=\"noreferrer\">https://github.com/tc39/proposal-bind-operator/issues/53#issuecomment-374271822</a></p>\n<p>The bind operator <code>::</code> is an ECMAScript <a href=\"https://github.com/zenparsing/es-function-bind\" rel=\"noreferrer\">proposal</a> and is <a href=\"https://babeljs.io/blog/2015/05/14/function-bind\" rel=\"noreferrer\">implemented in Babel</a> (<a href=\"https://babeljs.io/docs/plugins/preset-stage-0/\" rel=\"noreferrer\">stage 0</a>).</p>\n<pre><code>export default class MyObject {\n constructor (foo) {\n this._foo = foo;\n }\n\n publicFun () {\n return this::privateFun(">>");\n }\n}\n\nfunction privateFun (prefix) {\n return prefix + this._foo;\n}\n</code></pre>\n"
},
{
"answer_id": 25366378,
"author": "Fozi",
"author_id": 168683,
"author_profile": "https://Stackoverflow.com/users/168683",
"pm_score": 2,
"selected": false,
"text": "<p>Take any of the solutions that follow Crockford's <em>private</em> or <em>priviledged</em> pattern. For example:</p>\n\n<pre><code>function Foo(x) {\n var y = 5;\n var bar = function() {\n return y * x;\n };\n\n this.public = function(z) {\n return bar() + x * z;\n };\n}\n</code></pre>\n\n<p>In any case where the attacker has no \"execute\" right on the JS context he has no way of accessing any \"public\" or \"private\" fields or methods. In case the attacker does have that access he can execute this one-liner:</p>\n\n<pre><code>eval(\"Foo = \" + Foo.toString().replace(\n /{/, \"{ this.eval = function(code) { return eval(code); }; \"\n));\n</code></pre>\n\n<p>Note that the above code is generic to all constructor-type-privacy. It will fail with some of the solutions here but it should be clear that pretty much all of the closure based solutions can be broken like this with different <code>replace()</code> parameters. </p>\n\n<p>After this is executed any object created with <code>new Foo()</code> is going to have an <code>eval</code> method which can be called to return or change values or methods defined in the constructor's closure, e.g.:</p>\n\n<pre><code>f = new Foo(99);\nf.eval(\"x\");\nf.eval(\"y\");\nf.eval(\"x = 8\");\n</code></pre>\n\n<p>The only problem I can see with this that it won't work for cases where there is only one instance and it's created on load. But then there is no reason to actually define a prototype and in that case the attacker can simply recreate the object instead of the constructor as long as he has a way of passing the same parameters (e.g. they are constant or calculated from available values).</p>\n\n<p><strong>In my opinion, this pretty much makes Crockford's solution useless.</strong> Since the \"privacy\" is easily broken the downsides of his solution (reduced readability & maintainability, decreased performance, increased memory) makes the \"no privacy\" prototype based method the better choice. </p>\n\n<p>I do usually use leading underscores to mark <code>__private</code> and <code>_protected</code> methods and fields (Perl style), but the idea of having privacy in JavaScript just shows how it's a misunderstood language. </p>\n\n<p><strong>Therefore I disagree with <a href=\"http://crockford.com/javascript/private.html\" rel=\"nofollow noreferrer\">Crockford</a></strong> except for his first sentence.</p>\n\n<p><strong>So how do you get real privacy in JS?</strong> Put everything that is required to be private on the server side and use JS to do AJAX calls.</p>\n"
},
{
"answer_id": 27396880,
"author": "low_rents",
"author_id": 3391783,
"author_profile": "https://Stackoverflow.com/users/3391783",
"pm_score": 2,
"selected": false,
"text": "<p>Here's what i enjoyed the most so far regarding private/public methods/members and instantiation in javascript:</p>\n\n<p>here is the article: <a href=\"http://www.sefol.com/?p=1090\" rel=\"nofollow\">http://www.sefol.com/?p=1090</a></p>\n\n<p>and here is the example:</p>\n\n<pre><code>var Person = (function () {\n\n //Immediately returns an anonymous function which builds our modules \n return function (name, location) {\n\n alert(\"createPerson called with \" + name);\n\n var localPrivateVar = name;\n\n var localPublicVar = \"A public variable\";\n\n var localPublicFunction = function () {\n alert(\"PUBLIC Func called, private var is :\" + localPrivateVar)\n };\n\n var localPrivateFunction = function () {\n alert(\"PRIVATE Func called \")\n };\n\n var setName = function (name) {\n\n localPrivateVar = name;\n\n }\n\n return {\n\n publicVar: localPublicVar,\n\n location: location,\n\n publicFunction: localPublicFunction,\n\n setName: setName\n\n }\n\n }\n})();\n\n\n//Request a Person instance - should print \"createPerson called with ben\"\nvar x = Person(\"ben\", \"germany\");\n\n//Request a Person instance - should print \"createPerson called with candide\"\nvar y = Person(\"candide\", \"belgium\");\n\n//Prints \"ben\"\nx.publicFunction();\n\n//Prints \"candide\"\ny.publicFunction();\n\n//Now call a public function which sets the value of a private variable in the x instance\nx.setName(\"Ben 2\");\n\n//Shouldn't have changed this : prints \"candide\"\ny.publicFunction();\n\n//Should have changed this : prints \"Ben 2\"\nx.publicFunction();\n</code></pre>\n\n<p>JSFiddle: <a href=\"http://jsfiddle.net/northkildonan/kopj3dt3/1/\" rel=\"nofollow\">http://jsfiddle.net/northkildonan/kopj3dt3/1/</a></p>\n"
},
{
"answer_id": 28190815,
"author": "Maxim Balaganskiy",
"author_id": 944182,
"author_profile": "https://Stackoverflow.com/users/944182",
"pm_score": 0,
"selected": false,
"text": "<p>I know it's a bit too late but how about this?</p>\n\n<pre><code>var obj = function(){\n var pr = \"private\";\n var prt = Object.getPrototypeOf(this);\n if(!prt.hasOwnProperty(\"showPrivate\")){\n prt.showPrivate = function(){\n console.log(pr);\n }\n } \n}\n\nvar i = new obj();\ni.showPrivate();\nconsole.log(i.hasOwnProperty(\"pr\"));\n</code></pre>\n"
},
{
"answer_id": 28279952,
"author": "James",
"author_id": 1185191,
"author_profile": "https://Stackoverflow.com/users/1185191",
"pm_score": 2,
"selected": false,
"text": "<p>The module pattern is right in most cases. But if you have thousands of instances, classes save memory. If saving memory is a concern and your objects contain a small amount of private data, but have a lot of public functions, then you'll want all public functions to live in the .prototype to save memory.</p>\n\n<p>This is what I came up with:</p>\n\n<pre><code>var MyClass = (function () {\n var secret = {}; // You can only getPriv() if you know this\n function MyClass() {\n var that = this, priv = {\n foo: 0 // ... and other private values\n };\n that.getPriv = function (proof) {\n return (proof === secret) && priv;\n };\n }\n MyClass.prototype.inc = function () {\n var priv = this.getPriv(secret);\n priv.foo += 1;\n return priv.foo;\n };\n return MyClass;\n}());\nvar x = new MyClass();\nx.inc(); // 1\nx.inc(); // 2\n</code></pre>\n\n<p>The object <code>priv</code> contains private properties. It is accessible through the public function <code>getPriv()</code>, but this function returns <code>false</code> unless you pass it the <code>secret</code>, and this is only known inside the main closure.</p>\n"
},
{
"answer_id": 31042160,
"author": "Abdennour TOUMI",
"author_id": 747579,
"author_profile": "https://Stackoverflow.com/users/747579",
"pm_score": 2,
"selected": false,
"text": "<p>Wrap all code in Anonymous Function: Then , all functions will be private ,ONLY functions attached to <code>window</code> object : </p>\n\n<pre><code>(function(w,nameSpacePrivate){\n w.Person=function(name){\n this.name=name; \n return this;\n };\n\n w.Person.prototype.profilePublic=function(){\n return nameSpacePrivate.profile.call(this);\n }; \n\n nameSpacePrivate.profile=function(){\n return 'My name is '+this.name;\n };\n\n})(window,{});\n</code></pre>\n\n<p>Use this : </p>\n\n<pre><code> var abdennour=new Person('Abdennour');\n abdennour.profilePublic();\n</code></pre>\n\n<h1><a href=\"https://jsfiddle.net/abdennour/8nzgm64u/\" rel=\"nofollow\">FIDDLE</a></h1>\n"
},
{
"answer_id": 37141668,
"author": "thegunmaster",
"author_id": 3080469,
"author_profile": "https://Stackoverflow.com/users/3080469",
"pm_score": 0,
"selected": false,
"text": "<p>There are many answers on this question already, but nothing fitted my needs. So i came up with my own solution, I hope it is usefull for someone:</p>\n\n<pre><code>function calledPrivate(){\n var stack = new Error().stack.toString().split(\"\\n\");\n function getClass(line){\n var i = line.indexOf(\" \");\n var i2 = line.indexOf(\".\");\n return line.substring(i,i2);\n }\n return getClass(stack[2])==getClass(stack[3]);\n}\n\nclass Obj{\n privateMethode(){\n if(calledPrivate()){\n console.log(\"your code goes here\");\n }\n }\n publicMethode(){\n this.privateMethode();\n }\n}\n\nvar obj = new Obj();\nobj.publicMethode(); //logs \"your code goes here\"\nobj.privateMethode(); //does nothing\n</code></pre>\n\n<p>As you can see this system works when using this type of classes in javascript. As far as I figured out none of the methods commented above did.</p>\n"
},
{
"answer_id": 44423507,
"author": "John Slegers",
"author_id": 1946501,
"author_profile": "https://Stackoverflow.com/users/1946501",
"pm_score": 3,
"selected": false,
"text": "<p>Personally, I prefer the following pattern for creating classes in JavaScript :</p>\n<pre><code>var myClass = (function() {\n // Private class properties go here\n\n var blueprint = function() {\n // Private instance properties go here\n ...\n };\n\n blueprint.prototype = { \n // Public class properties go here\n ...\n };\n\n return {\n // Public class properties go here\n create : function() { return new blueprint(); }\n ...\n };\n})();\n</code></pre>\n<p>As you can see, it allows you to define both class properties and instance properties, each of which can be public and private.</p>\n<hr />\n<h3>Demo</h3>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var Restaurant = function() {\n var totalfoodcount = 0; // Private class property\n var totalrestroomcount = 0; // Private class property\n \n var Restaurant = function(name){\n var foodcount = 0; // Private instance property\n var restroomcount = 0; // Private instance property\n \n this.name = name\n \n this.incrementFoodCount = function() {\n foodcount++;\n totalfoodcount++;\n this.printStatus();\n };\n this.incrementRestroomCount = function() {\n restroomcount++;\n totalrestroomcount++;\n this.printStatus();\n };\n this.getRestroomCount = function() {\n return restroomcount;\n },\n this.getFoodCount = function() {\n return foodcount;\n }\n };\n \n Restaurant.prototype = {\n name : '',\n buy_food : function(){\n this.incrementFoodCount();\n },\n use_restroom : function(){\n this.incrementRestroomCount();\n },\n getTotalRestroomCount : function() {\n return totalrestroomcount;\n },\n getTotalFoodCount : function() {\n return totalfoodcount;\n },\n printStatus : function() {\n document.body.innerHTML\n += '<h3>Buying food at '+this.name+'</h3>'\n + '<ul>' \n + '<li>Restroom count at ' + this.name + ' : '+ this.getRestroomCount() + '</li>'\n + '<li>Food count at ' + this.name + ' : ' + this.getFoodCount() + '</li>'\n + '<li>Total restroom count : '+ this.getTotalRestroomCount() + '</li>'\n + '<li>Total food count : '+ this.getTotalFoodCount() + '</li>'\n + '</ul>';\n }\n };\n\n return { // Singleton public properties\n create : function(name) {\n return new Restaurant(name);\n },\n printStatus : function() {\n document.body.innerHTML\n += '<hr />'\n + '<h3>Overview</h3>'\n + '<ul>' \n + '<li>Total restroom count : '+ Restaurant.prototype.getTotalRestroomCount() + '</li>'\n + '<li>Total food count : '+ Restaurant.prototype.getTotalFoodCount() + '</li>'\n + '</ul>'\n + '<hr />';\n }\n };\n}();\n\nvar Wendys = Restaurant.create(\"Wendy's\");\nvar McDonalds = Restaurant.create(\"McDonald's\");\nvar KFC = Restaurant.create(\"KFC\");\nvar BurgerKing = Restaurant.create(\"Burger King\");\n\nRestaurant.printStatus();\n\nWendys.buy_food();\nWendys.use_restroom();\nKFC.use_restroom();\nKFC.use_restroom();\nWendys.use_restroom();\nMcDonalds.buy_food();\nBurgerKing.buy_food();\n\nRestaurant.printStatus();\n\nBurgerKing.buy_food();\nWendys.use_restroom();\nMcDonalds.buy_food();\nKFC.buy_food();\nWendys.buy_food();\nBurgerKing.buy_food();\nMcDonalds.buy_food();\n\nRestaurant.printStatus();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>See also <a href=\"https://jsfiddle.net/0yL21mr6/1/\" rel=\"noreferrer\"><strong>this Fiddle</strong></a>.</p>\n"
},
{
"answer_id": 48833952,
"author": "rich remer",
"author_id": 1078314,
"author_profile": "https://Stackoverflow.com/users/1078314",
"pm_score": 1,
"selected": false,
"text": "<p>I prefer to store private data in an associated <code>WeakMap</code>. This allows you to keep your public methods on the prototype where they belong. This seems to be the most efficient way to handle this problem for large numbers of objects.</p>\n\n<pre><code>const data = new WeakMap();\n\nfunction Foo(value) {\n data.set(this, {value});\n}\n\n// public method accessing private value\nFoo.prototype.accessValue = function() {\n return data.get(this).value;\n}\n\n// private 'method' accessing private value\nfunction accessValue(foo) {\n return data.get(foo).value;\n}\n\nexport {Foo};\n</code></pre>\n"
},
{
"answer_id": 51470058,
"author": "prograhammer",
"author_id": 1110941,
"author_profile": "https://Stackoverflow.com/users/1110941",
"pm_score": 3,
"selected": false,
"text": "<p>Don't be so verbose. It's Javascript. Use a <strong>Naming Convention</strong>.</p>\n\n<p>After years of working in es6 classes, I recently started work on an es5 project (using requireJS which is already very verbose-looking). I've been over and over all the strategies mentioned here and it all basically boils down to <strong>use a naming convention</strong>:</p>\n\n<ol>\n<li>Javascript doesn't have scope keywords like <code>private</code>. Other developers entering Javascript will know this upfront. Therefore, a simple naming convention is more than sufficient. A simple naming convention of prefixing with an underscore solves the problem of both private properties and private methods. </li>\n<li>Let's take advantage of the Prototype for speed reasons, but lets not get anymore verbose than that. Let's try to keep the es5 \"class\" looking as closely to what we might expect in other backend languages (and treat every file as a class, even if we don't need to return an instance).</li>\n<li>Let's demonstrate with a more realistic module situation (we'll use old es5 and old requireJs).</li>\n</ol>\n\n<p><strong>my-tooltip.js</strong> </p>\n\n<pre><code> define([\n 'tooltip'\n ],\n function(\n tooltip\n ){\n\n function MyTooltip() {\n // Later, if needed, we can remove the underscore on some\n // of these (make public) and allow clients of our class\n // to set them.\n this._selector = \"#my-tooltip\"\n this._template = 'Hello from inside my tooltip!';\n this._initTooltip();\n }\n\n MyTooltip.prototype = {\n constructor: MyTooltip,\n\n _initTooltip: function () {\n new tooltip.tooltip(this._selector, {\n content: this._template,\n closeOnClick: true,\n closeButton: true\n });\n }\n }\n\n return {\n init: function init() {\n new MyTooltip(); // <-- Our constructor adds our tooltip to the DOM so not much we need to do after instantiation.\n }\n\n // You could instead return a new instantiation, \n // if later you do more with this class.\n /* \n create: function create() {\n return new MyTooltip();\n }\n */\n }\n });\n</code></pre>\n"
},
{
"answer_id": 59474509,
"author": "D-Marc",
"author_id": 3822526,
"author_profile": "https://Stackoverflow.com/users/3822526",
"pm_score": 4,
"selected": false,
"text": "<h1><strong>ES12 Private Methods</strong></h1>\n<p>You can do this now with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields\" rel=\"nofollow noreferrer\">es12 private methods</a>. You just need to add a <code>#</code> before the method name.</p>\n<pre><code>class ClassWithPrivateMethod {\n #privateMethod() {\n return 'hello world';\n }\n\n getPrivateMessage() {\n return #privateMethod();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 63722178,
"author": "Daniel Shlomo",
"author_id": 1510406,
"author_profile": "https://Stackoverflow.com/users/1510406",
"pm_score": 0,
"selected": false,
"text": "<p>An ugly solution but it works:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function Class(cb) {\n const self = {};\n\n const constructor = (fn) => {\n func = fn; \n };\n\n const addPrivate = (fnName, obj) => {\n self[fnName] = obj;\n }\n\n const addPublic = (fnName, obj) => {\n this[fnName] = obj;\n self[fnName] = obj;\n func.prototype[fnName] = obj;\n }\n \n cb(constructor, addPrivate, addPublic, self);\n return func;\n}\n\nconst test = new Class((constructor, private, public, self) => {\n constructor(function (test) {\n console.log(test)\n });\n public('test', 'yay');\n private('qwe', 'nay');\n private('no', () => {\n return 'hello'\n })\n public('asd', () => {\n return 'this is public'\n })\n public('hello', () => {\n return self.qwe + self.no() + self.asd()\n })\n})\nconst asd = new test('qweqwe');\nconsole.log(asd.hello());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 64504570,
"author": "t_dom93",
"author_id": 6774916,
"author_profile": "https://Stackoverflow.com/users/6774916",
"pm_score": 4,
"selected": false,
"text": "<h2 id=\"es2021-es12-private-methods\">ES2021 / ES12 - Private Methods</h2>\n<p>Private method names start with a hash <code>#</code> prefix and can be accessed <strong>only</strong> inside the class where it is defined.</p>\n<pre><code>class Restaurant {\n\n // private method\n #private_stuff() {\n console.log("private stuff");\n }\n\n // public method\n buy_food() {\n this.#private_stuff();\n }\n\n};\n\nconst restaurant = new Restaurant();\nrestaurant.buy_food(); // "private stuff";\nrestaurant.private_stuff(); // Uncaught TypeError: restaurant.private_stuff is not a function\n</code></pre>\n"
},
{
"answer_id": 65552423,
"author": "Redu",
"author_id": 4543207,
"author_profile": "https://Stackoverflow.com/users/4543207",
"pm_score": 0,
"selected": false,
"text": "<p>Old question but this is a rather simple task that can be solved <strong>properly</strong> with core JS... without the Class abstraction of ES6. In fact as far as i can tell, the Class abstraction do not even solve this problem.</p>\n<p>We can do this job both with the good old constructor function or even better with <code>Object.create()</code>. Lets go with the constructor first. This will essentially be a similar solution to <a href=\"https://stackoverflow.com/a/55638/4543207\">georgebrock's answer</a> which is criticised because all restaurants created by the <code>Restaurant</code> constructor will have the same private methods. I will try to overcome that limitation.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function restaurantFactory(name,menu){\n\n function Restaurant(name){\n this.name = name;\n }\n\n function prototypeFactory(menu){\n // This is a private function\n function calculateBill(item){\n return menu[item] || 0;\n }\n // This is the prototype to be\n return { constructor: Restaurant\n , askBill : function(...items){\n var cost = items.reduce((total,item) => total + calculateBill(item) ,0)\n return \"Thank you for dining at \" + this.name + \". Total is: \" + cost + \"\\n\"\n }\n , callWaiter : function(){\n return \"I have just called the waiter at \" + this.name + \"\\n\";\n }\n }\n }\n\n Restaurant.prototype = prototypeFactory(menu);\n\n return new Restaurant(name,menu);\n}\n\nvar menu = { water: 1\n , coke : 2\n , beer : 3\n , beef : 15\n , rice : 2\n },\n name = \"Silver Scooop\",\n rest = restaurantFactory(name,menu);\n\nconsole.log(rest.callWaiter());\nconsole.log(rest.askBill(\"beer\", \"beef\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Now obviously we can not access <code>menu</code> from outside but we may easily rename the <code>name</code> property of a restaurant.</p>\n<p>This can also be done with <code>Object.create()</code> in which case we skip the constructor function and simply do like <code> var rest = Object.create(prototypeFactory(menu))</code> and add the name property to the <code>rest</code> object afterwards like <code>rest.name = name</code>.</p>\n"
},
{
"answer_id": 67235368,
"author": "yorg",
"author_id": 3225970,
"author_profile": "https://Stackoverflow.com/users/3225970",
"pm_score": 0,
"selected": false,
"text": "<p>I know it is an old topic but i tried to find a way to preserve the code 'simplicity' for maintainability purposes and keep a light memory load. It came with this pattern. Hope it helps.</p>\n<pre><code>const PublicClass=function(priv,pub,ro){\n let _priv=new PrivateClass(priv,pub,ro);\n ['publicMethod'].forEach(k=>this[k]=(...args)=>_priv[k](...args));\n ['publicVar'].forEach(k=>Object.defineProperty(this,k,{get:()=>_priv[k],set:v=>_priv[k]=v}));\n ['readOnlyVar'].forEach(k=>Object.defineProperty(this,k,{get:()=>_priv[k]}));\n};\n\nclass PrivateClass{\n constructor(priv,pub,ro){\n this.privateVar=priv;\n this.publicVar=pub;\n this.readOnlyVar=ro;\n }\n publicMethod(arg1,arg2){\n return this.privateMethod(arg1,arg2);\n }\n privateMethod(arg1,arg2){\n return arg1+''+arg2;\n }\n}\n// in node;\nmodule.exports=PublicClass;\n// in browser;\nconst PublicClass=(function(){\n // code here\n return PublicClass;\n})();\n</code></pre>\n<p>Same principle for old browsers :</p>\n<pre><code>var PublicClass=function(priv,pub,ro){\n var scope=this;\n var _priv=new PrivateClass(priv,pub,ro);\n ['publicMethod'].forEach(function(k){\n scope[k]=function(){return _priv[k].apply(_priv,arguments)};\n });\n ['publicVar'].forEach(function(k){\n Object.defineProperty(scope,k,{get:function(){return _priv[k]},set:function(v){_priv[k]=v}});\n });\n ['readOnlyVar'].forEach(function(k){\n Object.defineProperty(scope,k,{get:function(){return _priv[k]}});\n });\n};\n\nvar PrivateClass=function(priv,pub,ro){\n this.privateVar=priv;\n this.publicVar=pub;\n this.readOnlyVar=ro;\n};\nPrivateClass.prototype.publicMethod=function(arg1,arg2){\n return this.privateMethod(arg1,arg2);\n};\nPrivateClass.prototype.privateMethod=function(arg1,arg2){\n return arg1+''+arg2;\n};\n</code></pre>\n<hr />\n<p>To lighten public class verbosity and load, apply this pattern to a constructor :</p>\n<pre><code>const AbstractPublicClass=function(instanciate,inherit){\n let _priv=instanciate();\n inherit.methods?.forEach(k=>this[k]=(...args)=>_priv[k](...args));\n inherit.vars?.forEach(k=>Object.defineProperty(this,k,{get:()=>_priv[k],set:v=>_priv[k]=v}));\n inherit.readonly?.forEach(k=>Object.defineProperty(this,k,{get:()=>_priv[k]}));\n};\n\nAbstractPublicClass.static=function(_pub,_priv,inherit){\n inherit.methods?.forEach(k=>_pub[k]=(...args)=>_priv[k](...args));\n inherit.vars?.forEach(k=>Object.defineProperty(_pub,k,{get:()=>_priv[k],set:v=>_priv[k]=v}));\n inherit.readonly?.forEach(k=>Object.defineProperty(_pub,k,{get:()=>_priv[k]}));\n};\n</code></pre>\n<p>Use :</p>\n<pre><code>// PrivateClass ...\nPrivateClass.staticVar='zog';\nPrivateClass.staticMethod=function(){return 'hello '+this.staticVar;};\n\n\nconst PublicClass=function(priv,pub,ro){\n AbstractPublicClass.apply(this,[()=>new PrivateClass(priv,pub,ro),{\n methods:['publicMethod'],\n vars:['publicVar'],\n readonly:['readOnlyVar']\n }]);\n};\nAbstractPublicClass.static(PublicClass,PrivateClass,{\n methods:['staticMethod'],\n vars:['staticVar']\n});\n</code></pre>\n<hr />\n<p>PS : The default (negligeable most of the time) in this approach is it can take a tiny computing load compared to a full public. But as long as you dont use it whith highly solicited classes that should be ok.</p>\n"
},
{
"answer_id": 68978023,
"author": "denik1981",
"author_id": 13578650,
"author_profile": "https://Stackoverflow.com/users/13578650",
"pm_score": 1,
"selected": false,
"text": "<p><strong>2021 HERE!</strong></p>\n<p>This polyfill effectively hides your private properties and methods returning <strong>undefined</strong> when you try to read your private property and a <strong>TypeError</strong> when you try to execute your private method thus effectively making them both <strong>PRIVATE</strong> to the outside but giving you access to them by using your public methods.</p>\n<p>If you check it you will see it is very easy to implement. For the most part you don't need to do anything quirky like using Proxy objects, underscore functions (_myprivate), getters or setters. None of that. The only thing required is to place in your constructor that like snippet of code that is aimed to let you expose your public interface to the outside world.</p>\n<pre><code>((self) => ({\n pubProp: self.pubProp,\n // More public properties to export HERE\n // ...\n pubMethod: self.pubMethod.bind(self)\n // More public mehods to export HERE\n // Be sure bind each of them to self!!!\n // ... \n }))(self);\n</code></pre>\n<p>The above code is where the magic happens. It is an IIFE that returns an object with just the properties and methods you want to exposed and bound to the context of the object that was first instantiated.</p>\n<p>You can still access your hidden properties and methods but only through your public methods just the way OOP should do.<br />\nConsider that part of the code as your <strong>module.exports</strong></p>\n<p>BTW this is without using the latest ES6 "<strong>#</strong>" addition to the language.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>'use strict';\n\nclass MyClass {\n constructor(pubProp) {\n let self = this;\n self.pubProp = pubProp;\n self.privProp = \"I'm a private property!\";\n return ((self) => ({\n pubProp: self.pubProp,\n // More public properties to export HERE\n // ...\n pubMethod: self.pubMethod.bind(self)\n // More public mehods to export HERE\n // Be sure to bind each of them to self!!!\n // ... \n }))(self);\n }\n\n pubMethod() {\n console.log(\"I'm a public method!\");\n console.log(this.pubProp);\n\n return this.privMethod();\n }\n\n privMethod() {\n console.log(\"I'm a private method!\");\n return this.privProp\n }\n}\n\nconst myObj = new MyClass(\"I'm a public property!\");\nconsole.log(\"***DUMPING MY NEW INSTANCE***\");\nconsole.dir(myObj);\nconsole.log(\"\");\nconsole.log(\"***TESTING ACCESS TO PUBLIC PROPERTIES***\");\nconsole.log(myObj.pubProp);\nconsole.log(\"\");\nconsole.log(\"***TESTING ACCESS TO PRIVATE PROPERTIES***\");\nconsole.log(myObj.privProp);\nconsole.log(\"\");\nconsole.log(\"***TESTING ACCESS TO PUBLIC METHODS***\");\nconsole.log(\"1. pubMethod access pubProp \");\nconsole.log(\"2. pubMethod calls privMethod\");\nconsole.log(\"3. privMethod access privProp\");\nconsole.log(\"\")\nconsole.log(myObj.pubMethod());\nconsole.log(\"\");\nconsole.log(\"***TESTING ACCESS TO PRIVATE METHODS***\");\nconsole.log(myObj.privMethod());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><a href=\"https://git.io/JEPGi\" rel=\"nofollow noreferrer\">Check my gist</a></p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284/"
] | To make a JavaScript class with a public method I'd do something like:
```
function Restaurant() {}
Restaurant.prototype.buy_food = function(){
// something here
}
Restaurant.prototype.use_restroom = function(){
// something here
}
```
That way users of my class can:
```
var restaurant = new Restaurant();
restaurant.buy_food();
restaurant.use_restroom();
```
How do I create a private method that can be called by the `buy_food` and `use_restroom` methods but not externally by users of the class?
In other words, I want my method implementation to be able to do:
```
Restaurant.prototype.use_restroom = function() {
this.private_stuff();
}
```
But this shouldn't work:
```
var r = new Restaurant();
r.private_stuff();
```
How do I define `private_stuff` as a private method so both of these hold true?
I've read [Doug Crockford's writeup](http://javascript.crockford.com/private.html) a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally. | You can do it, but the downside is that it can't be part of the prototype:
```
function Restaurant() {
var myPrivateVar;
var private_stuff = function() { // Only visible inside Restaurant()
myPrivateVar = "I can set this here!";
}
this.use_restroom = function() { // use_restroom is visible to all
private_stuff();
}
this.buy_food = function() { // buy_food is visible to all
private_stuff();
}
}
``` |
55,677 | <p>What's the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?</p>
<p>No legacy browser compatibility required, Safari, Opera and Firefox will do.</p>
| [
{
"answer_id": 55723,
"author": "Brian Gianforcaro",
"author_id": 3415,
"author_profile": "https://Stackoverflow.com/users/3415",
"pm_score": -1,
"selected": false,
"text": "<p>Hey, this is in dojo, just cause it's what I had the code in already for a project.</p>\n\n<p>It should be fairly Obvious how to convert it back to non dojo vanilla JavaScript. </p>\n\n<pre><code> function onMouseClick(e) {\n var x = e.clientX;\n var y = e.clientY;\n }\n var canvas = dojo.byId(canvasId);\n dojo.connect(canvas,\"click\",onMouseClick);\n</code></pre>\n\n<p>Hope that helps. </p>\n"
},
{
"answer_id": 1516556,
"author": "fixermark",
"author_id": 57720,
"author_profile": "https://Stackoverflow.com/users/57720",
"pm_score": 3,
"selected": false,
"text": "<p>Be wary while doing the coordinate conversion; there are multiple non-cross-browser values returned in a click event. Using clientX and clientY alone are not sufficient if the browser window is scrolled (verified in Firefox 3.5 and Chrome 3.0). </p>\n\n<p><a href=\"http://www.quirksmode.org/js/events_properties.html\" rel=\"nofollow noreferrer\">This quirks mode</a> article provides a more correct function that can use either pageX or pageY or a combination of clientX with document.body.scrollLeft and clientY with document.body.scrollTop to calculate the click coordinate relative to the document origin. </p>\n\n<p>UPDATE: Additionally, offsetLeft and offsetTop are relative to the padded size of the element, not the interior size. A canvas with the padding: style applied will not report the top-left of its content region as offsetLeft. There are various solutions to this problem; the simplest one may be to clear all border, padding, etc. styles on the canvas itself and instead apply them to a box containing the canvas.</p>\n"
},
{
"answer_id": 4430498,
"author": "N4ppeL",
"author_id": 540725,
"author_profile": "https://Stackoverflow.com/users/540725",
"pm_score": 6,
"selected": false,
"text": "<p><strong>Edit 2018:</strong> This answer is pretty old and it uses checks for old browsers that are not necessary anymore, as the <code>clientX</code> and <code>clientY</code> properties work in all current browsers. You might want to check out <a href=\"https://stackoverflow.com/a/18053642/540725\">Patriques Answer</a> for a simpler, more recent solution.</p>\n\n<p><strong>Original Answer:</strong><br>\nAs described in an article i found back then but exists no longer:</p>\n\n<pre><code>var x;\nvar y;\nif (e.pageX || e.pageY) { \n x = e.pageX;\n y = e.pageY;\n}\nelse { \n x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; \n y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; \n} \nx -= gCanvasElement.offsetLeft;\ny -= gCanvasElement.offsetTop;\n</code></pre>\n\n<p>Worked perfectly fine for me.</p>\n"
},
{
"answer_id": 5417934,
"author": "Aldekein",
"author_id": 162118,
"author_profile": "https://Stackoverflow.com/users/162118",
"pm_score": 4,
"selected": false,
"text": "<p>According to fresh <a href=\"http://www.quirksmode.org/dom/w3c_cssom.html#mousepos\" rel=\"nofollow noreferrer\">Quirksmode</a> the <code>clientX</code> and <code>clientY</code> methods are supported in all major browsers.\nSo, here it goes - the good, working code that works in a scrolling div on a page with scrollbars:</p>\n\n<pre><code>function getCursorPosition(canvas, event) {\nvar x, y;\n\ncanoffset = $(canvas).offset();\nx = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - Math.floor(canoffset.left);\ny = event.clientY + document.body.scrollTop + document.documentElement.scrollTop - Math.floor(canoffset.top) + 1;\n\nreturn [x,y];\n}\n</code></pre>\n\n<p>This also requires <a href=\"https://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a> for <code>$(canvas).offset()</code>.</p>\n"
},
{
"answer_id": 5928525,
"author": "Manuel Ignacio López Quintero",
"author_id": 660826,
"author_profile": "https://Stackoverflow.com/users/660826",
"pm_score": 4,
"selected": false,
"text": "<p>I made a full demostration that works in every browser with the full source code of the solution of this problem: <a href=\"http://miloq.blogspot.com/2011/05/coordinates-mouse-click-canvas.html\" rel=\"noreferrer\">Coordinates of a mouse click on Canvas in Javascript</a>. To try the demo, copy the code and paste it into a text editor. Then save it as example.html and, finally, open the file with a browser.</p>\n"
},
{
"answer_id": 5932203,
"author": "Ryan Artecona",
"author_id": 671915,
"author_profile": "https://Stackoverflow.com/users/671915",
"pm_score": 8,
"selected": false,
"text": "<p><strong>Update</strong> (5/5/16): <a href=\"https://stackoverflow.com/a/18053642/1026023\">patriques' answer</a> should be used instead, as it's both simpler and more reliable.</p>\n\n<hr>\n\n<p>Since the canvas isn't always styled relative to the entire page, the <code>canvas.offsetLeft/Top</code> doesn't always return what you need. It will return the number of pixels it is offset relative to its offsetParent element, which can be something like a <code>div</code> element containing the canvas with a <code>position: relative</code> style applied. To account for this you need to loop through the chain of <code>offsetParent</code>s, beginning with the canvas element itself. This code works perfectly for me, tested in Firefox and Safari but should work for all. </p>\n\n<pre><code>function relMouseCoords(event){\n var totalOffsetX = 0;\n var totalOffsetY = 0;\n var canvasX = 0;\n var canvasY = 0;\n var currentElement = this;\n\n do{\n totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;\n totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;\n }\n while(currentElement = currentElement.offsetParent)\n\n canvasX = event.pageX - totalOffsetX;\n canvasY = event.pageY - totalOffsetY;\n\n return {x:canvasX, y:canvasY}\n}\nHTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;\n</code></pre>\n\n<p>The last line makes things convenient for getting the mouse coordinates relative to a canvas element. All that's needed to get the useful coordinates is</p>\n\n<pre><code>coords = canvas.relMouseCoords(event);\ncanvasX = coords.x;\ncanvasY = coords.y;\n</code></pre>\n"
},
{
"answer_id": 6837700,
"author": "JTE",
"author_id": 766115,
"author_profile": "https://Stackoverflow.com/users/766115",
"pm_score": 1,
"selected": false,
"text": "<p>In Prototype, use cumulativeOffset() to do the recursive summation as mentioned by Ryan Artecona above.</p>\n\n<p><a href=\"http://www.prototypejs.org/api/element/cumulativeoffset\" rel=\"nofollow\">http://www.prototypejs.org/api/element/cumulativeoffset</a></p>\n"
},
{
"answer_id": 9961416,
"author": "Cryptovirus",
"author_id": 1305768,
"author_profile": "https://Stackoverflow.com/users/1305768",
"pm_score": 4,
"selected": false,
"text": "<p>Here is a small modification to <a href=\"https://stackoverflow.com/a/5932203/1305768\">Ryan Artecona's answer</a> for canvases with a variable (%) width:</p>\n\n<pre><code> HTMLCanvasElement.prototype.relMouseCoords = function (event) {\n var totalOffsetX = 0;\n var totalOffsetY = 0;\n var canvasX = 0;\n var canvasY = 0;\n var currentElement = this;\n\n do {\n totalOffsetX += currentElement.offsetLeft;\n totalOffsetY += currentElement.offsetTop;\n }\n while (currentElement = currentElement.offsetParent)\n\n canvasX = event.pageX - totalOffsetX;\n canvasY = event.pageY - totalOffsetY;\n\n // Fix for variable canvas width\n canvasX = Math.round( canvasX * (this.width / this.offsetWidth) );\n canvasY = Math.round( canvasY * (this.height / this.offsetHeight) );\n\n return {x:canvasX, y:canvasY}\n}\n</code></pre>\n"
},
{
"answer_id": 12114213,
"author": "mafafu",
"author_id": 1296226,
"author_profile": "https://Stackoverflow.com/users/1296226",
"pm_score": 5,
"selected": false,
"text": "<p>Modern browser's now handle this for you. Chrome, IE9, and Firefox support the offsetX/Y like this, passing in the event from the click handler.</p>\n\n<pre><code>function getRelativeCoords(event) {\n return { x: event.offsetX, y: event.offsetY };\n}\n</code></pre>\n\n<p>Most modern browsers also support layerX/Y, however Chrome and IE use layerX/Y for the absolute offset of the click on the page including margin, padding, etc. In Firefox, layerX/Y and offsetX/Y are equivalent, but offset didn't previously exist. So, for compatibility with slightly older browsers, you can use:</p>\n\n<pre><code>function getRelativeCoords(event) {\n return { x: event.offsetX || event.layerX, y: event.offsetY || event.layerY };\n}\n</code></pre>\n"
},
{
"answer_id": 17178241,
"author": "Simon Hi",
"author_id": 2458202,
"author_profile": "https://Stackoverflow.com/users/2458202",
"pm_score": 0,
"selected": false,
"text": "<p>Here is some modifications of the above Ryan Artecona's solution.</p>\n\n<pre><code>function myGetPxStyle(e,p)\n{\n var r=window.getComputedStyle?window.getComputedStyle(e,null)[p]:\"\";\n return parseFloat(r);\n}\n\nfunction myGetClick=function(ev)\n{\n // {x:ev.layerX,y:ev.layerY} doesn't work when zooming with mac chrome 27\n // {x:ev.clientX,y:ev.clientY} not supported by mac firefox 21\n // document.body.scrollLeft and document.body.scrollTop seem required when scrolling on iPad\n // html is not an offsetParent of body but can have non null offsetX or offsetY (case of wordpress 3.5.1 admin pages for instance)\n // html.offsetX and html.offsetY don't work with mac firefox 21\n\n var offsetX=0,offsetY=0,e=this,x,y;\n var htmls=document.getElementsByTagName(\"html\"),html=(htmls?htmls[0]:0);\n\n do\n {\n offsetX+=e.offsetLeft-e.scrollLeft;\n offsetY+=e.offsetTop-e.scrollTop;\n } while (e=e.offsetParent);\n\n if (html)\n {\n offsetX+=myGetPxStyle(html,\"marginLeft\");\n offsetY+=myGetPxStyle(html,\"marginTop\");\n }\n\n x=ev.pageX-offsetX-document.body.scrollLeft;\n y=ev.pageY-offsetY-document.body.scrollTop;\n return {x:x,y:y};\n}\n</code></pre>\n"
},
{
"answer_id": 17401918,
"author": "FraZer",
"author_id": 2515750,
"author_profile": "https://Stackoverflow.com/users/2515750",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a very nice tutorial-</p>\n\n<p><a href=\"http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/\" rel=\"noreferrer\">http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/</a></p>\n\n<pre><code> <canvas id=\"myCanvas\" width=\"578\" height=\"200\"></canvas>\n<script>\n function writeMessage(canvas, message) {\n var context = canvas.getContext('2d');\n context.clearRect(0, 0, canvas.width, canvas.height);\n context.font = '18pt Calibri';\n context.fillStyle = 'black';\n context.fillText(message, 10, 25);\n }\n function getMousePos(canvas, evt) {\n var rect = canvas.getBoundingClientRect();\n return {\n x: evt.clientX - rect.left,\n y: evt.clientY - rect.top\n };\n }\n var canvas = document.getElementById('myCanvas');\n var context = canvas.getContext('2d');\n\n canvas.addEventListener('mousemove', function(evt) {\n var mousePos = getMousePos(canvas, evt);\n var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;\n writeMessage(canvas, message);\n }, false);\n</code></pre>\n\n<p>hope this helps!</p>\n"
},
{
"answer_id": 17418121,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I recommend this link-\n<a href=\"http://miloq.blogspot.in/2011/05/coordinates-mouse-click-canvas.html\" rel=\"nofollow\">http://miloq.blogspot.in/2011/05/coordinates-mouse-click-canvas.html</a></p>\n\n<p></p>\n\n<pre><code><style type=\"text/css\">\n\n #canvas{background-color: #000;}\n\n</style>\n\n<script type=\"text/javascript\">\n\n document.addEventListener(\"DOMContentLoaded\", init, false);\n\n function init()\n {\n var canvas = document.getElementById(\"canvas\");\n canvas.addEventListener(\"mousedown\", getPosition, false);\n }\n\n function getPosition(event)\n {\n var x = new Number();\n var y = new Number();\n var canvas = document.getElementById(\"canvas\");\n\n if (event.x != undefined && event.y != undefined)\n {\n x = event.x;\n y = event.y;\n }\n else // Firefox method to get the position\n {\n x = event.clientX + document.body.scrollLeft +\n document.documentElement.scrollLeft;\n y = event.clientY + document.body.scrollTop +\n document.documentElement.scrollTop;\n }\n\n x -= canvas.offsetLeft;\n y -= canvas.offsetTop;\n\n alert(\"x: \" + x + \" y: \" + y);\n }\n\n</script>\n</code></pre>\n"
},
{
"answer_id": 18053642,
"author": "patriques",
"author_id": 931738,
"author_profile": "https://Stackoverflow.com/users/931738",
"pm_score": 9,
"selected": true,
"text": "<p>If you like simplicity but still want cross-browser functionality I found this solution worked best for me. This is a simplification of @Aldekein´s solution but <strong>without jQuery</strong>.</p>\n\n<pre><code>function getCursorPosition(canvas, event) {\n const rect = canvas.getBoundingClientRect()\n const x = event.clientX - rect.left\n const y = event.clientY - rect.top\n console.log(\"x: \" + x + \" y: \" + y)\n}\n\nconst canvas = document.querySelector('canvas')\ncanvas.addEventListener('mousedown', function(e) {\n getCursorPosition(canvas, e)\n})\n</code></pre>\n"
},
{
"answer_id": 19740807,
"author": "user2310569",
"author_id": 2310569,
"author_profile": "https://Stackoverflow.com/users/2310569",
"pm_score": 1,
"selected": false,
"text": "<p>You could just do: </p>\n\n<pre><code>var canvas = yourCanvasElement;\nvar mouseX = (event.clientX - (canvas.offsetLeft - canvas.scrollLeft)) - 2;\nvar mouseY = (event.clientY - (canvas.offsetTop - canvas.scrollTop)) - 2;\n</code></pre>\n\n<p>This will give you the exact position of the mouse pointer.</p>\n"
},
{
"answer_id": 20310070,
"author": "Daniel Patru",
"author_id": 268040,
"author_profile": "https://Stackoverflow.com/users/268040",
"pm_score": 1,
"selected": false,
"text": "<p>See demo at <a href=\"http://jsbin.com/ApuJOSA/1/edit?html,output\" rel=\"nofollow\">http://jsbin.com/ApuJOSA/1/edit?html,output</a> .</p>\n\n<pre><code> function mousePositionOnCanvas(e) {\n var el=e.target, c=el;\n var scaleX = c.width/c.offsetWidth || 1;\n var scaleY = c.height/c.offsetHeight || 1;\n\n if (!isNaN(e.offsetX)) \n return { x:e.offsetX*scaleX, y:e.offsetY*scaleY };\n\n var x=e.pageX, y=e.pageY;\n do {\n x -= el.offsetLeft;\n y -= el.offsetTop;\n el = el.offsetParent;\n } while (el);\n return { x: x*scaleX, y: y*scaleY };\n }\n</code></pre>\n"
},
{
"answer_id": 20930829,
"author": "Wayne",
"author_id": 592746,
"author_profile": "https://Stackoverflow.com/users/592746",
"pm_score": 0,
"selected": false,
"text": "<p>First, as others have said, you need a function to get the <a href=\"http://www.quirksmode.org/js/findpos.html\" rel=\"nofollow\">position of the canvas element</a>. Here's a method that's a little more elegant than some of the others on this page (IMHO). You can pass it <em>any</em> element and get its position in the document:</p>\n\n<pre><code>function findPos(obj) {\n var curleft = 0, curtop = 0;\n if (obj.offsetParent) {\n do {\n curleft += obj.offsetLeft;\n curtop += obj.offsetTop;\n } while (obj = obj.offsetParent);\n return { x: curleft, y: curtop };\n }\n return undefined;\n}\n</code></pre>\n\n<p>Now calculate the current position of the cursor relative to that:</p>\n\n<pre><code>$('#canvas').mousemove(function(e) {\n var pos = findPos(this);\n var x = e.pageX - pos.x;\n var y = e.pageY - pos.y;\n var coordinateDisplay = \"x=\" + x + \", y=\" + y;\n writeCoordinateDisplay(coordinateDisplay);\n});\n</code></pre>\n\n<p>Notice that I've separated the generic <code>findPos</code> function from the event handling code. (<em>As it should be</em>. We should try to keep our functions to one task each.)</p>\n\n<p>The values of <code>offsetLeft</code> and <code>offsetTop</code> are relative to <code>offsetParent</code>, which could be some wrapper <code>div</code> node (or anything else, for that matter). When there is no element wrapping the <code>canvas</code> they're relative to the <code>body</code>, so there is no offset to subtract. This is why we need to determine the position of the canvas before we can do anything else.</p>\n\n<p>Similary, <code>e.pageX</code> and <code>e.pageY</code> give the position of the cursor relative to the document. That's why we subtract the canvas's offset from those values to arrive at the true position.</p>\n\n<p>An alternative for <em>positioned</em> elements is to directly use the values of <code>e.layerX</code> and <code>e.layerY</code>. This is less reliable than the method above for two reasons:</p>\n\n<ol>\n<li>These values are also relative to the entire document when the event does not take place inside a positioned element</li>\n<li>They are not part of any standard</li>\n</ol>\n"
},
{
"answer_id": 27204937,
"author": "Tomáš Zato",
"author_id": 607407,
"author_profile": "https://Stackoverflow.com/users/607407",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not sure what's the point of all these answers that <a href=\"https://stackoverflow.com/a/5932203/607407\">loop through parent elements</a> and do all kinds of <a href=\"http://en.wikipedia.org/wiki/Deep_magic\" rel=\"nofollow noreferrer\">weird stuff</a>.</p>\n\n<p>The <code>HTMLElement.getBoundingClientRect</code> method is designed to to handle actual screen position of any element. This includes scrolling, so stuff like <code>scrollTop</code> is not needed:</p>\n\n<blockquote>\n <p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect\" rel=\"nofollow noreferrer\"><strong>(from MDN)</strong></a> The amount of scrolling that has been done of the viewport area (or\n <strong>any other scrollable element</strong>) is taken into account when computing the\n bounding rectangle</p>\n</blockquote>\n\n<h3>Normal image</h3>\n\n<p>The <a href=\"https://stackoverflow.com/a/20788872/607407\">very simplest approach</a> was already posted here. This is correct as long as <em>no wild CSS</em> rules are involved.</p>\n\n<h3>Handling stretched canvas/image</h3>\n\n<p>When image pixel width isn't matched by it's CSS width, you'll need to apply some ratio on pixel values:</p>\n\n<pre><code>/* Returns pixel coordinates according to the pixel that's under the mouse cursor**/\nHTMLCanvasElement.prototype.relativeCoords = function(event) {\n var x,y;\n //This is the current screen rectangle of canvas\n var rect = this.getBoundingClientRect();\n var top = rect.top;\n var bottom = rect.bottom;\n var left = rect.left;\n var right = rect.right;\n //Recalculate mouse offsets to relative offsets\n x = event.clientX - left;\n y = event.clientY - top;\n //Also recalculate offsets of canvas is stretched\n var width = right - left;\n //I use this to reduce number of calculations for images that have normal size \n if(this.width!=width) {\n var height = bottom - top;\n //changes coordinates by ratio\n x = x*(this.width/width);\n y = y*(this.height/height);\n } \n //Return as an array\n return [x,y];\n}\n</code></pre>\n\n<p>As long as the canvas has no border, <a href=\"http://jsfiddle.net/Darker/cfzn01c6/\" rel=\"nofollow noreferrer\"><strong>it works for stretched images (jsFiddle)</strong></a>.</p>\n\n<h3>Handling CSS borders</h3>\n\n<p>If the canvas has thick border, <a href=\"http://jsfiddle.net/Darker/nrw7xu2r/1/\" rel=\"nofollow noreferrer\">the things get little complicated</a>. You'll literally need to subtract the border from the bounding rectangle. This can be done using <a href=\"https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle\" rel=\"nofollow noreferrer\">.getComputedStyle</a>. This <a href=\"https://stackoverflow.com/a/27204448/607407\">answer describes the process</a>.</p>\n\n<p>The function then grows up a little:</p>\n\n<pre><code>/* Returns pixel coordinates according to the pixel that's under the mouse cursor**/\nHTMLCanvasElement.prototype.relativeCoords = function(event) {\n var x,y;\n //This is the current screen rectangle of canvas\n var rect = this.getBoundingClientRect();\n var top = rect.top;\n var bottom = rect.bottom;\n var left = rect.left;\n var right = rect.right;\n //Subtract border size\n // Get computed style\n var styling=getComputedStyle(this,null);\n // Turn the border widths in integers\n var topBorder=parseInt(styling.getPropertyValue('border-top-width'),10);\n var rightBorder=parseInt(styling.getPropertyValue('border-right-width'),10);\n var bottomBorder=parseInt(styling.getPropertyValue('border-bottom-width'),10);\n var leftBorder=parseInt(styling.getPropertyValue('border-left-width'),10);\n //Subtract border from rectangle\n left+=leftBorder;\n right-=rightBorder;\n top+=topBorder;\n bottom-=bottomBorder;\n //Proceed as usual\n ...\n}\n</code></pre>\n\n<p>I can't think of anything that would confuse this final function. See yourself at <a href=\"http://jsfiddle.net/Darker/nrw7xu2r/2/\" rel=\"nofollow noreferrer\"><strong>JsFiddle</strong></a>.</p>\n\n<h3>Notes</h3>\n\n<p>If you don't like modifying the native <code>prototype</code>s, just change the function and call it with <code>(canvas, event)</code> (and replace any <code>this</code> with <code>canvas</code>).</p>\n"
},
{
"answer_id": 34781170,
"author": "Sarsaparilla",
"author_id": 226844,
"author_profile": "https://Stackoverflow.com/users/226844",
"pm_score": 2,
"selected": false,
"text": "<p>Using jQuery in 2016, to get click coordinates relative to the canvas, I do:</p>\n\n<pre><code>$(canvas).click(function(jqEvent) {\n var coords = {\n x: jqEvent.pageX - $(canvas).offset().left,\n y: jqEvent.pageY - $(canvas).offset().top\n };\n});\n</code></pre>\n\n<p>This works since both canvas offset() and jqEvent.pageX/Y are relative to the document regardless of scroll position.</p>\n\n<p>Note that if your canvas is scaled then these coordinates are not the same as canvas <strong>logical coordinates</strong>. To get those, you would <em>also</em> do:</p>\n\n<pre><code>var logicalCoords = {\n x: coords.x * (canvas.width / $(canvas).width()),\n y: coords.y * (canvas.height / $(canvas).height())\n}\n</code></pre>\n"
},
{
"answer_id": 37790303,
"author": "Aniket Betkikar",
"author_id": 5275732,
"author_profile": "https://Stackoverflow.com/users/5275732",
"pm_score": 0,
"selected": false,
"text": "<p>ThreeJS r77</p>\n\n<pre><code>var x = event.offsetX == undefined ? event.layerX : event.offsetX;\nvar y = event.offsetY == undefined ? event.layerY : event.offsetY;\n\nmouse2D.x = ( x / renderer.domElement.width ) * 2 - 1;\nmouse2D.y = - ( y / renderer.domElement.height ) * 2 + 1;\n</code></pre>\n\n<p>After trying many solutions. This worked for me. Might help someone else hence posting. Got it from <a href=\"http://www.scriptscoop2.com/t/f93cbd2d95e2/javascript-threejs-issue-with-raycaster-intersection.html\" rel=\"nofollow\">here</a></p>\n"
},
{
"answer_id": 54356770,
"author": "bb216b3acfd8f72cbc8f899d4d6963",
"author_id": 5513988,
"author_profile": "https://Stackoverflow.com/users/5513988",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a simplified solution (this doesn't work with borders/scrolling):</p>\n\n<pre><code>function click(event) {\n const bound = event.target.getBoundingClientRect();\n\n const xMult = bound.width / can.width;\n const yMult = bound.height / can.height;\n\n return {\n x: Math.floor(event.offsetX / xMult),\n y: Math.floor(event.offsetY / yMult),\n };\n}\n</code></pre>\n"
},
{
"answer_id": 56205486,
"author": "gman",
"author_id": 128511,
"author_profile": "https://Stackoverflow.com/users/128511",
"pm_score": 4,
"selected": false,
"text": "<p>So this is both simple but a slightly more complicated topic than it seems.</p>\n<p>First off there are usually to conflated questions here</p>\n<ol>\n<li><p><strong>How to get element relative mouse coordinates</strong></p>\n</li>\n<li><p><strong>How to get canvas pixel mouse coordinates for the 2D Canvas API or WebGL</strong></p>\n</li>\n</ol>\n<p>so, answers</p>\n<h1>How to get element relative mouse coordinates</h1>\n<p>Whether or not the element is a canvas getting element relative mouse coordinates is the same for all elements.</p>\n<p>There are 2 simple answers to the question "How to get canvas relative mouse coordinates"</p>\n<h3>Simple answer #1 use <code>offsetX</code> and <code>offsetY</code></h3>\n<pre><code>canvas.addEventListner('mousemove', (e) => {\n const x = e.offsetX;\n const y = e.offsetY;\n});\n</code></pre>\n<p>This answer works in Chrome, Firefox, and Safari. Unlike all the other event values <code>offsetX</code> and <code>offsetY</code> take CSS transforms into account.</p>\n<p>The biggest problem with <code>offsetX</code> and <code>offsetY</code> is as of 2019/05 they don't exist on touch events and so can't be used with iOS Safari. They do exist on Pointer Events which exist in Chrome and Firefox but not Safari although <a href=\"https://webkit.org/blog/8419/release-notes-for-safari-technology-preview-67/\" rel=\"noreferrer\">apparently Safari is working on it</a>.</p>\n<p>Another issue is the events must be on the canvas itself. If you put them on some other element or the window you can not later choose the canvas to be your point of reference.</p>\n<h2>Simple answer #2 use <code>clientX</code>, <code>clientY</code> and <code>canvas.getBoundingClientRect</code></h2>\n<p>If you don't care about CSS transforms the next simplest answer is to call <code>canvas. getBoundingClientRect()</code> and subtract the left from <code>clientX</code> and <code>top</code> from <code>clientY</code> as in</p>\n<pre><code>canvas.addEventListener('mousemove', (e) => {\n const rect = canvas.getBoundingClientRect();\n const x = e.clientX - rect.left;\n const y = e.clientY - rect.top;\n});\n</code></pre>\n<p>This will work as long as there are no CSS transforms. It also works with touch events and so will work with Safari iOS</p>\n<pre><code>canvas.addEventListener('touchmove', (e) => {\n const rect = canvas. getBoundingClientRect();\n const x = e.touches[0].clientX - rect.left;\n const y = e.touches[0].clientY - rect.top;\n});\n</code></pre>\n<h1>How to get canvas pixel mouse coordinates for the 2D Canvas API</h1>\n<p>For this we need to take the values we got above and convert from the size the canvas is displayed to the number of pixels in the canvas itself</p>\n<p>with <code>canvas.getBoundingClientRect</code> and <code>clientX</code> and <code>clientY</code></p>\n<pre><code>canvas.addEventListener('mousemove', (e) => {\n const rect = canvas.getBoundingClientRect();\n const elementRelativeX = e.clientX - rect.left;\n const elementRelativeY = e.clientY - rect.top;\n const canvasRelativeX = elementRelativeX * canvas.width / rect.width;\n const canvasRelativeY = elementRelativeY * canvas.height / rect.height;\n});\n</code></pre>\n<p>or with <code>offsetX</code> and <code>offsetY</code></p>\n<pre><code>canvas.addEventListener('mousemove', (e) => {\n const elementRelativeX = e.offsetX;\n const elementRelativeY = e.offsetY;\n const canvasRelativeX = elementRelativeX * canvas.width / canvas.clientWidth;\n const canvasRelativeY = elementRelativeY * canvas.height / canvas.clientHeight;\n});\n</code></pre>\n<h1>Note: <strong>In all cases do not add padding or borders to the canvas. Doing so will massively complicate the code. Instead of you want a border or padding surround the canvas in some other element and add the padding and or border to the outer element.</strong></h1>\n<p>Working example using <code>event.offsetX</code>, <code>event.offsetY</code></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>[...document.querySelectorAll('canvas')].forEach((canvas) => {\n const ctx = canvas.getContext('2d');\n ctx.canvas.width = ctx.canvas.clientWidth;\n ctx.canvas.height = ctx.canvas.clientHeight;\n let count = 0;\n\n function draw(e, radius = 1) {\n const pos = {\n x: e.offsetX * canvas.width / canvas.clientWidth,\n y: e.offsetY * canvas.height / canvas.clientHeight,\n };\n document.querySelector('#debug').textContent = count;\n ctx.beginPath();\n ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2);\n ctx.fillStyle = hsl((count++ % 100) / 100, 1, 0.5);\n ctx.fill();\n }\n\n function preventDefault(e) {\n e.preventDefault();\n }\n\n if (window.PointerEvent) {\n canvas.addEventListener('pointermove', (e) => {\n draw(e, Math.max(Math.max(e.width, e.height) / 2, 1));\n });\n canvas.addEventListener('touchstart', preventDefault, {passive: false});\n canvas.addEventListener('touchmove', preventDefault, {passive: false});\n } else {\n canvas.addEventListener('mousemove', draw);\n canvas.addEventListener('mousedown', preventDefault);\n }\n});\n\nfunction hsl(h, s, l) {\n return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.scene {\n width: 200px;\n height: 200px;\n perspective: 600px;\n}\n\n.cube {\n width: 100%;\n height: 100%;\n position: relative;\n transform-style: preserve-3d;\n animation-duration: 16s;\n animation-name: rotate;\n animation-iteration-count: infinite;\n animation-timing-function: linear;\n}\n\n@keyframes rotate {\n from { transform: translateZ(-100px) rotateX( 0deg) rotateY( 0deg); }\n to { transform: translateZ(-100px) rotateX(360deg) rotateY(720deg); }\n}\n\n.cube__face {\n position: absolute;\n width: 200px;\n height: 200px;\n display: block;\n}\n\n.cube__face--front { background: rgba(255, 0, 0, 0.2); transform: rotateY( 0deg) translateZ(100px); }\n.cube__face--right { background: rgba(0, 255, 0, 0.2); transform: rotateY( 90deg) translateZ(100px); }\n.cube__face--back { background: rgba(0, 0, 255, 0.2); transform: rotateY(180deg) translateZ(100px); }\n.cube__face--left { background: rgba(255, 255, 0, 0.2); transform: rotateY(-90deg) translateZ(100px); }\n.cube__face--top { background: rgba(0, 255, 255, 0.2); transform: rotateX( 90deg) translateZ(100px); }\n.cube__face--bottom { background: rgba(255, 0, 255, 0.2); transform: rotateX(-90deg) translateZ(100px); }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"scene\">\n <div class=\"cube\">\n <canvas class=\"cube__face cube__face--front\"></canvas>\n <canvas class=\"cube__face cube__face--back\"></canvas>\n <canvas class=\"cube__face cube__face--right\"></canvas>\n <canvas class=\"cube__face cube__face--left\"></canvas>\n <canvas class=\"cube__face cube__face--top\"></canvas>\n <canvas class=\"cube__face cube__face--bottom\"></canvas>\n </div>\n</div>\n<pre id=\"debug\"></pre></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Working example using <code>canvas.getBoundingClientRect</code> and <code>event.clientX</code> and <code>event.clientY</code></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const canvas = document.querySelector('canvas');\nconst ctx = canvas.getContext('2d');\nctx.canvas.width = ctx.canvas.clientWidth;\nctx.canvas.height = ctx.canvas.clientHeight;\nlet count = 0;\n\nfunction draw(e, radius = 1) {\n const rect = canvas.getBoundingClientRect();\n const pos = {\n x: (e.clientX - rect.left) * canvas.width / canvas.clientWidth,\n y: (e.clientY - rect.top) * canvas.height / canvas.clientHeight,\n };\n ctx.beginPath();\n ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2);\n ctx.fillStyle = hsl((count++ % 100) / 100, 1, 0.5);\n ctx.fill();\n}\n\nfunction preventDefault(e) {\n e.preventDefault();\n}\n\nif (window.PointerEvent) {\n canvas.addEventListener('pointermove', (e) => {\n draw(e, Math.max(Math.max(e.width, e.height) / 2, 1));\n });\n canvas.addEventListener('touchstart', preventDefault, {passive: false});\n canvas.addEventListener('touchmove', preventDefault, {passive: false});\n} else {\n canvas.addEventListener('mousemove', draw);\n canvas.addEventListener('mousedown', preventDefault);\n}\n\nfunction hsl(h, s, l) {\n return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>canvas { background: #FED; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><canvas width=\"400\" height=\"100\" style=\"width: 300px; height: 200px\"></canvas>\n<div>canvas deliberately has differnt CSS size vs drawingbuffer size</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 56363476,
"author": "Divyanshu Rawat",
"author_id": 5763627,
"author_profile": "https://Stackoverflow.com/users/5763627",
"pm_score": 1,
"selected": false,
"text": "<p>I was creating an application having a <strong>canvas</strong> over a pdf, that involved a lot of resizes of canvas like Zooming the pdf-in and out, and in turn on every zoom-in/out of PDF I had to resize the canvas to adapt the size of the pdf, I went through lot of answers in stackOverflow, and didn't found a perfect solution that will eventually solve the problem.</p>\n\n<p>I was using <strong>rxjs</strong> and angular 6, and didn't found any answer specific to the newest version.</p>\n\n<p>Here is the entire code snippet that would be helpful, to anyone leveraging <strong>rxjs</strong> to draw on top of canvas.</p>\n\n<pre><code> private captureEvents(canvasEl: HTMLCanvasElement) {\n\n this.drawingSubscription = fromEvent(canvasEl, 'mousedown')\n .pipe(\n switchMap((e: any) => {\n\n return fromEvent(canvasEl, 'mousemove')\n .pipe(\n takeUntil(fromEvent(canvasEl, 'mouseup').do((event: WheelEvent) => {\n const prevPos = {\n x: null,\n y: null\n };\n })),\n\n takeUntil(fromEvent(canvasEl, 'mouseleave')),\n pairwise()\n )\n })\n )\n .subscribe((res: [MouseEvent, MouseEvent]) => {\n const rect = this.cx.canvas.getBoundingClientRect();\n const prevPos = {\n x: Math.floor( ( res[0].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),\n y: Math.floor( ( res[0].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )\n };\n const currentPos = {\n x: Math.floor( ( res[1].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),\n y: Math.floor( ( res[1].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )\n };\n\n this.coordinatesArray[this.file.current_slide - 1].push(prevPos);\n this.drawOnCanvas(prevPos, currentPos);\n });\n }\n</code></pre>\n\n<p>And here is the snippet that fixes, mouse coordinates relative to size of the canvas, irrespective of how you zoom-in/out the canvas.</p>\n\n<pre><code>const prevPos = {\n x: Math.floor( ( res[0].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),\n y: Math.floor( ( res[0].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )\n};\nconst currentPos = {\n x: Math.floor( ( res[1].clientX - rect.left ) / ( rect.right - rect.left ) * this.cx.canvas.width ),\n y: Math.floor( ( res[1].clientY - rect.top ) / ( rect.bottom - rect.top ) * this.cx.canvas.height )\n};\n</code></pre>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
] | What's the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?
No legacy browser compatibility required, Safari, Opera and Firefox will do. | If you like simplicity but still want cross-browser functionality I found this solution worked best for me. This is a simplification of @Aldekein´s solution but **without jQuery**.
```
function getCursorPosition(canvas, event) {
const rect = canvas.getBoundingClientRect()
const x = event.clientX - rect.left
const y = event.clientY - rect.top
console.log("x: " + x + " y: " + y)
}
const canvas = document.querySelector('canvas')
canvas.addEventListener('mousedown', function(e) {
getCursorPosition(canvas, e)
})
``` |
55,709 | <p>I am building a java server that needs to scale. One of the servlets will be serving images stored in Amazon S3.</p>
<p>Recently under load, I ran out of memory in my VM and it was after I added the code to serve the images so I'm pretty sure that streaming larger servlet responses is causing my troubles.</p>
<p>My question is : is there any best practice in how to code a java servlet to stream a large (>200k) response back to a browser when read from a database or other cloud storage?</p>
<p>I've considered writing the file to a local temp drive and then spawning another thread to handle the streaming so that the tomcat servlet thread can be re-used. This seems like it would be io heavy.</p>
<p>Any thoughts would be appreciated. Thanks.</p>
| [
{
"answer_id": 55717,
"author": "airportyh",
"author_id": 5304,
"author_profile": "https://Stackoverflow.com/users/5304",
"pm_score": 4,
"selected": false,
"text": "<p>Why wouldn't you just point them to the S3 url? Taking an artifact from S3 and then streaming it through your own server to me defeats the purpose of using S3, which is to offload the bandwidth and processing of serving the images to Amazon.</p>\n"
},
{
"answer_id": 55751,
"author": "Marcio Aguiar",
"author_id": 4213,
"author_profile": "https://Stackoverflow.com/users/4213",
"pm_score": 0,
"selected": false,
"text": "<p>You have to check two things:</p>\n\n<ul>\n<li>Are you closing the stream? Very important</li>\n<li>Maybe you're giving stream connections \"for free\". The stream is not large, but many many streams at the same time can steal all your memory. Create a pool so that you cannot have a certain number of streams running at the same time</li>\n</ul>\n"
},
{
"answer_id": 55769,
"author": "Tony BenBrahim",
"author_id": 80075,
"author_profile": "https://Stackoverflow.com/users/80075",
"pm_score": 2,
"selected": false,
"text": "<p>toby is right, you should be pointing straight to S3, if you can. If you cannot, the question is a little vague to give an accurate response:\nHow big is your java heap? How many streams are open concurrently when you run out of memory?<br>\nHow big is your read write/bufer (8K is good)?<br>\nYou are reading 8K from the stream, then writing 8k to the output, right? You are not trying to read the whole image from S3, buffer it in memory, then sending the whole thing at once? </p>\n\n<p>If you use 8K buffers, you could have 1000 concurrent streams going in ~8Megs of heap space, so you are definitely doing something wrong....</p>\n\n<p>BTW, I did not pick 8K out of thin air, it is the default size for socket buffers, send more data, say 1Meg, and you will be blocking on the tcp/ip stack holding a large amount of memory.</p>\n"
},
{
"answer_id": 55788,
"author": "John Vasileff",
"author_id": 5076,
"author_profile": "https://Stackoverflow.com/users/5076",
"pm_score": 7,
"selected": true,
"text": "<p>When possible, you should not store the entire contents of a file to be served in memory. Instead, aquire an InputStream for the data, and copy the data to the Servlet OutputStream in pieces. For example:</p>\n\n<pre><code>ServletOutputStream out = response.getOutputStream();\nInputStream in = [ code to get source input stream ];\nString mimeType = [ code to get mimetype of data to be served ];\nbyte[] bytes = new byte[FILEBUFFERSIZE];\nint bytesRead;\n\nresponse.setContentType(mimeType);\n\nwhile ((bytesRead = in.read(bytes)) != -1) {\n out.write(bytes, 0, bytesRead);\n}\n\n// do the following in a finally block:\nin.close();\nout.close();\n</code></pre>\n\n<p>I do agree with toby, you should instead \"point them to the S3 url.\"</p>\n\n<p>As for the OOM exception, are you sure it has to do with serving the image data? Let's say your JVM has 256MB of \"extra\" memory to use for serving image data. With Google's help, \"256MB / 200KB\" = 1310. For 2GB \"extra\" memory (these days a very reasonable amount) over 10,000 simultaneous clients could be supported. Even so, 1300 simultaneous clients is a pretty large number. Is this the type of load you experienced? If not, you may need to look elsewhere for the cause of the OOM exception.</p>\n\n<p>Edit - Regarding:</p>\n\n<blockquote>\n <p>In this use case the images can contain sensitive data...</p>\n</blockquote>\n\n<p>When I read through the S3 documentation a few weeks ago, I noticed that you can generate time-expiring keys that can be attached to S3 URLs. So, you would not have to open up the files on S3 to the public. My understanding of the technique is:</p>\n\n<ol>\n<li>Initial HTML page has download links to your webapp</li>\n<li>User clicks on a download link</li>\n<li>Your webapp generates an S3 URL that includes a key that expires in, lets say, 5 minutes.</li>\n<li>Send an HTTP redirect to the client with the URL from step 3.</li>\n<li>The user downloads the file from S3. This works even if the download takes more than 5 minutes - once a download starts it can continue through completion.</li>\n</ol>\n"
},
{
"answer_id": 55890,
"author": "Johannes Passing",
"author_id": 4372,
"author_profile": "https://Stackoverflow.com/users/4372",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to what John suggested, you should repeatedly flush the output stream. Depending on your web container, it is possible that it caches parts or even all of your output and flushes it at-once (for example, to calculate the Content-Length header). That would burn quite a bit of memory.</p>\n"
},
{
"answer_id": 55896,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 2,
"selected": false,
"text": "<p>I agree strongly with both toby and John Vasileff--S3 is great for off loading large media objects if you can tolerate the associated issues. (An instance of own app does that for 10-1000MB FLVs and MP4s.) E.g.: No partial requests (byte range header), though. One has to handle that 'manually', occasional down time, etc..</p>\n\n<p>If that is not an option, John's code looks good. I have found that a byte buffer of 2k FILEBUFFERSIZE is the most efficient in microbench marks. Another option might be a shared FileChannel. (FileChannels are thread-safe.)</p>\n\n<p>That said, I'd also add that guessing at what caused an out of memory error is a classic optimization mistake. You would improve your chances of success by working with hard metrics.</p>\n\n<ol>\n<li>Place -XX:+HeapDumpOnOutOfMemoryError into you JVM startup parameters, just in case</li>\n<li>take use jmap on the running JVM (<strong>jmap -histo <pid></strong>) under load</li>\n<li>Analyize the metrics (jmap -histo out put, or have jhat look at your heap dump). It very well may be that your out of memory is coming from somewhere unexpected.</li>\n</ol>\n\n<p>There are of course other tools out there, but jmap & jhat come with Java 5+ 'out of the box'</p>\n\n<blockquote>\n <p>I've considered writing the file to a local temp drive and then spawning another thread to handle the streaming so that the tomcat servlet thread can be re-used. This seems like it would be io heavy.</p>\n</blockquote>\n\n<p>Ah, I don't think you can't do that. And even if you could, it sounds dubious. The tomcat thread that is managing the connection needs to in control. If you are experiencing thread starvation then increase the number of available threads in ./conf/server.xml. Again, metrics are the way to detect this--don't just guess. </p>\n\n<p>Question: Are you also running on EC2? What are your tomcat's JVM start up parameters?</p>\n"
},
{
"answer_id": 1504607,
"author": "Emil Sit",
"author_id": 55284,
"author_profile": "https://Stackoverflow.com/users/55284",
"pm_score": 0,
"selected": false,
"text": "<p>If you can structure your files so that the static files are separate and in their own bucket, the fastest performance today can likely be achieved by using the Amazon S3 CDN, <a href=\"http://aws.amazon.com/cloudfront/\" rel=\"nofollow noreferrer\">CloudFront</a>.</p>\n"
},
{
"answer_id": 23252476,
"author": "blast_hardcheese",
"author_id": 743614,
"author_profile": "https://Stackoverflow.com/users/743614",
"pm_score": 4,
"selected": false,
"text": "<p>I've seen a lot of code like john-vasilef's (currently accepted) answer, a tight while loop reading chunks from one stream and writing them to the other stream.</p>\n\n<p>The argument I'd make is against needless code duplication, in favor of using Apache's IOUtils. If you are already using it elsewhere, or if another library or framework you're using is already depending on it, it's a single line that is known and well-tested.</p>\n\n<p>In the following code, I'm streaming an object from Amazon S3 to the client in a servlet.</p>\n\n<pre><code>import java.io.InputStream;\nimport java.io.OutputStream;\nimport org.apache.commons.io.IOUtils;\n\nInputStream in = null;\nOutputStream out = null;\n\ntry {\n in = object.getObjectContent();\n out = response.getOutputStream();\n IOUtils.copy(in, out);\n} finally {\n IOUtils.closeQuietly(in);\n IOUtils.closeQuietly(out);\n}\n</code></pre>\n\n<p>6 lines of a well-defined pattern with proper stream closing seems pretty solid.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4974/"
] | I am building a java server that needs to scale. One of the servlets will be serving images stored in Amazon S3.
Recently under load, I ran out of memory in my VM and it was after I added the code to serve the images so I'm pretty sure that streaming larger servlet responses is causing my troubles.
My question is : is there any best practice in how to code a java servlet to stream a large (>200k) response back to a browser when read from a database or other cloud storage?
I've considered writing the file to a local temp drive and then spawning another thread to handle the streaming so that the tomcat servlet thread can be re-used. This seems like it would be io heavy.
Any thoughts would be appreciated. Thanks. | When possible, you should not store the entire contents of a file to be served in memory. Instead, aquire an InputStream for the data, and copy the data to the Servlet OutputStream in pieces. For example:
```
ServletOutputStream out = response.getOutputStream();
InputStream in = [ code to get source input stream ];
String mimeType = [ code to get mimetype of data to be served ];
byte[] bytes = new byte[FILEBUFFERSIZE];
int bytesRead;
response.setContentType(mimeType);
while ((bytesRead = in.read(bytes)) != -1) {
out.write(bytes, 0, bytesRead);
}
// do the following in a finally block:
in.close();
out.close();
```
I do agree with toby, you should instead "point them to the S3 url."
As for the OOM exception, are you sure it has to do with serving the image data? Let's say your JVM has 256MB of "extra" memory to use for serving image data. With Google's help, "256MB / 200KB" = 1310. For 2GB "extra" memory (these days a very reasonable amount) over 10,000 simultaneous clients could be supported. Even so, 1300 simultaneous clients is a pretty large number. Is this the type of load you experienced? If not, you may need to look elsewhere for the cause of the OOM exception.
Edit - Regarding:
>
> In this use case the images can contain sensitive data...
>
>
>
When I read through the S3 documentation a few weeks ago, I noticed that you can generate time-expiring keys that can be attached to S3 URLs. So, you would not have to open up the files on S3 to the public. My understanding of the technique is:
1. Initial HTML page has download links to your webapp
2. User clicks on a download link
3. Your webapp generates an S3 URL that includes a key that expires in, lets say, 5 minutes.
4. Send an HTTP redirect to the client with the URL from step 3.
5. The user downloads the file from S3. This works even if the download takes more than 5 minutes - once a download starts it can continue through completion. |
55,713 | <p>In effect, if I have a <code>class c</code> and instances of <code>$c1</code> and <code>$c2</code>
which might have different private variable amounts but all their public methods return the same values I would like to be able to check that <code>$c1 == $c2?</code></p>
<p>Does anyone know an easy way to do this?</p>
| [
{
"answer_id": 55731,
"author": "Rushi",
"author_id": 3983,
"author_profile": "https://Stackoverflow.com/users/3983",
"pm_score": 1,
"selected": false,
"text": "<p>You can define PHP's <strong>__toString</strong> magic method inside your class. </p>\n\n<p>For example</p>\n\n<pre><code>class cat {\n private $name;\n public function __contruct($catname) {\n $this->name = $catname;\n }\n\n public function __toString() {\n return \"My name is \" . $this->name . \"\\n\";\n }\n}\n\n$max = new cat('max');\n$toby = new cat('toby');\nprint $max; // echoes 'My name is max'\nprint $toby; // echoes 'My name is toby'\n\nif($max == $toby) {\n echo 'Woohoo!\\n';\n} else {\n echo 'Doh!\\n';\n}\n</code></pre>\n\n<p>Then you can use the equality operator to check if both instances are equal or not. </p>\n\n<p>HTH,</p>\n\n<p>Rushi</p>\n"
},
{
"answer_id": 55742,
"author": "Rushi",
"author_id": 3983,
"author_profile": "https://Stackoverflow.com/users/3983",
"pm_score": 1,
"selected": false,
"text": "<p>George: You may have already seen this but it may help: <a href=\"http://usphp.com/manual/en/language.oop5.object-comparison.php\" rel=\"nofollow noreferrer\">http://usphp.com/manual/en/language.oop5.object-comparison.php</a></p>\n\n<blockquote>\n <p>When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values, and are instances of the same class. </p>\n</blockquote>\n\n<p>They don't get implicitly converted to strings.</p>\n\n<p>If you want todo comparison, you will end up modifying your classes. You can also write some method of your own todo comparison using getters & setters</p>\n"
},
{
"answer_id": 55811,
"author": "Rushi",
"author_id": 3983,
"author_profile": "https://Stackoverflow.com/users/3983",
"pm_score": 0,
"selected": false,
"text": "<p>You can try writing a class of your own to plugin and write methods that do comparison based on what you define. For example:</p>\n\n<pre><code>class Validate {\n public function validateName($c1, $c2) {\n if($c1->FirstName == \"foo\" && $c2->LastName == \"foo\") {\n return true;\n } else if (// someother condition) {\n return // someval;\n } else {\n return false;\n }\n }\n\n public function validatePhoneNumber($c1, $c2) {\n // some code\n }\n}\n</code></pre>\n\n<p>This will probably be the only way where you wont have to modify the pre-existing class code</p>\n"
},
{
"answer_id": 56012,
"author": "reefnet_alex",
"author_id": 2745,
"author_profile": "https://Stackoverflow.com/users/2745",
"pm_score": 2,
"selected": false,
"text": "<p>It's difficult to follow exactly what you're after. Your question seems to imply that these public methods don't require arguments, or that if they did they would be the same arguments. </p>\n\n<p>You could probably get quite far using the inbuilt reflection classes. </p>\n\n<p>Pasted below is a quick test I knocked up to compare the returns of all the public methods of two classes and ensure they were they same. You could easily modify it to ignore non matching public methods (i.e. only check for equality on public methods in class2 which exist in class1). Giving a set of arguments to pass in would be trickier - but could be done with an array of methods names / arguments to call against each class. </p>\n\n<p>Anyway, this may have some bits in it which could be of use to you.</p>\n\n<pre><code>$class1 = new Class1();\n$class2 = new Class2();\n$class3 = new Class3();\n$class4 = new Class4();\n$class5 = new Class5();\n\necho ClassChecker::samePublicMethods($class1,$class2); //should be true\necho ClassChecker::samePublicMethods($class1,$class3); //should be false - different values\necho ClassChecker::samePublicMethods($class1,$class4); //should be false -- class3 contains extra public methods\necho ClassChecker::samePublicMethods($class1,$class5); //should be true -- class5 contains extra private methods\n\nclass ClassChecker {\n\n public static function samePublicMethods($class1, $class2) {\n\n $class1methods = array();\n\n $r = new ReflectionClass($class1);\n $methods = $r->getMethods();\n\n foreach($methods as $m) {\n if ($m->isPublic()) {\n @$result = call_user_method($m->getName(), $class1);\n $class1methods[$m->getName()] = $result;\n }\n }\n\n $r = new ReflectionClass($class2);\n $methods = $r->getMethods();\n\n foreach($methods as $m) {\n\n //only comparing public methods\n if ($m->isPublic()) {\n\n //public method doesn't match method in class1 so return false\n if(!isset($class1methods[$m->getName()])) {\n return false;\n }\n\n //public method of same name doesn't return same value so return false\n @$result = call_user_method($m->getName(), $class2);\n if ($class1methods[$m->getName()] !== $result) {\n return false;\n }\n }\n }\n\n return true;\n }\n}\n\n\nclass Class1 {\n\n private $b = 'bbb';\n\n public function one() {\n return 999;\n }\n\n public function two() {\n return \"bendy\";\n }\n\n\n}\n\nclass Class2 {\n\n private $a = 'aaa';\n\n public function one() {\n return 999;\n }\n\n public function two() {\n return \"bendy\";\n }\n}\n\nclass Class3 {\n\n private $c = 'ccc';\n\n public function one() {\n return 222;\n }\n\n public function two() {\n return \"bendy\";\n }\n\n\n}\n\nclass Class4 {\n\n public function one() {\n return 999;\n }\n\n public function two() {\n return \"bendy\";\n }\n\n public function three() {\n return true;\n }\n\n}\n\nclass Class5 {\n\n public function one() {\n return 999;\n }\n\n public function two() {\n return \"bendy\";\n }\n\n private function three() {\n return true;\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 56054,
"author": "VolkerK",
"author_id": 4833,
"author_profile": "https://Stackoverflow.com/users/4833",
"pm_score": 3,
"selected": true,
"text": "<p>You can also implement a equal($other) function like</p>\n\n<pre>\n<?php\nclass Foo {\n public function equals($o) {\n return ($o instanceof 'Foo') && $o.firstName()==$this.firstName();\n }\n}\n</pre>\n\n<p>or use foreach to iterate over the public properties (this behaviour might be overwritten) of one object and compare them to the other object's properties.</p>\n\n<pre>\n<?php\nfunction equalsInSomeWay($a, $b) {\n if ( !($b instanceof $a) ) {\n return false;\n }\n\n foreach($a as $name=>$value) {\n if ( !isset($b->$name) || $b->$name!=$value ) {\n return false;\n }\n }\n return true;\n}\n</pre>\n\n<p>(untested)</p>\n\n<p>or (more or less) the same using the Reflection classes, see <a href=\"http://php.net/manual/en/language.oop5.reflection.php#language.oop5.reflection.reflectionobject\" rel=\"nofollow noreferrer\">http://php.net/manual/en/language.oop5.reflection.php#language.oop5.reflection.reflectionobject</a><br />\nWith reflection you might also implement a more duck-typing kind of comparision, if you want to, like \"I don't care if it's an instance of or the same class as long as it has the same public methods and they return the 'same' values\"<br />\nit really depends on how you define \"equal\".</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | In effect, if I have a `class c` and instances of `$c1` and `$c2`
which might have different private variable amounts but all their public methods return the same values I would like to be able to check that `$c1 == $c2?`
Does anyone know an easy way to do this? | You can also implement a equal($other) function like
```
<?php
class Foo {
public function equals($o) {
return ($o instanceof 'Foo') && $o.firstName()==$this.firstName();
}
}
```
or use foreach to iterate over the public properties (this behaviour might be overwritten) of one object and compare them to the other object's properties.
```
<?php
function equalsInSomeWay($a, $b) {
if ( !($b instanceof $a) ) {
return false;
}
foreach($a as $name=>$value) {
if ( !isset($b->$name) || $b->$name!=$value ) {
return false;
}
}
return true;
}
```
(untested)
or (more or less) the same using the Reflection classes, see <http://php.net/manual/en/language.oop5.reflection.php#language.oop5.reflection.reflectionobject>
With reflection you might also implement a more duck-typing kind of comparision, if you want to, like "I don't care if it's an instance of or the same class as long as it has the same public methods and they return the 'same' values"
it really depends on how you define "equal". |
55,754 | <p>What is the best way, using Bash, to rename files in the form:</p>
<pre><code>(foo1, foo2, ..., foo1300, ..., fooN)
</code></pre>
<p>With zero-padded file names:</p>
<pre><code>(foo00001, foo00002, ..., foo01300, ..., fooN)
</code></pre>
| [
{
"answer_id": 55775,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 2,
"selected": false,
"text": "<p>The following will do it:</p>\n\n<pre><code>for ((i=1; i<=N; i++)) ; do mv foo$i `printf foo%05d $i` ; done\n</code></pre>\n\n<p><strong>EDIT:</strong> changed to use ((i=1,...)), thanks <a href=\"https://stackoverflow.com/users/4285/mweerden\">mweerden</a>!</p>\n"
},
{
"answer_id": 55778,
"author": "amrox",
"author_id": 4468,
"author_profile": "https://Stackoverflow.com/users/4468",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a quick solution that assumes a fixed length prefix (your \"foo\") and fixed length padding. If you need more flexibility, maybe this will at least be a helpful starting point.</p>\n\n<pre><code>#!/bin/bash\n\n# some test data\nfiles=\"foo1\nfoo2\nfoo100\nfoo200\nfoo9999\"\n\nfor f in $files; do\n prefix=`echo \"$f\" | cut -c 1-3` # chars 1-3 = \"foo\"\n number=`echo \"$f\" | cut -c 4-` # chars 4-end = the number\n printf \"%s%04d\\n\" \"$prefix\" \"$number\"\ndone\n</code></pre>\n"
},
{
"answer_id": 55782,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 6,
"selected": true,
"text": "<p>In case <code>N</code> is not a priori fixed:</p>\n<pre><code>for f in foo[0-9]*; do\n mv "$f" "$(printf 'foo%05d' "${f#foo}")"\ndone\n</code></pre>\n"
},
{
"answer_id": 506377,
"author": "Fritz G. Mehner",
"author_id": 57457,
"author_profile": "https://Stackoverflow.com/users/57457",
"pm_score": 3,
"selected": false,
"text": "<p>Pure Bash, no external processes other than 'mv':</p>\n\n<pre><code>for file in foo*; do\n newnumber='00000'${file#foo} # get number, pack with zeros\n newnumber=${newnumber:(-5)} # the last five characters\n mv $file foo$newnumber # rename\ndone\n</code></pre>\n"
},
{
"answer_id": 3700146,
"author": "Michael Baltaks",
"author_id": 23312,
"author_profile": "https://Stackoverflow.com/users/23312",
"pm_score": 4,
"selected": false,
"text": "<p>I had a more complex case where the file names had a postfix as well as a prefix. I also needed to perform a subtraction on the number from the filename.</p>\n\n<p>For example, I wanted <code>foo56.png</code> to become <code>foo00000055.png</code>.</p>\n\n<p>I hope this helps if you're doing something more complex.</p>\n\n<pre><code>#!/bin/bash\n\nprefix=\"foo\"\npostfix=\".png\"\ntargetDir=\"../newframes\"\npaddingLength=8\n\nfor file in ${prefix}[0-9]*${postfix}; do\n # strip the prefix off the file name\n postfile=${file#$prefix}\n # strip the postfix off the file name\n number=${postfile%$postfix}\n # subtract 1 from the resulting number\n i=$((number-1))\n # copy to a new name with padded zeros in a new folder\n cp ${file} \"$targetDir\"/$(printf $prefix%0${paddingLength}d$postfix $i)\ndone\n</code></pre>\n"
},
{
"answer_id": 4561801,
"author": "KARASZI István",
"author_id": 221213,
"author_profile": "https://Stackoverflow.com/users/221213",
"pm_score": 6,
"selected": false,
"text": "<p>It's not pure bash, but much easier with the Perl version of <code>rename</code>:</p>\n<pre><code>rename 's/\\d+/sprintf("%05d",$&)/e' foo*\n</code></pre>\n<p>Where <code>'s/\\d+/sprintf("%05d",$&)/e'</code> is the Perl replace regular expression.</p>\n<ul>\n<li><code>\\d+</code> will match the first set of numbers (at least one number)</li>\n<li><code>sprintf("%05d",$&)</code> will pass the matched numbers to Perl's <code>sprintf</code>, and <code>%05d</code> will pad to five digits</li>\n</ul>\n"
},
{
"answer_id": 45569550,
"author": "Pioz",
"author_id": 302005,
"author_profile": "https://Stackoverflow.com/users/302005",
"pm_score": 3,
"selected": false,
"text": "<p>The oneline command that I use is this:</p>\n\n<pre><code>ls * | cat -n | while read i f; do mv \"$f\" `printf \"PATTERN\" \"$i\"`; done\n</code></pre>\n\n<p>PATTERN can be for example:</p>\n\n<ul>\n<li>rename with increment counter: <code>%04d.${f#*.}</code> (keep original file extension)</li>\n<li>rename with increment counter with prefix: <code>photo_%04d.${f#*.}</code> (keep original extension)</li>\n<li>rename with increment counter and change extension to jpg: <code>%04d.jpg</code></li>\n<li>rename with increment counter with prefix and file basename: <code>photo_$(basename $f .${f#*.})_%04d.${f#*.}</code></li>\n<li>...</li>\n</ul>\n\n<p>You can filter the file to rename with for example <code>ls *.jpg | ...</code></p>\n\n<p>You have available the variable <code>f</code> that is the file name and <code>i</code> that is the counter.</p>\n\n<p>For your question the right command is:</p>\n\n<pre><code>ls * | cat -n | while read i f; do mv \"$f\" `printf \"foo%d05\" \"$i\"`; done\n</code></pre>\n"
},
{
"answer_id": 54888706,
"author": "AntonAL",
"author_id": 235158,
"author_profile": "https://Stackoverflow.com/users/235158",
"pm_score": 1,
"selected": false,
"text": "<p>My solution replaces numbers, <strong>everywhere in a string</strong></p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>for f in * ; do\n number=`echo $f | sed 's/[^0-9]*//g'`\n padded=`printf \"%04d\" $number`\n echo $f | sed \"s/${number}/${padded}/\";\ndone\n</code></pre>\n\n<p>You can easily try it, since it just prints transformed file names (no filesystem operations are performed).</p>\n\n<h2>Explanation:</h2>\n\n<h3>Looping through list of files</h3>\n\n<p>A loop: <code>for f in * ; do ;done</code>, lists all files and passes each filename as <code>$f</code> variable to loop body.</p>\n\n<h3>Grabbing the number from string</h3>\n\n<p>With <code>echo $f | sed</code> we pipe variable <code>$f</code> to <code>sed</code> program.</p>\n\n<p>In command <code>sed 's/[^0-9]*//g'</code>, part <code>[^0-9]*</code> with modifier <code>^</code> tells to match opposite from digit 0-9 (not a number) and then remove it it with empty replacement <code>//</code>. Why not just remove <code>[a-z]</code>? Because filename can contain dots, dashes etc. So, we strip everything, that is not a number and get a number.</p>\n\n<p>Next, we assign the result to <code>number</code> variable. Remember to not put spaces in assignment, like <code>number = …</code>, because you get different behavior.</p>\n\n<p>We assign execution result of a command to variable, wrapping the command with backtick symbols `.</p>\n\n<h3>Zero padding</h3>\n\n<p>Command <code>printf \"%04d\" $number</code> changes format of a number to 4 digits and adds zeros if our number contains less than 4 digits.</p>\n\n<h3>Replacing number to zero-padded number</h3>\n\n<p>We use <code>sed</code> again with replacement command like <code>s/substring/replacement/</code>. To interpret our variables, we use double quotes and substitute our variables in this way <code>${number}</code>.</p>\n\n<hr>\n\n<p>The script above just prints transformed names, so, let's do actual renaming job:</p>\n\n<pre><code>for f in *.js ; do\n number=`echo $f | sed 's/[^0-9]*//g'`\n padded=`printf \"%04d\" $number`\n new_name=`echo $f | sed \"s/${number}/${padded}/\"`\n mv $f $new_name;\ndone\n</code></pre>\n\n<p>Hope this helps someone.</p>\n\n<p>I spent several hours to figure this out.</p>\n"
},
{
"answer_id": 55409116,
"author": "Victoria Stuart",
"author_id": 1904943,
"author_profile": "https://Stackoverflow.com/users/1904943",
"pm_score": 3,
"selected": false,
"text": "<p>To left-pad numbers in filenames:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ ls -l\ntotal 0\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:24 010\n-rw-r--r-- 1 victoria victoria 0 Mar 28 18:09 050\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:23 050.zzz\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:24 10\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:23 1.zzz\n\n$ for f in [0-9]*.[a-z]*; do tmp=`echo $f | awk -F. '{printf \"%04d.%s\\n\", $1, $2}'`; mv \"$f\" \"$tmp\"; done;\n\n$ ls -l\ntotal 0\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:23 0001.zzz\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:23 0050.zzz\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:24 010\n-rw-r--r-- 1 victoria victoria 0 Mar 28 18:09 050\n-rw-r--r-- 1 victoria victoria 0 Mar 28 17:24 10\n</code></pre>\n\n<p><strong>Explanation</strong></p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>for f in [0-9]*.[a-z]*; do tmp=`echo $f | \\\nawk -F. '{printf \"%04d.%s\\n\", $1, $2}'`; mv \"$f\" \"$tmp\"; done;\n</code></pre>\n\n<ul>\n<li>note the backticks: <code>`echo ... $2}\\`</code> (The backslash, \\, immediately above just splits that one-liner over two lines for readability)</li>\n<li>in a loop find files that are named as numbers with lowercase alphabet extensions: <code>[0-9]*.[a-z]*</code></li>\n<li>echo that filename (<code>$f</code>) to pass it to <code>awk</code></li>\n<li><code>-F.</code> : <code>awk</code> field separator, a period (<code>.</code>): if matched, separates the file names as two fields (<code>$1</code> = number; <code>$2</code> = extension)</li>\n<li>format with <code>printf</code>: print first field (<code>$1</code>, the number part) as 4 digits (<code>%04d</code>), then print the period, then print the second field (<code>$2</code>: the extension) as a string (<code>%s</code>). All of that is assigned to the <code>$tmp</code> variable</li>\n<li>lastly, move the source file (<code>$f</code>) to the new filename (<code>$tmp</code>)</li>\n</ul>\n"
},
{
"answer_id": 69038695,
"author": "danday74",
"author_id": 1205871,
"author_profile": "https://Stackoverflow.com/users/1205871",
"pm_score": 1,
"selected": false,
"text": "<p>This answer is derived from Chris Conway's accepted answer but <strong>assumes your files have an extension</strong> (unlike Chris' answer). Just paste this (rather long) one liner into your command line.</p>\n<pre><code>for f in foo[0-9]*; do mv "$f" "$(printf 'foo%05d' "${f#foo}" 2> /dev/null)"; done; for f in foo[0-9]*; do mv "$f" "$f.ext"; done;\n</code></pre>\n<p><strong>OPTIONAL ADDITIONAL INFO</strong></p>\n<p>This script will rename</p>\n<pre><code>foo1.ext > foo00001.ext\nfoo2.ext > foo00002.ext\nfoo1300.ext > foo01300.ext\n</code></pre>\n<p>To test it on your machine, just paste this one liner into an <strong>EMPTY</strong> directory.</p>\n<pre><code>rm * 2> /dev/null; touch foo1.ext foo2.ext foo1300.ext; for f in foo[0-9]*; do mv "$f" "$(printf 'foo%05d' "${f#foo}" 2> /dev/null)"; done; for f in foo[0-9]*; do mv "$f" "$f.ext"; done;\n</code></pre>\n<p>This deletes the content of the directory, creates the files in the above example and then does the batch rename.</p>\n<p>For those who don't need a one liner, the script indented looks like this.</p>\n<pre><code>for f in foo[0-9]*;\n do mv "$f" "$(printf 'foo%05d' "${f#foo}" 2> /dev/null)";\ndone;\n\nfor f in foo[0-9]*;\n do mv "$f" "$f.ext";\ndone;\n</code></pre>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3020/"
] | What is the best way, using Bash, to rename files in the form:
```
(foo1, foo2, ..., foo1300, ..., fooN)
```
With zero-padded file names:
```
(foo00001, foo00002, ..., foo01300, ..., fooN)
``` | In case `N` is not a priori fixed:
```
for f in foo[0-9]*; do
mv "$f" "$(printf 'foo%05d' "${f#foo}")"
done
``` |
55,843 | <p>I am currently using Linq to NHibernate (although that is not an issue with regards to this question) to execute queries against my database and I want to be able to test whether the current <code>IQueryable</code> result instance has been executed or not.</p>
<p>The debugger knows that my <code>IQueryable</code> has not been <em>'invoked'</em> because it tells me that expanding the Results property will <em>'enumerate'</em> it. Is there a way for me to programmatically identify that as well.</p>
<p>I hope that makes sense :)</p>
| [
{
"answer_id": 55848,
"author": "Christian Hagelid",
"author_id": 202,
"author_profile": "https://Stackoverflow.com/users/202",
"pm_score": 0,
"selected": false,
"text": "<p>I believe you can use <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.data.linq.datacontext.log\" rel=\"nofollow noreferrer\">DataContext.Log</a> to log everything that is executed.</p>\n"
},
{
"answer_id": 81740,
"author": "Mark Pattison",
"author_id": 15519,
"author_profile": "https://Stackoverflow.com/users/15519",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming you're using Visual Studio, you can insert <code>DataContext.Log = Console.Out</code> into your code. You can then watch the SQL as it's executed, in the output window.</p>\n\n<p>I'm not sure whether it's possible to programatically test whether the query has been executed. You can force it to execute, for example by calling <code>.ToList</code> on the query.</p>\n"
},
{
"answer_id": 85732,
"author": "dcstraw",
"author_id": 10391,
"author_profile": "https://Stackoverflow.com/users/10391",
"pm_score": 3,
"selected": true,
"text": "<p>How about writing an IQueryable wrapper like this:</p>\n\n<pre><code>class QueryableWrapper<T> : IQueryable<T>\n{\n private IQueryable<T> _InnerQueryable;\n private bool _HasExecuted;\n\n public QueryableWrapper(IQueryable<T> innerQueryable)\n {\n _InnerQueryable = innerQueryable;\n }\n\n public bool HasExecuted\n {\n get\n {\n return _HasExecuted;\n }\n }\n\n public IEnumerator<T> GetEnumerator()\n {\n _HasExecuted = true;\n\n return _InnerQueryable.GetEnumerator();\n }\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n public Type ElementType\n {\n get { return _InnerQueryable.ElementType; }\n }\n\n public System.Linq.Expressions.Expression Expression\n {\n get { return _InnerQueryable.Expression; }\n }\n\n public IQueryProvider Provider\n {\n get { return _InnerQueryable.Provider; }\n }\n}\n</code></pre>\n\n<p>Then you can use it like this:</p>\n\n<pre><code>var query = new QueryableWrapper<string>(\n from str in myDataSource\n select str);\n\nDebug.WriteLine(\"HasExecuted: \" + query.HasExecuted.ToString());\n\nforeach (string str in query)\n{\n Debug.WriteLine(str);\n}\n\nDebug.WriteLine(\"HasExecuted: \" + query.HasExecuted.ToString());\n</code></pre>\n\n<p>Output is:</p>\n\n<p>False<br/>\nString0<br/>\nString1<br/>\n...<br/>\nTrue</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4884/"
] | I am currently using Linq to NHibernate (although that is not an issue with regards to this question) to execute queries against my database and I want to be able to test whether the current `IQueryable` result instance has been executed or not.
The debugger knows that my `IQueryable` has not been *'invoked'* because it tells me that expanding the Results property will *'enumerate'* it. Is there a way for me to programmatically identify that as well.
I hope that makes sense :) | How about writing an IQueryable wrapper like this:
```
class QueryableWrapper<T> : IQueryable<T>
{
private IQueryable<T> _InnerQueryable;
private bool _HasExecuted;
public QueryableWrapper(IQueryable<T> innerQueryable)
{
_InnerQueryable = innerQueryable;
}
public bool HasExecuted
{
get
{
return _HasExecuted;
}
}
public IEnumerator<T> GetEnumerator()
{
_HasExecuted = true;
return _InnerQueryable.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public Type ElementType
{
get { return _InnerQueryable.ElementType; }
}
public System.Linq.Expressions.Expression Expression
{
get { return _InnerQueryable.Expression; }
}
public IQueryProvider Provider
{
get { return _InnerQueryable.Provider; }
}
}
```
Then you can use it like this:
```
var query = new QueryableWrapper<string>(
from str in myDataSource
select str);
Debug.WriteLine("HasExecuted: " + query.HasExecuted.ToString());
foreach (string str in query)
{
Debug.WriteLine(str);
}
Debug.WriteLine("HasExecuted: " + query.HasExecuted.ToString());
```
Output is:
False
String0
String1
...
True |
55,855 | <p>I am following the <a href="http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx" rel="noreferrer">M-V-VM</a> pattern for my WPF UI. I would like to hook up a command to the TextChanged event of a TextBox to a command that is in my ViewModel class. The only way I can conceive of completing this task is to inherit from the TextBox control, and implement ICommandSource. I can then instruct the command to be fired from the TextChanged event. This seems to be too much work for something which appears to be so simple.</p>
<p>Is there an easier way (than subclassing the TextBox and implementing ICommandSource) to hook up the TextChanged event to my ViewModel class?</p>
| [
{
"answer_id": 56081,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 2,
"selected": false,
"text": "<p>Can you not just handle the TextChanged event and execute the command from there?</p>\n\n<pre><code>private void _textBox_TextChanged(object sender, EventArgs e)\n{\n MyCommand.Execute(null);\n}\n</code></pre>\n\n<p>The alternative, as you say, is to create a <code>TextBox</code> that acts as a command source, but that does seem like overkill unless it's something you're planning on sharing and leveraging in many places.</p>\n"
},
{
"answer_id": 56164,
"author": "Samuel Jack",
"author_id": 1727,
"author_profile": "https://Stackoverflow.com/users/1727",
"pm_score": 5,
"selected": true,
"text": "<p>First off, you've surely considered two-way data binding to your viewmodel, with an UpdateSourceTrigger of PropertyChanged? That way the property setter of the property you bind to will be called every time the text is changed?</p>\n\n<p>If that's not enough, then I would tackle this problem using Attached Behaviours. On Julian Dominguez’s Blog you'll find an <a href=\"http://blogs.southworks.net/jdominguez/2008/08/icommand-for-silverlight-with-attached-behaviors/\" rel=\"noreferrer\">article</a> about how to do something very similar in Silverlight, which should be easily adaptable to WPF.</p>\n\n<p>Basically, in a static class (called, say TextBoxBehaviours) you define an Attached Property called (perhaps) TextChangedCommand of type ICommand. Hook up an OnPropertyChanged handler for that property, and within the handler, check that the property is being set on a TextBox; if it is, add a handler to the TextChanged event on the textbox that will call the command specified in the property.</p>\n\n<p>Then, assuming your viewmodel has been assigned to the DataContext of your View, you would use it like:</p>\n\n<pre><code><TextBox\n x:Name=\"MyTextBox\"\n TextBoxBehaviours.TextChangedCommand=\"{Binding ViewModelTextChangedCommand}\" />\n</code></pre>\n"
},
{
"answer_id": 56191,
"author": "Nidonocu",
"author_id": 483,
"author_profile": "https://Stackoverflow.com/users/483",
"pm_score": 3,
"selected": false,
"text": "<p>Using the event binding and command method might not be the right thing to use.\nWhat exactly will this command do?</p>\n\n<p>You might want to consider using a Databinding to a string field in your VM. This way you can make a call to a command or function from there rather than having the UI care at all.</p>\n\n<pre><code><TextBox Text=\"{Binding WorldName}\"/>\n....\npublic string WorldName\n{\n get\n {\n return WorldData.Name;\n }\n set\n {\n WorldData.Name = value;\n OnPropertyChanged(\"WorldName\");\n // CallYourCustomFunctionHere();\n }\n}\n</code></pre>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
] | I am following the [M-V-VM](http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx) pattern for my WPF UI. I would like to hook up a command to the TextChanged event of a TextBox to a command that is in my ViewModel class. The only way I can conceive of completing this task is to inherit from the TextBox control, and implement ICommandSource. I can then instruct the command to be fired from the TextChanged event. This seems to be too much work for something which appears to be so simple.
Is there an easier way (than subclassing the TextBox and implementing ICommandSource) to hook up the TextChanged event to my ViewModel class? | First off, you've surely considered two-way data binding to your viewmodel, with an UpdateSourceTrigger of PropertyChanged? That way the property setter of the property you bind to will be called every time the text is changed?
If that's not enough, then I would tackle this problem using Attached Behaviours. On Julian Dominguez’s Blog you'll find an [article](http://blogs.southworks.net/jdominguez/2008/08/icommand-for-silverlight-with-attached-behaviors/) about how to do something very similar in Silverlight, which should be easily adaptable to WPF.
Basically, in a static class (called, say TextBoxBehaviours) you define an Attached Property called (perhaps) TextChangedCommand of type ICommand. Hook up an OnPropertyChanged handler for that property, and within the handler, check that the property is being set on a TextBox; if it is, add a handler to the TextChanged event on the textbox that will call the command specified in the property.
Then, assuming your viewmodel has been assigned to the DataContext of your View, you would use it like:
```
<TextBox
x:Name="MyTextBox"
TextBoxBehaviours.TextChangedCommand="{Binding ViewModelTextChangedCommand}" />
``` |
55,859 | <p>In C++, I'm trying to catch all types of exceptions in one catch (like <code>catch(Exception)</code> in C#). How is it done? And what's more, how can one catch divide-by-zero exceptions?</p>
| [
{
"answer_id": 55863,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 6,
"selected": true,
"text": "<pre><code>catch (...)\n{\n // Handle exceptions not covered.\n}\n</code></pre>\n\n<p>Important considerations:</p>\n\n<ul>\n<li>A better approach is to catch specific types of exception that you can actually recover from as opposed to all possible exceptions.</li>\n<li>catch(...) will also catch certain serious system level exceptions (varies depending on compiler) that you are not going to be able to recover reliably from. Catching them in this way and then swallowing them and continuing could cause further serious problems in your program.</li>\n<li>Depending on your context it can be acceptable to use catch(...), providing the exception is re-thrown. In this case, you log all useful local state information and then re-throw the exception to allow it to propagate up. However you should read up on the <a href=\"http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization\" rel=\"noreferrer\">RAII pattern</a> if you choose this route.</li>\n</ul>\n"
},
{
"answer_id": 55865,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 2,
"selected": false,
"text": "<p>Make all your custom exception classes inherit from std::exception, then you can simply catch std::exception. Here is some example code:</p>\n\n<pre><code>class WidgetError\n : public std::exception\n{\npublic:\n WidgetError()\n { }\n\n virtual ~WidgetError() throw()\n { }\n\n virtual const char *what() const throw()\n {\n return \"You got you a widget error!\";\n }\n};\n</code></pre>\n"
},
{
"answer_id": 55866,
"author": "Paul Wicks",
"author_id": 85,
"author_profile": "https://Stackoverflow.com/users/85",
"pm_score": -1,
"selected": false,
"text": "<p>If I recall correctly (it's been a while since I've looked at C++), I think the following should do the trick</p>\n\n<pre><code>try\n{\n // some code\n}\ncatch(...)\n{\n // catch anything\n}\n</code></pre>\n\n<p>and a quick google(<a href=\"http://www.oreillynet.com/pub/a/network/2003/05/05/cpluspocketref.html\" rel=\"nofollow noreferrer\">http://www.oreillynet.com/pub/a/network/2003/05/05/cpluspocketref.html</a>) seems to prove me correct.</p>\n"
},
{
"answer_id": 55867,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 1,
"selected": false,
"text": "<p>In C++, the standard does not define a divide-by-zero exception, and implementations tend to not throw them.</p>\n"
},
{
"answer_id": 55916,
"author": "Carl Seleborg",
"author_id": 2095,
"author_profile": "https://Stackoverflow.com/users/2095",
"pm_score": 4,
"selected": false,
"text": "<p>You <strong>don't</strong> want to be using catch (...) (i.e. catch with the ellipsis) unless you really, definitely, most provable have a need for it.</p>\n\n<p>The reason for this is that some compilers (Visual C++ 6 to name the most common) also turn errors like segmentation faults and other really bad conditions into exceptions that you can gladly handle using catch (...). This is very bad, because you don't see the crashes anymore.</p>\n\n<p>And technically, yes, you can also catch division by zero (you'll have to \"StackOverflow\" for that), but you really should be avoiding making such divisions in the first place.</p>\n\n<p>Instead, do the following:</p>\n\n<ul>\n<li>If you actually know what kind of exception(s) to expect, catch those types and no more, and</li>\n<li>If you need to throw exceptions yourself, and need to catch all the exceptions you will throw, make these exceptions derive from std::exception (as Adam Pierce suggested) and catch that.</li>\n</ul>\n"
},
{
"answer_id": 55934,
"author": "ima",
"author_id": 5733,
"author_profile": "https://Stackoverflow.com/users/5733",
"pm_score": 2,
"selected": false,
"text": "<p>If catching all exceptions - including OS ones - is really what you need, you need to take a look at your compiler and OS. For example, on Windows you probably have \"__try\" keyword or compiler switch to make \"try/catch\" catch SEH exceptions, or both.</p>\n"
},
{
"answer_id": 56274,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You can, of course, use <code>catch (...) { /* code here */ }</code>, but it really Depends On What You Want To Do. In C++ you have deterministic destructors (none of that finalisation rubbish), so if you want to mop up, the correct thing to do is to use RAII.</p>\n\n<p>For example. instead of:</p>\n\n<pre><code>void myfunc()\n{\n void* h = get_handle_that_must_be_released();\n try { random_func(h); }\n catch (...) { release_object(h); throw; }\n release_object(h);\n\n}\n</code></pre>\n\n<p>Do something like:</p>\n\n<pre><code>#include<boost/shared_ptr.hpp>\n\nvoid my_func()\n{\n boost::shared_ptr<void> h(get_handle_that_must_be_released(), release_object);\n random_func(h.get());\n}\n</code></pre>\n\n<p>Create your own class with a destructor if you don't use boost.</p>\n"
},
{
"answer_id": 57088,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 3,
"selected": false,
"text": "<p>If you are on windows and need to handle errors like divide by zero and access violation you can use a structured exception translator. And then inside of your translator you can throw a c++ exception:</p>\n\n<pre><code>void myTranslator(unsigned code, EXCEPTION_POINTERS*)\n{\n throw std::exception(<appropriate string here>);\n}\n\n_set_se_translator(myTranslator);\n</code></pre>\n\n<p>Note, the code will tell you what the error was. Also you need to compile with the /EHa option (C/C++ -> Code Generatrion -> Enable C/C++ Exceptions = Yes with SEH Exceptions).</p>\n\n<p>If that doesn't make sense checkout the docs for [_set_se_translator](<a href=\"http://msdn.microsoft.com/en-us/library/5z4bw5h5(VS.80).aspx)\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/5z4bw5h5(VS.80).aspx)</a></p>\n"
},
{
"answer_id": 58223526,
"author": "BuvinJ",
"author_id": 3220983,
"author_profile": "https://Stackoverflow.com/users/3220983",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>catch(...)</code> to catch EVERYTHING, but then <strong>you don't get a an object</strong> to inspect, rethrow, log, or do anything with exactly. So... you can \"double up\" the try block and rethrow into one outer catch that handles a single type. This works ideally if you define constructors for a custom exception type that can build itself from all the kinds you want to group together. You can then throw a default constructed one from the <code>catch(...)</code>, which might have a message or code in it like \"UNKNOWN\", or however you want to track such things.</p>\n\n<p>Example:</p>\n\n<pre><code>try\n{ \n try\n { \n // do something that can produce various exception types\n }\n catch( const CustomExceptionA &e ){ throw e; } \\\n catch( const CustomExceptionB &e ){ throw CustomExceptionA( e ); } \\\n catch( const std::exception &e ) { throw CustomExceptionA( e ); } \\\n catch( ... ) { throw CustomExceptionA(); } \\\n} \ncatch( const CustomExceptionA &e ) \n{\n // Handle any exception as CustomExceptionA\n}\n</code></pre>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/195/"
] | In C++, I'm trying to catch all types of exceptions in one catch (like `catch(Exception)` in C#). How is it done? And what's more, how can one catch divide-by-zero exceptions? | ```
catch (...)
{
// Handle exceptions not covered.
}
```
Important considerations:
* A better approach is to catch specific types of exception that you can actually recover from as opposed to all possible exceptions.
* catch(...) will also catch certain serious system level exceptions (varies depending on compiler) that you are not going to be able to recover reliably from. Catching them in this way and then swallowing them and continuing could cause further serious problems in your program.
* Depending on your context it can be acceptable to use catch(...), providing the exception is re-thrown. In this case, you log all useful local state information and then re-throw the exception to allow it to propagate up. However you should read up on the [RAII pattern](http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization) if you choose this route. |
55,860 | <p>Okay, here is the 411 - I have the following event handler in my Global.asax.cs file:</p>
<pre><code>private void Global_PostRequestHandlerExecute(object sender, EventArgs e)
{
if (/* logic that determines that this is an ajax call */)
{
// we want to set a cookie
Response.Cookies.Add(new HttpCookie("MyCookie", "true"));
}
}
</code></pre>
<p>That handler will run during Ajax requests (as a result of the Ajax framework I am using), as well as at other times - the condition of the if statement filters out non-Ajax events, and works just fine (it isn't relevant here, so I didn't include it for brevity's sake).</p>
<p>It suffices us to say that this works just fine - the cookie is set, I am able to read it on the client, and all is well up to that point.</p>
<p>Now for the part that drives me nuts.</p>
<p>Here is the JavaScript function I am using to delete the cookie:</p>
<pre><code>function deleteCookie(name) {
var cookieDate = new Date();
cookieDate.setTime(cookieDate.getTime() - 1);
document.cookie = (name + "=; expires=" + cookieDate.toGMTString());
}
</code></pre>
<p>So, of course, at some point after the cookie is set, I delete it like so:</p>
<pre><code>deleteCookie("MyCookie");
</code></pre>
<p>Only, that doesn't do the job; the cookie still exists. So, anyone know why?</p>
| [
{
"answer_id": 56261,
"author": "Erlend",
"author_id": 5746,
"author_profile": "https://Stackoverflow.com/users/5746",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried to use <code>;expires=Thu, 01-Jan-1970 00:00:01 GMT</code>?</p>\n"
},
{
"answer_id": 56287,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 2,
"selected": false,
"text": "<p>Weird.. The code you pasted is almost verbatim to this: <a href=\"http://www.quirksmode.org/js/cookies.html\" rel=\"nofollow noreferrer\">http://www.quirksmode.org/js/cookies.html</a> which works fine..</p>\n<p>I know you are using Ajax, but have you tried quickly <strong>knocking it to server side code to see if that works</strong>? This may help in figuring if it is a problem with the JS or something else (e.g mystery file locking on the cookie)?</p>\n<h3>Update</h3>\n<p>Just had a quick Google, looks like there may be issues with browser settings as well. I don't think your problem is the code here, it's more likely to be something else. I would suggest try the above as PoC and we can move from there. :)</p>\n"
},
{
"answer_id": 56740,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 2,
"selected": false,
"text": "<p>I posted a js cookie util a week or so ago on <a href=\"http://rickyrosario.com/blog/javascript-cookie-utility\" rel=\"nofollow noreferrer\">my blog</a>. This has worked for me on all \"A Grade\" browsers.</p>\n\n<pre><code>var CookieUtil = {\n createCookie:function(name,value,days) {\n if (days) {\n var date = new Date();\n date.setTime(date.getTime()+(days*24*60*60*1000));\n var expires = \"; expires=\"+date.toGMTString();\n }\n else var expires = \"\";\n document.cookie = name+\"=\"+value+expires+\"; path=/\";\n },\n readCookie:function(name) {\n var nameEQ = name + \"=\";\n var ca = document.cookie.split(';');\n for(var i=0;i < ca.length;i++) {\n var c = ca[i];\n while (c.charAt(0)==' ') c = c.substring(1,c.length);\n if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);\n }\n return null;\n },\n eraseCookie:function(name) {\n createCookie(name,\"\",-1);\n }\n};\n</code></pre>\n"
},
{
"answer_id": 56993,
"author": "Robert J. Walker",
"author_id": 4287,
"author_profile": "https://Stackoverflow.com/users/4287",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li>Have you checked the client-side and server-side cookie domains and paths to ensure they're the same?</li>\n<li>Is one cookie secure and the other not?</li>\n<li>Other than that, I would suspect server/client clock sync issues, as Erlend suggests.</li>\n</ul>\n"
},
{
"answer_id": 60379,
"author": "Tyler",
"author_id": 5642,
"author_profile": "https://Stackoverflow.com/users/5642",
"pm_score": 0,
"selected": false,
"text": "<p>Are we sure there's no code that sets the Cookie to HttpOnly (we're not missing anything above)? The HttpOnly property will stop (modern) browsers from modifying the cookie. I'd be interested to see if you can kill it server side like Rob suggests.</p>\n"
},
{
"answer_id": 163262,
"author": "benc",
"author_id": 2910,
"author_profile": "https://Stackoverflow.com/users/2910",
"pm_score": 0,
"selected": false,
"text": "<p>I assume you are calling this javascript on the browser side. Which browser are you using, how are you viewing the cookie to confirm it is still there? </p>\n"
},
{
"answer_id": 163307,
"author": "Andreas Petersson",
"author_id": 16542,
"author_profile": "https://Stackoverflow.com/users/16542",
"pm_score": 3,
"selected": false,
"text": "<p>you have to delete your cookie at the same path where you created it.\nso create your cookie with path=/ and delte it with path=/ as well..</p>\n"
},
{
"answer_id": 3714058,
"author": "just.jimmy",
"author_id": 435635,
"author_profile": "https://Stackoverflow.com/users/435635",
"pm_score": 1,
"selected": false,
"text": "<p>Also if a cookie domain was specified during the creation, I've found that you must also specify the cookie domain while trying to delete (expire) it.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1790/"
] | Okay, here is the 411 - I have the following event handler in my Global.asax.cs file:
```
private void Global_PostRequestHandlerExecute(object sender, EventArgs e)
{
if (/* logic that determines that this is an ajax call */)
{
// we want to set a cookie
Response.Cookies.Add(new HttpCookie("MyCookie", "true"));
}
}
```
That handler will run during Ajax requests (as a result of the Ajax framework I am using), as well as at other times - the condition of the if statement filters out non-Ajax events, and works just fine (it isn't relevant here, so I didn't include it for brevity's sake).
It suffices us to say that this works just fine - the cookie is set, I am able to read it on the client, and all is well up to that point.
Now for the part that drives me nuts.
Here is the JavaScript function I am using to delete the cookie:
```
function deleteCookie(name) {
var cookieDate = new Date();
cookieDate.setTime(cookieDate.getTime() - 1);
document.cookie = (name + "=; expires=" + cookieDate.toGMTString());
}
```
So, of course, at some point after the cookie is set, I delete it like so:
```
deleteCookie("MyCookie");
```
Only, that doesn't do the job; the cookie still exists. So, anyone know why? | you have to delete your cookie at the same path where you created it.
so create your cookie with path=/ and delte it with path=/ as well.. |
55,869 | <p>I'm downloading some images from a service that doesn't always include a content-type and doesn't provide an extension for the file I'm downloading (ugh, don't ask).</p>
<p>What's the best way to determine the image format in .NET?</p>
<p>The application that is reading these downloaded images needs to have a proper file extension or all hell breaks loose.</p>
| [
{
"answer_id": 55873,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 0,
"selected": false,
"text": "<p>Try loading the stream into a System.IO.BinaryReader. </p>\n\n<p>Then you will need to refer to the specifications for each image format you need, and load the header byte by byte to compare against the specifications. For example here are the <a href=\"http://www.libpng.org/pub/png/pngdocs.html\" rel=\"nofollow noreferrer\">PNG specifications</a></p>\n\n<p>Added: The actual <a href=\"http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html\" rel=\"nofollow noreferrer\">file structure</a> for PNG.</p>\n"
},
{
"answer_id": 55876,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 5,
"selected": false,
"text": "<p>All the image formats set their initial bytes to a particular value:</p>\n\n<ul>\n<li>JPG: <a href=\"http://en.wikipedia.org/wiki/JPEG#Syntax_and_structure\" rel=\"noreferrer\">0xFF 0xD8</a></li>\n<li>PNG: <a href=\"http://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header\" rel=\"noreferrer\">0x89 0x50 0x4E 0x47 0x0D 0x0A 0x1A 0x0A</a></li>\n<li>GIF: <a href=\"http://www.w3.org/Graphics/GIF/spec-gif89a.txt\" rel=\"noreferrer\">'G' 'I' 'F'</a></li>\n</ul>\n\n<p>Search for \"jpg file format\" replacing jpg with the other file formats you need to identify.</p>\n\n<p>As Garth recommends, there is a <a href=\"http://pwet.fr/man/linux/formats/magic\" rel=\"noreferrer\">database of such 'magic numbers'</a> showing the file type of many files. If you have to detect a lot of different file types it's worthwhile looking through it to find the information you need. If you do need to extend this to cover many, many file types, look at the associated <a href=\"http://pwet.fr/man/linux/commandes/posix/file\" rel=\"noreferrer\">file command</a> which implements the engine to use the database correctly (it's non trivial for many file formats, and is almost a statistical process)</p>\n\n<p>-Adam</p>\n"
},
{
"answer_id": 55879,
"author": "Garth Kidd",
"author_id": 5700,
"author_profile": "https://Stackoverflow.com/users/5700",
"pm_score": 3,
"selected": false,
"text": "<p>Adam is pointing in exactly the right direction. </p>\n\n<p>If you want to find out how to <strong>sense almost any file</strong>, look at the database behind the <code>file</code> command on a UNIX, Linux, or Mac OS X machine. </p>\n\n<p><code>file</code> uses a database of “magic numbers” — those initial bytes Adam listed — to sense a file's type. <code>man file</code> will tell you where to find the database on your machine, e.g. <code>/usr/share/file/magic</code>. <code>man magic</code> will tell you its <a href=\"http://linux.die.net/man/5/magic\" rel=\"noreferrer\">format</a>. </p>\n\n<p>You can either write your own detection code based on what you see in the database, use pre-packaged libraries (e.g. <a href=\"http://hupp.org/adam/hg/python-magic\" rel=\"noreferrer\">python-magic</a>), or — if you're <em>really</em> adventurous — implement a .NET version of <code>libmagic</code>. I couldn't find one, and hope another member can point one out. </p>\n\n<p>In case you don't have a UNIX machine handy, the database looks like this:</p>\n\n<pre>\n# PNG [Portable Network Graphics, or \"PNG's Not GIF\"] images\n# (Greg Roelofs, newt@uchicago.edu)\n# (Albert Cahalan, acahalan@cs.uml.edu)\n#\n# 137 P N G \\r \\n ^Z \\n [4-byte length] H E A D [HEAD data] [HEAD crc] ...\n#\n0 string \\x89PNG PNG image data,\n>4 belong !0x0d0a1a0a CORRUPTED,\n>4 belong 0x0d0a1a0a\n>>16 belong x %ld x\n>>20 belong x %ld,\n>>24 byte x %d-bit\n>>25 byte 0 grayscale,\n>>25 byte 2 \\b/color RGB,\n>>25 byte 3 colormap,\n>>25 byte 4 gray+alpha,\n>>25 byte 6 \\b/color RGBA,\n#>>26 byte 0 deflate/32K,\n>>28 byte 0 non-interlaced\n>>28 byte 1 interlaced\n1 string PNG PNG image data, CORRUPTED\n\n# GIF\n0 string GIF8 GIF image data\n>4 string 7a \\b, version 8%s,\n>4 string 9a \\b, version 8%s,\n>6 leshort >0 %hd x\n>8 leshort >0 %hd\n#>10 byte &0x80 color mapped,\n#>10 byte&0x07 =0x00 2 colors\n#>10 byte&0x07 =0x01 4 colors\n#>10 byte&0x07 =0x02 8 colors\n#>10 byte&0x07 =0x03 16 colors\n#>10 byte&0x07 =0x04 32 colors\n#>10 byte&0x07 =0x05 64 colors\n#>10 byte&0x07 =0x06 128 colors\n#>10 byte&0x07 =0x07 256 colors\n</pre>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 55887,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 7,
"selected": true,
"text": "<p>A probably easier approach would be to use Image.FromFile() and then use the RawFormat property, as it already knows about the magic bits in the headers for the most common formats, like this:</p>\n\n<pre><code>Image i = Image.FromFile(\"c:\\\\foo\");\nif (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(i.RawFormat)) \n MessageBox.Show(\"JPEG\");\nelse if (System.Drawing.Imaging.ImageFormat.Gif.Equals(i.RawFormat))\n MessageBox.Show(\"GIF\");\n//Same for the rest of the formats\n</code></pre>\n"
},
{
"answer_id": 12051761,
"author": "slobodans",
"author_id": 946580,
"author_profile": "https://Stackoverflow.com/users/946580",
"pm_score": 2,
"selected": false,
"text": "<p>There is programmatic way to determine image MIMETYPE.</p>\n\n<p>There is class <strong>System.Drawing.Imaging.ImageCodecInfo</strong>. </p>\n\n<p>This class have properties <strong>MimeType</strong> and <strong>FormatID</strong>. Also it have a method <strong>GetImageEncoders</strong> which return collection of all image encoders. \nIt is easy to create Dictionary of mime types indexed by format id.</p>\n\n<p>Class <strong>System.Drawing.Image</strong> have property <strong>RawFormat</strong> of Type <strong>System.Drawing.Imaging.ImageFormat</strong> which have property <strong>Guid</strong> which is equivalent of the property <strong>FormatID</strong> of class <strong>System.Drawing.Imaging.ImageCodecInfo</strong>, and that is key to take MIMETYPE from dictionary.</p>\n\n<p>Example:</p>\n\n<p>Static method to create dictionary of mime types</p>\n\n<pre><code>static Dictionary<Guid, string> GetImageFormatMimeTypeIndex()\n{\n Dictionary<Guid, string> ret = new Dictionary<Guid, string>();\n\n var encoders = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();\n\n foreach(var e in encoders)\n {\n ret.Add(e.FormatID, e.MimeType);\n }\n\n return ret;\n}\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>Dictionary<Guid, string> mimeTypeIndex = GetImageFormatMimeTypeIndex();\n\nFileStream imgStream = File.OpenRead(path);\nvar image = System.Drawing.Image.FromStream(imgStream);\nstring mimeType = mimeTypeIndex[image.RawFormat.Guid];\n</code></pre>\n"
},
{
"answer_id": 12451102,
"author": "Ivan Kochurkin",
"author_id": 1046374,
"author_profile": "https://Stackoverflow.com/users/1046374",
"pm_score": 5,
"selected": false,
"text": "<p>You can use code below without reference of System.Drawing and unnecessary creation of object Image. Also you can use <a href=\"https://stackoverflow.com/a/9446083/1046374\">Alex</a> solution even without stream and reference of System.IO.</p>\n\n<pre><code>public enum ImageFormat\n{\n bmp,\n jpeg,\n gif,\n tiff,\n png,\n unknown\n}\n\npublic static ImageFormat GetImageFormat(Stream stream)\n{\n // see http://www.mikekunz.com/image_file_header.html\n var bmp = Encoding.ASCII.GetBytes(\"BM\"); // BMP\n var gif = Encoding.ASCII.GetBytes(\"GIF\"); // GIF\n var png = new byte[] { 137, 80, 78, 71 }; // PNG\n var tiff = new byte[] { 73, 73, 42 }; // TIFF\n var tiff2 = new byte[] { 77, 77, 42 }; // TIFF\n var jpeg = new byte[] { 255, 216, 255, 224 }; // jpeg\n var jpeg2 = new byte[] { 255, 216, 255, 225 }; // jpeg canon\n\n var buffer = new byte[4];\n stream.Read(buffer, 0, buffer.Length);\n\n if (bmp.SequenceEqual(buffer.Take(bmp.Length)))\n return ImageFormat.bmp;\n\n if (gif.SequenceEqual(buffer.Take(gif.Length)))\n return ImageFormat.gif;\n\n if (png.SequenceEqual(buffer.Take(png.Length)))\n return ImageFormat.png;\n\n if (tiff.SequenceEqual(buffer.Take(tiff.Length)))\n return ImageFormat.tiff;\n\n if (tiff2.SequenceEqual(buffer.Take(tiff2.Length)))\n return ImageFormat.tiff;\n\n if (jpeg.SequenceEqual(buffer.Take(jpeg.Length)))\n return ImageFormat.jpeg;\n\n if (jpeg2.SequenceEqual(buffer.Take(jpeg2.Length)))\n return ImageFormat.jpeg;\n\n return ImageFormat.unknown;\n}\n</code></pre>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5277/"
] | I'm downloading some images from a service that doesn't always include a content-type and doesn't provide an extension for the file I'm downloading (ugh, don't ask).
What's the best way to determine the image format in .NET?
The application that is reading these downloaded images needs to have a proper file extension or all hell breaks loose. | A probably easier approach would be to use Image.FromFile() and then use the RawFormat property, as it already knows about the magic bits in the headers for the most common formats, like this:
```
Image i = Image.FromFile("c:\\foo");
if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(i.RawFormat))
MessageBox.Show("JPEG");
else if (System.Drawing.Imaging.ImageFormat.Gif.Equals(i.RawFormat))
MessageBox.Show("GIF");
//Same for the rest of the formats
``` |
55,899 | <p>I'm using a custom-built inhouse application that generates a standard set of reports on a weekly basis. I have no access to the source code of the application, and everyone tells me there is no documentation available for the Oracle database schema. (Aargh!)</p>
<p>I've been asked to define the specs for a variant of an existing report (e.g., apply additional filters to constrain the data set, and modify the layout slightly). This sounds simple enough in principle, but is difficult without any existing documentation. </p>
<p>It's my understanding that the logs can't help me because the report only queries the database; it does not actually insert, delete, or update database values, so there is nothing to log (is this correct?).</p>
<p>So my question is this: is there a tool or utility (Oracle or otherwise) that I can use to see the actual SQL statement that is being executed while the report generation job is still running? I figure, if I can see what tables are actually being accessed to produce the existing report, I'll have a very good starting point for exploring the schema and determining the correct SQL to use for my own report.</p>
| [
{
"answer_id": 55912,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 2,
"selected": false,
"text": "<p>I think the <a href=\"http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14237/dynviews_2129.htm\" rel=\"nofollow noreferrer\">V$SQLAREA</a> table contains what you're looking for (see columns <strong>SQL_TEXT</strong> and <strong>SQL_FULLTEXT</strong>).</p>\n"
},
{
"answer_id": 55914,
"author": "Mark Nold",
"author_id": 4134,
"author_profile": "https://Stackoverflow.com/users/4134",
"pm_score": 6,
"selected": true,
"text": "<p>On the data dictionary side there are a lot of tools you can use to such as <a href=\"http://schemaspy.sourceforge.net/\" rel=\"noreferrer\">Schema Spy</a></p>\n\n<p>To look at what queries are running look at views sys.v_$sql and sys.v_$sqltext. You will also need access to sys.all_users</p>\n\n<p>One thing to note that queries that use parameters will show up once with entries like </p>\n\n<pre><code>and TABLETYPE=’:b16’\n</code></pre>\n\n<p>while others that dont will show up multiple times such as:</p>\n\n<pre><code>and TABLETYPE=’MT’\n</code></pre>\n\n<p>An example of these tables in action is the following SQL to find the top 20 diskread hogs. You could change this by removing the <strong>WHERE rownum <= 20</strong> and maybe add <strong>ORDER BY module</strong>. You often find the module will give you a bog clue as to what software is running the query (eg: \"TOAD 9.0.1.8\", \"JDBC Thin Client\", \"runcbl@somebox (TNS V1-V3)\" etc)</p>\n\n<pre><code>SELECT \n module, \n sql_text, \n username, \n disk_reads_per_exec, \n buffer_gets, \n disk_reads, \n parse_calls, \n sorts, \n executions, \n rows_processed, \n hit_ratio, \n first_load_time, \n sharable_mem, \n persistent_mem, \n runtime_mem, \n cpu_time, \n elapsed_time, \n address, \n hash_value \nFROM \n (SELECT\n module, \n sql_text , \n u.username , \n round((s.disk_reads/decode(s.executions,0,1, s.executions)),2) disk_reads_per_exec, \n s.disk_reads , \n s.buffer_gets , \n s.parse_calls , \n s.sorts , \n s.executions , \n s.rows_processed , \n 100 - round(100 * s.disk_reads/greatest(s.buffer_gets,1),2) hit_ratio, \n s.first_load_time , \n sharable_mem , \n persistent_mem , \n runtime_mem, \n cpu_time, \n elapsed_time, \n address, \n hash_value \n FROM\n sys.v_$sql s, \n sys.all_users u \n WHERE\n s.parsing_user_id=u.user_id \n and UPPER(u.username) not in ('SYS','SYSTEM') \n ORDER BY\n 4 desc) \nWHERE\n rownum <= 20;\n</code></pre>\n\n<p>Note that if the query is long .. you will have to query v_$sqltext. This stores the whole query. You will have to look up the ADDRESS and HASH_VALUE and pick up all the pieces. Eg:</p>\n\n<pre><code>SELECT\n *\nFROM\n sys.v_$sqltext\nWHERE\n address = 'C0000000372B3C28'\n and hash_value = '1272580459'\nORDER BY \n address, hash_value, command_type, piece\n;\n</code></pre>\n"
},
{
"answer_id": 55915,
"author": "Hobo",
"author_id": 1714,
"author_profile": "https://Stackoverflow.com/users/1714",
"pm_score": 2,
"selected": false,
"text": "<p>Yep, that's definitely possible. The v$sql views contain that info. Something like <a href=\"http://www.oracle.com/technology/oramag/code/tips2005/100305.html\" rel=\"nofollow noreferrer\">this piece of code</a> should point you in the right direction. I haven't tried that specific piece of code myself - nowhere near an Oracle DB right now.</p>\n\n<p>[Edit] Damn two other answers already. Must type faster next time ;-)</p>\n"
},
{
"answer_id": 55920,
"author": "Ethan Post",
"author_id": 4527,
"author_profile": "https://Stackoverflow.com/users/4527",
"pm_score": 3,
"selected": false,
"text": "<p>Sorry for the short answer but it is late. Google \"oracle event 10046 sql trace\". It would be best to trace an individual session because figuring which SQL belongs to which session from v$sql is no easy if it is shared sql and being used by multiple users.</p>\n\n<p>If you want to impress your Oracle DBA friends, learn how to set an oracle trace with event 10046, interpret the meaning of the wait events and find the top cpu consumers. </p>\n\n<p>Quest had a free product that allowed you to capture the SQL as it went out from the client side but not sure if it works with your product/version of Oracle. Google \"quest oracle sql monitor\" for this.</p>\n\n<p>Good night.</p>\n"
},
{
"answer_id": 73179,
"author": "metadave",
"author_id": 7237,
"author_profile": "https://Stackoverflow.com/users/7237",
"pm_score": 0,
"selected": false,
"text": "<p>I had (have) a similar problem in a Java application. I wrote a JDBC driver wrapper around the Oracle driver so all output is sent to a log file. </p>\n"
},
{
"answer_id": 74558,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 1,
"selected": false,
"text": "<p>-- i use something like this, with concepts and some code stolen from asktom. <BR>\n-- suggestions for improvements are welcome <BR>\n<BLOCKQUOTE>\nWITH <BR>\nsess AS<BR>\n(<BR>\n SELECT *<BR>\n FROM V$SESSION<BR>\n WHERE USERNAME = USER <BR>\n ORDER BY SID<BR>\n)<BR>\nSELECT si.SID,<BR>\n si.LOCKWAIT,<BR>\n si.OSUSER,<BR>\n si.PROGRAM,<BR>\n si.LOGON_TIME,<BR>\n si.STATUS,<BR>\n (<BR>\n SELECT ROUND(USED_UBLK*8/1024,1) <BR>\n FROM V$TRANSACTION,<BR>\n sess<BR>\n WHERE sess.TADDR = V$TRANSACTION.ADDR<BR>\n AND sess.SID = si.SID<BR>\n<BR>\n ) rollback_remaining,<BR>\n<BR>\n (<BR>\n SELECT (MAX(DECODE(PIECE, 0,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 1,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 2,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 3,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 4,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 5,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 6,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 7,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 8,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 9,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 10,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 11,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 12,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 13,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 14,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 15,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 16,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 17,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 18,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 19,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 20,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 21,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 22,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 23,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 24,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 25,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 26,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 27,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 28,SQL_TEXT,NULL)) ||<BR>\n MAX(DECODE(PIECE, 29,SQL_TEXT,NULL))) <BR>\n FROM V$SQLTEXT_WITH_NEWLINES<BR>\n WHERE ADDRESS = SI.SQL_ADDRESS AND <BR>\n PIECE < 30<BR>\n ) SQL_TEXT<BR>\nFROM sess si;<BR>\n</BLOCKQUOTE></p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/480/"
] | I'm using a custom-built inhouse application that generates a standard set of reports on a weekly basis. I have no access to the source code of the application, and everyone tells me there is no documentation available for the Oracle database schema. (Aargh!)
I've been asked to define the specs for a variant of an existing report (e.g., apply additional filters to constrain the data set, and modify the layout slightly). This sounds simple enough in principle, but is difficult without any existing documentation.
It's my understanding that the logs can't help me because the report only queries the database; it does not actually insert, delete, or update database values, so there is nothing to log (is this correct?).
So my question is this: is there a tool or utility (Oracle or otherwise) that I can use to see the actual SQL statement that is being executed while the report generation job is still running? I figure, if I can see what tables are actually being accessed to produce the existing report, I'll have a very good starting point for exploring the schema and determining the correct SQL to use for my own report. | On the data dictionary side there are a lot of tools you can use to such as [Schema Spy](http://schemaspy.sourceforge.net/)
To look at what queries are running look at views sys.v\_$sql and sys.v\_$sqltext. You will also need access to sys.all\_users
One thing to note that queries that use parameters will show up once with entries like
```
and TABLETYPE=’:b16’
```
while others that dont will show up multiple times such as:
```
and TABLETYPE=’MT’
```
An example of these tables in action is the following SQL to find the top 20 diskread hogs. You could change this by removing the **WHERE rownum <= 20** and maybe add **ORDER BY module**. You often find the module will give you a bog clue as to what software is running the query (eg: "TOAD 9.0.1.8", "JDBC Thin Client", "runcbl@somebox (TNS V1-V3)" etc)
```
SELECT
module,
sql_text,
username,
disk_reads_per_exec,
buffer_gets,
disk_reads,
parse_calls,
sorts,
executions,
rows_processed,
hit_ratio,
first_load_time,
sharable_mem,
persistent_mem,
runtime_mem,
cpu_time,
elapsed_time,
address,
hash_value
FROM
(SELECT
module,
sql_text ,
u.username ,
round((s.disk_reads/decode(s.executions,0,1, s.executions)),2) disk_reads_per_exec,
s.disk_reads ,
s.buffer_gets ,
s.parse_calls ,
s.sorts ,
s.executions ,
s.rows_processed ,
100 - round(100 * s.disk_reads/greatest(s.buffer_gets,1),2) hit_ratio,
s.first_load_time ,
sharable_mem ,
persistent_mem ,
runtime_mem,
cpu_time,
elapsed_time,
address,
hash_value
FROM
sys.v_$sql s,
sys.all_users u
WHERE
s.parsing_user_id=u.user_id
and UPPER(u.username) not in ('SYS','SYSTEM')
ORDER BY
4 desc)
WHERE
rownum <= 20;
```
Note that if the query is long .. you will have to query v\_$sqltext. This stores the whole query. You will have to look up the ADDRESS and HASH\_VALUE and pick up all the pieces. Eg:
```
SELECT
*
FROM
sys.v_$sqltext
WHERE
address = 'C0000000372B3C28'
and hash_value = '1272580459'
ORDER BY
address, hash_value, command_type, piece
;
``` |
55,943 | <p>Is their any profilers that support Silverlight? I have tried ANTS (Version 3.1) without any success? Does version 4 support it? Any other products I can try?</p>
<p><strong>Updated</strong>
since the release of Silverlight 4, it is now possible to do full profiling on SL applications... check out <a href="http://blogs.msdn.com/seema/archive/2010/01/28/pdc-vs2010-profiling-silverlight-4.aspx" rel="noreferrer">this</a> article on the topic</p>
<blockquote>
<p>At PDC, I announced that Silverlight 4 came with the new CoreCLR capability of being profile-able by the VS2010 profilers: this means that for the first time, we give you the power to profile the managed and native code (user or platform) used by a Silverlight application. woohoo. kudos to the CLR team.</p>
<p>Sidenote: From silverlight 1-3, one could only use things like xperf (see XPerf: A CPU Sampler for Silverlight) which is very powerful to see the layout/text/media/gfx/etc pipelines, but only gives the native callstack.)</p>
</blockquote>
<p>From <a href="http://blogs.msdn.com/seema" rel="noreferrer">SilverLite</a> (<a href="http://blogs.msdn.com/seema/archive/2010/01/28/pdc-vs2010-profiling-silverlight-4.aspx" rel="noreferrer">PDC video, TechEd Iceland, VS2010, profiling, Silverlight 4</a>)</p>
| [
{
"answer_id": 55954,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 5,
"selected": true,
"text": "<p>Install XPerf and xperfview as available here: <a href=\"https://web.archive.org/web/20140825011849/http://blogs.msdn.com:80/b/seema/archive/2008/10/08/xperf-a-cpu-sampler-for-silverlight.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/cc305218.aspx</a></p>\n<p>(1) Startup your sample</p>\n<p>(2) xperf -on base</p>\n<p>(3) wait for a bit</p>\n<p>(4) xperf –d myprofile.etl</p>\n<p>(5) when this is done, set your symbol path: <pre>\nset _NT_SYMBOL_PATH= srv<em>C:\\symbols</em><a href=\"http://msdl.microsoft.com/downloads/symbols\" rel=\"nofollow noreferrer\">http://msdl.microsoft.com/downloads/symbols</a></pre></p>\n<p>(6) xperfview myprofile.etl</p>\n<p>(7) Trace -> Load Symbols</p>\n<ul>\n<li>Select the area of the CPU graph that you want to see</li>\n<li>Right-click and select Summary Table</li>\n</ul>\n<p>(8) Accept the EULA for using symbols, expand IExplore, expand agcore.dll or whatever is your top module</p>\n"
},
{
"answer_id": 258072,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://blogs.msdn.com/seema/archive/2008/10/08/xperf-a-cpu-sampler-for-silverlight.aspx\" rel=\"nofollow noreferrer\">Here</a> is a detailed blog entry about using XPerf... Also check out <a href=\"http://channel9.msdn.com/pdc2008/PC06/\" rel=\"nofollow noreferrer\">this</a> video (at PDC) about profiling silverlight!!!</p>\n"
},
{
"answer_id": 1381259,
"author": "zuraff",
"author_id": 111148,
"author_profile": "https://Stackoverflow.com/users/111148",
"pm_score": 1,
"selected": false,
"text": "<p>AtoLogic SilverProfiler should work for you. See <a href=\"http://www.atologic.com\" rel=\"nofollow noreferrer\">http://www.atologic.com</a></p>\n"
},
{
"answer_id": 2480070,
"author": "Naveen",
"author_id": 19407,
"author_profile": "https://Stackoverflow.com/users/19407",
"pm_score": 1,
"selected": false,
"text": "<p>SL 4.0 has coreclr etw events. Should be able to diagnose exception,gc, threading and few others using the XPERF and <a href=\"http://bcl.codeplex.com/releases/view/42784\" rel=\"nofollow noreferrer\">Perfmonitor</a> and clr etw. I have <a href=\"http://naveensrinivasan.wordpress.com/2010/03/15/undocumented-silverlight-feature-%e2%80%93-etw-tracing/\" rel=\"nofollow noreferrer\">blogged</a> about this. </p>\n\n<p>FYI using Perfmonitor should be able to provide call-stacks. </p>\n\n<p>ETW is available only in Windows. </p>\n"
},
{
"answer_id": 2577752,
"author": "Ivan Shakhov",
"author_id": 309130,
"author_profile": "https://Stackoverflow.com/users/309130",
"pm_score": 2,
"selected": false,
"text": "<p>Try JetBrains dotTrace performance profiler.\nHere is the detail how to:\n<a href=\"http://confluence.jetbrains.net/display/NetProf/How+to+profile+silverlight+application\" rel=\"nofollow noreferrer\">http://confluence.jetbrains.net/display/NetProf/How+to+profile+silverlight+application</a></p>\n"
},
{
"answer_id": 2746446,
"author": "Oren",
"author_id": 329961,
"author_profile": "https://Stackoverflow.com/users/329961",
"pm_score": 3,
"selected": false,
"text": "<p>Visual Studio 2010 (with the Silverlight 4 tools) comes with command line support for profiling Silverlight apps.</p>\n\n<p>Full instructions for profiling SL4 can be found at: <a href=\"http://www.nachmore.com/2010/profiling-silverlight-4-with-visual-studio-2010/\" rel=\"noreferrer\">http://www.nachmore.com/2010/profiling-silverlight-4-with-visual-studio-2010/</a></p>\n"
},
{
"answer_id": 4750195,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 1,
"selected": false,
"text": "<p>I like RedGate ANTS. I find it to be a much nicer profiler than dotTrace.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5147/"
] | Is their any profilers that support Silverlight? I have tried ANTS (Version 3.1) without any success? Does version 4 support it? Any other products I can try?
**Updated**
since the release of Silverlight 4, it is now possible to do full profiling on SL applications... check out [this](http://blogs.msdn.com/seema/archive/2010/01/28/pdc-vs2010-profiling-silverlight-4.aspx) article on the topic
>
> At PDC, I announced that Silverlight 4 came with the new CoreCLR capability of being profile-able by the VS2010 profilers: this means that for the first time, we give you the power to profile the managed and native code (user or platform) used by a Silverlight application. woohoo. kudos to the CLR team.
>
>
> Sidenote: From silverlight 1-3, one could only use things like xperf (see XPerf: A CPU Sampler for Silverlight) which is very powerful to see the layout/text/media/gfx/etc pipelines, but only gives the native callstack.)
>
>
>
From [SilverLite](http://blogs.msdn.com/seema) ([PDC video, TechEd Iceland, VS2010, profiling, Silverlight 4](http://blogs.msdn.com/seema/archive/2010/01/28/pdc-vs2010-profiling-silverlight-4.aspx)) | Install XPerf and xperfview as available here: [http://msdn.microsoft.com/en-us/library/cc305218.aspx](https://web.archive.org/web/20140825011849/http://blogs.msdn.com:80/b/seema/archive/2008/10/08/xperf-a-cpu-sampler-for-silverlight.aspx)
(1) Startup your sample
(2) xperf -on base
(3) wait for a bit
(4) xperf –d myprofile.etl
(5) when this is done, set your symbol path:
```
set _NT_SYMBOL_PATH= srv*C:\symbols*<http://msdl.microsoft.com/downloads/symbols>
```
(6) xperfview myprofile.etl
(7) Trace -> Load Symbols
* Select the area of the CPU graph that you want to see
* Right-click and select Summary Table
(8) Accept the EULA for using symbols, expand IExplore, expand agcore.dll or whatever is your top module |
55,956 | <p>is there an alternative for <code>mysql_insert_id()</code> php function for PostgreSQL? Most of the frameworks are solving the problem partially by finding the current value of the sequence used in the ID. However, there are times that the primary key is not a serial column....</p>
| [
{
"answer_id": 55959,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 2,
"selected": false,
"text": "<p>Check out the <a href=\"http://www.postgresql.org/docs/current/interactive/sql-insert.html\" rel=\"nofollow noreferrer\">RETURNING optional clause</a> for an INSERT statement. (Link to official PostgreSQL documentation)</p>\n\n<p>But basically, you do:</p>\n\n<pre><code>INSERT INTO table (col1, col2) VALUES (1, 2) RETURNING pkey_col\n</code></pre>\n\n<p>and the INSERT statement itself returns the id (or whatever expression you specify) of the affected row.</p>\n"
},
{
"answer_id": 56055,
"author": "Vertigo",
"author_id": 5468,
"author_profile": "https://Stackoverflow.com/users/5468",
"pm_score": 2,
"selected": false,
"text": "<p>From php.net:</p>\n\n<pre><code>$res=pg_query(\"SELECT nextval('foo_key_seq') as key\");\n$row=pg_fetch_array($res, 0);\n$key=$row['key'];\n// now we have the serial value in $key, let's do the insert\npg_query(\"INSERT INTO foo (key, foo) VALUES ($key, 'blah blah')\");\n</code></pre>\n\n<p>This should always provide unique key, because key retrieved from database will be never retrieved again.</p>\n"
},
{
"answer_id": 56133,
"author": "angch",
"author_id": 5386,
"author_profile": "https://Stackoverflow.com/users/5386",
"pm_score": 6,
"selected": true,
"text": "<p>From the PostgreSQL point of view, in pseudo-code:</p>\n\n<pre><code> * $insert_id = INSERT...RETURNING foo_id;-- only works for PostgreSQL >= 8.2. \n\n * INSERT...; $insert_id = SELECT lastval(); -- works for PostgreSQL >= 8.1\n\n * $insert_id = SELECT nextval('foo_seq'); INSERT INTO table (foo...) values ($insert_id...) for older PostgreSQL (and newer PostgreSQL)\n</code></pre>\n\n<p><code>pg_last_oid()</code> only works where you have OIDs. OIDs have been off by default since PostgreSQL 8.1.</p>\n\n<p>So, depending on which PostgreSQL version you have, you should pick one of the above method. Ideally, of course, use a database abstraction library which abstracts away the above. Otherwise, in low level code, it looks like:</p>\n\n<h1>Method one: INSERT... RETURNING</h1>\n\n<pre><code>// yes, we're not using pg_insert()\n$result = pg_query($db, \"INSERT INTO foo (bar) VALUES (123) RETURNING foo_id\");\n$insert_row = pg_fetch_row($result);\n$insert_id = $insert_row[0];\n</code></pre>\n\n<h1>Method two: INSERT; lastval()</h1>\n\n<pre><code>$result = pg_execute($db, \"INSERT INTO foo (bar) values (123);\");\n$insert_query = pg_query(\"SELECT lastval();\");\n$insert_row = pg_fetch_row($insert_query);\n$insert_id = $insert_row[0];\n</code></pre>\n\n<h1>Method three: nextval(); INSERT</h1>\n\n<pre><code>$insert_query = pg_query($db, \"SELECT nextval('foo_seq');\");\n$insert_row = pg_fetch_row($insert_query);\n$insert_id = $insert_row[0];\n$result = pg_execute($db, \"INSERT INTO foo (foo_id, bar) VALUES ($insert_id, 123);\");\n</code></pre>\n\n<p>The safest bet would be the third method, but it's unwieldy. The cleanest is the first, but you'd need to run a recent PostgreSQL. Most db abstraction libraries don't yet use the first method though.</p>\n"
},
{
"answer_id": 5863620,
"author": "Jenaro",
"author_id": 634605,
"author_profile": "https://Stackoverflow.com/users/634605",
"pm_score": 2,
"selected": false,
"text": "<p>You also can use:</p>\n\n<pre><code>$result = pg_query($db, \"INSERT INTO foo (bar) VALUES (123) RETURNING foo_id\");\n$insert_row = pg_fetch_result($result, 0, 'foo_id');\n</code></pre>\n\n<p>You have to specify in pg_fetch_result the number of the row and the name of the field that you are looking for, this is a more precise way to get the data that you need, but I don't know if this has some penalty in the performance of the query. Remember that this method is for PostgreSQL versions 8.2 and up.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5742/"
] | is there an alternative for `mysql_insert_id()` php function for PostgreSQL? Most of the frameworks are solving the problem partially by finding the current value of the sequence used in the ID. However, there are times that the primary key is not a serial column.... | From the PostgreSQL point of view, in pseudo-code:
```
* $insert_id = INSERT...RETURNING foo_id;-- only works for PostgreSQL >= 8.2.
* INSERT...; $insert_id = SELECT lastval(); -- works for PostgreSQL >= 8.1
* $insert_id = SELECT nextval('foo_seq'); INSERT INTO table (foo...) values ($insert_id...) for older PostgreSQL (and newer PostgreSQL)
```
`pg_last_oid()` only works where you have OIDs. OIDs have been off by default since PostgreSQL 8.1.
So, depending on which PostgreSQL version you have, you should pick one of the above method. Ideally, of course, use a database abstraction library which abstracts away the above. Otherwise, in low level code, it looks like:
Method one: INSERT... RETURNING
===============================
```
// yes, we're not using pg_insert()
$result = pg_query($db, "INSERT INTO foo (bar) VALUES (123) RETURNING foo_id");
$insert_row = pg_fetch_row($result);
$insert_id = $insert_row[0];
```
Method two: INSERT; lastval()
=============================
```
$result = pg_execute($db, "INSERT INTO foo (bar) values (123);");
$insert_query = pg_query("SELECT lastval();");
$insert_row = pg_fetch_row($insert_query);
$insert_id = $insert_row[0];
```
Method three: nextval(); INSERT
===============================
```
$insert_query = pg_query($db, "SELECT nextval('foo_seq');");
$insert_row = pg_fetch_row($insert_query);
$insert_id = $insert_row[0];
$result = pg_execute($db, "INSERT INTO foo (foo_id, bar) VALUES ($insert_id, 123);");
```
The safest bet would be the third method, but it's unwieldy. The cleanest is the first, but you'd need to run a recent PostgreSQL. Most db abstraction libraries don't yet use the first method though. |
55,964 | <p>How can I make a major upgrade to an installation set (MSI) built with <a href="http://en.wikipedia.org/wiki/WiX" rel="noreferrer">WiX</a> install into the same folder as the original installation?</p>
<p>The installation is correctly detected as an upgrade, but the directory selection screen is still shown and with the default value (not necessarily the current installation folder).</p>
<p>Do I have to do manual work like saving the installation folder in a registry key upon first installing and then read this key upon upgrade? If so, is there any example?</p>
<p>Or is there some easier way to achieve this in <a href="http://en.wikipedia.org/wiki/Windows_Installer" rel="noreferrer">MSI</a> or WiX?</p>
<p>As reference, I my current WiX file is below:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2003/01/wi">
<Product Id="a2298d1d-ba60-4c4d-92e3-a77413f54a53"
Name="MyCompany Integration Framework 1.0.0"
Language="1033"
Version="1.0.0"
Manufacturer="MyCompany"
UpgradeCode="9071eacc-9b5a-48e3-bb90-8064d2b2c45d">
<!-- Package information -->
<Package Keywords="Installer"
Id="e85e6190-1cd4-49f5-8924-9da5fcb8aee8"
Description="Installs MyCompany Integration Framework 1.0.0"
Comments="Installs MyCompany Integration Framework 1.0.0"
InstallerVersion="100"
Compressed="yes" />
<Upgrade Id='9071eacc-9b5a-48e3-bb90-8064d2b2c45d'>
<UpgradeVersion Property="PATCHFOUND"
OnlyDetect="no"
Minimum="0.0.1"
IncludeMinimum="yes"
Maximum="1.0.0"
IncludeMaximum="yes"/>
</Upgrade>
<!-- Useless but necessary... -->
<Media Id="1" Cabinet="MyCompany.cab" EmbedCab="yes" />
<!-- Precondition: .NET 2 must be installed -->
<Condition Message='This setup requires the .NET Framework 2 or higher.'>
<![CDATA[MsiNetAssemblySupport >= "2.0.50727"]]>
</Condition>
<Directory Id="TARGETDIR"
Name="SourceDir">
<Directory Id="MyCompany"
Name="MyCompany">
<Directory Id="INSTALLDIR"
Name="Integrat"
LongName="MyCompany Integration Framework">
<Component Id="MyCompanyDllComponent"
Guid="4f362043-03a0-472d-a84f-896522ce7d2b"
DiskId="1">
<File Id="MyCompanyIntegrationDll"
Name="IbIntegr.dll"
src="..\Build\MyCompany.Integration.dll"
Vital="yes"
LongName="MyCompany.Integration.dll" />
<File Id="MyCompanyServiceModelDll"
Name="IbSerMod.dll"
src="..\Build\MyCompany.ServiceModel.dll"
Vital="yes"
LongName="MyCompany.ServiceModel.dll" />
</Component>
<!-- More components -->
</Directory>
</Directory>
</Directory>
<Feature Id="MyCompanyProductFeature"
Title='MyCompany Integration Framework'
Description='The complete package'
Display='expand'
Level="1"
InstallDefault='local'
ConfigurableDirectory="INSTALLDIR">
<ComponentRef Id="MyCompanyDllComponent" />
</Feature>
<!-- Task scheduler application. It has to be used as a property -->
<Property Id="finaltaskexe"
Value="MyCompany.Integration.Host.exe" />
<Property Id="WIXUI_INSTALLDIR"
Value="INSTALLDIR" />
<InstallExecuteSequence>
<!-- command must be executed: MyCompany.Integration.Host.exe /INITIALCONFIG parameters.xml -->
<Custom Action='PropertyAssign'
After='InstallFinalize'>NOT Installed AND NOT PATCHFOUND</Custom>
<Custom Action='LaunchFile'
After='InstallFinalize'>NOT Installed AND NOT PATCHFOUND</Custom>
<RemoveExistingProducts Before='CostInitialize' />
</InstallExecuteSequence>
<!-- execute comand -->
<CustomAction Id='PropertyAssign'
Property='PathProperty'
Value='[INSTALLDIR][finaltaskexe]' />
<CustomAction Id='LaunchFile'
Property='PathProperty'
ExeCommand='/INITIALCONFIG "[INSTALLDIR]parameters.xml"'
Return='asyncNoWait' />
<!-- User interface information -->
<UIRef Id="WixUI_InstallDir" />
<UIRef Id="WixUI_ErrorProgressText" />
</Product>
</Wix>
</code></pre>
| [
{
"answer_id": 56123,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 6,
"selected": true,
"text": "<p>There's an example in the WiX tutorial: <a href=\"https://www.firegiant.com/wix/tutorial/getting-started/where-to-install/\" rel=\"nofollow noreferrer\">https://www.firegiant.com/wix/tutorial/getting-started/where-to-install/</a></p>\n\n<pre><code><Property Id=\"INSTALLDIR\">\n <RegistrySearch Id='AcmeFoobarRegistry' Type='raw'\n Root='HKLM' Key='Software\\Acme\\Foobar 1.0' Name='InstallDir' />\n</Property>\n</code></pre>\n\n<p>Of course, you've got to set the registry key as part of the install too. Stick this inside a component that's part of the original install:</p>\n\n<pre><code><RegistryKey\n Key=\"Software\\Software\\Acme\\Foobar 1.0\"\n Root=\"HKLM\">\n <RegistryValue Id=\"FoobarRegInstallDir\"\n Type=\"string\"\n Name=\"InstallDir\"\n Value=\"[INSTALLDIR]\" />\n</RegistryKey> \n</code></pre>\n"
},
{
"answer_id": 8894372,
"author": "Serge SB",
"author_id": 1153863,
"author_profile": "https://Stackoverflow.com/users/1153863",
"pm_score": 3,
"selected": false,
"text": "<p>'Registry' is deprecated. Now that part of code should look like this:</p>\n\n<pre><code><RegistryKey Id=\"FoobarRegRoot\"\n Action=\"createAndRemoveOnUninstall\"\n Key=\"Software\\Software\\Acme\\Foobar 1.0\"\n Root=\"HKLM\">\n <RegistryValue Id=\"FoobarRegInstallDir\"\n Type=\"string\"\n Name=\"InstallDir\"\n Value=\"[INSTALLDIR]\" />\n</RegistryKey>\n</code></pre>\n"
},
{
"answer_id": 23121035,
"author": "Jamie",
"author_id": 645431,
"author_profile": "https://Stackoverflow.com/users/645431",
"pm_score": 2,
"selected": false,
"text": "<p>You don't really need to separate RegistryKey from RegistryValue in a simple case like this. Also, using HKMU instead of HKLM takes care of it whether you're doing a machine or user install.</p>\n\n<pre><code><RegistryValue\n Root=\"HKMU\"\n Key=\"Software\\[Manufacturer]\\[ProductName]\"\n Name=\"InstallDir\"\n Type=\"string\"\n Value=\"[INSTALLDIR]\"\n KeyPath=\"yes\" />\n</code></pre>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4683/"
] | How can I make a major upgrade to an installation set (MSI) built with [WiX](http://en.wikipedia.org/wiki/WiX) install into the same folder as the original installation?
The installation is correctly detected as an upgrade, but the directory selection screen is still shown and with the default value (not necessarily the current installation folder).
Do I have to do manual work like saving the installation folder in a registry key upon first installing and then read this key upon upgrade? If so, is there any example?
Or is there some easier way to achieve this in [MSI](http://en.wikipedia.org/wiki/Windows_Installer) or WiX?
As reference, I my current WiX file is below:
```
<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2003/01/wi">
<Product Id="a2298d1d-ba60-4c4d-92e3-a77413f54a53"
Name="MyCompany Integration Framework 1.0.0"
Language="1033"
Version="1.0.0"
Manufacturer="MyCompany"
UpgradeCode="9071eacc-9b5a-48e3-bb90-8064d2b2c45d">
<!-- Package information -->
<Package Keywords="Installer"
Id="e85e6190-1cd4-49f5-8924-9da5fcb8aee8"
Description="Installs MyCompany Integration Framework 1.0.0"
Comments="Installs MyCompany Integration Framework 1.0.0"
InstallerVersion="100"
Compressed="yes" />
<Upgrade Id='9071eacc-9b5a-48e3-bb90-8064d2b2c45d'>
<UpgradeVersion Property="PATCHFOUND"
OnlyDetect="no"
Minimum="0.0.1"
IncludeMinimum="yes"
Maximum="1.0.0"
IncludeMaximum="yes"/>
</Upgrade>
<!-- Useless but necessary... -->
<Media Id="1" Cabinet="MyCompany.cab" EmbedCab="yes" />
<!-- Precondition: .NET 2 must be installed -->
<Condition Message='This setup requires the .NET Framework 2 or higher.'>
<![CDATA[MsiNetAssemblySupport >= "2.0.50727"]]>
</Condition>
<Directory Id="TARGETDIR"
Name="SourceDir">
<Directory Id="MyCompany"
Name="MyCompany">
<Directory Id="INSTALLDIR"
Name="Integrat"
LongName="MyCompany Integration Framework">
<Component Id="MyCompanyDllComponent"
Guid="4f362043-03a0-472d-a84f-896522ce7d2b"
DiskId="1">
<File Id="MyCompanyIntegrationDll"
Name="IbIntegr.dll"
src="..\Build\MyCompany.Integration.dll"
Vital="yes"
LongName="MyCompany.Integration.dll" />
<File Id="MyCompanyServiceModelDll"
Name="IbSerMod.dll"
src="..\Build\MyCompany.ServiceModel.dll"
Vital="yes"
LongName="MyCompany.ServiceModel.dll" />
</Component>
<!-- More components -->
</Directory>
</Directory>
</Directory>
<Feature Id="MyCompanyProductFeature"
Title='MyCompany Integration Framework'
Description='The complete package'
Display='expand'
Level="1"
InstallDefault='local'
ConfigurableDirectory="INSTALLDIR">
<ComponentRef Id="MyCompanyDllComponent" />
</Feature>
<!-- Task scheduler application. It has to be used as a property -->
<Property Id="finaltaskexe"
Value="MyCompany.Integration.Host.exe" />
<Property Id="WIXUI_INSTALLDIR"
Value="INSTALLDIR" />
<InstallExecuteSequence>
<!-- command must be executed: MyCompany.Integration.Host.exe /INITIALCONFIG parameters.xml -->
<Custom Action='PropertyAssign'
After='InstallFinalize'>NOT Installed AND NOT PATCHFOUND</Custom>
<Custom Action='LaunchFile'
After='InstallFinalize'>NOT Installed AND NOT PATCHFOUND</Custom>
<RemoveExistingProducts Before='CostInitialize' />
</InstallExecuteSequence>
<!-- execute comand -->
<CustomAction Id='PropertyAssign'
Property='PathProperty'
Value='[INSTALLDIR][finaltaskexe]' />
<CustomAction Id='LaunchFile'
Property='PathProperty'
ExeCommand='/INITIALCONFIG "[INSTALLDIR]parameters.xml"'
Return='asyncNoWait' />
<!-- User interface information -->
<UIRef Id="WixUI_InstallDir" />
<UIRef Id="WixUI_ErrorProgressText" />
</Product>
</Wix>
``` | There's an example in the WiX tutorial: <https://www.firegiant.com/wix/tutorial/getting-started/where-to-install/>
```
<Property Id="INSTALLDIR">
<RegistrySearch Id='AcmeFoobarRegistry' Type='raw'
Root='HKLM' Key='Software\Acme\Foobar 1.0' Name='InstallDir' />
</Property>
```
Of course, you've got to set the registry key as part of the install too. Stick this inside a component that's part of the original install:
```
<RegistryKey
Key="Software\Software\Acme\Foobar 1.0"
Root="HKLM">
<RegistryValue Id="FoobarRegInstallDir"
Type="string"
Name="InstallDir"
Value="[INSTALLDIR]" />
</RegistryKey>
``` |
55,978 | <p>I know how to test an object to see if it is of a type, using the IS keyword e.g.</p>
<pre><code>if (foo is bar)
{
//do something here
}
</code></pre>
<p>but how do you test for it not being "bar"?, I can't seem to find a keyword that works with IS to test for a negative result. </p>
<p>BTW - I have a horrible feeling this is soooo obvious, so apologies in advance...</p>
| [
{
"answer_id": 55980,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": true,
"text": "<pre><code>if (!(foo is bar)) {\n}\n</code></pre>\n"
},
{
"answer_id": 55981,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>There is no specific keyword</p>\n\n<pre><code>if (!(foo is bar)) ...\nif (foo.GetType() != bar.GetType()) .. // foo & bar should be on the same level of type hierarchy\n</code></pre>\n"
},
{
"answer_id": 55991,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use the <a href=\"http://msdn.microsoft.com/en-us/library/cscsdfbt(VS.71).aspx\" rel=\"nofollow noreferrer\">as operator</a>.</p>\n\n<blockquote>\n <p>The as operator is used to perform\n conversions between compatible types.</p>\n</blockquote>\n\n<pre><code>bar aBar = foo as bar; // aBar is null if foo is not bar\n</code></pre>\n"
},
{
"answer_id": 85100,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 1,
"selected": false,
"text": "<p>You should clarify whether you want to test that an object is <em>exactly</em> a certain type or <em>assignable</em> from a certain type. For example:</p>\n\n<pre><code>public class Foo : Bar {}\n</code></pre>\n\n<p>And suppose you have: </p>\n\n<pre><code>Foo foo = new Foo();\n</code></pre>\n\n<p>If you want to know whether foo is not Bar(), then you would do this:</p>\n\n<pre><code>if(!(foo.GetType() == tyepof(Bar))) {...}\n</code></pre>\n\n<p>But if you want to make sure that foo does not derive from Bar, then an easy check is to use the as keyword.</p>\n\n<pre><code>Bar bar = foo as Bar;\nif(bar == null) {/* foo is not a bar */}\n</code></pre>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5175/"
] | I know how to test an object to see if it is of a type, using the IS keyword e.g.
```
if (foo is bar)
{
//do something here
}
```
but how do you test for it not being "bar"?, I can't seem to find a keyword that works with IS to test for a negative result.
BTW - I have a horrible feeling this is soooo obvious, so apologies in advance... | ```
if (!(foo is bar)) {
}
``` |
55,984 | <p>What is the difference between <strong><code>const</code></strong> and <strong><code>readonly</code></strong> in C#? </p>
<p>When would you use one over the other?</p>
| [
{
"answer_id": 55987,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 4,
"selected": false,
"text": "<p>I believe a <code>const</code> value is the same for all objects (and must be initialized with a literal expression), whereas <code>readonly</code> can be different for each instantiation...</p>\n"
},
{
"answer_id": 55988,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://en.csharp-online.net/const,_static_and_readonly\" rel=\"noreferrer\">This explains it</a>. Summary: const must be initialized at declaration time, readonly can be initialized on the constructor (and thus have a different value depending on the constructor used).</p>\n\n<p>EDIT: See Gishu's gotcha above for the subtle difference</p>\n"
},
{
"answer_id": 55993,
"author": "Wheelie",
"author_id": 1131,
"author_profile": "https://Stackoverflow.com/users/1131",
"pm_score": 5,
"selected": false,
"text": "<p>A const is a compile-time constant whereas readonly allows a value to be calculated at run-time and set in the constructor or field initializer. So, a 'const' is always constant but 'readonly' is read-only once it is assigned.</p>\n<p>Eric Lippert of the C# team has <a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-one-kinds-of-immutability\" rel=\"noreferrer\">more information</a> on different types of immutability.</p>\n"
},
{
"answer_id": 56003,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 8,
"selected": false,
"text": "<p>There is a gotcha with consts! If you reference a constant from another assembly, its value will be compiled right into the calling assembly. That way when you update the constant in the referenced assembly it won't change in the calling assembly!</p>\n"
},
{
"answer_id": 56024,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 12,
"selected": true,
"text": "<p>Apart from the apparent difference of</p>\n<ul>\n<li>having to declare the value at the time of a definition for a <code>const</code> VS <code>readonly</code> values can be computed dynamically but need to be assigned before the constructor exits. After that it is frozen.</li>\n<li><code>const</code>'s are implicitly <code>static</code>. You use a <code>ClassName.ConstantName</code> notation to access them.</li>\n</ul>\n<p>There is a subtle difference. Consider a class defined in <code>AssemblyA</code>.</p>\n<pre><code>public class Const_V_Readonly\n{\n public const int I_CONST_VALUE = 2;\n public readonly int I_RO_VALUE;\n public Const_V_Readonly()\n {\n I_RO_VALUE = 3;\n }\n}\n</code></pre>\n<p><code>AssemblyB</code> references <code>AssemblyA</code> and uses these values in code. When this is compiled:</p>\n<ul>\n<li>in the case of the <code>const</code> value, it is like a find-replace. The value 2 is 'baked into' the <code>AssemblyB</code>'s IL. This means that if tomorrow I update <code>I_CONST_VALUE</code> to 20, <em><code>AssemblyB</code> would still have 2 till I recompile it</em>.</li>\n<li>in the case of the <code>readonly</code> value, it is like a <code>ref</code> to a memory location. The value is not baked into <code>AssemblyB</code>'s IL. This means that if the memory location is updated, <code>AssemblyB</code> gets the new value without recompilation. So if <code>I_RO_VALUE</code> is updated to 30, you only need to build <code>AssemblyA</code> and all clients do not need to be recompiled.</li>\n</ul>\n<p>So if you are confident that the value of the constant won't change, use a <code>const</code>.</p>\n<pre><code>public const int CM_IN_A_METER = 100;\n</code></pre>\n<p>But if you have a constant that may change (e.g. w.r.t. precision) or when in doubt, use a <code>readonly</code>.</p>\n<pre><code>public readonly float PI = 3.14;\n</code></pre>\n<p><em>Update: Aku needs to get a mention because he pointed this out first. Also I need to plug where I learned this: <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321245660\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Effective C# - Bill Wagner</a></em></p>\n"
},
{
"answer_id": 56051,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 3,
"selected": false,
"text": "<p>Variables marked const are little more than strongly typed #define macros, at compile time const variable references are replaced with inline literal values. As a consequence only certain built-in primitive value types can be used in this way. Variables marked readonly can be set, in a constructor, at run-time and their read-only-ness is enforced during run-time as well. There is some minor performance cost associated with this but it means you can use readonly with any type (even reference types).</p>\n\n<p>Also, const variables are inherently static, whereas readonly variables can be instance specific if desired.</p>\n"
},
{
"answer_id": 56233,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>Just to add, <code>readonly</code> for reference types only makes the reference read only not the values. For example:</p>\n<pre><code>public class Const_V_Readonly\n{\n public const int I_CONST_VALUE = 2;\n public readonly char[] I_RO_VALUE = new Char[]{'a', 'b', 'c'};\n\n public UpdateReadonly()\n {\n I_RO_VALUE[0] = 'V'; //perfectly legal and will update the value\n I_RO_VALUE = new char[]{'V'}; //will cause compiler error\n }\n}\n</code></pre>\n"
},
{
"answer_id": 62090,
"author": "Anthony",
"author_id": 5599,
"author_profile": "https://Stackoverflow.com/users/5599",
"pm_score": 0,
"selected": false,
"text": "<p>One thing to add to what people have said above. If you have an assembly containing a readonly value (e.g. readonly MaxFooCount = 4; ), you can change the value that calling assemblies see by shipping a new version of that assembly with a different value (e.g. readonly MaxFooCount = 5;)</p>\n\n<p>But with a const, it would be folded into the caller's code when the caller was compiled.</p>\n\n<p>If you've reached this level of C# proficiency, you are ready for Bill Wagner's book, Effective C#: 50 Specific Ways to Improve Your C#\nWhich answers this question in detail, (and 49 other things).</p>\n"
},
{
"answer_id": 67192,
"author": "AlanR",
"author_id": 7311,
"author_profile": "https://Stackoverflow.com/users/7311",
"pm_score": 0,
"selected": false,
"text": "<p>The key difference is that Const is the C equivalent of #DEFINE. The number literally gets substituted a-la precompiler. Readonly is actually treated as a variable. </p>\n\n<p>This distinction is especially relevant when you have Project A depending on a Public constant from Project B. Suppose the public constant changes. Now your choice of const/readonly will impact the behavior on project A:</p>\n\n<p>Const: project A does not catch the new value (unless it is recompiled with the new const, of course) because it was compiled with the constants subtituted in.</p>\n\n<p>ReadOnly: Project A will always ask project B for it's variable value, so it will pick up the new value of the public constant in B.</p>\n\n<p>Honestly, I would recommend you use readonly for nearly everything except truly universal constants ( e.g. Pi, Inches_To_Centimeters). For anything that could possibly change, I say use readonly.</p>\n\n<p>Hope this helps,\nAlan.</p>\n"
},
{
"answer_id": 82893,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 3,
"selected": false,
"text": "<p>They are both constant, but a const is available also at compile time. This means that one aspect of the difference is that you can use const variables as input to attribute constructors, but not readonly variables.</p>\n\n<p>Example:</p>\n\n<pre><code>public static class Text {\n public const string ConstDescription = \"This can be used.\";\n public readonly static string ReadonlyDescription = \"Cannot be used.\";\n}\n\npublic class Foo \n{\n [Description(Text.ConstDescription)]\n public int BarThatBuilds {\n { get; set; }\n }\n\n [Description(Text.ReadOnlyDescription)]\n public int BarThatDoesNotBuild {\n { get; set; }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 83173,
"author": "Mark T",
"author_id": 10722,
"author_profile": "https://Stackoverflow.com/users/10722",
"pm_score": 2,
"selected": false,
"text": "<p>Another <I>gotcha</I>.<P>\nSince const really only works with basic data types, if you want to work with a class, you may feel \"forced\" to use ReadOnly. However, beware of the trap! ReadOnly means that you can not replace the object with another object (you can't make it refer to another object). But any process that has a reference to the object is free to modify the values <B><I>inside</I></B> the object!<P>\nSo don't be confused into thinking that ReadOnly implies a user can't change things. There is no simple syntax in C# to prevent an instantiation of a class from having its internal values changed (as far as I know).</p>\n"
},
{
"answer_id": 164500,
"author": "Scott Lawrence",
"author_id": 3475,
"author_profile": "https://Stackoverflow.com/users/3475",
"pm_score": 3,
"selected": false,
"text": "<p>One of the team members in our office provided the following guidance on when to use const, static, and readonly:</p>\n\n<ul>\n<li>Use <strong>const</strong> when you have a variable of a type you can know at runtime (string literal, int, double, enums,...) that you want all instances or consumers of a class to have access to where the value should not change.</li>\n<li>Use <strong>static</strong> when you have data that you want all instances or consumers of a class to have access to where the value can change.</li>\n<li>Use <strong>static readonly</strong> when you have a variable of a type that you cannot know at runtime (objects) that you want all instances or consumers of a class to have access to where the value should not change.</li>\n<li>Use <strong>readonly</strong> when you have an instance level variable you will know at the time of object creation that should not change.</li>\n</ul>\n\n<p>One final note: a const field is static, but the inverse is not true.</p>\n"
},
{
"answer_id": 217058,
"author": "Mike Two",
"author_id": 23659,
"author_profile": "https://Stackoverflow.com/users/23659",
"pm_score": 5,
"selected": false,
"text": "<p>There is a small gotcha with readonly. A readonly field can be set multiple times within the constructor(s). Even if the value is set in two different chained constructors it is still allowed.</p>\n<pre><code>public class Sample {\n private readonly string ro;\n\n public Sample() {\n ro = "set";\n }\n\n public Sample(string value) : this() {\n ro = value; // this works even though it was set in the no-arg ctor\n }\n}\n</code></pre>\n"
},
{
"answer_id": 333728,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "<h2>Constants</h2>\n\n<ul>\n<li>Constants are static by default</li>\n<li>They must have a value at compilation-time (you can have e.g. 3.14 * 2, but cannot call methods)</li>\n<li>Could be declared within functions</li>\n<li>Are copied into every assembly that uses them (every assembly gets a local copy of values)</li>\n<li>Can be used in attributes</li>\n</ul>\n\n<h2>Readonly instance fields</h2>\n\n<ul>\n<li>Must have set value, by the time constructor exits</li>\n<li>Are evaluated when instance is created</li>\n</ul>\n\n<h2>Static readonly fields</h2>\n\n<ul>\n<li>Are evaluated when code execution hits class reference (when new instance is created or a static method is executed)</li>\n<li>Must have an evaluated value by the time the static constructor is done</li>\n<li>It's not recommended to put ThreadStaticAttribute on these (static constructors will be executed in one thread only and will set the value for its thread; all other threads will have this value uninitialized)</li>\n</ul>\n"
},
{
"answer_id": 498685,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.anotherchris.net/csharp/const-vs-readonly-in-csharp/\" rel=\"noreferrer\">Here's another link</a> demonstrating how const isn't version safe, or relevant for reference types.</p>\n\n<p><strong>Summary</strong>:</p>\n\n<ul>\n<li>The value of your const property is set at compile time and can't change at runtime</li>\n<li>Const can't be marked as static - the keyword denotes they are static, unlike readonly fields which can.</li>\n<li>Const can't be anything except value (primitive) types</li>\n<li>The readonly keyword marks the field as unchangeable. However the property can be changed inside the constructor of the class</li>\n<li>The readonly only keyword can also be combined with static to make it act in the same way as a const (atleast on the surface). There is a marked difference when you look at the IL between the two</li>\n<li>const fields are marked as \"literal\" in IL while readonly is \"initonly\"</li>\n</ul>\n"
},
{
"answer_id": 1393687,
"author": "Brett Ryan",
"author_id": 140037,
"author_profile": "https://Stackoverflow.com/users/140037",
"pm_score": 2,
"selected": false,
"text": "<p>A constant will be compiled into the consumer as a literal value while the static string will serve as a reference to the value defined.</p>\n\n<p>As an exercise, try creating an external library and consume it in a console application, then alter the values in the library and recompile it (without recompiling the consumer program), drop the DLL into the directory and run the EXE manually, you should find that the constant string does not change.</p>\n"
},
{
"answer_id": 1393708,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 1,
"selected": false,
"text": "<p>Principally; you can assign a value to a static readonly field to a non-constant value at runtime, whereas a const has to be assigned a constant value.</p>\n"
},
{
"answer_id": 1557937,
"author": "Greg",
"author_id": 12971,
"author_profile": "https://Stackoverflow.com/users/12971",
"pm_score": 4,
"selected": false,
"text": "<p>Yet another gotcha: readonly values can be changed by \"devious\" code via reflection.</p>\n\n<pre><code>var fi = this.GetType()\n .BaseType\n .GetField(\"_someField\", \n BindingFlags.Instance | BindingFlags.NonPublic);\nfi.SetValue(this, 1);\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/1401458/can-i-change-a-private-readonly-inherited-field-in-c-using-reflection/1401499#1401499\">Can I change a private readonly inherited field in C# using reflection?</a></p>\n"
},
{
"answer_id": 5057030,
"author": "Greg",
"author_id": 431780,
"author_profile": "https://Stackoverflow.com/users/431780",
"pm_score": 2,
"selected": false,
"text": "<p>A <code>const</code> has to be <strong>hard-coded</strong>, where as <code>readonly</code> can be <strong>set in the constructor</strong> of the class.</p>\n"
},
{
"answer_id": 6082004,
"author": "Deepthi",
"author_id": 763996,
"author_profile": "https://Stackoverflow.com/users/763996",
"pm_score": 6,
"selected": false,
"text": "<p><code>const</code>: Can't be changed anywhere.</p>\n\n<p><code>readonly</code>: This value can only be changed in the constructor. Can't be changed in normal functions.</p>\n"
},
{
"answer_id": 12458557,
"author": "Sujit",
"author_id": 792713,
"author_profile": "https://Stackoverflow.com/users/792713",
"pm_score": 5,
"selected": false,
"text": "<p>A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the <code>const</code> keyword and must be initialized as they are declared.</p>\n\n<pre><code>public class MyClass\n{\n public const double PI1 = 3.14159;\n}\n</code></pre>\n\n<p>A <code>readonly</code> member is like a constant in that it represents an unchanging value. The difference is that a <code>readonly</code> member can be initialized at runtime, in a constructor, as well being able to be initialized as they are declared.</p>\n\n<pre><code>public class MyClass1\n{\n public readonly double PI2 = 3.14159;\n\n //or\n\n public readonly double PI3;\n\n public MyClass2()\n {\n PI3 = 3.14159;\n }\n}\n</code></pre>\n\n<p><strong>const</strong></p>\n\n<ul>\n<li>They can not be declared as <code>static</code> (they are implicitly static)</li>\n<li>The value of constant is evaluated at compile time</li>\n<li>constants are initialized at declaration only</li>\n</ul>\n\n<p><strong>readonly</strong></p>\n\n<ul>\n<li>They can be either instance-level or static</li>\n<li>The value is evaluated at run time</li>\n<li>readonly can be initialized in declaration or by code in the constructor</li>\n</ul>\n"
},
{
"answer_id": 19064906,
"author": "Ramesh Rajendran",
"author_id": 2218635,
"author_profile": "https://Stackoverflow.com/users/2218635",
"pm_score": 2,
"selected": false,
"text": "<p>Const and readonly are similar, but they are not exactly the same. A const field is a compile-time constant, meaning that that value can be computed at compile-time. A readonly field enables additional scenarios in which some code must be run during construction of the type. After construction, a readonly field cannot be changed.</p>\n\n<p>For instance, const members can be used to define members like:</p>\n\n<pre><code>struct Test\n{\n public const double Pi = 3.14;\n public const int Zero = 0;\n}\n</code></pre>\n\n<p>since values like 3.14 and 0 are compile-time constants. However, consider the case where you define a type and want to provide some pre-fab instances of it. E.g., you might want to define a Color class and provide \"constants\" for common colors like Black, White, etc. It isn't possible to do this with const members, as the right hand sides are not compile-time constants. One could do this with regular static members:</p>\n\n<pre><code>public class Color\n{\n public static Color Black = new Color(0, 0, 0);\n public static Color White = new Color(255, 255, 255);\n public static Color Red = new Color(255, 0, 0);\n public static Color Green = new Color(0, 255, 0);\n public static Color Blue = new Color(0, 0, 255);\n private byte red, green, blue;\n\n public Color(byte r, byte g, byte b) {\n red = r;\n green = g;\n blue = b;\n }\n}\n</code></pre>\n\n<p>but then there is nothing to keep a client of Color from mucking with it, perhaps by swapping the Black and White values. Needless to say, this would cause consternation for other clients of the Color class. The \"readonly\" feature addresses this scenario. By simply introducing the readonly keyword in the declarations, we preserve the flexible initialization while preventing client code from mucking around.</p>\n\n<pre><code>public class Color\n{\n public static readonly Color Black = new Color(0, 0, 0);\n public static readonly Color White = new Color(255, 255, 255);\n public static readonly Color Red = new Color(255, 0, 0);\n public static readonly Color Green = new Color(0, 255, 0);\n public static readonly Color Blue = new Color(0, 0, 255);\n private byte red, green, blue;\n\n public Color(byte r, byte g, byte b) {\n red = r;\n green = g;\n blue = b;\n }\n}\n</code></pre>\n\n<p>It is interesting to note that const members are always static, whereas a readonly member can be either static or not, just like a regular field.</p>\n\n<p>It is possible to use a single keyword for these two purposes, but this leads to either versioning problems or performance problems. Assume for a moment that we used a single keyword for this (const) and a developer wrote:</p>\n\n<pre><code>public class A\n{\n public static const C = 0;\n}\n</code></pre>\n\n<p>and a different developer wrote code that relied on A:</p>\n\n<pre><code>public class B\n{\n static void Main() {\n Console.WriteLine(A.C);\n }\n}\n</code></pre>\n\n<p>Now, can the code that is generated rely on the fact that A.C is a compile-time constant? I.e., can the use of A.C simply be replaced by the value 0? If you say \"yes\" to this, then that means that the developer of A cannot change the way that A.C is initialized -- this ties the hands of the developer of A without permission. If you say \"no\" to this question then an important optimization is missed. Perhaps the author of A is positive that A.C will always be zero. The use of both const and readonly allows the developer of A to specify the intent. This makes for better versioning behavior and also better performance.</p>\n"
},
{
"answer_id": 21326956,
"author": "donstack",
"author_id": 1750877,
"author_profile": "https://Stackoverflow.com/users/1750877",
"pm_score": 2,
"selected": false,
"text": "<p>ReadOnly :The value will be initialized only once from the constructor of the class.<br>\nconst: can be initialized in any function but only once</p>\n"
},
{
"answer_id": 22882273,
"author": "Yonatan Nir",
"author_id": 1164004,
"author_profile": "https://Stackoverflow.com/users/1164004",
"pm_score": 2,
"selected": false,
"text": "<p>The difference is that the value of a static readonly field is set at run time, so it can have a different value for different executions of the program. However, the value of a const field is set to a compile time constant. </p>\n\n<p>Remember:\nFor reference types, in both cases (static and instance), the readonly modifier only prevents you from assigning a new reference to the field. It specifically does not make immutable the object pointed to by the reference.</p>\n\n<p>For details, please refer to C# Frequently Asked Questions on this topic:\n<a href=\"http://blogs.msdn.com/csharpfaq/archive/2004/12/03/274791.aspx\" rel=\"nofollow\">http://blogs.msdn.com/csharpfaq/archive/2004/12/03/274791.aspx</a></p>\n"
},
{
"answer_id": 27484700,
"author": "Chirag",
"author_id": 2004144,
"author_profile": "https://Stackoverflow.com/users/2004144",
"pm_score": 3,
"selected": false,
"text": "<p>There is notable difference between const and readonly fields in C#.Net</p>\n\n<p>const is by default static and needs to be initialized with constant value, which can not be modified later on. Change of value is not allowed in constructors, too. It can not be used with all datatypes. For ex- DateTime. It can not be used with DateTime datatype.</p>\n\n<pre><code>public const DateTime dt = DateTime.Today; //throws compilation error\npublic const string Name = string.Empty; //throws compilation error\npublic readonly string Name = string.Empty; //No error, legal\n</code></pre>\n\n<p>readonly can be declared as static, but not necessary. No need to initialize at the time of declaration. Its value can be assigned or changed using constructor. So, it gives advantage when used as instance class member. Two different instantiation may have different value of readonly field. For ex -</p>\n\n<pre><code>class A\n{\n public readonly int Id;\n\n public A(int i)\n {\n Id = i;\n }\n}\n</code></pre>\n\n<p>Then readonly field can be initialised with instant specific values, as follows:</p>\n\n<pre><code>A objOne = new A(5);\nA objTwo = new A(10);\n</code></pre>\n\n<p>Here, instance objOne will have value of readonly field as 5 and objTwo has 10. Which is not possible using const.</p>\n"
},
{
"answer_id": 34750395,
"author": "Yeasin Abedin",
"author_id": 2672014,
"author_profile": "https://Stackoverflow.com/users/2672014",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Read Only</strong> :\nValue can be changed through Ctor at runtime. But not through member Function</p>\n<p><strong>Constant</strong> :\nBy default static. Value cannot be changed from anywhere ( Ctor, Function, runtime etc no-where)</p>\n"
},
{
"answer_id": 52232734,
"author": "Muhammad VP",
"author_id": 2779217,
"author_profile": "https://Stackoverflow.com/users/2779217",
"pm_score": 3,
"selected": false,
"text": "<h2>CONST</h2>\n\n<ol>\n<li>const keyword can be applied to fields or local variables</li>\n<li>We must assign const field at time of declaration </li>\n<li>No Memory Allocated Because const value is embedded in IL code itself after compilation.\nIt is like find all occurrences of const variable and replace by its value.\nSo the IL code after compilation will have hard-coded values in place of const variables</li>\n<li>Const in C# are by default static. </li>\n<li>The value is constant for all objects</li>\n<li>There is dll versioning issue - This means that whenever we change a public const variable or property , (In fact, it is not supposed to be changed theoretically), any other dll or assembly which uses this variable has to be re-built </li>\n<li>Only C# built-in types can be declared as constant</li>\n<li>Const field can not be passed as ref or out parameter</li>\n</ol>\n\n<h2>ReadOnly</h2>\n\n<ol>\n<li>readonly keyword applies only to fields not local variables</li>\n<li>We can assign readonly field at the time of declaration or in constructor,not in any other methods.</li>\n<li>dynamic memory allocated for readonly fields and we can get the value at run time.</li>\n<li>Readonly belongs to the object created so accessed through only instance of class. To make it class member we need to add static keyword before readonly.</li>\n<li>The value may be different depending upon constructor used (as it belongs to object of the class)</li>\n<li>If you declare a non-primitive types (reference type) as readonly only reference is immutable not the object it contains.</li>\n<li>Since the value is obtained at run time, there is no dll versioning problem with readonly fields/ properties.</li>\n<li>We can pass readonly field as ref or out parameters in the constructor context.</li>\n</ol>\n"
},
{
"answer_id": 55910384,
"author": "Bigeyes",
"author_id": 6476538,
"author_profile": "https://Stackoverflow.com/users/6476538",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Const</strong>: Absolute constant value during the application life time.</p>\n\n<p><strong>Readonly</strong>: It can be changed in running time. </p>\n"
},
{
"answer_id": 56450673,
"author": "Ryan Efendy",
"author_id": 5265992,
"author_profile": "https://Stackoverflow.com/users/5265992",
"pm_score": 3,
"selected": false,
"text": "<ul>\n<li><p>when to use <code>const</code> or <code>readonly</code></p>\n\n<ul>\n<li><p><code>const</code></p>\n\n<ul>\n<li><strong>compile-time</strong> constant: <strong>absolute</strong> constant, value is set during declaration, is in the IL code itself</li>\n</ul></li>\n<li><p><code>readonly</code></p>\n\n<ul>\n<li><strong>run-time</strong> constant: can be set in the constructor/init via config file i.e. <code>App.config</code>, but once it initializes it can't be changed</li>\n</ul></li>\n</ul></li>\n</ul>\n"
},
{
"answer_id": 67244864,
"author": "Moni",
"author_id": 12546097,
"author_profile": "https://Stackoverflow.com/users/12546097",
"pm_score": 0,
"selected": false,
"text": "<p>The value of readonly field can be changed. However, The value of the const field can not be changed.</p>\n<p>In readonly fields, we can assign values at the time of declaration or in the contructor of that class.Incase of constant we can only assign values at the time of declaration.</p>\n<p>Readonly can be used with Static modifiers but constant cannot be used with static.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/55984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | What is the difference between **`const`** and **`readonly`** in C#?
When would you use one over the other? | Apart from the apparent difference of
* having to declare the value at the time of a definition for a `const` VS `readonly` values can be computed dynamically but need to be assigned before the constructor exits. After that it is frozen.
* `const`'s are implicitly `static`. You use a `ClassName.ConstantName` notation to access them.
There is a subtle difference. Consider a class defined in `AssemblyA`.
```
public class Const_V_Readonly
{
public const int I_CONST_VALUE = 2;
public readonly int I_RO_VALUE;
public Const_V_Readonly()
{
I_RO_VALUE = 3;
}
}
```
`AssemblyB` references `AssemblyA` and uses these values in code. When this is compiled:
* in the case of the `const` value, it is like a find-replace. The value 2 is 'baked into' the `AssemblyB`'s IL. This means that if tomorrow I update `I_CONST_VALUE` to 20, *`AssemblyB` would still have 2 till I recompile it*.
* in the case of the `readonly` value, it is like a `ref` to a memory location. The value is not baked into `AssemblyB`'s IL. This means that if the memory location is updated, `AssemblyB` gets the new value without recompilation. So if `I_RO_VALUE` is updated to 30, you only need to build `AssemblyA` and all clients do not need to be recompiled.
So if you are confident that the value of the constant won't change, use a `const`.
```
public const int CM_IN_A_METER = 100;
```
But if you have a constant that may change (e.g. w.r.t. precision) or when in doubt, use a `readonly`.
```
public readonly float PI = 3.14;
```
*Update: Aku needs to get a mention because he pointed this out first. Also I need to plug where I learned this: [Effective C# - Bill Wagner](https://rads.stackoverflow.com/amzn/click/com/0321245660)* |
56,011 | <p>According to the documentation, they're pretty much interchangeable. Is there a stylistic reason to use one over the other?</p>
| [
{
"answer_id": 56025,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "<p>Your team's taste or your project's coding guidelines.</p>\n\n<p>If you are in a multilanguage environment, you might wish to encourage the use of the same type of quotes for strings that the other language uses, for instance. Else, I personally like best the look of '</p>\n"
},
{
"answer_id": 56029,
"author": "Mario F",
"author_id": 3785,
"author_profile": "https://Stackoverflow.com/users/3785",
"pm_score": 0,
"selected": false,
"text": "<p>None as far as I know. Although if you look at some code, \" \" is commonly used for strings of text (I guess ' is more common inside text than \"), and ' ' appears in hashkeys and things like that.</p>\n"
},
{
"answer_id": 56041,
"author": "Tony Meyer",
"author_id": 4966,
"author_profile": "https://Stackoverflow.com/users/4966",
"pm_score": 5,
"selected": false,
"text": "<p>If the string you have contains one, then you should use the other. For example, <code>\"You're able to do this\"</code>, or <code>'He said \"Hi!\"'</code>. Other than that, you should simply be as consistent as you can (within a module, within a package, within a project, within an organisation).</p>\n\n<p>If your code is going to be read by people who work with C/C++ (or if you switch between those languages and Python), then using <code>''</code> for single-character strings, and <code>\"\"</code> for longer strings might help ease the transition. (Likewise for following other languages where they are not interchangeable).</p>\n\n<p>The Python code I've seen in the wild tends to favour <code>\"</code> over <code>'</code>, but only slightly. The one exception is that <code>\"\"\"these\"\"\"</code> are much more common than <code>'''these'''</code>, from what I have seen.</p>\n"
},
{
"answer_id": 56047,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 2,
"selected": false,
"text": "<p>I use double quotes in general, but not for any specific reason - Probably just out of habit from Java.</p>\n\n<p>I guess you're also more likely to want apostrophes in an inline literal string than you are to want double quotes.</p>\n"
},
{
"answer_id": 56073,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 7,
"selected": false,
"text": "<p>I used to prefer <code>'</code>, especially for <code>'''docstrings'''</code>, as I find <code>\"\"\"this creates some fluff\"\"\"</code>. Also, <code>'</code> can be typed without the <kbd>Shift</kbd> key on my Swiss German keyboard.</p>\n\n<p>I have since changed to using triple quotes for <code>\"\"\"docstrings\"\"\"</code>, to conform to <a href=\"http://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257</a>.</p>\n"
},
{
"answer_id": 56190,
"author": "Will Harris",
"author_id": 4702,
"author_profile": "https://Stackoverflow.com/users/4702",
"pm_score": 10,
"selected": true,
"text": "<p>I like to use double quotes around strings that are used for interpolation or that are natural language messages, and single quotes for small symbol-like strings, but will break the rules if the strings contain quotes, or if I forget. I use triple double quotes for docstrings and raw string literals for regular expressions even if they aren't needed.</p>\n\n<p>For example:</p>\n\n<pre><code>LIGHT_MESSAGES = {\n 'English': \"There are %(number_of_lights)s lights.\",\n 'Pirate': \"Arr! Thar be %(number_of_lights)s lights.\"\n}\n\ndef lights_message(language, number_of_lights):\n \"\"\"Return a language-appropriate string reporting the light count.\"\"\"\n return LIGHT_MESSAGES[language] % locals()\n\ndef is_pirate(message):\n \"\"\"Return True if the given message sounds piratical.\"\"\"\n return re.search(r\"(?i)(arr|avast|yohoho)!\", message) is not None\n</code></pre>\n"
},
{
"answer_id": 56210,
"author": "Garth Kidd",
"author_id": 5700,
"author_profile": "https://Stackoverflow.com/users/5700",
"pm_score": 5,
"selected": false,
"text": "<p>I'm with Will: </p>\n\n<ul>\n<li>Double quotes for text</li>\n<li>Single quotes for anything that behaves like an identifier</li>\n<li>Double quoted raw string literals for regexps</li>\n<li>Tripled double quotes for docstrings</li>\n</ul>\n\n<p>I'll stick with that even if it means a lot of escaping. </p>\n\n<p>I get the most value out of single quoted identifiers standing out because of the quotes. The rest of the practices are there just to give those single quoted identifiers some standing room. </p>\n"
},
{
"answer_id": 104842,
"author": "Mike",
"author_id": 19215,
"author_profile": "https://Stackoverflow.com/users/19215",
"pm_score": 2,
"selected": false,
"text": "<p>It's probably a stylistic preference more than anything. I just checked PEP 8 and didn't see any mention of single versus double quotes.</p>\n\n<p>I prefer single quotes because its only one keystroke instead of two. That is, I don't have to mash the shift key to make single quote.</p>\n"
},
{
"answer_id": 144163,
"author": "conny",
"author_id": 23023,
"author_profile": "https://Stackoverflow.com/users/23023",
"pm_score": 7,
"selected": false,
"text": "<p>Quoting the official docs at <a href=\"https://docs.python.org/2.0/ref/strings.html\" rel=\"noreferrer\">https://docs.python.org/2.0/ref/strings.html</a>:</p>\n\n<blockquote>\n <p>In plain English: String literals can be enclosed in matching single quotes (') or double quotes (\").</p>\n</blockquote>\n\n<p>So there is no difference. Instead, people will tell you to choose whichever style that matches the context, <em>and to be consistent</em>. And I would agree - adding that it is pointless to try to come up with \"conventions\" for this sort of thing because you'll only end up confusing any newcomers.</p>\n"
},
{
"answer_id": 145149,
"author": "schwa",
"author_id": 23113,
"author_profile": "https://Stackoverflow.com/users/23113",
"pm_score": 2,
"selected": false,
"text": "<p>Personally I stick with one or the other. It doesn't matter. And providing your own meaning to either quote is just to confuse other people when you collaborate.</p>\n"
},
{
"answer_id": 629106,
"author": "Andrew Dalke",
"author_id": 64618,
"author_profile": "https://Stackoverflow.com/users/64618",
"pm_score": 1,
"selected": false,
"text": "<p>I chose to use double quotes because they are easier to see.</p>\n"
},
{
"answer_id": 1167795,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I just use whatever strikes my fancy at the time; it's convenient to be able to switch between the two at a whim!</p>\n\n<p>Of course, when quoting quote characetrs, switching between the two might not be so whimsical after all...</p>\n"
},
{
"answer_id": 1209191,
"author": "jblocksom",
"author_id": 20626,
"author_profile": "https://Stackoverflow.com/users/20626",
"pm_score": 4,
"selected": false,
"text": "<p>Triple quoted comments are an interesting subtopic of this question. <a href=\"http://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">PEP 257 specifies triple quotes for doc strings</a>. I did a quick check using Google Code Search and found that <a href=\"http://www.google.com/codesearch?hl=en&lr=&q=lang%3Apython+%22%22%22\" rel=\"noreferrer\">triple double quotes in Python</a> are about 10x as popular as <a href=\"http://www.google.com/codesearch?hl=en&lr=&q=lang%3Apython+%27%27%27\" rel=\"noreferrer\">triple single quotes</a> -- 1.3M vs 131K occurrences in the code Google indexes. So in the multi line case your code is probably going to be more familiar to people if it uses triple double quotes.</p>\n"
},
{
"answer_id": 2091077,
"author": "kn3l",
"author_id": 128618,
"author_profile": "https://Stackoverflow.com/users/128618",
"pm_score": -1,
"selected": false,
"text": "<p><code>'</code> = <code>\"</code></p>\n\n<p><code>/</code> = <code>\\</code> = <code>\\\\</code></p>\n\n<p>example : </p>\n\n<pre><code>f = open('c:\\word.txt', 'r')\nf = open(\"c:\\word.txt\", \"r\")\nf = open(\"c:/word.txt\", \"r\")\nf = open(\"c:\\\\\\word.txt\", \"r\")\n</code></pre>\n\n<p>Results are the same</p>\n\n<p>=>> no, they're not the same.\nA single backslash will escape characters. You just happen to luck out in that example because <code>\\k</code> and <code>\\w</code> aren't valid escapes like <code>\\t</code> or <code>\\n</code> or <code>\\\\</code> or <code>\\\"</code></p>\n\n<p>If you want to use single backslashes (and have them interpreted as such), then you need to use a \"raw\" string. You can do this by putting an '<code>r</code>' in front of the string</p>\n\n<pre><code>im_raw = r'c:\\temp.txt'\nnon_raw = 'c:\\\\temp.txt'\nanother_way = 'c:/temp.txt'\n</code></pre>\n\n<p>As far as paths in Windows are concerned, forward slashes are interpreted the same way. Clearly the string itself is different though. I wouldn't guarantee that they're handled this way on an external device though.</p>\n"
},
{
"answer_id": 3179568,
"author": "Peterino",
"author_id": 202834,
"author_profile": "https://Stackoverflow.com/users/202834",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>In Perl you want to use single quotes when you have a string which doesn't need to interpolate variables or escaped characters like \\n, \\t, \\r, etc.</p>\n</blockquote>\n\n<p>PHP makes the same distinction as Perl: content in single quotes will not be interpreted (not even \\n will be converted), as opposed to double quotes which can contain variables to have their value printed out.</p>\n\n<p>Python does not, I'm afraid. Technically seen, there is no $ token (or the like) to separate a name/text from a variable in Python. Both features make Python more readable, less confusing, after all. Single and double quotes can be used interchangeably in Python.</p>\n"
},
{
"answer_id": 3179675,
"author": "Philipp",
"author_id": 178761,
"author_profile": "https://Stackoverflow.com/users/178761",
"pm_score": -1,
"selected": false,
"text": "<p>I use double quotes because I have been doing so for years in most languages (C++, Java, VB…) except Bash, because I also use double quotes in normal text and because I'm using a (modified) non-English keyboard where both characters require the shift key.</p>\n"
},
{
"answer_id": 4776742,
"author": "Michael",
"author_id": 584811,
"author_profile": "https://Stackoverflow.com/users/584811",
"pm_score": 3,
"selected": false,
"text": "<p>Python uses quotes something like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>mystringliteral1=\"this is a string with 'quotes'\"\nmystringliteral2='this is a string with \"quotes\"'\nmystringliteral3=\"\"\"this is a string with \"quotes\" and more 'quotes'\"\"\"\nmystringliteral4='''this is a string with 'quotes' and more \"quotes\"'''\nmystringliteral5='this is a string with \\\"quotes\\\"'\nmystringliteral6='this is a string with \\042quotes\\042'\nmystringliteral6='this is a string with \\047quotes\\047'\n\nprint mystringliteral1\nprint mystringliteral2\nprint mystringliteral3\nprint mystringliteral4\nprint mystringliteral5\nprint mystringliteral6\n</code></pre>\n\n<p>Which gives the following output:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>this is a string with 'quotes'\nthis is a string with \"quotes\"\nthis is a string with \"quotes\" and more 'quotes'\nthis is a string with 'quotes' and more \"quotes\"\nthis is a string with \"quotes\"\nthis is a string with 'quotes'\n</code></pre>\n"
},
{
"answer_id": 7514799,
"author": "yurisich",
"author_id": 881224,
"author_profile": "https://Stackoverflow.com/users/881224",
"pm_score": 4,
"selected": false,
"text": "<pre><code>\"If you're going to use apostrophes, \n ^\n\nyou'll definitely want to use double quotes\".\n ^\n</code></pre>\n\n<p>For that simple reason, I always use double quotes on the outside. <em>Always</em></p>\n\n<p>Speaking of fluff, what good is streamlining your string literals with ' if you're going to have to use escape characters to represent apostrophes? Does it offend coders to read novels? I can't imagine how painful high school English class was for you!</p>\n"
},
{
"answer_id": 16048319,
"author": "Asclepius",
"author_id": 832230,
"author_profile": "https://Stackoverflow.com/users/832230",
"pm_score": 0,
"selected": false,
"text": "<p>I aim to minimize both pixels and surprise. I typically prefer <code>'</code> in order to minimize pixels, but <code>\"</code> instead if the string has an apostrophe, again to minimize pixels. For a docstring, however, I prefer <code>\"\"\"</code> over <code>'''</code> because the latter is non-standard, uncommon, and therefore surprising. If now I have a bunch of strings where I used <code>\"</code> per the above logic, but also one that can get away with a <code>'</code>, I may still use <code>\"</code> in it to preserve consistency, only to minimize surprise.</p>\n\n<p>Perhaps it helps to think of the pixel minimization philosophy in the following way. Would you rather that English characters looked like <code>A B C</code> or <code>AA BB CC</code>? The latter choice wastes 50% of the non-empty pixels.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | According to the documentation, they're pretty much interchangeable. Is there a stylistic reason to use one over the other? | I like to use double quotes around strings that are used for interpolation or that are natural language messages, and single quotes for small symbol-like strings, but will break the rules if the strings contain quotes, or if I forget. I use triple double quotes for docstrings and raw string literals for regular expressions even if they aren't needed.
For example:
```
LIGHT_MESSAGES = {
'English': "There are %(number_of_lights)s lights.",
'Pirate': "Arr! Thar be %(number_of_lights)s lights."
}
def lights_message(language, number_of_lights):
"""Return a language-appropriate string reporting the light count."""
return LIGHT_MESSAGES[language] % locals()
def is_pirate(message):
"""Return True if the given message sounds piratical."""
return re.search(r"(?i)(arr|avast|yohoho)!", message) is not None
``` |
56,037 | <p>I am working with fixtures on rails and I want one of the fixture fields to be blank.</p>
<p>Example:</p>
<pre><code>two:
name: test
path: - I want this blank but not to act as a group heading.
test: 4
</code></pre>
<p>But, I do not know how to leave <code>path:</code> blank without it acting as a group title. Does anybody know how to do that?</p>
| [
{
"answer_id": 56060,
"author": "Paul Wicks",
"author_id": 85,
"author_profile": "https://Stackoverflow.com/users/85",
"pm_score": 1,
"selected": false,
"text": "<p>Google <a href=\"http://groups.google.com/group/ruby-talk-google/browse_thread/thread/f8b1635528665a85\" rel=\"nofollow noreferrer\">says</a> the following should work:</p>\n\n<pre><code>path: \\\"\\\"\n</code></pre>\n"
},
{
"answer_id": 56519,
"author": "Tom",
"author_id": 4753,
"author_profile": "https://Stackoverflow.com/users/4753",
"pm_score": 4,
"selected": true,
"text": "<p>YAML files are based on indentation. Once you actually have correct indentation it will read everything at the same level as siblings.</p>\n\n<pre><code>\ntwo:\n name: test\n path: \n test: 4\n</code></pre>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] | I am working with fixtures on rails and I want one of the fixture fields to be blank.
Example:
```
two:
name: test
path: - I want this blank but not to act as a group heading.
test: 4
```
But, I do not know how to leave `path:` blank without it acting as a group title. Does anybody know how to do that? | YAML files are based on indentation. Once you actually have correct indentation it will read everything at the same level as siblings.
```
two:
name: test
path:
test: 4
``` |
56,045 | <p>I'm having some internationalisation woes:</p>
<p>My UTF-8 string fields are being rendered in the browser as ???? after being returned from the database.</p>
<p>After retrieval from the database using Hibernate, the String fields are presented correctly on inspection using the eclipse debugger.</p>
<p>However Struts2/Tiles is rendering these strings as ???? in the HTML sent to the browser.</p>
<p>The charset directive is present in the HTML header:
</p>
<p>Perhaps I need to add something to my struts2 or tiles configurations?</p>
| [
{
"answer_id": 56358,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 0,
"selected": false,
"text": "<p>Try setting the lang attribute on the <html/> element.</p>\n\n<p>HTML example:</p>\n\n<pre>\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html lang=\"ja\"> \n</pre>\n\n<p>XHTML example:</p>\n\n<pre>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"ja\"> \n</pre>\n"
},
{
"answer_id": 56626,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 1,
"selected": true,
"text": "<p>You could try something like this.</p>\n\n<p>It's taken from sun's page on <a href=\"http://java.sun.com/j2ee/1.4/docs/tutorial/doc/WebI18N5.html\" rel=\"nofollow noreferrer\">Character Sets and Encodings</a>.\nI think this has to be the very first line in your jsp.</p>\n\n<pre><code><%@ page contentType=\"text/html; charset=UTF-8\" %>\n</code></pre>\n"
},
{
"answer_id": 78724,
"author": "chickeninabiscuit",
"author_id": 3966,
"author_profile": "https://Stackoverflow.com/users/3966",
"pm_score": 1,
"selected": false,
"text": "<p>OMG - it turns out that the cause was a total WTF?</p>\n\n<p>all our tile responses were being served by a homegrown servlet that was ignoring the </p>\n\n<p><code><%@ page contentType=\"text/html; charset=UTF-8\" %></code></p>\n\n<p>directive (and who know what else).</p>\n\n<p><code>TilesDispatchExtensionServlet</code> : bloody architecture astronauts, i shake my fist at ye.</p>\n"
},
{
"answer_id": 224193,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You need to use a filter. See:</p>\n\n<p><a href=\"http://wiki.apache.org/tomcat/Tomcat/UTF-8\" rel=\"nofollow noreferrer\">http://wiki.apache.org/tomcat/Tomcat/UTF-8</a></p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3966/"
] | I'm having some internationalisation woes:
My UTF-8 string fields are being rendered in the browser as ???? after being returned from the database.
After retrieval from the database using Hibernate, the String fields are presented correctly on inspection using the eclipse debugger.
However Struts2/Tiles is rendering these strings as ???? in the HTML sent to the browser.
The charset directive is present in the HTML header:
Perhaps I need to add something to my struts2 or tiles configurations? | You could try something like this.
It's taken from sun's page on [Character Sets and Encodings](http://java.sun.com/j2ee/1.4/docs/tutorial/doc/WebI18N5.html).
I think this has to be the very first line in your jsp.
```
<%@ page contentType="text/html; charset=UTF-8" %>
``` |
56,052 | <p>EditPad Lite has a nice feature (<kbd>CTRL</kbd>-<kbd>E</kbd>, <kbd>CTRL</kbd>-<kbd>I</kbd>) which inserts a time stamp e.g. "2008-09-11 10:34:53" into your code.</p>
<p>What is the best way to get this functionality in Vim?</p>
<p>(I am using Vim 6.1 on a Linux server via SSH. In the current situation a number of us share a login so I don't want to create abbreviations in the home directory if there is another built-in way to get a timestamp.)</p>
| [
{
"answer_id": 56061,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 8,
"selected": true,
"text": "<p><a href=\"http://kenno.wordpress.com/2006/08/03/vim-tip-insert-time-stamp/\" rel=\"noreferrer\">http://kenno.wordpress.com/2006/08/03/vim-tip-insert-time-stamp/</a></p>\n\n<p>Tried it out, it works on my mac:</p>\n\n<pre><code>:r! date\n</code></pre>\n\n<p>produces:</p>\n\n<pre><code>Thu Sep 11 10:47:30 CEST 2008\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>:r! date \"+\\%Y-\\%m-\\%d \\%H:\\%M:\\%S\"\n</code></pre>\n\n<p>produces:</p>\n\n<pre><code>2008-09-11 10:50:56\n</code></pre>\n"
},
{
"answer_id": 56064,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "<p>:r! date </p>\n\n<p>You can then add format to the date command (man date) if you want the exact same format and add this as a vim alias as well</p>\n\n<p>:r! date +\"\\%Y-\\%m-\\%d \\%H:\\%M:\\%S\"</p>\n\n<p>That produces the format you showed in your example (date in the shell does not use \\%, but just %, vim replaces % by the name of the current file, so you need to escape it).</p>\n\n<p>You can add a map in your .vimrc for it to put the command automatically, for instance, each time you press F3:</p>\n\n<pre><code>:map <F3> :r! date +\"\\%Y-\\%m-\\%d \\%H:\\%M:\\%S\"<cr>\n</code></pre>\n\n<p>(Edited the from above :) )\n(Edit: change text part to code, so that </p>\n\n<pre><code><F3> \n</code></pre>\n\n<p>can be displayed)</p>\n"
},
{
"answer_id": 56069,
"author": "fijter",
"author_id": 3215,
"author_profile": "https://Stackoverflow.com/users/3215",
"pm_score": 2,
"selected": false,
"text": "<p>For a unix timestamp:</p>\n\n<pre>\n:r! date +\\%s\n</pre>\n\n<p>You can also map this command to a key (for example F12) in VIM if you use it a lot:</p>\n\n<p>Put this in your .vimrc:</p>\n\n<pre><code>\nmap <F12> :r! date +\\%s<cr>\n</code></pre>\n"
},
{
"answer_id": 58604,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 7,
"selected": false,
"text": "<p>To make it work cross-platform, just put the following in your <code>vimrc</code>:</p>\n\n<pre><code>nmap <F3> i<C-R>=strftime(\"%Y-%m-%d %a %I:%M %p\")<CR><Esc>\nimap <F3> <C-R>=strftime(\"%Y-%m-%d %a %I:%M %p\")<CR>\n</code></pre>\n\n<p>Now you can just press F3 any time inside Vi/Vim and you'll get a timestamp like <code>2016-01-25 Mo 12:44</code> inserted at the cursor.</p>\n\n<p>For a complete description of the available parameters check the <a href=\"http://www.cplusplus.com/reference/ctime/strftime/\" rel=\"noreferrer\">documentation of the C function strftime()</a>.</p>\n"
},
{
"answer_id": 2979150,
"author": "intuited",
"author_id": 192812,
"author_profile": "https://Stackoverflow.com/users/192812",
"pm_score": 3,
"selected": false,
"text": "<p>As an extension to @Swaroop C H's answer,</p>\n\n<pre><code>^R=strftime(\"%FT%T%z\")\n</code></pre>\n\n<p>is a more compact form that will also print the time zone (actually the difference from UTC, in an ISO-8601-compliant form).</p>\n\n<p>If you prefer to use an external tool for some reason,</p>\n\n<pre><code>:r !date --rfc-3339=s\n</code></pre>\n\n<p>will give you a full RFC-3339 compliant timestamp; use <code>ns</code> instead of <code>s</code> for Spock-like precision, and pipe through <code>tr ' ' T</code> to use a capital T instead of a space between date and time.</p>\n\n<p>Also you might find it useful to know that</p>\n\n<pre><code>:source somefile.vim\n</code></pre>\n\n<p>will read in commands from <code>somefile.vim</code>: this way you could set up a custom set of mappings, etc., and then load it when you're using vim on that account.</p>\n"
},
{
"answer_id": 7681121,
"author": "luser droog",
"author_id": 733077,
"author_profile": "https://Stackoverflow.com/users/733077",
"pm_score": 4,
"selected": false,
"text": "<p>Why is everybody using <code>:r!</code>? Find a blank line and type <code>!!date</code> from command-mode. Save a keystroke!</p>\n\n<p>[n.b. This will pipe the current line into stdin, and then replace the line with the command output; hence the \"find a blank line\" part.]</p>\n"
},
{
"answer_id": 11325690,
"author": "lukmac",
"author_id": 555951,
"author_profile": "https://Stackoverflow.com/users/555951",
"pm_score": 0,
"selected": false,
"text": "<p>Another quick way not included by previous answers: type-</p>\n\n<p>!!date</p>\n"
},
{
"answer_id": 22578234,
"author": "user3449771",
"author_id": 3449771,
"author_profile": "https://Stackoverflow.com/users/3449771",
"pm_score": 3,
"selected": false,
"text": "<p>From the <a href=\"http://vim.wikia.com/wiki/Insert_current_date_or_time\" rel=\"noreferrer\">Vim Wikia</a>.</p>\n\n<p>I use this instead of having to move my hand to hit an F key:</p>\n\n<pre><code>:iab <expr> tds strftime(\"%F %b %T\")\n</code></pre>\n\n<p>Now in Insert mode it just type tds and as soon as I hit the space bar or return, I get the date and keep typing.</p>\n\n<p>I put the <code>%b</code> in there, because I like seeing the month name. The <code>%F</code> gives me something to sort by date. I might change that to <code>%Y%m%d</code> so there are no characters between the units.</p>\n"
},
{
"answer_id": 24840035,
"author": "byte-pirate",
"author_id": 1637043,
"author_profile": "https://Stackoverflow.com/users/1637043",
"pm_score": 3,
"selected": false,
"text": "<h3>Unix,use:</h3>\n<pre><code>!!date\n</code></pre>\n<h3>Windows, use:</h3>\n<pre><code>!!date /t\n</code></pre>\n<h3>More details:see <a href=\"http://vim.wikia.com/wiki/Insert_current_date_or_time\" rel=\"nofollow noreferrer\">Insert_current_date_or_time</a></h3>\n"
},
{
"answer_id": 57789091,
"author": "luator",
"author_id": 2095383,
"author_profile": "https://Stackoverflow.com/users/2095383",
"pm_score": 2,
"selected": false,
"text": "<p>I wanted a custom command <code>:Date</code> (not a key mapping) to insert the date at the current cursor position.</p>\n\n<p>Unfortunately straightforward commands like <code>r!date</code> result in a new line. So finally I came up with the following:</p>\n\n<pre><code>command Date execute \"normal i<C-R>=strftime('%F %T')<CR><ESC>\"\n</code></pre>\n\n<p>which adds the date/time string at the cursor position without adding any new line (change to <code>normal a</code> add after the cursor position).</p>\n"
},
{
"answer_id": 66021073,
"author": "mmrtnt",
"author_id": 9302794,
"author_profile": "https://Stackoverflow.com/users/9302794",
"pm_score": 1,
"selected": false,
"text": "<p>I'm using vi in an Eterm for reasons and it turns out that strftime() is not available in vi.</p>\n<p>Fought long and hard and finally came up with this:</p>\n<pre><code>map T :r! date +"\\%m/\\%d/\\%Y \\%H:\\%M" <CR>"kkddo<CR>\n</code></pre>\n<p>Result: 02/02/2021 16:45</p>\n<p>For some reason, adding the date-time alone resulted in a blank line <em>above</em> the date-time and the cursor set <em>on</em> the date-time line.</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th></th>\n<th></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>date +"[etc]" <CR></td>\n<td>Enters the date-time</td>\n</tr>\n<tr>\n<td>"kk</td>\n<td>Moves up two lines</td>\n</tr>\n<tr>\n<td>dd</td>\n<td>Deletes the line above the date-time</td>\n</tr>\n<tr>\n<td>o <CR></td>\n<td>Opens a line below the time and adds a carriage return (linefeed)</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p><strong>Bonus:</strong></p>\n<p>vi doesn't read ~/.vimrc, it reads ~/.exrc</p>\n<p>Also, this is how it looks in vim/.vimrc:</p>\n<pre><code>map T "=strftime("%m/%d/%y %H:%M")<CR>po<CR>\n</code></pre>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] | EditPad Lite has a nice feature (`CTRL`-`E`, `CTRL`-`I`) which inserts a time stamp e.g. "2008-09-11 10:34:53" into your code.
What is the best way to get this functionality in Vim?
(I am using Vim 6.1 on a Linux server via SSH. In the current situation a number of us share a login so I don't want to create abbreviations in the home directory if there is another built-in way to get a timestamp.) | <http://kenno.wordpress.com/2006/08/03/vim-tip-insert-time-stamp/>
Tried it out, it works on my mac:
```
:r! date
```
produces:
```
Thu Sep 11 10:47:30 CEST 2008
```
This:
```
:r! date "+\%Y-\%m-\%d \%H:\%M:\%S"
```
produces:
```
2008-09-11 10:50:56
``` |
56,070 | <p><strong>Edit</strong>: Solved, there was a trigger with a loop on the table (read my own answer further below).</p>
<hr>
<p>We have a simple delete statement that looks like this:</p>
<pre><code>DELETE FROM tablename WHERE pk = 12345
</code></pre>
<p>This just hangs, no timeout, no nothing.</p>
<p>We've looked at the execution plan, and it consists of many lookups on related tables to ensure no foreign keys would trip up the delete, but we've verified that none of those other tables have any rows referring to that particular row.</p>
<p>There is no other user connected to the database at this time.</p>
<p>We've run DBCC CHECKDB against it, and it reports 0 errors.</p>
<p>Looking at the results of <em><code>sp_who</code></em> and <em><code>sp_lock</code></em> while the query is hanging, I notice that my spid has plenty of PAG and KEY locks, as well as the occasional TAB lock.</p>
<p>The table has 1.777.621 rows, and yes, pk is the primary key, so it's a single row delete based on index. There is no table scan in the execution plan, though I notice that it contains something that says <em>Table Spool (Eager Spool)</em>, but says Estimated number of rows 1. Can this actually be a table-scan in disguise? It only says it looks at the primary key column.</p>
<p>Tried DBCC DBREINDEX and UPDATE STATISTICS on the table. Both completed within reasonable time.</p>
<p>There is unfortunately a high number of indexes on this particular table. It is the core table in our system, with plenty of columns, and references, both outgoing and incoming. The exact number is 48 indexes + the primary key clustered index.</p>
<p>What else should we look at?</p>
<p>Note also that this table did not have this problem before, this problem occured suddently today. We also have many databases with the same table setup (copies of customer databases), and they behave as expected, it's just this one that is problematic.</p>
| [
{
"answer_id": 56128,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 2,
"selected": false,
"text": "<p>Try recreating the index on that table, and try regenerating the statistics.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa258828(SQL.80).aspx\" rel=\"nofollow noreferrer\">DBCC REINDEX</a><br/></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa260645(SQL.80).aspx\" rel=\"nofollow noreferrer\">UPDATE STATISTICS</a></p>\n"
},
{
"answer_id": 56163,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 4,
"selected": true,
"text": "<p>One piece of information missing is the number of indices on the table you are deleting the data from. As SQL Server uses the Primary Key as a pointer in every index, any change to the primary index requires updating every index. Though, unless we are talking a high number, this shouldn't be an issue.</p>\n\n<p>I am guessing, from your description, that this is a primary table in the database, referenced by many other tables in FK relationships. This would account for the large number of locks as it checks the rest of the tables for references. And, if you have cascading deletes turned on, this could lead to a delete in table a requiring checks several tables deep.</p>\n"
},
{
"answer_id": 56437,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, this is embarrasing.</p>\n\n<p>A collegue had added a trigger to that table a while ago, and the trigger had a bug. Although he had fixed the bug, the trigger had never been recreated for that table.</p>\n\n<p>So the server was actually doing nothing, it just did it a huge number of times.</p>\n\n<p>Oh well...</p>\n\n<p>Thanks for the eyeballs to everyone who read this and pondered the problem.</p>\n\n<p>I'm going to accept Josef's answer, as his was the closest, and indirectly thouched upon the issue with the cascading deletes.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
] | **Edit**: Solved, there was a trigger with a loop on the table (read my own answer further below).
---
We have a simple delete statement that looks like this:
```
DELETE FROM tablename WHERE pk = 12345
```
This just hangs, no timeout, no nothing.
We've looked at the execution plan, and it consists of many lookups on related tables to ensure no foreign keys would trip up the delete, but we've verified that none of those other tables have any rows referring to that particular row.
There is no other user connected to the database at this time.
We've run DBCC CHECKDB against it, and it reports 0 errors.
Looking at the results of *`sp_who`* and *`sp_lock`* while the query is hanging, I notice that my spid has plenty of PAG and KEY locks, as well as the occasional TAB lock.
The table has 1.777.621 rows, and yes, pk is the primary key, so it's a single row delete based on index. There is no table scan in the execution plan, though I notice that it contains something that says *Table Spool (Eager Spool)*, but says Estimated number of rows 1. Can this actually be a table-scan in disguise? It only says it looks at the primary key column.
Tried DBCC DBREINDEX and UPDATE STATISTICS on the table. Both completed within reasonable time.
There is unfortunately a high number of indexes on this particular table. It is the core table in our system, with plenty of columns, and references, both outgoing and incoming. The exact number is 48 indexes + the primary key clustered index.
What else should we look at?
Note also that this table did not have this problem before, this problem occured suddently today. We also have many databases with the same table setup (copies of customer databases), and they behave as expected, it's just this one that is problematic. | One piece of information missing is the number of indices on the table you are deleting the data from. As SQL Server uses the Primary Key as a pointer in every index, any change to the primary index requires updating every index. Though, unless we are talking a high number, this shouldn't be an issue.
I am guessing, from your description, that this is a primary table in the database, referenced by many other tables in FK relationships. This would account for the large number of locks as it checks the rest of the tables for references. And, if you have cascading deletes turned on, this could lead to a delete in table a requiring checks several tables deep. |
56,078 | <p>I got a Function that returns a <code>Collection<string></code>, and that calls itself recursively to eventually return one big <code>Collection<string></code>.</p>
<p>Now, i just wonder what the best approach to merge the lists? <code>Collection.CopyTo()</code> only copies to string[], and using a <code>foreach()</code> loop feels like being inefficient. However, since I also want to filter out duplicates, I feel like i'll end up with a foreach that calls <code>Contains()</code> on the <code>Collection</code>.</p>
<p>I wonder, is there a more efficient way to have a recursive function that returns a list of strings without duplicates? I don't have to use a <code>Collection</code>, it can be pretty much any suitable data type.</p>
<p>Only exclusion, I'm bound to Visual Studio 2005 and .net 3.0, so no LINQ.</p>
<p><strong>Edit:</strong> To clarify: The Function takes a user out of Active Directory, looks at the Direct Reports of the user, and then recursively looks at the direct reports of every user. So the end result is a List of all users that are in the "command chain" of a given user.Since this is executed quite often and at the moment takes 20 Seconds for some users, i'm looking for ways to improve it. Caching the result for 24 Hours is also on my list btw., but I want to see how to improve it before applying caching.</p>
| [
{
"answer_id": 56092,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 1,
"selected": false,
"text": "<p>I think <a href=\"http://msdn.microsoft.com/en-us/library/bb359438.aspx\" rel=\"nofollow noreferrer\"><code>HashSet<T></code></a> is a great help.</p>\n\n<blockquote>\n <p>The <code>HashSet<T></code> class provides\n high performance set operations. A set\n is a collection that contains no\n duplicate elements, and whose elements\n are in no particular order.</p>\n</blockquote>\n\n<p>Just add items to it and then use CopyTo.</p>\n\n<hr>\n\n<p><strong>Update</strong>: <code>HashSet<T></code> is in .Net 3.5</p>\n\n<p>Maybe you can use <a href=\"http://msdn.microsoft.com/en-us/library/xfhwa508.aspx\" rel=\"nofollow noreferrer\"><code>Dictionary<TKey, TValue></code></a>. Setting a duplicate key to a dictionary will not raise an exception.</p>\n"
},
{
"answer_id": 56100,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 5,
"selected": true,
"text": "<p>If you're using List<> you can use .AddRange to add one list to the other list.</p>\n\n<p>Or you can use yield return to combine lists on the fly like this:</p>\n\n<pre><code>public IEnumerable<string> Combine(IEnumerable<string> col1, IEnumerable<string> col2)\n{\n foreach(string item in col1)\n yield return item;\n\n foreach(string item in col2)\n yield return item;\n}\n</code></pre>\n"
},
{
"answer_id": 56104,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 1,
"selected": false,
"text": "<p>You might want to take a look at <a href=\"http://www.codeproject.com/KB/recipes/sets.aspx\" rel=\"nofollow noreferrer\">Iesi.Collections</a> and <a href=\"http://www.codeproject.com/KB/recipes/GenericISet.aspx?display=Print\" rel=\"nofollow noreferrer\">Extended Generic Iesi.Collections</a> (because the first edition was made in 1.1 when there were no generics yet).</p>\n\n<p>Extended Iesi has an ISet class which acts exactly as a HashSet: it enforces unique members and does not allow duplicates.</p>\n\n<p>The nifty thing about Iesi is that it has set operators instead of methods for merging collections, so you have the choice between a union (|), intersection (&), XOR (^) and so forth.</p>\n"
},
{
"answer_id": 56108,
"author": "Matthew M. Osborn",
"author_id": 5235,
"author_profile": "https://Stackoverflow.com/users/5235",
"pm_score": 1,
"selected": false,
"text": "<p>Can you pass the Collection into you method by refernce so that you can just add items to it, that way you dont have to return anything. This is what it might look like if you did it in c#.</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n Collection<string> myitems = new Collection<string>();\n myMthod(ref myitems);\n Console.WriteLine(myitems.Count.ToString());\n Console.ReadLine();\n }\n\n static void myMthod(ref Collection<string> myitems)\n {\n myitems.Add(\"string\");\n if(myitems.Count <5)\n myMthod(ref myitems);\n }\n}\n</code></pre>\n\n<p>As Stated by @Zooba Passing by ref is not necessary here, if you passing by value it will also work.</p>\n"
},
{
"answer_id": 56345,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>As far as merging goes:</p>\n\n<blockquote>\n <p>I wonder, is there a more efficient\n way to have a recursive function that\n returns a list of strings without\n duplicates? I don't have to use a\n Collection, it can be pretty much any\n suitable data type.</p>\n</blockquote>\n\n<p>Your function assembles a return value, right? You're splitting the supplied list in half, invoking self again (twice) and then merging those results. </p>\n\n<p>During the merge step, why not just check before you add each string to the result? If it's already there, skip it.</p>\n\n<p>Assuming you're working with sorted lists of course.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] | I got a Function that returns a `Collection<string>`, and that calls itself recursively to eventually return one big `Collection<string>`.
Now, i just wonder what the best approach to merge the lists? `Collection.CopyTo()` only copies to string[], and using a `foreach()` loop feels like being inefficient. However, since I also want to filter out duplicates, I feel like i'll end up with a foreach that calls `Contains()` on the `Collection`.
I wonder, is there a more efficient way to have a recursive function that returns a list of strings without duplicates? I don't have to use a `Collection`, it can be pretty much any suitable data type.
Only exclusion, I'm bound to Visual Studio 2005 and .net 3.0, so no LINQ.
**Edit:** To clarify: The Function takes a user out of Active Directory, looks at the Direct Reports of the user, and then recursively looks at the direct reports of every user. So the end result is a List of all users that are in the "command chain" of a given user.Since this is executed quite often and at the moment takes 20 Seconds for some users, i'm looking for ways to improve it. Caching the result for 24 Hours is also on my list btw., but I want to see how to improve it before applying caching. | If you're using List<> you can use .AddRange to add one list to the other list.
Or you can use yield return to combine lists on the fly like this:
```
public IEnumerable<string> Combine(IEnumerable<string> col1, IEnumerable<string> col2)
{
foreach(string item in col1)
yield return item;
foreach(string item in col2)
yield return item;
}
``` |
56,091 | <p>Whilst refactoring some legacy C++ code I found that I could potentially remove some code duplication by somehow defining a variable that could point to any class method that shared the same signature. After a little digging, I found that I could do something like the following:</p>
<pre><code>class MyClass
{
protected:
bool CaseMethod1( int abc, const std::string& str )
{
cout << "case 1:" << str;
return true;
}
bool CaseMethod2( int abc, const std::string& str )
{
cout << "case 2:" << str;
return true;
}
bool CaseMethod3( int abc, const std::string& str )
{
cout << "case 3:" << str;
return true;
}
public:
bool TestSwitch( int num )
{
bool ( MyClass::*CaseMethod )( int, const std::string& );
switch ( num )
{
case 1: CaseMethod = &MyClass::CaseMethod1;
break;
case 2: CaseMethod = &MyClass::CaseMethod2;
break;
case 3: CaseMethod = &MyClass::CaseMethod3;
break;
}
...
bool res = CaseMethod( 999, "hello world" );
...
reurn res;
}
};
</code></pre>
<p>My question is - <strong>is this the correct way to go about this?</strong> Should I consider anything that <em>Boost</em> has to offer?</p>
<p>Edit...</p>
<p>Ok, my mistake - I should be calling the method like so:</p>
<pre><code>bool res = ( (*this).*CaseMethod )( 999, "Hello World" );
</code></pre>
| [
{
"answer_id": 56101,
"author": "Paulius",
"author_id": 1353085,
"author_profile": "https://Stackoverflow.com/users/1353085",
"pm_score": 1,
"selected": false,
"text": "<p>You can certainly do it, although the CaseMethod call isn't correct (it's a pointer to member function, so you have to specify the object on which the method should be called). The correct call would look like this:</p>\n\n<pre><code>bool res = this->*CaseMethod( 999, \"hello world\" );\n</code></pre>\n\n<p>On the other hand, I'd recommend <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/bind/mem_fn.html\" rel=\"nofollow noreferrer\">boost::mem_fn</a> - you'll have less chances to screw it up. ;)</p>\n"
},
{
"answer_id": 56111,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 4,
"selected": true,
"text": "<p>What you have there is a pointer-to-member-function. It will solve your problem. I am surprised that your \"TestSwitch\" function compiles, as the calling syntax is slightly different to what you might expect. It should be:</p>\n\n<pre><code>bool res = (this->*CaseMethod)( 999, \"hello world\" );\n</code></pre>\n\n<p>However, you might find a combination of boost::function and boost::bind makes things a little easier, as you can avoid the bizarre calling syntax.</p>\n\n<pre><code>boost::function<bool(int,std::string)> f=\n boost::bind(&MyClass::CaseMethod1,this,_1,_2);\n</code></pre>\n\n<p>Of course, this will bind it to the current <code>this</code> pointer: you can make the <code>this</code> pointer of the member function an explicit third parameter if you like:</p>\n\n<pre><code>boost::function<bool(MyClass*,int,std::string)> f=\n boost::bind(&MyClass::CaseMethod1,_1,_2,_3);\n</code></pre>\n\n<p>Another alternative might be to use virtual functions and derived classes, but that might require major changes to your code.</p>\n"
},
{
"answer_id": 56129,
"author": "Nik",
"author_id": 5354,
"author_profile": "https://Stackoverflow.com/users/5354",
"pm_score": 0,
"selected": false,
"text": "<p>There's nothing intrinsically wrong with the localised example you've given here, but class method pointers can often be tricky to keep 'safe' if you use them in a wider context, such as outside the class they're a pointer of, or in conjunction with a complex inheritance tree. The way compilers typically manage method pointers is different to 'normal' pointers (since there's extra information beyond just a code entry point), and consequently there are a lot of restrictions on what you can do with them.</p>\n\n<p>If you're just keeping simple pointers the way you describe then you'll be fine, but fore more complex uses you may want to take a look at a more generalised functor system such as <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/bind/bind.html#with_member_pointers\" rel=\"nofollow noreferrer\">boost::bind</a>. These can take pointers to just about any callable code pointer, and can also bind instanced function arguments if necessary.</p>\n"
},
{
"answer_id": 56160,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 1,
"selected": false,
"text": "<p>I don't see the difference between your call and simply calling the method within the switch statement.</p>\n\n<p>No, there is no semantic or readability difference.</p>\n\n<p>The only difference I see is that you are taking a pointer to a method and so forbids to the compiler to inline it or optimizes any call to that method.</p>\n"
},
{
"answer_id": 57045,
"author": "Simon Steele",
"author_id": 4591,
"author_profile": "https://Stackoverflow.com/users/4591",
"pm_score": 2,
"selected": false,
"text": "<p>You could also build a lookup (if your key range is reasonable) so that you end up writing:</p>\n\n<pre><code>this->*Methods[num]( 999, \"hello world\" );\n</code></pre>\n\n<p>This removes the switch as well, and makes the cleanup a bit more worthwhile.</p>\n"
},
{
"answer_id": 57101,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Without wider context, it's hard to figure out the right answer, but I sew three possibilities here:</p>\n\n<ul>\n<li><p>stay with normal switch statement, no need to do anything. This is the most likely solution</p></li>\n<li><p>use pointers to member function in conjunction with an array, as @Simon says, or may be with a map. For a case statement with a large number of cases, this may be faster.</p></li>\n<li><p>split t he class into a number of classes, each carrying one function to call, and use virtual functions. This is probably the best solution, buy it will require some serious refatoring. Consider GoF patterns such as State or Visitor or some such.</p></li>\n</ul>\n"
},
{
"answer_id": 58798,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 0,
"selected": false,
"text": "<p>There are other approaches available, such as using an abstract base class, or specialized template functions.</p>\n\n<p>I'll describe the base class idea.</p>\n\n<p>You can define an abstract base class</p>\n\n<pre><code>class Base { virtual bool Method(int i, const string& s) = 0; };\n</code></pre>\n\n<p>Then write each of your cases as a subclass, such as</p>\n\n<pre><code>class Case1 : public Base { virtual bool Method(..) { /* implement */; } };\n</code></pre>\n\n<p>At some point, you will get your \"num\" variable that indicates which test to execute. You could write a factory function that takes this num (I'll call it which_case), and returns a pointer to Base, and then call Method from that pointer.</p>\n\n<pre><code>Base* CreateBase(int which_num) { /* metacode: return new Case[which_num]; */ }\n// ... later, when you want to actually call your method ...\nBase* base = CreateBase(23);\nbase->Method(999, \"hello world!\");\ndelete base; // Or use a scoped pointer.\n</code></pre>\n\n<p>By the way, this application makes me wish C++ supported static virtual functions, or something like \"type\" as a builtin type - but it doesn't.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2958/"
] | Whilst refactoring some legacy C++ code I found that I could potentially remove some code duplication by somehow defining a variable that could point to any class method that shared the same signature. After a little digging, I found that I could do something like the following:
```
class MyClass
{
protected:
bool CaseMethod1( int abc, const std::string& str )
{
cout << "case 1:" << str;
return true;
}
bool CaseMethod2( int abc, const std::string& str )
{
cout << "case 2:" << str;
return true;
}
bool CaseMethod3( int abc, const std::string& str )
{
cout << "case 3:" << str;
return true;
}
public:
bool TestSwitch( int num )
{
bool ( MyClass::*CaseMethod )( int, const std::string& );
switch ( num )
{
case 1: CaseMethod = &MyClass::CaseMethod1;
break;
case 2: CaseMethod = &MyClass::CaseMethod2;
break;
case 3: CaseMethod = &MyClass::CaseMethod3;
break;
}
...
bool res = CaseMethod( 999, "hello world" );
...
reurn res;
}
};
```
My question is - **is this the correct way to go about this?** Should I consider anything that *Boost* has to offer?
Edit...
Ok, my mistake - I should be calling the method like so:
```
bool res = ( (*this).*CaseMethod )( 999, "Hello World" );
``` | What you have there is a pointer-to-member-function. It will solve your problem. I am surprised that your "TestSwitch" function compiles, as the calling syntax is slightly different to what you might expect. It should be:
```
bool res = (this->*CaseMethod)( 999, "hello world" );
```
However, you might find a combination of boost::function and boost::bind makes things a little easier, as you can avoid the bizarre calling syntax.
```
boost::function<bool(int,std::string)> f=
boost::bind(&MyClass::CaseMethod1,this,_1,_2);
```
Of course, this will bind it to the current `this` pointer: you can make the `this` pointer of the member function an explicit third parameter if you like:
```
boost::function<bool(MyClass*,int,std::string)> f=
boost::bind(&MyClass::CaseMethod1,_1,_2,_3);
```
Another alternative might be to use virtual functions and derived classes, but that might require major changes to your code. |
56,112 | <p>I have written a Silverlight 2 application communicating with a WCF service (BasicHttpBinding). The site hosting the Silverlight content is protected using a ASP.NET Membership Provider. I can access the current user using HttpContext.Current.User.Identity.Name from my WCF service, and I have turned on AspNetCompatibilityRequirementsMode. </p>
<p>I now want to write a Windows application using the exact same web service. To handle authentication I have enabled the <a href="http://msdn.microsoft.com/en-us/library/bb386582.aspx" rel="noreferrer">Authentication service</a>, and can call "login" to authenticate my user... Okey, all good... But how the heck do I get that authentication cookie set on my other service client?! </p>
<p>Both services are hosted on the same domain </p>
<ul>
<li>MyDataService.svc <- the one dealing with my data</li>
<li>AuthenticationService.svc <- the one the windows app has to call to authenticate.</li>
</ul>
<p>I don't want to create a new service for the windows client, or use another binding...</p>
<p>The Client Application Services is another alternative, but all the examples is limited to show how to get the user, roles and his profile... But once we're authenticated using the Client Application Services there should be a way to get that authentication cookie attached to my service clients when calling back to the same server.</p>
<p>According to input from colleagues the solution is adding a wsHttpBinding end-point, but I'm hoping I can get around that...</p>
| [
{
"answer_id": 57520,
"author": "Jeremy McGee",
"author_id": 3546,
"author_profile": "https://Stackoverflow.com/users/3546",
"pm_score": 2,
"selected": false,
"text": "<p>Web services, such as those created by WCF, are often best used in a \"stateless\" way, so each call to a Web service starts afresh. This simplifies the server code, as there's no need to have a \"session\" that recalls the state of the client. It also simplifies the client code as there's no need to hold tickets, cookies, or other geegaws that assume something about the state of the server.</p>\n\n<p>Creating two services in the way that is described introduces statefulness. The client is either \"authenticated\" or \"not authenticated\", and the MyDataService.svc has to figure out which. </p>\n\n<p>As it happens, I've found WCF to work well when the membership provider is used to authenticate <em>every</em> call to a service. So, in the example given, you'd want to add the membership provider authentication gubbins to the service configuration for MyDataService, and not have a separate authentication service at all.</p>\n\n<p>For details, see the MSDN article <a href=\"http://msdn.microsoft.com/en-us/library/ms731049.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>[What's very attractive about this to me, as I'm lazy, is that this is entirely declarative. I simply scatter the right configuration entries for my MembershipProvider in the app.config for the application and! bingo! all calls to every contract in the service are authenticated.]</p>\n\n<p>It's fair to note that this is not going to be particularly quick. If you're using SQL Server for your authentication database you'll have at least one, perhaps two stored procedure calls per service call. In many cases (especially for HTTP bindings) the overhead of the service call itself will be greater; if not, consider rolling your own implementation of a membership provider that caches authentication requests.</p>\n\n<p>One thing that this <em>doesn't</em> give is the ability to provide a \"login\" capability. For that, you can either provide an (authenticated!) service contract that does nothing (other than raise a fault if the authentication fails), or you can use the membership provider service as described in the original referenced article.</p>\n"
},
{
"answer_id": 57760,
"author": "Jonas Follesø",
"author_id": 1199387,
"author_profile": "https://Stackoverflow.com/users/1199387",
"pm_score": 4,
"selected": true,
"text": "<p>I finally found a way to make this work. For authentication I'm using the \"<a href=\"http://msdn.microsoft.com/en-us/library/bb386582.aspx\" rel=\"noreferrer\">WCF Authentication Service</a>\". When authenticating the service will try to set an authentication cookie. I need to get this cookie out of the response, and add it to any other request made to other web services on the same machine. The code to do that looks like this:</p>\n\n<pre><code>var authService = new AuthService.AuthenticationServiceClient();\nvar diveService = new DiveLogService.DiveLogServiceClient();\n\nstring cookieHeader = \"\";\nusing (OperationContextScope scope = new OperationContextScope(authService.InnerChannel))\n{\n HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();\n OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty;\n bool isGood = authService.Login(\"jonas\", \"jonas\", string.Empty, true);\n MessageProperties properties = OperationContext.Current.IncomingMessageProperties;\n HttpResponseMessageProperty responseProperty = (HttpResponseMessageProperty)properties[HttpResponseMessageProperty.Name];\n cookieHeader = responseProperty.Headers[HttpResponseHeader.SetCookie]; \n}\n\nusing (OperationContextScope scope = new OperationContextScope(diveService.InnerChannel))\n{\n HttpRequestMessageProperty httpRequest = new HttpRequestMessageProperty();\n OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest);\n httpRequest.Headers.Add(HttpRequestHeader.Cookie, cookieHeader);\n var res = diveService.GetDives();\n} \n</code></pre>\n\n<p>As you can see I have two service clients, one fo the authentication service, and one for the service I'm actually going to use. The first block will call the Login method, and grab the authentication cookie out of the response. The second block will add the header to the request before calling the \"GetDives\" service method.</p>\n\n<p>I'm not happy with this code at all, and I think a better alternative might be to use \"Web Reference\" in stead of \"Service Reference\" and use the .NET 2.0 stack instead.</p>\n"
},
{
"answer_id": 62049,
"author": "larsw",
"author_id": 2732,
"author_profile": "https://Stackoverflow.com/users/2732",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible to hide much of the extra code behind a custom message inspector & behavior so you don't need to take care of tinkering with the OperationContextScope yourself.</p>\n\n<p>I'll try to mock something later and send it to you.</p>\n\n<p>--larsw</p>\n"
},
{
"answer_id": 451503,
"author": "Chuck",
"author_id": 9714,
"author_profile": "https://Stackoverflow.com/users/9714",
"pm_score": 0,
"selected": false,
"text": "<p>You should take a look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.net.cookiecontainer.aspx\" rel=\"nofollow noreferrer\">CookieContainer</a> object in System.Net. This object allows a non-browser client to hang on to cookies. This is what my team used the last time we ran into that problem.</p>\n\n<p><a href=\"http://www.justskins.com/forums/session-state-and-winforms-consuming-a-web-service-9763.html\" rel=\"nofollow noreferrer\">Here is a brief article</a> on how to go about using it. There may be better ones out there, but this should get you started.</p>\n\n<p>We went the stateless route for our current set of WCF services and Silverlight 2 application. It is possible to get Silverlight 2 to work with services bound with TransportWithMessageCredential security, though it takes some custom security code on the Silverlight side. The upshot is that any application can access the services simply by setting the Username and Password in the message headers. This can be done once in a custom IRequestChannel implementation so that developers never need to worry about setting the values themselves. Though WCF does have an easy way for developers to do this which I believe is serviceProxy.Security.Username and serviceProxy.Security.Password or something equally simple. </p>\n"
},
{
"answer_id": 850002,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I wrote this a while back when I was using Client Application Services to authenticate against web services. It uses a message inspector to insert the cookie header. There is a word file with documentation and a demo project. Although its not exactly what you are doing, its pretty close. You can download it from <a href=\"http://www.baileysc.com/releases/clientappservicesdemo.zip\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 1101813,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>On the client modify your <binding> tag for the service (inside <system.serviceModel>) to include: allowCookies=\"true\"</p>\n\n<p>The app should now persist the cookie and use it. You'll note that IsLoggedIn now returns true after you log in -- it returns false if you're not allowing cookies.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199387/"
] | I have written a Silverlight 2 application communicating with a WCF service (BasicHttpBinding). The site hosting the Silverlight content is protected using a ASP.NET Membership Provider. I can access the current user using HttpContext.Current.User.Identity.Name from my WCF service, and I have turned on AspNetCompatibilityRequirementsMode.
I now want to write a Windows application using the exact same web service. To handle authentication I have enabled the [Authentication service](http://msdn.microsoft.com/en-us/library/bb386582.aspx), and can call "login" to authenticate my user... Okey, all good... But how the heck do I get that authentication cookie set on my other service client?!
Both services are hosted on the same domain
* MyDataService.svc <- the one dealing with my data
* AuthenticationService.svc <- the one the windows app has to call to authenticate.
I don't want to create a new service for the windows client, or use another binding...
The Client Application Services is another alternative, but all the examples is limited to show how to get the user, roles and his profile... But once we're authenticated using the Client Application Services there should be a way to get that authentication cookie attached to my service clients when calling back to the same server.
According to input from colleagues the solution is adding a wsHttpBinding end-point, but I'm hoping I can get around that... | I finally found a way to make this work. For authentication I'm using the "[WCF Authentication Service](http://msdn.microsoft.com/en-us/library/bb386582.aspx)". When authenticating the service will try to set an authentication cookie. I need to get this cookie out of the response, and add it to any other request made to other web services on the same machine. The code to do that looks like this:
```
var authService = new AuthService.AuthenticationServiceClient();
var diveService = new DiveLogService.DiveLogServiceClient();
string cookieHeader = "";
using (OperationContextScope scope = new OperationContextScope(authService.InnerChannel))
{
HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty;
bool isGood = authService.Login("jonas", "jonas", string.Empty, true);
MessageProperties properties = OperationContext.Current.IncomingMessageProperties;
HttpResponseMessageProperty responseProperty = (HttpResponseMessageProperty)properties[HttpResponseMessageProperty.Name];
cookieHeader = responseProperty.Headers[HttpResponseHeader.SetCookie];
}
using (OperationContextScope scope = new OperationContextScope(diveService.InnerChannel))
{
HttpRequestMessageProperty httpRequest = new HttpRequestMessageProperty();
OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest);
httpRequest.Headers.Add(HttpRequestHeader.Cookie, cookieHeader);
var res = diveService.GetDives();
}
```
As you can see I have two service clients, one fo the authentication service, and one for the service I'm actually going to use. The first block will call the Login method, and grab the authentication cookie out of the response. The second block will add the header to the request before calling the "GetDives" service method.
I'm not happy with this code at all, and I think a better alternative might be to use "Web Reference" in stead of "Service Reference" and use the .NET 2.0 stack instead. |
56,118 | <p>I am trying to write a formula in ActionScript 3 that will give me var "z" (please see image below) in degrees, which I will then convert to radians.</p>
<p>I will already know the value of vars "x" and "y". Using trigonometry, how can I calculate the length of the hypotenuse and therefore the variable angle of var z? A solution in either AS3 or psuedocode would be very helpful. Thanks.</p>
<p><img src="https://i.stack.imgur.com/B0nfz.jpg" alt="triangle"></p>
| [
{
"answer_id": 56126,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 2,
"selected": false,
"text": "<p>z is equivalent to 180 - angle of yH. Or: </p>\n\n<pre><code>180 - arctan(x/y) //Degrees\npi - arctan(x/y) //radians\n</code></pre>\n\n<p>Also, if actionscript's math libraries have it, use arctan2, which takes both the x and y and deals with signs correctly.</p>\n"
},
{
"answer_id": 56131,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 0,
"selected": false,
"text": "<p>What @Patrick said, also the hypotenuse is <code>sqrt(x^2 + y^2)</code>.</p>\n"
},
{
"answer_id": 56239,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 1,
"selected": false,
"text": "<p>The angle you want is the same as the angle opposed to the one wetween y and h.</p>\n\n<p>Let's call <code>a</code> the angle between <code>y</code> and <code>h</code>, the angle you want is actually <code>180 - a</code> or <code>PI - a</code> depending on your unit (degrees or radians).</p>\n\n<p>Now geometry tells us that:</p>\n\n<pre><code>cos(a) = y/h\nsin(a) = x/h\ntan(a) = x/y\n</code></pre>\n\n<p>Using tan(), we get:</p>\n\n<pre><code>a = arctan(x/y)\n</code></pre>\n\n<p>As we are looking for 180 - a, you should compute:</p>\n\n<pre><code>180 - arctan(x/y)\n</code></pre>\n"
},
{
"answer_id": 57362,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 4,
"selected": true,
"text": "<p>What you need is this:</p>\n\n<pre><code>var h:Number = Math.sqrt(x*x + y*y);\nvar z:Number = Math.atan2(y, x);\n</code></pre>\n\n<p>That should give you the angle in radians, you might need to swap x/y and possibly add or remove 90 degrees but it should do the trick! (Note that you don't even need <strong>h</strong> to get <strong>z</strong> when you're using atan2)</p>\n\n<p>I use multiplication instead of Math.pow() just because Math is pretty slow, you can do:</p>\n\n<pre><code>var h:Number = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));\n</code></pre>\n\n<p>And it should be exactly the same.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] | I am trying to write a formula in ActionScript 3 that will give me var "z" (please see image below) in degrees, which I will then convert to radians.
I will already know the value of vars "x" and "y". Using trigonometry, how can I calculate the length of the hypotenuse and therefore the variable angle of var z? A solution in either AS3 or psuedocode would be very helpful. Thanks.
 | What you need is this:
```
var h:Number = Math.sqrt(x*x + y*y);
var z:Number = Math.atan2(y, x);
```
That should give you the angle in radians, you might need to swap x/y and possibly add or remove 90 degrees but it should do the trick! (Note that you don't even need **h** to get **z** when you're using atan2)
I use multiplication instead of Math.pow() just because Math is pretty slow, you can do:
```
var h:Number = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
```
And it should be exactly the same. |
56,168 | <p>The code in <a href="https://stackoverflow.com/questions/17181/test-cases-vs-assertion-statement">this question</a> made me think</p>
<pre><code>assert(value>0); //Precondition
if (value>0)
{
//Doit
}
</code></pre>
<p>I never write the if-statement. Asserting is enough/all you <em>can</em> do.
"Crash early, crash often"</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0735619670" rel="nofollow noreferrer" rel="nofollow noreferrer">CodeComplete</a> states:</p>
<ul>
<li>The assert-statement makes the application Correct </li>
<li>The if-test makes the application Robust</li>
</ul>
<p>I don't think you've made an application more robust by correcting invalid input values, or skipping code:</p>
<pre><code>assert(value >= 0 ); //Precondition
assert(value <= 90); //Precondition
if(value < 0) //Just in case
value = 0;
if (value > 90) //Just in case
value = 90;
//Doit
</code></pre>
<p>These corrections are based on assumptions you made about the outside world.
Only the caller knows what "a valid input value" is for your function, and he must check its validity before he calls your function.</p>
<p>To paraphrase <a href="https://rads.stackoverflow.com/amzn/click/com/0735619670" rel="nofollow noreferrer" rel="nofollow noreferrer">CodeComplete</a>:
"Real-world programs <em>become</em> too messy when we <em>don't</em> rely solely on assertions."</p>
<p>Question: Am I wrong, stuborn, stupid, too non-defensive...</p>
| [
{
"answer_id": 56173,
"author": "Tnilsson",
"author_id": 4165,
"author_profile": "https://Stackoverflow.com/users/4165",
"pm_score": 3,
"selected": false,
"text": "<p>The problem with trusting just Asserts, is that they may be turned off in a production environment. To quote the wikipedia article:</p>\n\n<blockquote>\n <p>Most languages allow assertions to be\n enabled or disabled globally, and\n sometimes independently. Assertions\n are often enabled during development\n and disabled during final testing and\n on release to the customer. Not\n checking assertions avoiding the cost\n of evaluating the assertions while,\n assuming the assertions are free of\n side effects, still producing the same\n result under normal conditions. Under\n abnormal conditions, disabling\n assertion checking can mean that a\n program that would have aborted will\n continue to run. This is sometimes\n preferable.\n <a href=\"http://en.wikipedia.org/wiki/Assertion_(computing)\" rel=\"noreferrer\">Wikipedia</a></p>\n</blockquote>\n\n<p>So if the correctness of your code relies on the Asserts to be there you may run into serious problems. Sure, if the code worked during testing it should work during production... Now enter the second guy that works on the code and is just going to fix a small problem...</p>\n"
},
{
"answer_id": 56174,
"author": "Rik",
"author_id": 5409,
"author_profile": "https://Stackoverflow.com/users/5409",
"pm_score": 2,
"selected": false,
"text": "<p>I some cases, asserts are disabled when building for release. You may not have control over this (otherwise, you could build with asserts on), so it might be a good idea to do it like this.</p>\n\n<p>The problem with \"correcting\" the input values is that the caller will not get what they expect, and this can lead to problems or even crashes in wholly different parts of the program, making debugging a nightmare.</p>\n\n<p>I usually throw an exception in the if-statement to take over the role of the assert in case they are disabled </p>\n\n<pre><code>assert(value>0);\nif(value<=0) throw new ArgumentOutOfRangeException(\"value\");\n//do stuff\n</code></pre>\n"
},
{
"answer_id": 56178,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 1,
"selected": false,
"text": "<p>If I remember correctly from CS-class</p>\n\n<p>Preconditions define on what conditions the output of your function is defined. If you make your function handle errorconditions your function is defined for those condition and you don't need the assert statement.</p>\n\n<p>So I agree. Usually you don't need both.</p>\n\n<p>As Rik commented this can cause problems if you remove asserts in released code. Usually I don't do that except in performance-critical places.</p>\n"
},
{
"answer_id": 56179,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": -1,
"selected": false,
"text": "<p>A problem with assertions is that they can (and usually will) be compiled out of the code, so you need to add both walls in case one gets thrown away by the compiler.</p>\n"
},
{
"answer_id": 56189,
"author": "Andrew",
"author_id": 1389,
"author_profile": "https://Stackoverflow.com/users/1389",
"pm_score": 1,
"selected": false,
"text": "<p>Don't forget that most languages allow you to turn off assertions... Personally, if I was prepared to write if tests to protect against <strong>all</strong> ranges of invalid input, I wouldn't bother with the assertion in the first place.</p>\n\n<p>If, on the other hand you don't write logic to handle all cases (possibly because it's not sensible to try and continue with invalid input) then I would be using the assertion statement and going for the \"fail early\" approach.</p>\n"
},
{
"answer_id": 56192,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 0,
"selected": false,
"text": "<p>For internal functions, ones that only you will use, use <strong>asserts</strong> only. The asserts will help catch bugs during your testing, but won't hamper performance in production.</p>\n\n<p>Check inputs that originate externally with <strong>if-conditions</strong>. By externally, that's anywhere outside the code that you/your team control and test.</p>\n\n<p>Optionally, you can have <strong>both</strong>. This would be for external facing functions where integration testing is going to be done before production.</p>\n"
},
{
"answer_id": 56194,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>I would disagree with this statement:</p>\n\n<blockquote>\n <p>Only the caller knows what \"a valid\n input value\" is for your function, and\n he must check its validity before he\n calls your function.</p>\n</blockquote>\n\n<p>Caller might <em>think</em> that he know that input value is correct. Only method author knows how it suppose to work. Programmer's best goal is to make client to fall into \"<a href=\"http://blogs.msdn.com/brada/archive/2003/10/02/50420.aspx\" rel=\"nofollow noreferrer\">pit of success</a>\". You should decide what behavior is more appropriate in given case. In some cases incorrect input values can be forgivable, in other you should throw exception\\return error.</p>\n\n<p>As for Asserts, I'd repeat other commenters, assert is a <em>debug</em> time check for code author, not code clients.</p>\n"
},
{
"answer_id": 56243,
"author": "jan",
"author_id": 1163,
"author_profile": "https://Stackoverflow.com/users/1163",
"pm_score": 0,
"selected": false,
"text": "<p>I should have stated I was aware of the fact that asserts (here) dissappear in production code.</p>\n\n<p>If the if-statement actually corrects invalid input data in production code, this means the assert never went off during testing on debug code, this means you wrote code that you never executed.</p>\n\n<p>For me it's an OR situation:</p>\n\n<p>(quote Andrew) \"protect against all ranges of invalid input, I wouldn't bother with the assertion in the first place.\" -> write an if-test.</p>\n\n<p>(quote aku) \"incorrect input values can be forgivable\" -> write an assert.</p>\n\n<p>I can't <em>stand</em> both...</p>\n"
},
{
"answer_id": 56252,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 2,
"selected": false,
"text": "<p>Use assertions for validating input you control: private methods and such.</p>\n\n<p>Use if statements for validating input you don't control: public interfaces designed for consumption by the user, user input testing etc.</p>\n\n<p>Test you application with assertions built in. Then deploy without the assertions.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1163/"
] | The code in [this question](https://stackoverflow.com/questions/17181/test-cases-vs-assertion-statement) made me think
```
assert(value>0); //Precondition
if (value>0)
{
//Doit
}
```
I never write the if-statement. Asserting is enough/all you *can* do.
"Crash early, crash often"
[CodeComplete](https://rads.stackoverflow.com/amzn/click/com/0735619670) states:
* The assert-statement makes the application Correct
* The if-test makes the application Robust
I don't think you've made an application more robust by correcting invalid input values, or skipping code:
```
assert(value >= 0 ); //Precondition
assert(value <= 90); //Precondition
if(value < 0) //Just in case
value = 0;
if (value > 90) //Just in case
value = 90;
//Doit
```
These corrections are based on assumptions you made about the outside world.
Only the caller knows what "a valid input value" is for your function, and he must check its validity before he calls your function.
To paraphrase [CodeComplete](https://rads.stackoverflow.com/amzn/click/com/0735619670):
"Real-world programs *become* too messy when we *don't* rely solely on assertions."
Question: Am I wrong, stuborn, stupid, too non-defensive... | The problem with trusting just Asserts, is that they may be turned off in a production environment. To quote the wikipedia article:
>
> Most languages allow assertions to be
> enabled or disabled globally, and
> sometimes independently. Assertions
> are often enabled during development
> and disabled during final testing and
> on release to the customer. Not
> checking assertions avoiding the cost
> of evaluating the assertions while,
> assuming the assertions are free of
> side effects, still producing the same
> result under normal conditions. Under
> abnormal conditions, disabling
> assertion checking can mean that a
> program that would have aborted will
> continue to run. This is sometimes
> preferable.
> [Wikipedia](http://en.wikipedia.org/wiki/Assertion_(computing))
>
>
>
So if the correctness of your code relies on the Asserts to be there you may run into serious problems. Sure, if the code worked during testing it should work during production... Now enter the second guy that works on the code and is just going to fix a small problem... |
56,208 | <p>I've having trouble directly accessing the <strong>Win32_OperatingSystem</strong> management class that is exposed via WMI.</p>
<p>It is a singleton class, and I'm pretty certain "Win32_OperatingSystem=@" is the correct path syntax to get the instance of a singleton.</p>
<p>The call to InvokeMethod produces the exception listed at the bottom of the question, as does accessing the ClassPath property (commented line).</p>
<p>What am I doing wrong?</p>
<p>[I'm aware that I can use ManagementObjectSearcher/ObjectQuery to return a collection of Win32_OperatingSystem (which would contain only one), but since I know it is a singleton, I want to access it directly.]</p>
<hr>
<pre><code>ManagementScope cimv2 = InitScope(string.Format(@"\\{0}\root\cimv2", this.Name));
ManagementObject os = new ManagementObject(
cimv2,
new ManagementPath("Win32_OperatingSystem=@"),
new ObjectGetOptions());
//ManagementPath p = os.ClassPath;
os.InvokeMethod("Reboot", null);
</code></pre>
<hr>
<p>System.Management.ManagementException was caught
Message="Invalid object path "
Source="System.Management"
StackTrace:
at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
at System.Management.ManagementObject.Initialize(Boolean getObject)
at System.Management.ManagementBaseObject.get_wbemObject()
at System.Management.ManagementObject.get_ClassPath()
at System.Management.ManagementObject.GetMethodParameters(String methodName, ManagementBaseObject& inParameters, IWbemClassObjectFreeThreaded& inParametersClass, IWbemClassObjectFreeThreaded& outParametersClass)
at System.Management.ManagementObject.InvokeMethod(String methodName, Object[] args)</p>
<hr>
<p>Thanks for the replies.</p>
<p><strong>Nick</strong> - I don't know how to go about doing that :)</p>
<p><strong>Uros</strong> - I was under the impression that it was a singleton class because of <a href="http://msdn.microsoft.com/en-us/library/aa394239.aspx" rel="nofollow noreferrer">this</a> MSDN page. Also, opening the class in the WBEMTest utility shows <a href="http://img247.imageshack.us/img247/5686/64933271au3.png" rel="nofollow noreferrer">this</a>.</p>
<hr>
<p>The instances dialog shows: "1 objects" and "max. batch: 1" in those fields and lists "Win32_OperatingSystem=@"</p>
<p>The ManagementScope is verified as working, so I don't know what's up. I'm a WMI novice, but this seems like one of the simplest use cases!</p>
| [
{
"answer_id": 57808,
"author": "Nick Randell",
"author_id": 5932,
"author_profile": "https://Stackoverflow.com/users/5932",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not 100% sure of the answer, but have you tried using reflector to look at what ManagementObjectSearcher does? It may give you some clue as to what you are doing wrong.</p>\n"
},
{
"answer_id": 65735,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Win32_OperatingSystem is not a singleton class - if you check its qualifiers, you'll see that there is no Singleton qualifier defined for it, so you'll have to use ManagementObjectSearcher.Get() or ManagementClass.GetInstances() even though there is only one instance of the class. Win32_OperatingSystem key property is Name, so there is an option to get the instance directly, using </p>\n\n<pre><code>ManagementObject OS = new ManagementObject(@\"Win32_OperatingSystem.Name='OSname'\")\n</code></pre>\n\n<p>but in my experience, OSName is always something like:</p>\n\n<p>\"Microsoft Windows XP Professional|C:\\WINDOWS|\\Device\\Harddisk0\\Partition1\"</p>\n\n<p>so using ManagementObjectSearcher is probably the easiest solution.</p>\n"
},
{
"answer_id": 73199,
"author": "dcstraw",
"author_id": 10391,
"author_profile": "https://Stackoverflow.com/users/10391",
"pm_score": 1,
"selected": false,
"text": "<p>I would probably construct a query that gets the instance where Primary = true. I haven't used Win32_OperatingSystem in a while, but I seem to remember getting multiple instances, and the one that was currently booted had Primary equal to true.</p>\n"
},
{
"answer_id": 74863,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>Duncan wrote:</p>\n \n <p>The instances dialog shows: \"1 objects\" and \"max. batch: 1\" in those fields and >lists \"Win32_OperatingSystem=@\"</p>\n</blockquote>\n\n<p>It sure looks like it should work. You could test your code with another singleton class, like:</p>\n\n<p>\"Win32_WmiSetting=@\"</p>\n\n<p>and see if you still get the exception.</p>\n"
},
{
"answer_id": 90709,
"author": "Nick Randell",
"author_id": 5932,
"author_profile": "https://Stackoverflow.com/users/5932",
"pm_score": 2,
"selected": false,
"text": "<p>I've just tried this simple app that worked ok</p>\n\n<pre><code>using System;\nusing System.Management;\n\nnamespace WmiPlay\n{\n class Program\n {\n static void Main(string[] args)\n {\n try\n {\n ManagementScope cimv2 = new ManagementScope(@\"\\\\.\\root\\cimv2\");\n ManagementObject os = new ManagementObject(cimv2, new ManagementPath(\"Win32_OperatingSystem=@\"), new ObjectGetOptions());\n Console.Out.WriteLine(os);\n }\n catch (Exception ex)\n {\n Console.Error.WriteLine(ex);\n }\n }\n }\n}\n</code></pre>\n\n<p>See if this works for you? I did run it in Visual Studio which I normally run as administrator under Vista x64.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/82/"
] | I've having trouble directly accessing the **Win32\_OperatingSystem** management class that is exposed via WMI.
It is a singleton class, and I'm pretty certain "Win32\_OperatingSystem=@" is the correct path syntax to get the instance of a singleton.
The call to InvokeMethod produces the exception listed at the bottom of the question, as does accessing the ClassPath property (commented line).
What am I doing wrong?
[I'm aware that I can use ManagementObjectSearcher/ObjectQuery to return a collection of Win32\_OperatingSystem (which would contain only one), but since I know it is a singleton, I want to access it directly.]
---
```
ManagementScope cimv2 = InitScope(string.Format(@"\\{0}\root\cimv2", this.Name));
ManagementObject os = new ManagementObject(
cimv2,
new ManagementPath("Win32_OperatingSystem=@"),
new ObjectGetOptions());
//ManagementPath p = os.ClassPath;
os.InvokeMethod("Reboot", null);
```
---
System.Management.ManagementException was caught
Message="Invalid object path "
Source="System.Management"
StackTrace:
at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
at System.Management.ManagementObject.Initialize(Boolean getObject)
at System.Management.ManagementBaseObject.get\_wbemObject()
at System.Management.ManagementObject.get\_ClassPath()
at System.Management.ManagementObject.GetMethodParameters(String methodName, ManagementBaseObject& inParameters, IWbemClassObjectFreeThreaded& inParametersClass, IWbemClassObjectFreeThreaded& outParametersClass)
at System.Management.ManagementObject.InvokeMethod(String methodName, Object[] args)
---
Thanks for the replies.
**Nick** - I don't know how to go about doing that :)
**Uros** - I was under the impression that it was a singleton class because of [this](http://msdn.microsoft.com/en-us/library/aa394239.aspx) MSDN page. Also, opening the class in the WBEMTest utility shows [this](http://img247.imageshack.us/img247/5686/64933271au3.png).
---
The instances dialog shows: "1 objects" and "max. batch: 1" in those fields and lists "Win32\_OperatingSystem=@"
The ManagementScope is verified as working, so I don't know what's up. I'm a WMI novice, but this seems like one of the simplest use cases! | Win32\_OperatingSystem is not a singleton class - if you check its qualifiers, you'll see that there is no Singleton qualifier defined for it, so you'll have to use ManagementObjectSearcher.Get() or ManagementClass.GetInstances() even though there is only one instance of the class. Win32\_OperatingSystem key property is Name, so there is an option to get the instance directly, using
```
ManagementObject OS = new ManagementObject(@"Win32_OperatingSystem.Name='OSname'")
```
but in my experience, OSName is always something like:
"Microsoft Windows XP Professional|C:\WINDOWS|\Device\Harddisk0\Partition1"
so using ManagementObjectSearcher is probably the easiest solution. |
56,215 | <p>Not so long ago I was in an interview, that required solving two very interesting problems. I'm curious how would you approach the solutions.</p>
<p>Problem 1 :</p>
<p><strong>Product of everything except current</strong> </p>
<p>Write a function that takes as input two integer arrays of length len, input and index, and generates a third array, result, such that:
result[i] = product of everything in input except input[index[i]]</p>
<p>For instance, if the function is called with len=4, input={2,3,4,5}, and index={1,3,2,0}, then result will be set to {40,24,30,60}.</p>
<p>IMPORTANT: Your algorithm must run in linear time.</p>
<p>Problem 2 : ( the topic was in one of Jeff posts )</p>
<p><strong>Shuffle card deck evenly</strong></p>
<ol>
<li><p>Design (either in C++ or in C#) a class Deck to represent an ordered deck of cards, where a deck contains 52 cards, divided in 13 ranks (A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K) of the four suits: spades (?), hearts (?), diamonds (?) and clubs (?).</p></li>
<li><p>Based on this class, devise and implement an efficient algorithm to shuffle a deck of cards. The cards must be evenly shuffled, that is, every card in the original deck must have the same probability to end up in any possible position in the shuffled deck.
The algorithm should be implemented in a method shuffle() of the class Deck:
void shuffle()</p></li>
<li><p>What is the complexity of your algorithm (as a function of the number n of cards in the deck)?</p></li>
<li><p>Explain how you would test that the cards are evenly shuffled by your method (black box testing).</p></li>
</ol>
<p>P.S. I had two hours to code the solutions</p>
| [
{
"answer_id": 56225,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 1,
"selected": false,
"text": "<p>For the first one, first calculate the product of entire contents of input, and then for every element of index, divide the calculated product by input[index[i]], to fill in your result array.</p>\n\n<p>Of course I have to assume that the input has no zeros.</p>\n"
},
{
"answer_id": 56236,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Vaibhav, unfortunately we have to assume, that there could be a 0 in the input table.</p>\n"
},
{
"answer_id": 56270,
"author": "Tnilsson",
"author_id": 4165,
"author_profile": "https://Stackoverflow.com/users/4165",
"pm_score": 3,
"selected": false,
"text": "<p>First question: </p>\n\n<pre><code>int countZeroes (int[] vec) {\nint ret = 0;\nforeach(int i in vec) if (i == 0) ret++;\n\nreturn ret;\n}\n\nint[] mysticCalc(int[] values, int[] indexes) {\n int zeroes = countZeroes(values); \n int[] retval = new int[values.length];\n int product = 1;\n\n if (zeroes >= 2) { // 2 or more zeroes, all results will be 0\n for (int i = 0; i > values.length; i++) {\n retval[i] = 0; \n }\n return retval;\n }\n foreach (int i in values) {\n if (i != 0) product *= i; // we have at most 1 zero, dont include in product;\n }\n int indexcounter = 0;\n foreach(int idx in indexes) {\n if (zeroes == 1 && values[idx] != 0) { // One zero on other index. Our value will be 0\n retval[indexcounter] = 0;\n }\n else if (zeroes == 1) { // One zero on this index. result is product\n retval[indexcounter] = product;\n }\n else { // No zeros. Return product/value at index\n retval[indexcounter] = product / values[idx];\n }\n indexcouter++;\n } \n return retval;\n}\n</code></pre>\n\n<p>Worst case this program will step through 3 vectors once.</p>\n"
},
{
"answer_id": 56275,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 1,
"selected": false,
"text": "<h1>Product of everything except current in C</h1>\n\n<pre><code>void product_except_current(int input[], int index[], int out[], \n int len) {\n int prod = 1, nzeros = 0, izero = -1;\n\n for (int i = 0; i < len; ++i) \n if ((out[i] = input[index[i]]) != 0)\n // compute product of non-zero elements \n prod *= out[i]; // ignore possible overflow problem\n else {\n if (++nzeros == 2) \n // if number of zeros greater than 1 then out[i] = 0 for all i\n break; \n izero = i; // save index of zero-valued element\n }\n\n // \n for (int i = 0; i < len; ++i) \n out[i] = nzeros ? 0 : prod / out[i]; \n\n if (nzeros == 1)\n out[izero] = prod; // the only non-zero-valued element\n}\n</code></pre>\n"
},
{
"answer_id": 56280,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Tnilsson, great solution ( because I've done it the exact same way :P ).</p>\n\n<p>I don't see any other way to do it in linear time. Does anybody ? Because the recruiting manager told me, that this solution was not strong enough.</p>\n\n<p>Are we missing some super complex, do everything in one return line, solution ?</p>\n"
},
{
"answer_id": 56291,
"author": "Tnilsson",
"author_id": 4165,
"author_profile": "https://Stackoverflow.com/users/4165",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Second problem.</strong></p>\n\n<pre><code> public static void shuffle (int[] array) \n {\n Random rng = new Random(); // i.e., java.util.Random.\n int n = array.length; // The number of items left to shuffle (loop invariant).\n while (n > 1) \n {\n int k = rng.nextInt(n); // 0 <= k < n.\n n--; // n is now the last pertinent index;\n int temp = array[n]; // swap array[n] with array[k] (does nothing if k == n).\n array[n] = array[k];\n array[k] = temp;\n }\n }\n</code></pre>\n\n<p>This is a copy/paste from the wikipedia article about the <a href=\"http://en.wikipedia.org/wiki/Fisher-Yates_shuffle\" rel=\"nofollow noreferrer\">Fisher-Yates</a> shuffle. O(n) complexity</p>\n"
},
{
"answer_id": 56314,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Tnilsson, I agree that YXJuLnphcnQ solution is arguably faster, but the idee is the same. I forgot to add, that the language is optional in the first problem, as well as int the second.</p>\n\n<p>You're right, that calculationg zeroes, and the product int the same loop is better. Maybe that was the thing.</p>\n"
},
{
"answer_id": 56323,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Tnilsson, I've also uset the Fisher-Yates shuffle :). I'm very interested dough, about the testing part :)</p>\n"
},
{
"answer_id": 56379,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "<h1>Shuffle card deck evenly in C++</h1>\n\n<pre><code>#include <algorithm>\n\nclass Deck {\n // each card is 8-bit: 4-bit for suit, 4-bit for value\n // suits and values are extracted using bit-magic\n char cards[52];\n public:\n // ...\n void shuffle() {\n std::random_shuffle(cards, cards + 52);\n }\n // ...\n};\n</code></pre>\n\n<p>Complexity: Linear in N. Exactly 51 swaps are performed. See <a href=\"http://www.sgi.com/tech/stl/random_shuffle.html\" rel=\"nofollow noreferrer\">http://www.sgi.com/tech/stl/random_shuffle.html</a></p>\n\n<p><strong>Testing</strong>:</p>\n\n<pre><code> // ...\n int main() {\n typedef std::map<std::pair<size_t, Deck::value_type>, size_t> Map;\n Map freqs; \n Deck d;\n const size_t ntests = 100000;\n\n // compute frequencies of events: card at position\n for (size_t i = 0; i < ntests; ++i) {\n d.shuffle();\n size_t pos = 0;\n for(Deck::const_iterator j = d.begin(); j != d.end(); ++j, ++pos) \n ++freqs[std::make_pair(pos, *j)]; \n }\n\n // if Deck.shuffle() is correct then all frequencies must be similar\n for (Map::const_iterator j = freqs.begin(); j != freqs.end(); ++j)\n std::cout << \"pos=\" << j->first.first << \" card=\" << j->first.second \n << \" freq=\" << j->second << std::endl; \n }\n</code></pre>\n\n<p>As usual, one test is not sufficient.</p>\n"
},
{
"answer_id": 56482,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Trilsson made a separate topic about the testing part of the question</p>\n\n<p><a href=\"https://stackoverflow.com/questions/56411/how-to-test-randomness-case-in-point-shuffling\">How to test randomness (case in point - Shuffling)</a></p>\n\n<p>very good idea Trilsson:)</p>\n"
},
{
"answer_id": 56501,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>YXJuLnphcnQ, that's the way I did it too. It's the most obvious. </p>\n\n<p>But the fact is, that if you write an algorithm, that just shuffles all the cards in the collection one position to the right every time you call sort() it would pass the test, even though the output is not random.</p>\n"
},
{
"answer_id": 56549,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 1,
"selected": false,
"text": "<p>A linear-time solution in C#3 for the first problem is:-</p>\n\n<pre><code>IEnumerable<int> ProductExcept(List<int> l, List<int> indexes) {\n if (l.Count(i => i == 0) == 1) {\n int singleZeroProd = l.Aggregate(1, (x, y) => y != 0 ? x * y : x);\n return from i in indexes select l[i] == 0 ? singleZeroProd : 0;\n } else {\n int prod = l.Aggregate(1, (x, y) => x * y);\n return from i in indexes select prod == 0 ? 0 : prod / l[i];\n }\n}\n</code></pre>\n\n<p><strong>Edit:</strong> Took into account a single zero!! My last solution took me 2 minutes while I was at work so I don't feel so bad :-)</p>\n"
},
{
"answer_id": 56940,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 1,
"selected": false,
"text": "<p>Here's the answer to the second one in C# with a test method. Shuffle looks O(n) to me.</p>\n\n<p><strong>Edit:</strong> Having looked at the Fisher-Yates shuffle, I discovered that I'd re-invented that algorithm without knowing about it :-) it is obvious, however. I implemented the Durstenfeld approach which takes us from O(n^2) -> O(n), really clever!</p>\n\n<pre><code>public enum CardValue { A, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, J, Q, K }\npublic enum Suit { Spades, Hearts, Diamonds, Clubs }\n\npublic class Card {\n public Card(CardValue value, Suit suit) {\n Value = value;\n Suit = suit;\n }\n\n public CardValue Value { get; private set; }\n public Suit Suit { get; private set; }\n}\n\npublic class Deck : IEnumerable<Card> {\n public Deck() {\n initialiseDeck();\n Shuffle();\n }\n\n private Card[] cards = new Card[52];\n\n private void initialiseDeck() {\n for (int i = 0; i < 4; ++i) {\n for (int j = 0; j < 13; ++j) {\n cards[i * 13 + j] = new Card((CardValue)j, (Suit)i);\n }\n }\n }\n\n public void Shuffle() {\n Random random = new Random();\n\n for (int i = 0; i < 52; ++i) {\n int j = random.Next(51 - i);\n // Swap the cards.\n Card temp = cards[51 - i];\n cards[51 - i] = cards[j];\n cards[j] = temp;\n }\n }\n\n public IEnumerator<Card> GetEnumerator() {\n foreach (Card c in cards) yield return c;\n }\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {\n foreach (Card c in cards) yield return c;\n }\n}\n\nclass Program {\n static void Main(string[] args) {\n foreach (Card c in new Deck()) {\n Console.WriteLine(\"{0} of {1}\", c.Value, c.Suit);\n }\n\n Console.ReadKey(true);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 292078,
"author": "Darius Bacon",
"author_id": 27024,
"author_profile": "https://Stackoverflow.com/users/27024",
"pm_score": 1,
"selected": false,
"text": "<p>In Haskell:</p>\n\n<pre><code>import Array\n\nproblem1 input index = [(left!i) * (right!(i+1)) | i <- index]\n where left = scanWith scanl\n right = scanWith scanr\n scanWith scan = listArray (0, length input) (scan (*) 1 input)\n</code></pre>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Not so long ago I was in an interview, that required solving two very interesting problems. I'm curious how would you approach the solutions.
Problem 1 :
**Product of everything except current**
Write a function that takes as input two integer arrays of length len, input and index, and generates a third array, result, such that:
result[i] = product of everything in input except input[index[i]]
For instance, if the function is called with len=4, input={2,3,4,5}, and index={1,3,2,0}, then result will be set to {40,24,30,60}.
IMPORTANT: Your algorithm must run in linear time.
Problem 2 : ( the topic was in one of Jeff posts )
**Shuffle card deck evenly**
1. Design (either in C++ or in C#) a class Deck to represent an ordered deck of cards, where a deck contains 52 cards, divided in 13 ranks (A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K) of the four suits: spades (?), hearts (?), diamonds (?) and clubs (?).
2. Based on this class, devise and implement an efficient algorithm to shuffle a deck of cards. The cards must be evenly shuffled, that is, every card in the original deck must have the same probability to end up in any possible position in the shuffled deck.
The algorithm should be implemented in a method shuffle() of the class Deck:
void shuffle()
3. What is the complexity of your algorithm (as a function of the number n of cards in the deck)?
4. Explain how you would test that the cards are evenly shuffled by your method (black box testing).
P.S. I had two hours to code the solutions | First question:
```
int countZeroes (int[] vec) {
int ret = 0;
foreach(int i in vec) if (i == 0) ret++;
return ret;
}
int[] mysticCalc(int[] values, int[] indexes) {
int zeroes = countZeroes(values);
int[] retval = new int[values.length];
int product = 1;
if (zeroes >= 2) { // 2 or more zeroes, all results will be 0
for (int i = 0; i > values.length; i++) {
retval[i] = 0;
}
return retval;
}
foreach (int i in values) {
if (i != 0) product *= i; // we have at most 1 zero, dont include in product;
}
int indexcounter = 0;
foreach(int idx in indexes) {
if (zeroes == 1 && values[idx] != 0) { // One zero on other index. Our value will be 0
retval[indexcounter] = 0;
}
else if (zeroes == 1) { // One zero on this index. result is product
retval[indexcounter] = product;
}
else { // No zeros. Return product/value at index
retval[indexcounter] = product / values[idx];
}
indexcouter++;
}
return retval;
}
```
Worst case this program will step through 3 vectors once. |
56,227 | <p>I would like to start tagging my deployed binaries with the latest SVN revision number.</p>
<p>However, because SVN is file-based and not directory/project-based, I need to scan through all the directory's and subdirectory's files in order to determine the highest revision number.</p>
<p>Using <code>svn info</code> on the root doesn't work (it just reports the version of that directory, not files in subdirectories):</p>
<p>I was wondering if there is a shortcut using the <code>svn</code> command to do this. Otherwise, can anyone suggest a simple script that is network-efficient (I would prefer if it didn't hit the remote server at all)?</p>
<p>I also understand that one alternative approach is to keep a <em>version file</em> with the <code>svn:keywords</code>. This works (I've used it on other projects), but I get tired of dealing with making sure the file is dirty and dealing with the inevitable merge conflicts.</p>
<p><strong>Answer</strong> I see my problem lied with not doing a proper <code>svn up</code> before calling <code>svn info</code> in the root directory:</p>
<pre><code>$ svn info
Path: .
...
Last Changed Author: fak
Last Changed Rev: 713
Last Changed Date: 2008-08-29 00:40:53 +0300 (Fri, 29 Aug 2008)
$ svn up
At revision 721.
$ svn info
Path: .
...
Revision: 721
Last Changed Author: reuben
Last Changed Rev: 721
Last Changed Date: 2008-08-31 22:55:22 +0300 (Sun, 31 Aug 2008)
</code></pre>
| [
{
"answer_id": 56240,
"author": "Charles Miller",
"author_id": 3052,
"author_profile": "https://Stackoverflow.com/users/3052",
"pm_score": 6,
"selected": true,
"text": "<p>One way. When you check out the code, look at the last line of svn output:</p>\n\n<pre><code>$ svn up\n...stuff...\nUpdated to revision 66593.\n</code></pre>\n\n<p>A more direct way:</p>\n\n<pre><code>$ svn info\nPath: .\nURL: https://svn.example.com/svn/myproject/trunk\nRepository Root: https://svn.example.com/svn/\nRepository UUID: d2a7a951-c712-0410-832a-9abccabd3052\nRevision: 66593\nNode Kind: directory\nSchedule: normal\nLast Changed Author: bnguyen\nLast Changed Rev: 66591\nLast Changed Date: 2008-09-11 18:25:27 +1000 (Thu, 11 Sep 2008)\n</code></pre>\n"
},
{
"answer_id": 56241,
"author": "Troels Arvin",
"author_id": 4462,
"author_profile": "https://Stackoverflow.com/users/4462",
"pm_score": 1,
"selected": false,
"text": "<p>\"svn info\" will show you the working copy's revision number (see the \"Revision\" line in the output from \"svn info\"). Your build system probably allows you to place the relevant part of \"svn info\"'s output somewhere where it will be reflected in your application. For example, you may specify that when building, a temporary (un-versioned) file should be created, containing output from \"svn info\"; and you then include this file when compiling.</p>\n"
},
{
"answer_id": 56258,
"author": "jan",
"author_id": 1163,
"author_profile": "https://Stackoverflow.com/users/1163",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know if you are using MSBuild(Visual Studio) to build your binaries.\nBut if you would: \nthere is a connection possible between Subverion and MSBuild through\n<a href=\"http://msbuildtasks.tigris.org/\" rel=\"nofollow noreferrer\">MSBuild Community Tasks Project</a> </p>\n\n<p>Here's part of our build script: our (C#) application gets the svn revision number included:</p>\n\n<pre><code> <SvnVersion LocalPath=\"$(MSBuildProjectDirectory)\" ToolPath=\"installationpath\\of\\subversion\\bin\">\n <Output TaskParameter=\"Revision\" PropertyName=\"Revision\" />\n </SvnVersion>\n <Message Text=\"Version: $(Major).$(Minor).$(Build).$(Revision)\"/>\n...\n AssemblyVersion=\"$(Major).$(Minor).$(Build).$(Revision)\"\n AssemblyFileVersion=\"$(Major).$(Minor).$(Build).$(Revision)\"\n</code></pre>\n\n<p>Jan</p>\n"
},
{
"answer_id": 56267,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 2,
"selected": false,
"text": "<p>The answers provided by @Charles Miller and @Troels Arvin are correct - you can use the output of the <code>svn update</code> or <code>svn info</code>, but as you hint, the latter only works if the repository is up to date. Then again, I'm not sure what value <em>any</em> revision number is going to be to you if part of your source tree is on a different revision than another part. It really sounds to me like you should be working on a homogeneous tree.\nI'd suggest either updating before running info (or if you've already updated for your build, you're golden) or using <code>svn info URL-to-source</code>. </p>\n"
},
{
"answer_id": 249905,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"http://svnbook.red-bean.com/en/1.7/svn.ref.svnversion.re.html\" rel=\"noreferrer\"><code>svnversion</code></a> seems to be the cleanest way to do this:</p>\n\n<pre><code>svnversion -c /path/to/your-projects-local-working-copy/. | sed -e 's/[MS]//g' -e 's/^[[:digit:]]*://'\n</code></pre>\n\n<p>The above command will clean out any M and S letters (indicating local modifications or switchedness) from the output, as well as the smaller revision number in case <code>svnversion</code> returns a range instead of just one revision number (see <a href=\"http://svnbook.red-bean.com/en/1.1/re57.html\" rel=\"noreferrer\">the docs</a> for more info). If you don't want to filter the output, take out the pipe and the <code>sed</code> part of that command.</p>\n\n<p>If you want to use <code>svn info</code>, you need to use the \"recursive\" (<code>-R</code>) argument to get the info from all of the subdirectories as well. Since the output then becomes a long list, you'll need to do some filtering to get the last changed revision number from all of those that is the highest:</p>\n\n<pre><code>svn info -R /path/to/your-projects-local-working-copy/. | awk '/^Last Changed Rev:/ {print $NF}' | sort -n | tail -n 1\n</code></pre>\n\n<p>What that command does is that it takes all of the lines that include the string <code>\"Last Changed Rev\"</code>, then removes everything from each of those lines except the last field (i.e. the revision number), then sorts these lines numerically and removes everything but the last line, resulting in just the highest revision number. If you're running Windows, I'm sure you can do this quite easily in PowerShell as well, for example.</p>\n\n<p>Just to be clear: the above approaches get you the recursive last changed revision number of just the path in the repo that your local working copy represents, <em>for that local working copy,</em> without hitting the server. So if someone has updated something in this path onto the repository server after your last <code>svn update</code>, it won't be reflected in this output. </p>\n\n<p>If what you want is the last changed revision of this path <em>on the server</em>, you can do:</p>\n\n<pre><code>svn info /path/to/your-projects-local-working-copy/.@HEAD | awk '/^Last Changed Rev:/ {print $NF}'\n</code></pre>\n"
},
{
"answer_id": 250254,
"author": "Sam Stokes",
"author_id": 20131,
"author_profile": "https://Stackoverflow.com/users/20131",
"pm_score": 3,
"selected": false,
"text": "<p>Duplicate of <a href=\"https://stackoverflow.com/questions/110175/how-to-access-the-current-subversion-build-number#112674\">this question</a>. As I posted there, the <code>svnversion</code> command is your friend. No need to parse the output, no need to update first, just does the job.</p>\n"
},
{
"answer_id": 250258,
"author": "David",
"author_id": 26144,
"author_profile": "https://Stackoverflow.com/users/26144",
"pm_score": 2,
"selected": false,
"text": "<p>There is a program distributed with Subversion called <a href=\"http://svnbook.red-bean.com/en/1.1/re57.html\" rel=\"nofollow noreferrer\">svnversion</a> that does exactly what you want to do. It's how we tag our websites.</p>\n"
},
{
"answer_id": 13057020,
"author": "Daniel Sokolowski",
"author_id": 913223,
"author_profile": "https://Stackoverflow.com/users/913223",
"pm_score": 0,
"selected": false,
"text": "<p>This is ridiculous but <code>svn info</code> or <code>svnversion</code> wont take into consideration subdirectories; it's a feature called working 'Mixed Revisions' - I call it torture. I just needed to find the latest 'revision' of the live codebase and the hacked way below worked for me - it might take a while to run:</p>\n\n<pre><code>repo_root# find ./ | xargs -l svn info | grep 'Revision: ' | sort\n...\nRevision: 86\nRevision: 86\nRevision: 89\nRevision: 90\nroot@fairware:/home/stage_vancity#\n</code></pre>\n"
},
{
"answer_id": 14368458,
"author": "Maria Ananieva",
"author_id": 1985264,
"author_profile": "https://Stackoverflow.com/users/1985264",
"pm_score": 1,
"selected": false,
"text": "<p>For me the best way to find out the last revision number of the trunk/branch is to get it from the remote URL. It is important NOT to use the working dir because it may be obsolete. Here is a snippet with batch ( I hate a much ;-)):</p>\n\n<pre><code>@for /f \"tokens=4\" %%f in ('svn info %SVNURL% ^|find \"Last Changed Rev:\"') do set lastPathRev=%%f\n\necho trunk rev no: %lastPathRev%\n</code></pre>\n\n<p>Nevertheless I have a problem to hardcode this number as interim version into sources containing $Rev:$. The problem is that $Rev:$ contains the file rev. no. So if trunk rev no is larger then the rev no of version file, I need to modify this file \"artificially\" and to commit it to get the correct interim version (=trunk version). This is a pane! Does somebody has better idea? \nMany thanks</p>\n"
},
{
"answer_id": 34048048,
"author": "KymikoLoco",
"author_id": 2196304,
"author_profile": "https://Stackoverflow.com/users/2196304",
"pm_score": 2,
"selected": false,
"text": "<p>If you just want the revision number of the latest change that was committed, and are using Windows without grep/awk/xargs, here is the bare-bones command to run (command line):</p>\n\n<pre><code>X:\\trunk>svn info -r COMMITTED | for /F \"tokens=2\" %r in ('findstr /R \"^Revision\"') DO @echo %r\n67000\n</code></pre>\n\n<p><code>svn info -r COMMITTED</code> will give you the latest committed change to the directory you are currently in:</p>\n\n<pre><code>X:\\Trunk>svn info -r COMMITTED\nPath: trunk\nURL: https://svn.example.com/svn/myproject/trunk\nRepository Root: https://svn.example.com/svn/\nRepository UUID: d2a7a951-c712-0410-832a-9abccabd3052\nRevision: 67400\nNode Kind: directory\nLast Changed Author: example\nLast Changed Rev: 67400\nLast Changed Date: 2008-09-11 18:25:27 +1000 (Thu, 11 Sep 2008)\n</code></pre>\n\n<p>The for loop runs <code>findstr</code> to locate the Revision portion of the output from <code>svn info</code>. The output from this will be (you won't see this): </p>\n\n<pre><code>Revision: 67000\n</code></pre>\n\n<p>Which then splits the <a href=\"http://ss64.com/nt/for_cmd.html\" rel=\"nofollow\">tokens</a>, and returns the 2nd, to be <code>echo</code>ed out:</p>\n\n<pre><code>67000\n</code></pre>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338/"
] | I would like to start tagging my deployed binaries with the latest SVN revision number.
However, because SVN is file-based and not directory/project-based, I need to scan through all the directory's and subdirectory's files in order to determine the highest revision number.
Using `svn info` on the root doesn't work (it just reports the version of that directory, not files in subdirectories):
I was wondering if there is a shortcut using the `svn` command to do this. Otherwise, can anyone suggest a simple script that is network-efficient (I would prefer if it didn't hit the remote server at all)?
I also understand that one alternative approach is to keep a *version file* with the `svn:keywords`. This works (I've used it on other projects), but I get tired of dealing with making sure the file is dirty and dealing with the inevitable merge conflicts.
**Answer** I see my problem lied with not doing a proper `svn up` before calling `svn info` in the root directory:
```
$ svn info
Path: .
...
Last Changed Author: fak
Last Changed Rev: 713
Last Changed Date: 2008-08-29 00:40:53 +0300 (Fri, 29 Aug 2008)
$ svn up
At revision 721.
$ svn info
Path: .
...
Revision: 721
Last Changed Author: reuben
Last Changed Rev: 721
Last Changed Date: 2008-08-31 22:55:22 +0300 (Sun, 31 Aug 2008)
``` | One way. When you check out the code, look at the last line of svn output:
```
$ svn up
...stuff...
Updated to revision 66593.
```
A more direct way:
```
$ svn info
Path: .
URL: https://svn.example.com/svn/myproject/trunk
Repository Root: https://svn.example.com/svn/
Repository UUID: d2a7a951-c712-0410-832a-9abccabd3052
Revision: 66593
Node Kind: directory
Schedule: normal
Last Changed Author: bnguyen
Last Changed Rev: 66591
Last Changed Date: 2008-09-11 18:25:27 +1000 (Thu, 11 Sep 2008)
``` |
56,229 | <p>I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?</p>
<p>This is similar to what I'm actually doing:</p>
<pre><code>import xml.etree.ElementTree as ET
root = ET.Element('html')
head = ET.SubElement(root,'head')
script = ET.SubElement(head,'script')
script.set('type','text/javascript')
script.text = "var a = 'I love &aacute; letters'"
body = ET.SubElement(root,'body')
h1 = ET.SubElement(body,'h1')
h1.text = "And I like the fact that 3 > 1"
tree = ET.ElementTree(root)
tree.write('foo.xhtml')
# more foo.xhtml
<html><head><script type="text/javascript">var a = 'I love &amp;aacute;
letters'</script></head><body><h1>And I like the fact that 3 &gt; 1</h1>
</body></html>
</code></pre>
| [
{
"answer_id": 56262,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 2,
"selected": false,
"text": "<p>don't you actually want something like:</p>\n\n<pre><code>html(head(script(type='text/javascript', content='var a = ...')),\nbody(h1('And I like the fact that 3 < 1'), p('just some paragraph'))\n</code></pre>\n\n<p>I think I saw something like that somewhere. This would be wonderful.</p>\n\n<p><strong>EDIT:</strong> Actually, I went and wrote a library today to do <em>just that</em>: <a href=\"http://pypi.python.org/pypi/magictree\" rel=\"nofollow noreferrer\">magictree</a></p>\n\n<p>You can use it like this:</p>\n\n<pre><code>from magictree import html, head, script, body, h1, p\nroot = html(\n head(\n script('''var a = 'I love &amp;aacute; letters''', \n type='text/javascript')),\n body(\n h1('And I like the fact that 3 > 1')))\n\n# root is a plain Element object, like those created with ET.Element...\n# so you can write it out using ElementTree :)\ntree = ET.ElementTree(root)\ntree.write('foo.xhtml')\n</code></pre>\n\n<p>The magic in <code>magictree</code> lies in how the importing works: The <code>Element</code> factories are created when needed. Have a <a href=\"http://code.google.com/p/pymagictree/source/browse/trunk/magictree.py\" rel=\"nofollow noreferrer\">look at the source</a>, it is <a href=\"https://stackoverflow.com/questions/2447353/getattr-on-a-module\">based on an answer to another StackOverflow question</a>.</p>\n"
},
{
"answer_id": 56269,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 5,
"selected": false,
"text": "<p>Another way is using the <a href=\"http://codespeak.net/lxml/tutorial.html#the-e-factory\" rel=\"nofollow noreferrer\">E Factory</a> builder from lxml (available in <a href=\"http://effbot.org/zone/element-builder.htm\" rel=\"nofollow noreferrer\">Elementtree</a> too)</p>\n\n<pre><code>>>> from lxml import etree\n\n>>> from lxml.builder import E\n\n>>> def CLASS(*args): # class is a reserved word in Python\n... return {\"class\":' '.join(args)}\n\n>>> html = page = (\n... E.html( # create an Element called \"html\"\n... E.head(\n... E.title(\"This is a sample document\")\n... ),\n... E.body(\n... E.h1(\"Hello!\", CLASS(\"title\")),\n... E.p(\"This is a paragraph with \", E.b(\"bold\"), \" text in it!\"),\n... E.p(\"This is another paragraph, with a\", \"\\n \",\n... E.a(\"link\", href=\"http://www.python.org\"), \".\"),\n... E.p(\"Here are some reserved characters: <spam&egg>.\"),\n... etree.XML(\"<p>And finally an embedded XHTML fragment.</p>\"),\n... )\n... )\n... )\n\n>>> print(etree.tostring(page, pretty_print=True))\n<html>\n <head>\n <title>This is a sample document</title>\n </head>\n <body>\n <h1 class=\"title\">Hello!</h1>\n <p>This is a paragraph with <b>bold</b> text in it!</p>\n <p>This is another paragraph, with a\n <a href=\"http://www.python.org\">link</a>.</p>\n <p>Here are some reservered characters: &lt;spam&amp;egg&gt;.</p>\n <p>And finally an embedded XHTML fragment.</p>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 56470,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 4,
"selected": true,
"text": "<p>I assume that you're actually creating an XML DOM tree, because you want to validate that what goes into this file is valid XML, since otherwise you'd just write a static string to a file. If validating your output is indeed your goal, then I'd suggest</p>\n\n<pre><code>from xml.dom.minidom import parseString\n\ndoc = parseString(\"\"\"<html>\n <head>\n <script type=\"text/javascript\">\n var a = 'I love &amp;aacute; letters'\n </script>\n </head>\n <body>\n <h1>And I like the fact that 3 &gt; 1</h1>\n </body>\n </html>\"\"\")\n\nwith open(\"foo.xhtml\", \"w\") as f:\n f.write( doc.toxml() )\n</code></pre>\n\n<p>This lets you just write the XML you want to output, validate that it's correct (since parseString will raise an exception if it's invalid) and have your code look much nicer.</p>\n\n<p>Presumably you're not just writing the same static XML every time and want some substitution. In this case I'd have lines like</p>\n\n<pre><code>var a = '%(message)s'\n</code></pre>\n\n<p>and then use the % operator to do the substitution, like</p>\n\n<pre><code></html>\"\"\" % {\"message\": \"I love &amp;aacute; letters\"})\n</code></pre>\n"
},
{
"answer_id": 58460,
"author": "DaveP",
"author_id": 3577,
"author_profile": "https://Stackoverflow.com/users/3577",
"pm_score": 0,
"selected": false,
"text": "<p>Try <a href=\"http://uche.ogbuji.net/tech/4suite/amara\" rel=\"nofollow noreferrer\">http://uche.ogbuji.net/tech/4suite/amara</a>. It is quite complete and has a straight forward set of access tools. Normal Unicode support, etc. </p>\n\n<pre><code>#\n#Output the XML entry\n#\ndef genFileOLD(out,label,term,idval):\n filename=entryTime() + \".html\"\n writer=MarkupWriter(out, indent=u\"yes\")\n writer.startDocument()\n #Test element and attribute writing\n ans=namespace=u'http://www.w3.org/2005/Atom'\n xns=namespace=u'http://www.w3.org/1999/xhtml'\n writer.startElement(u'entry',\n ans,\n extraNss={u'x':u'http://www.w3.org/1999/xhtml' ,\n u'dc':u'http://purl.org/dc/elements/1.1'})\n #u'a':u'http://www.w3.org/2005/Atom',\n #writer.attribute(u'xml:lang',unicode(\"en-UK\"))\n\n writer.simpleElement(u'title',ans,content=unicode(label))\n #writer.simpleElement(u'a:subtitle',ans,content=u' ')\n id=unicode(\"http://www.dpawson.co.uk/nodesets/\"+afn.split(\".\")[0])\n writer.simpleElement(u'id',ans,content=id)\n writer.simpleElement(u'updated',ans,content=unicode(dtime()))\n writer.startElement(u'author',ans)\n writer.simpleElement(u'name',ans,content=u'Dave ')\n writer.simpleElement(u'uri',ans,\n content=u'http://www.dpawson.co.uk/nodesets/'+afn+\".xml\")\n writer.endElement(u'author')\n writer.startElement(u'category', ans)\n if (prompt):\n label=unicode(raw_input(\"Enter label \"))\n writer.attribute(u'label',unicode(label))\n if (prompt):\n term = unicode(raw_input(\"Enter term to use \"))\n writer.attribute(u'term', unicode(term))\n writer.endElement(u'category')\n writer.simpleElement(u'rights',ans,content=u'\\u00A9 Dave 2005-2008')\n writer.startElement(u'link',ans)\n writer.attribute(u'href',\n unicode(\"http://www.dpawson.co.uk/nodesets/entries/\"+afn+\".html\"))\n writer.attribute(u'rel',unicode(\"alternate\"))\n writer.endElement(u'link')\n writer.startElement(u'published', ans)\n dt=dtime()\n dtu=unicode(dt)\n writer.text(dtu)\n writer.endElement(u'published')\n writer.simpleElement(u'summary',ans,content=unicode(label))\n writer.startElement(u'content',ans)\n writer.attribute(u'type',unicode(\"xhtml\"))\n writer.startElement(u'div',xns)\n writer.simpleElement(u'h3',xns,content=unicode(label))\n writer.endElement(u'div')\n writer.endElement(u'content')\n writer.endElement(u'entry')\n</code></pre>\n"
},
{
"answer_id": 62157,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>I ended up using saxutils.escape(str) to generate valid XML strings and then validating it with Eli's approach to be sure I didn't miss any tag</p>\n\n<pre><code>from xml.sax import saxutils\nfrom xml.dom.minidom import parseString\nfrom xml.parsers.expat import ExpatError\n\nxml = '''<?xml version=\"1.0\" encoding=\"%s\"?>\\n\n<contents title=\"%s\" crawl_date=\"%s\" in_text_date=\"%s\" \nurl=\"%s\">\\n<main_post>%s</main_post>\\n</contents>''' %\n(self.encoding, saxutils.escape(title), saxutils.escape(time), \nsaxutils.escape(date), saxutils.escape(url), saxutils.escape(contents))\ntry:\n minidoc = parseString(xml)\ncatch ExpatError:\n print \"Invalid xml\"\n</code></pre>\n"
},
{
"answer_id": 3098902,
"author": "oasisbob",
"author_id": 335903,
"author_profile": "https://Stackoverflow.com/users/335903",
"pm_score": 5,
"selected": false,
"text": "<p>There's always <a href=\"http://effbot.org/zone/xml-writer.htm\" rel=\"noreferrer\">SimpleXMLWriter</a>, part of the ElementTree toolkit. The interface is dead simple.</p>\n\n<p>Here's an example: </p>\n\n<pre><code>from elementtree.SimpleXMLWriter import XMLWriter\nimport sys\n\nw = XMLWriter(sys.stdout)\nhtml = w.start(\"html\")\n\nw.start(\"head\")\nw.element(\"title\", \"my document\")\nw.element(\"meta\", name=\"generator\", value=\"my application 1.0\")\nw.end()\n\nw.start(\"body\")\nw.element(\"h1\", \"this is a heading\")\nw.element(\"p\", \"this is a paragraph\")\n\nw.start(\"p\")\nw.data(\"this is \")\nw.element(\"b\", \"bold\")\nw.data(\" and \")\nw.element(\"i\", \"italic\")\nw.data(\".\")\nw.end(\"p\")\n\nw.close(html)\n</code></pre>\n"
},
{
"answer_id": 7060046,
"author": "Mikhail Korobov",
"author_id": 114795,
"author_profile": "https://Stackoverflow.com/users/114795",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://github.com/galvez/xmlwitch\">https://github.com/galvez/xmlwitch</a>:</p>\n\n<pre><code>import xmlwitch\nxml = xmlwitch.Builder(version='1.0', encoding='utf-8')\nwith xml.feed(xmlns='http://www.w3.org/2005/Atom'):\n xml.title('Example Feed')\n xml.updated('2003-12-13T18:30:02Z')\n with xml.author:\n xml.name('John Doe')\n xml.id('urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6')\n with xml.entry:\n xml.title('Atom-Powered Robots Run Amok')\n xml.id('urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a')\n xml.updated('2003-12-13T18:30:02Z')\n xml.summary('Some text.')\nprint(xml)\n</code></pre>\n"
},
{
"answer_id": 19728898,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 2,
"selected": false,
"text": "<p>For anyone encountering this now, there's actually a way to do this hidden away in Python's standard library in <a href=\"http://docs.python.org/2.7/library/xml.sax.utils.html\" rel=\"nofollow\">xml.sax.utils.XMLGenerator</a>. Here's an example of it in action:</p>\n\n<pre><code>>>> from xml.sax.saxutils import XMLGenerator\n>>> import StringIO\n>>> w = XMLGenerator(out, 'utf-8')\n>>> w.startDocument()\n>>> w.startElement(\"test\", {'bar': 'baz'})\n>>> w.characters(\"Foo\")\n>>> w.endElement(\"test\")\n>>> w.endDocument()\n>>> print out.getvalue()\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<test bar=\"baz\">Foo</test>\n</code></pre>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
] | I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of?
This is similar to what I'm actually doing:
```
import xml.etree.ElementTree as ET
root = ET.Element('html')
head = ET.SubElement(root,'head')
script = ET.SubElement(head,'script')
script.set('type','text/javascript')
script.text = "var a = 'I love á letters'"
body = ET.SubElement(root,'body')
h1 = ET.SubElement(body,'h1')
h1.text = "And I like the fact that 3 > 1"
tree = ET.ElementTree(root)
tree.write('foo.xhtml')
# more foo.xhtml
<html><head><script type="text/javascript">var a = 'I love &aacute;
letters'</script></head><body><h1>And I like the fact that 3 > 1</h1>
</body></html>
``` | I assume that you're actually creating an XML DOM tree, because you want to validate that what goes into this file is valid XML, since otherwise you'd just write a static string to a file. If validating your output is indeed your goal, then I'd suggest
```
from xml.dom.minidom import parseString
doc = parseString("""<html>
<head>
<script type="text/javascript">
var a = 'I love &aacute; letters'
</script>
</head>
<body>
<h1>And I like the fact that 3 > 1</h1>
</body>
</html>""")
with open("foo.xhtml", "w") as f:
f.write( doc.toxml() )
```
This lets you just write the XML you want to output, validate that it's correct (since parseString will raise an exception if it's invalid) and have your code look much nicer.
Presumably you're not just writing the same static XML every time and want some substitution. In this case I'd have lines like
```
var a = '%(message)s'
```
and then use the % operator to do the substitution, like
```
</html>""" % {"message": "I love &aacute; letters"})
``` |
56,249 | <p>From what I've seen the tag is ignored when hosting a WCF service in IIS. I understand that when self-hosting this is required but is this harmful or even used when operating under IIS?</p>
<p>ex.</p>
<pre><code><system.serviceModel>
<service blah blah blah>
<host>
<baseAddresses>
<add baseAddress="http://localhost/blah" />
</baseAddresses>
</host>
</service>
</system.serviceModel>
</code></pre>
<p>From what I've seen you can take a config file describing a service from one machine and use that on a completely different machine and it works fine. It looks as if IIS completely ignores this section.</p>
<p>Thanks,
kyle</p>
| [
{
"answer_id": 56286,
"author": "Paul Lalonde",
"author_id": 5782,
"author_profile": "https://Stackoverflow.com/users/5782",
"pm_score": 6,
"selected": true,
"text": "<p>As you have guessed, the baseAddresses element is completely ignored when hosting in IIS. The service's base address is determined by the web site & virtual directory into which your wcf service is placed.</p>\n\n<p>Even when self-hosting, baseAddresses is not required. It is merely a convenience that avoids you having to enter a full address for each endpoint. If it is present, the endpoints can have relative addresses (relative to the base address, that is).</p>\n"
},
{
"answer_id": 7846836,
"author": "0cool",
"author_id": 228718,
"author_profile": "https://Stackoverflow.com/users/228718",
"pm_score": 2,
"selected": false,
"text": "<p>base address required for selfhosting. IIS/WAS hosts ignores the base address.</p>\n"
},
{
"answer_id": 20620577,
"author": "CodeCowboyOrg",
"author_id": 3099743,
"author_profile": "https://Stackoverflow.com/users/3099743",
"pm_score": 2,
"selected": false,
"text": "<p>According to the MSDN Microsoft documentation in the below link, midway through the page in the Note section states, \"Services hosted under Internet Information Services (IIS) or Windows Process Activation Service (WAS) use the virtual directory as their base address.\"</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ee358768(v=vs.110).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ee358768(v=vs.110).aspx</a></p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5772/"
] | From what I've seen the tag is ignored when hosting a WCF service in IIS. I understand that when self-hosting this is required but is this harmful or even used when operating under IIS?
ex.
```
<system.serviceModel>
<service blah blah blah>
<host>
<baseAddresses>
<add baseAddress="http://localhost/blah" />
</baseAddresses>
</host>
</service>
</system.serviceModel>
```
From what I've seen you can take a config file describing a service from one machine and use that on a completely different machine and it works fine. It looks as if IIS completely ignores this section.
Thanks,
kyle | As you have guessed, the baseAddresses element is completely ignored when hosting in IIS. The service's base address is determined by the web site & virtual directory into which your wcf service is placed.
Even when self-hosting, baseAddresses is not required. It is merely a convenience that avoids you having to enter a full address for each endpoint. If it is present, the endpoints can have relative addresses (relative to the base address, that is). |
56,271 | <p>I am using Forms authentication in my asp.net (3.5) application. I am also using roles to define what user can access which subdirectories of the app. Thus, the pertinent sections of my web.config file look like this:</p>
<pre><code><system.web>
<authentication mode="Forms">
<forms loginUrl="Default.aspx" path="/" protection="All" timeout="360" name="MyAppName" cookieless="UseCookies" />
</authentication>
<authorization >
<allow users="*"/>
</authorization>
</system.web>
<location path="Admin">
<system.web>
<authorization>
<allow roles="Admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
</code></pre>
<p>Based on what I have read, this should ensure that the only users able to access the Admin directory will be users who have been Authenticated and assigned the Admin role.</p>
<p>User authentication, saving the authentication ticket, and other related issues all work fine. If I remove the tags from the web.config file, everything works fine. The problem comes when I try to enforce that only users with the Admin role should be able to access the Admin directory.</p>
<p>Based on this <a href="http://support.microsoft.com/kb/311495" rel="nofollow noreferrer">MS KB article</a> along with other webpages giving the same information, I have added the following code to my Global.asax file:</p>
<pre><code>protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
if (HttpContext.Current.User != null) {
if (Request.IsAuthenticated == true) {
// Debug#1
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
// In this case, ticket.UserData = "Admin"
string[] roles = new string[1] { ticket.UserData };
FormsIdentity id = new FormsIdentity(ticket);
Context.User = new System.Security.Principal.GenericPrincipal(id, roles);
// Debug#2
}
}
}
</code></pre>
<p>However, when I try to log in, I am unable to access the Admin folder (get redirected to login page). </p>
<p>Trying to debug the issue, if I step through a request, if I execute Context.User.IsInRole("Admin") at the line marked Debug#1 above, it returns a false. If I execute the same statement at line Debug#2, it equals true. So at least as far as Global.asax is concerned, the Role is being assigned properly.</p>
<p>After Global.asax, execution jumps right to the Login page (since the lack of role causes the page load in the admin folder to be rejected). However, when I execute the same statement on the first line of Page_Load of the login, it returns false. So somewhere after Application_AuthenticateRequest in Global.asax and the initial load of the WebForm in the restricted directory, the role information is being lost, causing authentication to fail (note: in Page_Load, the proper Authentication ticket is still assigned to Context.User.Id - only the role is being lost).</p>
<p>What am I doing wrong, and how can I get it to work properly?</p>
<hr>
<p><strong>Update: I entered the <a href="https://stackoverflow.com/questions/56271/contextuser-losing-roles-after-being-assigned-in-globalasaxapplicationauthentic#57040">solution below</a></strong></p>
| [
{
"answer_id": 56506,
"author": "Jordan H.",
"author_id": 1540,
"author_profile": "https://Stackoverflow.com/users/1540",
"pm_score": 0,
"selected": false,
"text": "<p>this is just a random shot, but are you getting blocked because of the order of authorization for Admin? Maybe you should try switching your deny all and your all Admin.</p>\n\n<p>Just in case it's getting overwritten by the deny.</p>\n\n<p>(I had code samples in here but they weren't showing up.</p>\n"
},
{
"answer_id": 57040,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 4,
"selected": true,
"text": "<p><strong>Here was the problem and solution</strong>: </p>\n\n<p>Earlier in development I had gone to the Website menu and clicked on Asp.net configuration. This resulted in the following line being added to the web.config: </p>\n\n<pre><code><system.web>\n <roleManager enabled=\"true\" />\n</system.web>\n</code></pre>\n\n<p>From that point on, the app was assuming that I was doing roles through the Asp.net site manager, and not through FormsAuthentication roles. Thus the repeated failures, despite the fact that the actual authentication and roles logic was set up correctly.</p>\n\n<p>After this line was removed from web.config everything worked perfectly.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51/"
] | I am using Forms authentication in my asp.net (3.5) application. I am also using roles to define what user can access which subdirectories of the app. Thus, the pertinent sections of my web.config file look like this:
```
<system.web>
<authentication mode="Forms">
<forms loginUrl="Default.aspx" path="/" protection="All" timeout="360" name="MyAppName" cookieless="UseCookies" />
</authentication>
<authorization >
<allow users="*"/>
</authorization>
</system.web>
<location path="Admin">
<system.web>
<authorization>
<allow roles="Admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
```
Based on what I have read, this should ensure that the only users able to access the Admin directory will be users who have been Authenticated and assigned the Admin role.
User authentication, saving the authentication ticket, and other related issues all work fine. If I remove the tags from the web.config file, everything works fine. The problem comes when I try to enforce that only users with the Admin role should be able to access the Admin directory.
Based on this [MS KB article](http://support.microsoft.com/kb/311495) along with other webpages giving the same information, I have added the following code to my Global.asax file:
```
protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
if (HttpContext.Current.User != null) {
if (Request.IsAuthenticated == true) {
// Debug#1
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
// In this case, ticket.UserData = "Admin"
string[] roles = new string[1] { ticket.UserData };
FormsIdentity id = new FormsIdentity(ticket);
Context.User = new System.Security.Principal.GenericPrincipal(id, roles);
// Debug#2
}
}
}
```
However, when I try to log in, I am unable to access the Admin folder (get redirected to login page).
Trying to debug the issue, if I step through a request, if I execute Context.User.IsInRole("Admin") at the line marked Debug#1 above, it returns a false. If I execute the same statement at line Debug#2, it equals true. So at least as far as Global.asax is concerned, the Role is being assigned properly.
After Global.asax, execution jumps right to the Login page (since the lack of role causes the page load in the admin folder to be rejected). However, when I execute the same statement on the first line of Page\_Load of the login, it returns false. So somewhere after Application\_AuthenticateRequest in Global.asax and the initial load of the WebForm in the restricted directory, the role information is being lost, causing authentication to fail (note: in Page\_Load, the proper Authentication ticket is still assigned to Context.User.Id - only the role is being lost).
What am I doing wrong, and how can I get it to work properly?
---
**Update: I entered the [solution below](https://stackoverflow.com/questions/56271/contextuser-losing-roles-after-being-assigned-in-globalasaxapplicationauthentic#57040)** | **Here was the problem and solution**:
Earlier in development I had gone to the Website menu and clicked on Asp.net configuration. This resulted in the following line being added to the web.config:
```
<system.web>
<roleManager enabled="true" />
</system.web>
```
From that point on, the app was assuming that I was doing roles through the Asp.net site manager, and not through FormsAuthentication roles. Thus the repeated failures, despite the fact that the actual authentication and roles logic was set up correctly.
After this line was removed from web.config everything worked perfectly. |
56,303 | <p>I need to specify a date value in a sybase where clause. For example:</p>
<pre><code>select *
from data
where dateVal < [THE DATE]
</code></pre>
| [
{
"answer_id": 56310,
"author": "cmsherratt",
"author_id": 3512,
"author_profile": "https://Stackoverflow.com/users/3512",
"pm_score": 5,
"selected": false,
"text": "<p>Use the convert function, for example:</p>\n\n<pre><code>select * from data \nwhere dateVal < convert(datetime, '01/01/2008', 103)\n</code></pre>\n\n<p>Where the convert style (103) determines the date format to use.</p>\n"
},
{
"answer_id": 74525,
"author": "Jose B.",
"author_id": 5413,
"author_profile": "https://Stackoverflow.com/users/5413",
"pm_score": 2,
"selected": false,
"text": "<p>Several ways to accomplish that but be aware that your DB <strong>date_format option</strong> & <strong>date_order option</strong> settings could affect the incoming format:</p>\n\n<pre><code>Select \n cast('2008-09-16' as date)\n convert(date,'16/09/2008',103)\n date('2008-09-16')\nfrom dummy;\n</code></pre>\n"
},
{
"answer_id": 826535,
"author": "Edwin",
"author_id": 99363,
"author_profile": "https://Stackoverflow.com/users/99363",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a good reference on the different formatting you can use with regard to the date:</p>\n\n<p><a href=\"http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc38151.1510/html/iqrefbb/Convert.htm\" rel=\"nofollow noreferrer\">http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc38151.1510/html/iqrefbb/Convert.htm</a></p>\n"
},
{
"answer_id": 9204851,
"author": "Jackie",
"author_id": 410289,
"author_profile": "https://Stackoverflow.com/users/410289",
"pm_score": -1,
"selected": false,
"text": "<p>102 is the rule of thumb,\nconvert (varchar, creat_tms, 102) > '2011'</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3512/"
] | I need to specify a date value in a sybase where clause. For example:
```
select *
from data
where dateVal < [THE DATE]
``` | Use the convert function, for example:
```
select * from data
where dateVal < convert(datetime, '01/01/2008', 103)
```
Where the convert style (103) determines the date format to use. |
56,324 | <p>I have a little routine that's run under Linux and Windows written in C and displays output on the console. I'm not linking in any form of curses or anything like that.</p>
<p>Currently I clear the screen using</p>
<pre><code>#ifdef __WIN32
system( "cls" );
#else
system( "clear" );
#endif
</code></pre>
<p>Then I have a bunch of printf statements to update the status. What I'd like just reset the screenpointer to 0,0 so I can then just overlay my printfs. I'd rather avoid compiling in any more extensions especially since I'm coding for 2 different OS'.</p>
| [
{
"answer_id": 56335,
"author": "Paul Hargreaves",
"author_id": 5330,
"author_profile": "https://Stackoverflow.com/users/5330",
"pm_score": 1,
"selected": true,
"text": "<p>Looks like I may have found a windows specific way of doing it <a href=\"http://msdn.microsoft.com/en-us/library/ms686025(VS.85).aspx\" rel=\"nofollow noreferrer\">SetConsoleCursorPosition</a></p>\n\n<p>Ansi escape sequence \\033[0;0H for Linux - just printf that to the console.</p>\n"
},
{
"answer_id": 56348,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "<p>For Unix-like platforms, the usual way to do this is using the <a href=\"http://en.wikipedia.org/wiki/Curses_(programming_library)\" rel=\"nofollow noreferrer\">curses</a> library.</p>\n"
},
{
"answer_id": 98562,
"author": "wnoise",
"author_id": 15464,
"author_profile": "https://Stackoverflow.com/users/15464",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, for unix platforms, curses (or ncurses, these days) is the way to go. And there are versions that work under windows, so you could do it the same way on both systems.</p>\n"
},
{
"answer_id": 425208,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": 0,
"selected": false,
"text": "<p>For windows - You can use ANSI escape characters. </p>\n\n<p><a href=\"http://www.lexipixel.com/news/star_dot_star/using_ansi_escape_sequences.htm\" rel=\"nofollow noreferrer\">http://www.lexipixel.com/news/star_dot_star/using_ansi_escape_sequences.htm</a> </p>\n\n<p><a href=\"http://www.robvanderwoude.com/ansi.html\" rel=\"nofollow noreferrer\">http://www.robvanderwoude.com/ansi.html</a> </p>\n\n<pre><code>printf \"\\x[0;0H\"\n</code></pre>\n\n<p>It used to be that Ansi.sys needed to be loaded before you could do this, but it's worth a shot. </p>\n\n<p>Instructions for adding ANSI support \n<a href=\"http://www.windowsnetworking.com/kbase/WindowsTips/WindowsXP/UserTips/CommandPrompt/CommandInterpreterAnsiSupport.html\" rel=\"nofollow noreferrer\">http://www.windowsnetworking.com/kbase/WindowsTips/WindowsXP/UserTips/CommandPrompt/CommandInterpreterAnsiSupport.html</a>\nNote: that Ansi.sys only works under command.com. You can't use it with cmd.exe</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5330/"
] | I have a little routine that's run under Linux and Windows written in C and displays output on the console. I'm not linking in any form of curses or anything like that.
Currently I clear the screen using
```
#ifdef __WIN32
system( "cls" );
#else
system( "clear" );
#endif
```
Then I have a bunch of printf statements to update the status. What I'd like just reset the screenpointer to 0,0 so I can then just overlay my printfs. I'd rather avoid compiling in any more extensions especially since I'm coding for 2 different OS'. | Looks like I may have found a windows specific way of doing it [SetConsoleCursorPosition](http://msdn.microsoft.com/en-us/library/ms686025(VS.85).aspx)
Ansi escape sequence \033[0;0H for Linux - just printf that to the console. |
56,334 | <p>Suppose that two tables exist: <code>users</code> and <code>groups</code>.</p>
<p><strong>How does one provide "simple search" in which a user enters text and results contain both users and groups whose names contain the text?</strong></p>
<p>The result of the search must distinguish between the two types.</p>
| [
{
"answer_id": 56336,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 3,
"selected": true,
"text": "<p>The trick is to combine a <code>UNION</code> with a literal string to determine the type of 'object' returned. In most (?) cases, UNION ALL will be more efficient, and should be used unless duplicates are required in the sub-queries. The following pattern should suffice:</p>\n\n<pre><code> SELECT \"group\" type, name\n FROM groups\n WHERE name LIKE \"%$text%\"\nUNION ALL\n SELECT \"user\" type, name\n FROM users\n WHERE name LIKE \"%$text%\"\n</code></pre>\n\n<p><strong>NOTE</strong>: I've added the answer myself, because I came across this problem yesterday, couldn't find a good solution, and used this method. If someone has a better approach, please feel free to add it.</p>\n"
},
{
"answer_id": 56346,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 1,
"selected": false,
"text": "<p>If you use \"UNION ALL\" then the db doesn't try to remove duplicates - you won't have duplicates between the two queries anyway (since the first column is different), so UNION ALL will be faster.<br>\n(I assume that you don't have duplicates inside each query that you want to remove)</p>\n"
},
{
"answer_id": 56389,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 1,
"selected": false,
"text": "<p>Using LIKE will cause a number of problems as it will require a table scan every single time when the LIKE comparator starts with a %. This forces SQL to check every single row and work it's way, byte by byte, through the string you are using for comparison. While this may be fine when you start, it quickly causes scaling issues.</p>\n\n<p>A better way to handle this is using Full Text Search. While this would be a more complex option, it will provide you with better results for very large databases. Then you can use a functioning version of the example Bobby Jack gave you to <code>UNION ALL</code> your two result sets together and display the results.</p>\n"
},
{
"answer_id": 56423,
"author": "Mark Nold",
"author_id": 4134,
"author_profile": "https://Stackoverflow.com/users/4134",
"pm_score": 1,
"selected": false,
"text": "<p>I would suggest another addition</p>\n\n<pre><code> SELECT \"group\" type, name\n FROM groups\n WHERE UPPER(name) LIKE UPPER(\"%$text%\")\nUNION ALL\n SELECT \"user\" type, name\n FROM users\n WHERE UPPER(name) LIKE UPPER(\"%$text%\")\n</code></pre>\n\n<p>You could convert $text to upper case first or do just do it in the query. This way you get a case insensitive search. </p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058/"
] | Suppose that two tables exist: `users` and `groups`.
**How does one provide "simple search" in which a user enters text and results contain both users and groups whose names contain the text?**
The result of the search must distinguish between the two types. | The trick is to combine a `UNION` with a literal string to determine the type of 'object' returned. In most (?) cases, UNION ALL will be more efficient, and should be used unless duplicates are required in the sub-queries. The following pattern should suffice:
```
SELECT "group" type, name
FROM groups
WHERE name LIKE "%$text%"
UNION ALL
SELECT "user" type, name
FROM users
WHERE name LIKE "%$text%"
```
**NOTE**: I've added the answer myself, because I came across this problem yesterday, couldn't find a good solution, and used this method. If someone has a better approach, please feel free to add it. |
56,340 | <p>I have a class in system-C with some data members as such: </p>
<pre><code>long double x[8];
</code></pre>
<p>I'm initializing it in the construction like this:</p>
<pre><code>for (i = 0; i < 8; ++i) {
x[i] = 0;
}
</code></pre>
<p>But the first time I use it in my code I have garbage there.</p>
<p>Because of the way the system is built I can't connect a debugger easily. Are there any methods to set a data breakpoint in the code so that it tells me where in the code the variables were actually changed, but without hooking up a debugger?</p>
<p>Edit:
@Prakash:
Actually, this is a typo in the <em>question</em>, but not in my code... Thanks!</p>
| [
{
"answer_id": 56336,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 3,
"selected": true,
"text": "<p>The trick is to combine a <code>UNION</code> with a literal string to determine the type of 'object' returned. In most (?) cases, UNION ALL will be more efficient, and should be used unless duplicates are required in the sub-queries. The following pattern should suffice:</p>\n\n<pre><code> SELECT \"group\" type, name\n FROM groups\n WHERE name LIKE \"%$text%\"\nUNION ALL\n SELECT \"user\" type, name\n FROM users\n WHERE name LIKE \"%$text%\"\n</code></pre>\n\n<p><strong>NOTE</strong>: I've added the answer myself, because I came across this problem yesterday, couldn't find a good solution, and used this method. If someone has a better approach, please feel free to add it.</p>\n"
},
{
"answer_id": 56346,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 1,
"selected": false,
"text": "<p>If you use \"UNION ALL\" then the db doesn't try to remove duplicates - you won't have duplicates between the two queries anyway (since the first column is different), so UNION ALL will be faster.<br>\n(I assume that you don't have duplicates inside each query that you want to remove)</p>\n"
},
{
"answer_id": 56389,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 1,
"selected": false,
"text": "<p>Using LIKE will cause a number of problems as it will require a table scan every single time when the LIKE comparator starts with a %. This forces SQL to check every single row and work it's way, byte by byte, through the string you are using for comparison. While this may be fine when you start, it quickly causes scaling issues.</p>\n\n<p>A better way to handle this is using Full Text Search. While this would be a more complex option, it will provide you with better results for very large databases. Then you can use a functioning version of the example Bobby Jack gave you to <code>UNION ALL</code> your two result sets together and display the results.</p>\n"
},
{
"answer_id": 56423,
"author": "Mark Nold",
"author_id": 4134,
"author_profile": "https://Stackoverflow.com/users/4134",
"pm_score": 1,
"selected": false,
"text": "<p>I would suggest another addition</p>\n\n<pre><code> SELECT \"group\" type, name\n FROM groups\n WHERE UPPER(name) LIKE UPPER(\"%$text%\")\nUNION ALL\n SELECT \"user\" type, name\n FROM users\n WHERE UPPER(name) LIKE UPPER(\"%$text%\")\n</code></pre>\n\n<p>You could convert $text to upper case first or do just do it in the query. This way you get a case insensitive search. </p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
] | I have a class in system-C with some data members as such:
```
long double x[8];
```
I'm initializing it in the construction like this:
```
for (i = 0; i < 8; ++i) {
x[i] = 0;
}
```
But the first time I use it in my code I have garbage there.
Because of the way the system is built I can't connect a debugger easily. Are there any methods to set a data breakpoint in the code so that it tells me where in the code the variables were actually changed, but without hooking up a debugger?
Edit:
@Prakash:
Actually, this is a typo in the *question*, but not in my code... Thanks! | The trick is to combine a `UNION` with a literal string to determine the type of 'object' returned. In most (?) cases, UNION ALL will be more efficient, and should be used unless duplicates are required in the sub-queries. The following pattern should suffice:
```
SELECT "group" type, name
FROM groups
WHERE name LIKE "%$text%"
UNION ALL
SELECT "user" type, name
FROM users
WHERE name LIKE "%$text%"
```
**NOTE**: I've added the answer myself, because I came across this problem yesterday, couldn't find a good solution, and used this method. If someone has a better approach, please feel free to add it. |
56,347 | <p>I'm returning to c++ after being away for a bit and trying to dust off the old melon. </p>
<p>In Java Iterator is an interface to a container having methods: <code>hasNext()</code>, <code>next()</code> and <code>remove()</code>. The presence of <code>hasNext()</code> means it <strong>has the concept of a limit</strong> for the container being traversed.</p>
<pre><code>//with an Iterator
Iterator<String> iter = trees.iterator();
while (iter.hasNext())
{
System.out.println(iter.next());
}
</code></pre>
<p>In the C++ standard template library, iterators seem to represent a datatype or class the supports the <code>operator++</code> and <code>operator==</code> but has <strong>no concept of a limit</strong> built in so comparison is required before advancing to the next item. The limit has to checked by the user comparing two iterators in the normal case the second iterator is the container end.</p>
<pre><code>vector<int> vec;
vector<int>::iterator iter;
// Add some elements to vector
v.push_back(1);
v.push_back(4);
v.push_back(8);
for (iter= v.begin(); iter != v.end(); iter++)
{
cout << *i << " "; //Should output 1 4 8
}
</code></pre>
<p>The interesting part here is that in C++ a pointer is an iterator to an array. The STL took what was existing and build convention around it.</p>
<p>It there any further subtlety to this that I am missing?</p>
| [
{
"answer_id": 56370,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 5,
"selected": true,
"text": "<p>Yes, there is a large conceptual difference. C++ utilizes different \"classes\" of iterators. Some are used for random access (unlike Java), some are used for forward access (like java). While even others are used for writing data (for use with, say, <code>transform</code>). </p>\n\n<p>See the iterators concept in the <a href=\"http://en.cppreference.com/w/cpp/iterator\" rel=\"noreferrer\">C++ Documentation</a>:</p>\n\n<ul>\n<li>Input Iterator</li>\n<li>Output Iterator</li>\n<li>Forward Iterator</li>\n<li>Bidirectional Iterator</li>\n<li>Random Access Iterator</li>\n</ul>\n\n<p>These are far more interesting and powerful compared to Java/C#'s puny iterators. Hopefully these conventions will be codified using C++0x's <a href=\"http://en.wikipedia.org/wiki/C%2B%2B0x#Concepts\" rel=\"noreferrer\">Concepts</a>.</p>\n"
},
{
"answer_id": 56396,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 1,
"selected": false,
"text": "<p>Iterators are only equivalent to pointers in the trivial case of iterating over the contents of an array in sequence. An iterator could be supplying objects from any number of other sources: from a database, from a file, from the network, from some other calculation, etc.</p>\n"
},
{
"answer_id": 56401,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 3,
"selected": false,
"text": "<p>A pointer to an array element is indeed an iterator into the array.</p>\n\n<p>As you say, in Java, an iterator has more knowledge of the underlying container than in C++. C++ iterators are general, and a <em>pair</em> of iterators can denote any range: this can be a sub-range of a container, a range over multiple containers (see <a href=\"http://www.justsoftwaresolutions.co.uk/articles/pair_iterators.pdf\" rel=\"noreferrer\">http://www.justsoftwaresolutions.co.uk/articles/pair_iterators.pdf</a> or <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/zip_iterator.html\" rel=\"noreferrer\">http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/zip_iterator.html</a>) or even a range of numbers (see <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/counting_iterator.html\" rel=\"noreferrer\">http://www.boost.org/doc/libs/1_36_0/libs/iterator/doc/counting_iterator.html</a>)</p>\n\n<p>The iterator categories identify what you can and can't do with a given iterator.</p>\n"
},
{
"answer_id": 56419,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<p>Perhaps a bit more theoretical. Mathematically, collections in C++ can be described as a half-open interval of iterators, namely one iterator pointing to the start of the collection and one iterator pointing <em>just behind</em> the last element.</p>\n\n<p>This convention opens up a host of possibilities. The way algorithms work in C++, they can all be applied to subsequences of a larger collection. To make such a thing work in Java, you have to create a wrapper around an existing collection that returns a different iterator.</p>\n\n<p>Another important aspect of iterators has already been mentioned by Frank. There are different concepts of iterators. Java iterators correspond to C++' input iterators, i.e. they are read-only iterators that can only be incremented one step at a time and can't go backwards.</p>\n\n<p>On the other extreme, you have C pointers which correspond exactly to C++' concept of a random access iterator.</p>\n\n<p>All in all, C++ offers a much richer and purer concept that can be applied to a much wider variety of tasks than either C pointers or Java iterators.</p>\n"
},
{
"answer_id": 56441,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 1,
"selected": false,
"text": "<p>C++ library (the part formerly known as STL) iterators are designed to be compatible with pointers. Java, without pointer arithmetic, had the freedom to be more programmer-friendly.</p>\n\n<p>In C++ you end up having to use a pair of iterators. In Java you either use an iterator or a collection. Iterators are supposed to be the glue between algorithm and data structure. Code written for 1.5+ rarely need mention iterators, unless it is implementing a particular algorithm or data structure (which the vary majority of programmers have no need to do). As Java goes for dynamic polymorphism subsets and the like are much easier to handle.</p>\n"
},
{
"answer_id": 56795,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 2,
"selected": false,
"text": "<p>To me the fundamental difference is that Java Iterators point between items, whereas C++ STL iterators point at items.</p>\n"
},
{
"answer_id": 58660,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 2,
"selected": false,
"text": "<p>C++ iterators are a generalization of the pointer concept; they make it applicable to a wider range of situations. It means that they can be used to do such things as define arbitrary ranges.</p>\n\n<p>Java iterators are relatively dumb enumerators (though not so bad as C#'s; at least Java has ListIterator and can be used to mutate the collection).</p>\n"
},
{
"answer_id": 161439,
"author": "Aaron",
"author_id": 14153,
"author_profile": "https://Stackoverflow.com/users/14153",
"pm_score": 4,
"selected": false,
"text": "<p>As mentioned, Java and C# iterators describe an intermixed position(state)-and-range(value), while C++ iterators separate the concepts of position and range. C++ iterators represent 'where am I now' separately from 'where can I go?'.</p>\n\n<p><strong>Java and C# iterators can't be copied. You can't recover a previous position. The common C++ iterators can.</strong></p>\n\n<p>Consider <a href=\"http://codepad.org/5D2xR6EV\" rel=\"noreferrer\">this example</a>:</p>\n\n<pre><code>// for each element in vec\nfor(iter a = vec.begin(); a != vec.end(); ++a){\n // critical step! We will revisit 'a' later.\n iter cur = a; \n unsigned i = 0;\n // print 3 elements\n for(; cur != vec.end() && i < 3; ++cur, ++i){\n cout << *cur << \" \";\n }\n cout << \"\\n\";\n}\n</code></pre>\n\n<p>Click the above link to see program output.</p>\n\n<p>This rather silly loop goes through a sequence (using forward iterator semantics only), printing each contiguous subsequence of 3 elements exactly once (and a couple shorter subsequences at the end). But supposing N elements, and M elements per line instead of 3, this algorithm would still be O(N*M) iterator increments, and O(1) space.</p>\n\n<p>The Java style iterators lack the ability to store position independently. You will either</p>\n\n<ul>\n<li>lose O(1) space, using (for example) an array of size M to store history as you iterate</li>\n<li>will need to traverse the list N times, making O(N^2+N*M) time</li>\n<li>or use a concrete Array type with GetAt member function, losing genericism and the ability to use linked list container types.</li>\n</ul>\n\n<p>Since only forward iteration mechanics were used in this example, i was able to swap in a list with <a href=\"http://codepad.org/aRsFuoA4\" rel=\"noreferrer\">no problems</a>. This is critical to authoring generic algorithms, such as search, delayed initialization and evaluation, sorting, etc.</p>\n\n<p>The inability to retain state corresponds most closely to the C++ STL input iterator, on which very few algorithms are built. </p>\n"
},
{
"answer_id": 29954778,
"author": "Neo M Hacker",
"author_id": 983732,
"author_profile": "https://Stackoverflow.com/users/983732",
"pm_score": 2,
"selected": false,
"text": "<p>There are plenty of good answers about the differences, but I felt the thing that annoys me the most with Java iterators wasn't emphasized--You can't read the current value multiple times. This is really useful in a lot of scenarios, especially when you are merging iterators. </p>\n\n<p>In c++, you have a method to advance the iterator and to read the current value. Reading its value doesn't advance the iteration; so you can read it multiple times. This is not possible with Java iterators, and I end up creating wrappers that do this.</p>\n\n<p>A side note: one easy way to create a wrapper is to use an existing one--<a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/PeekingIterator.html\" rel=\"nofollow\">PeekingIterator</a> from Guava. </p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445087/"
] | I'm returning to c++ after being away for a bit and trying to dust off the old melon.
In Java Iterator is an interface to a container having methods: `hasNext()`, `next()` and `remove()`. The presence of `hasNext()` means it **has the concept of a limit** for the container being traversed.
```
//with an Iterator
Iterator<String> iter = trees.iterator();
while (iter.hasNext())
{
System.out.println(iter.next());
}
```
In the C++ standard template library, iterators seem to represent a datatype or class the supports the `operator++` and `operator==` but has **no concept of a limit** built in so comparison is required before advancing to the next item. The limit has to checked by the user comparing two iterators in the normal case the second iterator is the container end.
```
vector<int> vec;
vector<int>::iterator iter;
// Add some elements to vector
v.push_back(1);
v.push_back(4);
v.push_back(8);
for (iter= v.begin(); iter != v.end(); iter++)
{
cout << *i << " "; //Should output 1 4 8
}
```
The interesting part here is that in C++ a pointer is an iterator to an array. The STL took what was existing and build convention around it.
It there any further subtlety to this that I am missing? | Yes, there is a large conceptual difference. C++ utilizes different "classes" of iterators. Some are used for random access (unlike Java), some are used for forward access (like java). While even others are used for writing data (for use with, say, `transform`).
See the iterators concept in the [C++ Documentation](http://en.cppreference.com/w/cpp/iterator):
* Input Iterator
* Output Iterator
* Forward Iterator
* Bidirectional Iterator
* Random Access Iterator
These are far more interesting and powerful compared to Java/C#'s puny iterators. Hopefully these conventions will be codified using C++0x's [Concepts](http://en.wikipedia.org/wiki/C%2B%2B0x#Concepts). |
56,362 | <p>I'm starting to learn ruby. I'm also a day-to-day C++ dev.
For C++ projects I usually go with following dir structure</p>
<pre><code>/
-/bin <- built binaries
-/build <- build time temporary object (eg. .obj, cmake intermediates)
-/doc <- manuals and/or Doxygen docs
-/src
--/module-1
--/module-2
-- non module specific sources, like main.cpp
- IDE project files (.sln), etc.
</code></pre>
<p>What dir layout for Ruby (non-Rails, non-Merb) would you suggest to keep it clean, simple and maintainable?</p>
| [
{
"answer_id": 56377,
"author": "ujh",
"author_id": 4936,
"author_profile": "https://Stackoverflow.com/users/4936",
"pm_score": 1,
"selected": false,
"text": "<p>Why not use just the same layout? Normally you won't need build because there's no compilation step, but the rest seems OK to me.</p>\n\n<p>I'm not sure what you mean by a module but if it's just a single class a separate folder wouldn't be necessary and if there's more than one file you normally write a module-1.rb file (at the name level as the module-1 folder) that does nothing more than require everything in module-1/.</p>\n\n<p>Oh, and I would suggest using <a href=\"http://rake.rubyforge.org/\" rel=\"nofollow noreferrer\">Rake</a> for the management tasks (instead of make).</p>\n"
},
{
"answer_id": 56448,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/users/5731/dentharg\">Dentharg</a>: your \"include one to include all sub-parts\" is a common pattern. Like anything, it has its advantages (easy to get the things you want) and its disadvantages (the many includes can pollute namespaces and you have no control over them). Your pattern looks like this:</p>\n\n<pre><code>- src/\n some_ruby_file.rb:\n require 'spider'\n Spider.do_something\n\n+ doc/\n\n- lib/\n - spider/\n spider.rb:\n $: << File.expand_path(File.dirname(__FILE__))\n module Spider\n # anything that needs to be done before including submodules\n end\n\n require 'spider/some_helper'\n require 'spider/some/other_helper'\n ...\n</code></pre>\n\n<p>I might recommend this to allow a little more control:</p>\n\n<pre><code>- src/\n some_ruby_file.rb:\n require 'spider'\n Spider.include_all\n Spider.do_something\n\n+ doc/\n\n- lib\n - spider/\n spider.rb:\n $: << File.expand_path(File.dirname(__FILE__))\n module Spider\n def self.include_all\n require 'spider/some_helper'\n require 'spider/some/other_helper'\n ...\n end\n end\n</code></pre>\n"
},
{
"answer_id": 62964,
"author": "François Beausoleil",
"author_id": 7355,
"author_profile": "https://Stackoverflow.com/users/7355",
"pm_score": 5,
"selected": true,
"text": "<p>Bundler includes the necessary infrastructure to generate a gem:</p>\n\n<pre><code>$ bundle gem --coc --mit --test=minitest --exe spider\nCreating gem 'spider'...\nMIT License enabled in config\nCode of conduct enabled in config\n create spider/Gemfile\n create spider/lib/spider.rb\n create spider/lib/spider/version.rb\n create spider/spider.gemspec\n create spider/Rakefile\n create spider/README.md\n create spider/bin/console\n create spider/bin/setup\n create spider/.gitignore\n create spider/.travis.yml\n create spider/test/test_helper.rb\n create spider/test/spider_test.rb\n create spider/LICENSE.txt\n create spider/CODE_OF_CONDUCT.md\n create spider/exe/spider\nInitializing git repo in /Users/francois/Projects/spider\nGem 'spider' was successfully created. For more information on making a RubyGem visit https://bundler.io/guides/creating_gem.html\n</code></pre>\n\n<p>Then, in lib/, you create modules as needed:</p>\n\n<pre><code>lib/\n spider/\n base.rb\n crawler/\n base.rb\n spider.rb\n require \"spider/base\"\n require \"crawler/base\"\n</code></pre>\n\n<p>Read the manual page for <a href=\"https://bundler.io/man/bundle-gem.1.html\" rel=\"nofollow noreferrer\">bundle gem</a> for details on the <code>--coc</code>, <code>--exe</code> and <code>--mit</code> options.</p>\n"
},
{
"answer_id": 71564,
"author": "0124816",
"author_id": 11521,
"author_profile": "https://Stackoverflow.com/users/11521",
"pm_score": 0,
"selected": false,
"text": "<p>I would stick to something similar to what you are familiar with: there's no point being a stranger in your own project directory. :-)</p>\n\n<p>Typical things I always have are lib|src, bin, test.</p>\n\n<p>(I dislike these monster generators: the first thing I want to do with a new project is get some code down, not write a README, docs, etc.!)</p>\n"
},
{
"answer_id": 82736,
"author": "Marcin Gil",
"author_id": 5731,
"author_profile": "https://Stackoverflow.com/users/5731",
"pm_score": 0,
"selected": false,
"text": "<p>So I went with newgem.\nI removed all unnecessary RubyForge/gem stuff (hoe, setup, etc.), created git repo, imported project into NetBeans. All took 20 minutes and everything's on green.\nThat even gave me a basic rake task for spec files.</p>\n\n<p>Thank you all.</p>\n"
},
{
"answer_id": 7061080,
"author": "troutwine",
"author_id": 314318,
"author_profile": "https://Stackoverflow.com/users/314318",
"pm_score": 4,
"selected": false,
"text": "<p>As of 2011, it is common to use <a href=\"https://github.com/technicalpickles/jeweler\">jeweler</a> instead of newgem as the latter is effectively abandoned. </p>\n"
},
{
"answer_id": 14019444,
"author": "trans",
"author_id": 1086638,
"author_profile": "https://Stackoverflow.com/users/1086638",
"pm_score": 4,
"selected": false,
"text": "<p>The core structure of a standard Ruby project is basically:</p>\n\n<pre><code> lib/\n foo.rb\n foo/\n share/\n foo/\n test/\n helper.rb\n test_foo.rb\n HISTORY.md (or CHANGELOG.md)\n LICENSE.txt\n README.md\n foo.gemspec\n</code></pre>\n\n<p>The <code>share/</code> is rare and is sometimes called <code>data/</code> instead. It is for general purpose non-ruby files. Most projects don't need it, but even when they do many times everything is just kept in <code>lib/</code>, though that is probably not best practice.</p>\n\n<p>The <code>test/</code> directory might be called <code>spec/</code> if BDD is being used instead of TDD, though you might also see <code>features/</code> if Cucumber is used, or <code>demo/</code> if QED is used.</p>\n\n<p>These days <code>foo.gemspec</code> can just be <code>.gemspec</code> --especially if it is not manually maintained.</p>\n\n<p>If your project has command line executables, then add:</p>\n\n<pre><code> bin/\n foo\n man/\n foo.1\n foo.1.md or foo.1.ronn\n</code></pre>\n\n<p>In addition, most Ruby project's have:</p>\n\n<pre><code> Gemfile\n Rakefile\n</code></pre>\n\n<p>The <code>Gemfile</code> is for using Bundler, and the <code>Rakefile</code> is for Rake build tool. But there are other options if you would like to use different tools.</p>\n\n<p>A few other not-so-uncommon files:</p>\n\n<pre><code> VERSION\n MANIFEST\n</code></pre>\n\n<p>The <code>VERSION</code> file just contains the current version number. And the <code>MANIFEST</code> (or <code>Manifest.txt</code>) contains a list of files to be included in the project's package file(s) (e.g. gem package).</p>\n\n<p>What else you might see, but usage is sporadic:</p>\n\n<pre><code> config/\n doc/ (or docs/)\n script/\n log/\n pkg/\n task/ (or tasks/)\n vendor/\n web/ (or site/)\n</code></pre>\n\n<p>Where <code>config/</code> contains various configuration files; <code>doc/</code> contains either generated documentation, e.g. RDoc, or sometimes manually maintained documentation; <code>script/</code> contains shell scripts for use by the project; <code>log/</code> contains generated project logs, e.g. test coverage reports; <code>pkg/</code> holds generated package files, e.g. <code>foo-1.0.0.gem</code>; <code>task/</code> could hold various task files such as <code>foo.rake</code> or <code>foo.watchr</code>; <code>vendor/</code> contains copies of the other projects, e.g. git submodules; and finally <code>web/</code> contains the project's website files.</p>\n\n<p>Then some tool specific files that are also relatively common:</p>\n\n<pre><code> .document\n .gitignore\n .yardopts\n .travis.yml\n</code></pre>\n\n<p>They are fairly self-explanatory.</p>\n\n<p>Finally, I will add that I personally add a <code>.index</code> file and a <code>var/</code> directory to build that file (search for \"Rubyworks Indexer\" for more about that) and often have a <code>work</code> directory, something like:</p>\n\n<pre><code> work/\n NOTES.md\n consider/\n reference/\n sandbox/\n</code></pre>\n\n<p>Just sort of a scrapyard for development purposes. </p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5731/"
] | I'm starting to learn ruby. I'm also a day-to-day C++ dev.
For C++ projects I usually go with following dir structure
```
/
-/bin <- built binaries
-/build <- build time temporary object (eg. .obj, cmake intermediates)
-/doc <- manuals and/or Doxygen docs
-/src
--/module-1
--/module-2
-- non module specific sources, like main.cpp
- IDE project files (.sln), etc.
```
What dir layout for Ruby (non-Rails, non-Merb) would you suggest to keep it clean, simple and maintainable? | Bundler includes the necessary infrastructure to generate a gem:
```
$ bundle gem --coc --mit --test=minitest --exe spider
Creating gem 'spider'...
MIT License enabled in config
Code of conduct enabled in config
create spider/Gemfile
create spider/lib/spider.rb
create spider/lib/spider/version.rb
create spider/spider.gemspec
create spider/Rakefile
create spider/README.md
create spider/bin/console
create spider/bin/setup
create spider/.gitignore
create spider/.travis.yml
create spider/test/test_helper.rb
create spider/test/spider_test.rb
create spider/LICENSE.txt
create spider/CODE_OF_CONDUCT.md
create spider/exe/spider
Initializing git repo in /Users/francois/Projects/spider
Gem 'spider' was successfully created. For more information on making a RubyGem visit https://bundler.io/guides/creating_gem.html
```
Then, in lib/, you create modules as needed:
```
lib/
spider/
base.rb
crawler/
base.rb
spider.rb
require "spider/base"
require "crawler/base"
```
Read the manual page for [bundle gem](https://bundler.io/man/bundle-gem.1.html) for details on the `--coc`, `--exe` and `--mit` options. |
56,373 | <p>I am writing a unit test to check that a private method will close a stream.</p>
<p>The unit test calls methodB and the variable something is null</p>
<p>The unit test doesn't mock the class on test</p>
<p>The private method is within a public method that I am calling.</p>
<p>Using emma in eclipse (via the eclemma plugin) the method call is displayed as not being covered even though the code within the method is</p>
<p>e.g</p>
<pre><code>public methodA(){
if (something==null) {
methodB(); //Not displayed as covered
}
}
private methodB(){
lineCoveredByTest; //displayed as covered
}
</code></pre>
<p>Why would the method call not be highlighted as being covered?</p>
| [
{
"answer_id": 56816,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 0,
"selected": false,
"text": "<p>I assume when you say 'the unit test calls <code>methodB()</code>', you mean not directly and via <code>methodA()</code>. </p>\n\n<p>So, is it possible <code>methodB()</code> is being called elsewhere, by another unit test or <code>methodC()</code> maybe?</p>\n"
},
{
"answer_id": 72586,
"author": "fivemile",
"author_id": 12219,
"author_profile": "https://Stackoverflow.com/users/12219",
"pm_score": 2,
"selected": false,
"text": "<p>I have found that the eclipse plugin for EMMA is quite buggy, and have had similar experiences to the one you describe. Better to just use EMMA on its own (via ANT if required). Make sure you always regenerate the metadata files produced by EMMA, to avoid merging confusion (which I suspect is the problem with the eclipse plugin).</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am writing a unit test to check that a private method will close a stream.
The unit test calls methodB and the variable something is null
The unit test doesn't mock the class on test
The private method is within a public method that I am calling.
Using emma in eclipse (via the eclemma plugin) the method call is displayed as not being covered even though the code within the method is
e.g
```
public methodA(){
if (something==null) {
methodB(); //Not displayed as covered
}
}
private methodB(){
lineCoveredByTest; //displayed as covered
}
```
Why would the method call not be highlighted as being covered? | I have found that the eclipse plugin for EMMA is quite buggy, and have had similar experiences to the one you describe. Better to just use EMMA on its own (via ANT if required). Make sure you always regenerate the metadata files produced by EMMA, to avoid merging confusion (which I suspect is the problem with the eclipse plugin). |
56,391 | <p>Trying to honor a feature request from our customers, I'd like that my application, when Internet is available, check on our website if a new version is available.</p>
<p>The problem is that I have no idea about what have to be done on the server side.</p>
<p>I can imagine that my application (developped in C++ using Qt) has to send a request (HTTP ?) to the server, but what is going to respond to this request ? In order to go through firewalls, I guess I'll have to use port 80 ? Is this correct ?</p>
<p>Or, for such a feature, do I have to ask our network admin to open a specific port number through which I'll communicate ?</p>
<hr>
<p>@<a href="https://stackoverflow.com/questions/56391/automatically-checking-for-a-new-version-of-my-application/56418#56418">pilif</a> : thanks for your detailed answer. There is still something which is unclear for me :</p>
<blockquote>
<p>like</p>
<p><code>http://www.example.com/update?version=1.2.4</code></p>
<p>Then you can return what ever you want, probably also the download-URL of the installer of the new version.</p>
</blockquote>
<p>How do I return something ? Will it be a php or asp page (I know nothing about PHP nor ASP, I have to confess) ? How can I decode the <code>?version=1.2.4</code> part in order to return something accordingly ?</p>
| [
{
"answer_id": 56404,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest way to make this happen is to fire an HTTP request using a library like <a href=\"http://curl.haxx.se/libcurl/\" rel=\"nofollow noreferrer\">libcurl</a> and make it download an ini or xml file which contains the online version and where a new version would be available online.</p>\n\n<p>After parsing the xml file you can determine if a new version is needed and download the new version with libcurl and install it.</p>\n"
},
{
"answer_id": 56405,
"author": "wvdschel",
"author_id": 2018,
"author_profile": "https://Stackoverflow.com/users/2018",
"pm_score": 0,
"selected": false,
"text": "<p>Just put an (XML) file on your server with the version number of the latest version, and a URL to the download the new version from. Your application can then request the XML file, look if the version differs from its own, and take action accordingly.</p>\n"
},
{
"answer_id": 56407,
"author": "Marcin Gil",
"author_id": 5731,
"author_profile": "https://Stackoverflow.com/users/5731",
"pm_score": 0,
"selected": false,
"text": "<p>I think that simple XML file on the server would be sufficient for version checking only purposes.</p>\n\n<p>You would need then only an ftp account on your server and build system that is able to send a file via ftp after it has built a new version. That build system could even put installation files/zip on your website directly!</p>\n"
},
{
"answer_id": 56408,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 1,
"selected": false,
"text": "<p>On the server you could just have a simple file \"latestversion.txt\" which contains the version number (and maybe download URL) of the latest version. The client then just needs to read this file using a simple HTTP request (yes, to port 80) to retrieve <a href=\"http://your.web.site/latestversion.txt\" rel=\"nofollow noreferrer\">http://your.web.site/latestversion.txt</a>, which you can then parse to get the version number. This way you don't need any fancy server code --- you just need to add a simple file to your existing website.</p>\n"
},
{
"answer_id": 56412,
"author": "Alex Duggleby",
"author_id": 5790,
"author_profile": "https://Stackoverflow.com/users/5790",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to keep it really basic, simply upload a version.txt to a webserver, that contains an integer version number. Download that check against the latest version.txt you downloaded and then just download the msi or setup package and run it.</p>\n\n<p>More advanced versions would be to use rss, xml or similar. It would be best to use a third-party library to parse the rss and you could include information that is displayed to your user about changes if you wish to do so.</p>\n\n<p>Basically you just need simple download functionality.</p>\n\n<p>Both these solutions will only require you to access port 80 outgoing from the client side. This should normally not require any changes to firewalls or networking (on the client side) and you simply need to have a internet facing web server (web hosting, colocation or your own server - all would work here).</p>\n\n<p>There are a couple of commercial auto-update solutions available. I'll leave the recommendations for those to others answerers, because I only have experience on the .net side with Click-Once and Updater Application Block (the latter is not continued any more).</p>\n"
},
{
"answer_id": 56418,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 6,
"selected": true,
"text": "<p>I would absolutely recommend to just do a plain HTTP request to your website. Everything else is bound to fail.</p>\n\n<p>I'd make a HTTP GET request to a certain page on your site containing the version of the local application.</p>\n\n<p>like</p>\n\n<pre><code>http://www.example.com/update?version=1.2.4\n</code></pre>\n\n<p>Then you can return what ever you want, probably also the download-URL of the installer of the new version. </p>\n\n<p>Why not just put a static file with the latest version to the server and let the client decide? Because you may want (or need) to have control over the process. Maybe 1.2 won't be compatible with the server in the future, so you want the server to force the update to 1.3, but the update from 1.2.4 to 1.2.6 could be uncritical, so you might want to present the client with an optional update.</p>\n\n<p>Or you want to have a breakdown over the installed base.</p>\n\n<p>Or whatever. Usually, I've learned it's best to keep as much intelligence on the server, because the server is what you have ultimate control over.</p>\n\n<p>Speaking here with a bit of experience in the field, here's a small preview of what can (and will - trust me) go wrong:</p>\n\n<ul>\n<li>Your Application will be prevented from making HTTP-Requests by the various Personal Firewall applications out there.</li>\n<li>A considerable percentage of users won't have the needed permissions to actually get the update process going.</li>\n<li>Even if your users have allowed the old version past their personal firewall, said tool will complain because the .EXE has changed and will recommend the user not to allow the new exe to connect (users usually comply with the wishes of their security tool here).</li>\n<li>In managed environments, you'll be shot and hanged (not necessarily in that order) for loading executable content from the web and then actually executing it.</li>\n</ul>\n\n<p>So to keep the damage as low as possible, </p>\n\n<ul>\n<li>fail silently when you can't connect to the update server</li>\n<li>before updating, make sure that you have write-permission to the install directory and warn the user if you do not, or just don't update at all.</li>\n<li>Provide a way for administrators to turn the auto-update off.</li>\n</ul>\n\n<p>It's no fun to do what you are about to do - especially when you deal with non technically inclined users as I had to numerous times.</p>\n"
},
{
"answer_id": 56440,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 4,
"selected": false,
"text": "<p>Pilif answer was good, and I have lots of experience with this too, but I'd like to add something more:</p>\n\n<p>Remember that if you start yourapp.exe, then the \"updater\" will try to overwrite yourapp.exe with the newest version. Depending upon your operating system and programming environment (you've mentioned C++/QT, I have no experience with those), you will <strong>not</strong> be able to overwrite <em>yourapp.exe</em> because it will be in use. </p>\n\n<p>What I have done is create a launcher. I have a MyAppLauncher.exe that uses a config file (xml, very simple) to launch the \"real exe\". Should a new version exist, the Launcher can update the \"real exe\" because it's not in use, and then relaunch the new version.</p>\n\n<p>Just keep that in mind and you'll be safe. </p>\n"
},
{
"answer_id": 56454,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 3,
"selected": false,
"text": "<p>Martin, </p>\n\n<p>you are absolutely right of course. But I would deliver the launcher with the installer. Or just download the installer, launch it and quit myself as soon as possible. The reason is bugs in the launcher. You would never, ever, want to be dependent on a component you cannot update (or forget to include in the initial drop).</p>\n\n<p>So the payload I distribute with the updating process of my application is just the standard installer, but devoid of any significant UI. Once the client has checked that the installer has a chance of running successfully and once it has downloaded the updater, it runs that and quits itself.</p>\n\n<p>The updater than runs, installs its payload into the original installation directory and restarts the (hopefully updated) application.</p>\n\n<p>Still: The process is hairy and you better think twice before implementing an Auto Update functionality on the Windows Platform when your application has a wide focus of usage.</p>\n"
},
{
"answer_id": 56532,
"author": "robsoft",
"author_id": 3897,
"author_profile": "https://Stackoverflow.com/users/3897",
"pm_score": 2,
"selected": false,
"text": "<p>I would agree with @Martin and @Pilif's answer, but add;</p>\n\n<p>Consider allowing your end-users to decide if they want to actually install the update there and then, or delay the installation of the update until they've finished using the program. </p>\n\n<p>I don't know the purpose/function of your app but many applications are launched when the user needs to do something specific there and then - nothing more annoying than launching an app and then being told it's found a new version, and you having to wait for it to download, shut down the app and relaunch itself. If your program has other resources that might be updated (reference files, databases etc) the problem gets worse.</p>\n\n<p>We had an EPOS system running in about 400 shops, and initially we thought it would be great to have the program spot updates and download them (using a file containing a version number very similar to the suggestions you have above)... great idea. Until all of the shops started up their systems at around the same time (8:45-8:50am), and our server was hit serving a 20+Mb download to 400 remote servers, which would then update the local software and cause a restart. Chaos - with nobody able to trade for about 10 minutes.</p>\n\n<p>Needless to say that this caused us to subsequently turn off the 'check for updates' feature and redesign it to allow the shops to 'delay' the update until later in the day. :-)</p>\n\n<p>EDIT: And if anyone from ADOBE is reading - for god's sake why does the damn acrobat reader insist on trying to download updates and crap when I just want to fire-it-up to read a document? Isn't it slow enough at starting, and bloated enough, as it is, without wasting a further 20-30 seconds of my life looking for updates every time I want to read a PDF?<br>\n<b>DONT THEY USE THEIR OWN SOFTWARE??!!!</b> :-)</p>\n"
},
{
"answer_id": 56593,
"author": "Peter Turner",
"author_id": 1765,
"author_profile": "https://Stackoverflow.com/users/1765",
"pm_score": 1,
"selected": false,
"text": "<p>if you keep your files in the update directory on example.com, this PHP script should download them for you given the request previously mentioned. (your update would be yourprogram.1.2.4.exe</p>\n\n<pre><code>$version = $_GET['version']; \n$filename = \"yourprogram\" . $version . \".exe\";\n$filesize = filesize($filename);\nheader(\"Pragma: public\");\nheader(\"Expires: 0\");\nheader(\"Cache-Control: post-check=0, pre-check=0\");\nheader(\"Content-type: application-download\");\nheader('Content-Length: ' . $filesize);\nheader('Content-Disposition: attachment; filename=\"' . basename($filename).'\"');\nheader(\"Content-Transfer-Encoding: binary\");\n</code></pre>\n\n<p>This makes your web browser think it's downloading an application. </p>\n"
},
{
"answer_id": 56997,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 3,
"selected": false,
"text": "<p>in php, the thing is easy:</p>\n\n<pre><code><?php\n if (version_compare($_GET['version'], \"1.4.0\") < 0){\n echo \"http://www.example.com/update.exe\";\n }else{\n echo \"no update\";\n }\n?>\n</code></pre>\n\n<p>if course you could extend this so the currently available version isn't hard-coded inside the script, but this is just about illustrating the point.</p>\n\n<p>In your application you would have this pseudo code:</p>\n\n<pre><code>result = makeHTTPRequest(\"http://www.example.com/update?version=\" + getExeVersion());\nif result != \"no update\" then\n updater = downloadUpdater(result);\n ShellExecute(updater);\n ExitApplication;\nend;\n</code></pre>\n\n<p>Feel free to extend the \"protocol\" by specifying something the PHP script could return to tell the client whether it's an important, mandatory update or not. </p>\n\n<p>Or you can add some text to display to the user - maybe containing some information about what's changed.</p>\n\n<p>Your possibilities are quite limitless.</p>\n"
},
{
"answer_id": 60572,
"author": "Andy Brice",
"author_id": 455552,
"author_profile": "https://Stackoverflow.com/users/455552",
"pm_score": 2,
"selected": false,
"text": "<p>My Qt app just uses QHttp to read tiny XML file off my website that contains the latest version number. If this is greater than the current version number it gives the option to go to the download page. Very simple. Works fine.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2796/"
] | Trying to honor a feature request from our customers, I'd like that my application, when Internet is available, check on our website if a new version is available.
The problem is that I have no idea about what have to be done on the server side.
I can imagine that my application (developped in C++ using Qt) has to send a request (HTTP ?) to the server, but what is going to respond to this request ? In order to go through firewalls, I guess I'll have to use port 80 ? Is this correct ?
Or, for such a feature, do I have to ask our network admin to open a specific port number through which I'll communicate ?
---
@[pilif](https://stackoverflow.com/questions/56391/automatically-checking-for-a-new-version-of-my-application/56418#56418) : thanks for your detailed answer. There is still something which is unclear for me :
>
> like
>
>
> `http://www.example.com/update?version=1.2.4`
>
>
> Then you can return what ever you want, probably also the download-URL of the installer of the new version.
>
>
>
How do I return something ? Will it be a php or asp page (I know nothing about PHP nor ASP, I have to confess) ? How can I decode the `?version=1.2.4` part in order to return something accordingly ? | I would absolutely recommend to just do a plain HTTP request to your website. Everything else is bound to fail.
I'd make a HTTP GET request to a certain page on your site containing the version of the local application.
like
```
http://www.example.com/update?version=1.2.4
```
Then you can return what ever you want, probably also the download-URL of the installer of the new version.
Why not just put a static file with the latest version to the server and let the client decide? Because you may want (or need) to have control over the process. Maybe 1.2 won't be compatible with the server in the future, so you want the server to force the update to 1.3, but the update from 1.2.4 to 1.2.6 could be uncritical, so you might want to present the client with an optional update.
Or you want to have a breakdown over the installed base.
Or whatever. Usually, I've learned it's best to keep as much intelligence on the server, because the server is what you have ultimate control over.
Speaking here with a bit of experience in the field, here's a small preview of what can (and will - trust me) go wrong:
* Your Application will be prevented from making HTTP-Requests by the various Personal Firewall applications out there.
* A considerable percentage of users won't have the needed permissions to actually get the update process going.
* Even if your users have allowed the old version past their personal firewall, said tool will complain because the .EXE has changed and will recommend the user not to allow the new exe to connect (users usually comply with the wishes of their security tool here).
* In managed environments, you'll be shot and hanged (not necessarily in that order) for loading executable content from the web and then actually executing it.
So to keep the damage as low as possible,
* fail silently when you can't connect to the update server
* before updating, make sure that you have write-permission to the install directory and warn the user if you do not, or just don't update at all.
* Provide a way for administrators to turn the auto-update off.
It's no fun to do what you are about to do - especially when you deal with non technically inclined users as I had to numerous times. |
56,402 | <p>I am trying to make SVG XML documents with a mixture of lines and brief text snippets (two or three words typically). The major problem I'm having is getting the text aligning with line segments.</p>
<p>For horizontal alignment I can use <code>text-anchor</code> with <code>left</code>, <code>middle</code> or <code>right</code>. I can't find a equivalent for vertical alignment; <code>alignment-baseline</code> doesn't seem to do it, so at present I'm using <code>dy="0.5ex"</code> as a kludge for centre alignment.</p>
<p>Is there a proper manner for aligning with the vertical centre or top of the text?</p>
| [
{
"answer_id": 73257,
"author": "Ian G",
"author_id": 5764,
"author_profile": "https://Stackoverflow.com/users/5764",
"pm_score": 7,
"selected": true,
"text": "<p>It turns out that you don't need explicit text paths. Firefox 3 has only partial support of the vertical alignment tags (<a href=\"http://groups.google.com/group/mozilla.dev.tech.svg/browse_thread/thread/1be0c56cfbfb3053?fwc=1\" rel=\"noreferrer\">see this thread</a>). It also seems that dominant-baseline only works when applied as a style whereas text-anchor can be part of the style or a tag attribute.</p>\n\n<pre><code><path d=\"M10, 20 L17, 20\"\n style=\"fill:none; color:black; stroke:black; stroke-width:1.00\"/>\n<text fill=\"black\" font-family=\"sans-serif\" font-size=\"16\"\n x=\"27\" y=\"20\" style=\"dominant-baseline: central;\">\n Vertical\n</text>\n\n<path d=\"M60, 40 L60, 47\"\n style=\"fill:none; color:red; stroke:red; stroke-width:1.00\"/>\n<text fill=\"red\" font-family=\"sans-serif\" font-size=\"16\"\n x=\"60\" y=\"70\" style=\"text-anchor: middle;\">\n Horizontal\n</text>\n\n<path d=\"M60, 90 L60, 97\"\n style=\"fill:none; color:blue; stroke:blue; stroke-width:1.00\"/>\n<text fill=\"blue\" font-family=\"sans-serif\" font-size=\"16\"\n x=\"60\" y=\"97\" style=\"text-anchor: middle; dominant-baseline: hanging;\">\n Bit of Both\n</text>\n</code></pre>\n\n<p>This works in Firefox. Unfortunately Inkscape doesn't seem to handle dominant-baseline (or at least not in the same way).</p>\n"
},
{
"answer_id": 23681125,
"author": "mjswensen",
"author_id": 926279,
"author_profile": "https://Stackoverflow.com/users/926279",
"pm_score": 2,
"selected": false,
"text": "<p>This effect can indeed be achieved by setting <code>alignment-baseline</code> to <code>central</code> or <code>middle</code>.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5764/"
] | I am trying to make SVG XML documents with a mixture of lines and brief text snippets (two or three words typically). The major problem I'm having is getting the text aligning with line segments.
For horizontal alignment I can use `text-anchor` with `left`, `middle` or `right`. I can't find a equivalent for vertical alignment; `alignment-baseline` doesn't seem to do it, so at present I'm using `dy="0.5ex"` as a kludge for centre alignment.
Is there a proper manner for aligning with the vertical centre or top of the text? | It turns out that you don't need explicit text paths. Firefox 3 has only partial support of the vertical alignment tags ([see this thread](http://groups.google.com/group/mozilla.dev.tech.svg/browse_thread/thread/1be0c56cfbfb3053?fwc=1)). It also seems that dominant-baseline only works when applied as a style whereas text-anchor can be part of the style or a tag attribute.
```
<path d="M10, 20 L17, 20"
style="fill:none; color:black; stroke:black; stroke-width:1.00"/>
<text fill="black" font-family="sans-serif" font-size="16"
x="27" y="20" style="dominant-baseline: central;">
Vertical
</text>
<path d="M60, 40 L60, 47"
style="fill:none; color:red; stroke:red; stroke-width:1.00"/>
<text fill="red" font-family="sans-serif" font-size="16"
x="60" y="70" style="text-anchor: middle;">
Horizontal
</text>
<path d="M60, 90 L60, 97"
style="fill:none; color:blue; stroke:blue; stroke-width:1.00"/>
<text fill="blue" font-family="sans-serif" font-size="16"
x="60" y="97" style="text-anchor: middle; dominant-baseline: hanging;">
Bit of Both
</text>
```
This works in Firefox. Unfortunately Inkscape doesn't seem to handle dominant-baseline (or at least not in the same way). |
56,430 | <p>I have a foxpro app, that contains hard coded path for icons and bitmaps. That's how foxpro does it and there is no way around it. And this works fine, except that when a removable drive has been used but is not connected, and when is connected windows assigns the same letter as hard coded path, when opening any form that contains such path, the following error message apears (<strong>FROM WINDOWS</strong>, not fox):</p>
<p>Windows-No disk
Exception Processing Message c0000012 Parameters .....</p>
<p>Any help please
Nelson Marmol</p>
| [
{
"answer_id": 56487,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 2,
"selected": false,
"text": "<p>Nelson:</p>\n\n<p>\"That's how foxpro does it and there is no way around it\"?</p>\n\n<p>I'm using FOX since FoxPro 2.5 to Visual FoxPro 9, and you are NEVER forced in any way to hard-code a path, you can use SET PATH TO (sYourPath), you can embed the icons and bitmaps in your EXE / APP file and therefore there's no need of including this resources externally.</p>\n\n<p>You say that you have a \"Foxpro App\": which version? Old MS-DOS FoxPro o Visual FoxPro?\nIf you're using VFP 8+, you can use SYS(2450, 1):</p>\n\n<pre><code>Specifies how an application searches for data and resources such as functions, procedures, executable files, and so on. \n\nYou can use SYS(2450) to specify that Visual FoxPro searches within an application for a specific procedure or user-defined function (UDF) before it searches along the SET DEFAULT and SET PATH locations. Setting SYS(2450) can help improve performance for applications that run on a local or wide area network.\n\n\nSYS(2450 [, 0 | 1 ])\n\n\n\nParameters\n0 \nSearch along path and default locations before searching in the application. (Default)\n\n1 \nSearch within the application for the specified procedure or UDF before searching the path and default locations.\n</code></pre>\n\n<p>One quick workaround could be assign another letter to your USB via the Disk Manager.</p>\n"
},
{
"answer_id": 56515,
"author": "robsoft",
"author_id": 3897,
"author_profile": "https://Stackoverflow.com/users/3897",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with @PabloG - it's been over a decade since I worked with FoxPro (Dos & Windows) but even back in FPW2.6 you could determine where your app was running 'from', set absolute or relative search paths and even bundle your resources straight into the \"compiled\" (heh) exe. All of our resources lived in a specific subfolder within the app folder, the database files in another subfolder also below the app folder. We used relative paths for everything as I recall.</p>\n\n<p>Can you give us a bit more information about the problem?</p>\n\n<p>If you think it would be helpful I could try and dig out some of our FPW2.6 code where we're doing this kind of thing. :-)</p>\n"
},
{
"answer_id": 56726,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It's VFP8 and sorry if I did not explained myself corectly. Also I think \"there's no way around it\" may sounded bad. What I meant is the property \"<strong>ICON</strong>\" in the forms. Since we have each component type separated in folders (forms,reports, menus, icons, etc), if you try to make the path relative, next time you edit the file, foxpro will include the fullpath. This problem started recently and we found that our clients started using external usb drives as means for backups.</p>\n"
},
{
"answer_id": 63279,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds to me like you are distributing the forms/reports/labels etc to the clients. If you build an EXE, then you shouldn't get the \"path\" problem as VFP will embed the resource (in this case icon) into the exe and will know how to extract it at runtime.</p>\n\n<p>Peterson</p>\n"
},
{
"answer_id": 133256,
"author": "nmarmol",
"author_id": 20448,
"author_profile": "https://Stackoverflow.com/users/20448",
"pm_score": 0,
"selected": false,
"text": "<p>No, we are no distributing forms or anything with the app... it's an exe. I forgot to mention that the EXE is compressed and obfuscated with <strong>KONXIZE 1.0.</strong></p>\n"
},
{
"answer_id": 1150726,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming your application can determine the path to the icon file at runtime, then in the load event of the form, you can set the icon with:</p>\n\n<pre><code>THIS.Icon=<path to file>\n</code></pre>\n"
},
{
"answer_id": 1685207,
"author": "nstenz",
"author_id": 203656,
"author_profile": "https://Stackoverflow.com/users/203656",
"pm_score": 0,
"selected": false,
"text": "<p>If anybody else runs across this, you can generally type something like this for the Icon property in the Properties window to force it to be evaluated, which will probably prevent the path auto-filling:</p>\n\n<p><strong>=\"icon.ico\"</strong></p>\n\n<p>instead of just <strong>icon.ico</strong>.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I have a foxpro app, that contains hard coded path for icons and bitmaps. That's how foxpro does it and there is no way around it. And this works fine, except that when a removable drive has been used but is not connected, and when is connected windows assigns the same letter as hard coded path, when opening any form that contains such path, the following error message apears (**FROM WINDOWS**, not fox):
Windows-No disk
Exception Processing Message c0000012 Parameters .....
Any help please
Nelson Marmol | Nelson:
"That's how foxpro does it and there is no way around it"?
I'm using FOX since FoxPro 2.5 to Visual FoxPro 9, and you are NEVER forced in any way to hard-code a path, you can use SET PATH TO (sYourPath), you can embed the icons and bitmaps in your EXE / APP file and therefore there's no need of including this resources externally.
You say that you have a "Foxpro App": which version? Old MS-DOS FoxPro o Visual FoxPro?
If you're using VFP 8+, you can use SYS(2450, 1):
```
Specifies how an application searches for data and resources such as functions, procedures, executable files, and so on.
You can use SYS(2450) to specify that Visual FoxPro searches within an application for a specific procedure or user-defined function (UDF) before it searches along the SET DEFAULT and SET PATH locations. Setting SYS(2450) can help improve performance for applications that run on a local or wide area network.
SYS(2450 [, 0 | 1 ])
Parameters
0
Search along path and default locations before searching in the application. (Default)
1
Search within the application for the specified procedure or UDF before searching the path and default locations.
```
One quick workaround could be assign another letter to your USB via the Disk Manager. |
56,443 | <p>I currently have a class and I'm trying to create an easy GUI to create a collection of this class. Most of the attributes of this class are strings. However, one of the attributes I want the user to be able to set is an Enum. Therefore, I would like the user interface, to have a dropdownlist for this enum, to restrict the user from entering a value that is not valid. Currently, I am taking the initial list of objects, adding them to a DataTable and setting the DataSource of my DataGridView to the table. Works nicely, even creates a checkbox column for the one Boolean property. But, I don't know how to make the column for the enum into a dropdownlist. I am using C# and .NET 2.0.</p>
<p>Also, I have tried assigning the DataSource of the DataGridView to the list of my objects, but when I do this, it doesn't help with the enum and I'm unable to create new rows in the DataGridView, but I am definitely not bound to using a DataTable as my DataSource, it was simply the option I have semi-working.</p>
| [
{
"answer_id": 56483,
"author": "Ozgur Ozcitak",
"author_id": 976,
"author_profile": "https://Stackoverflow.com/users/976",
"pm_score": 6,
"selected": true,
"text": "<p>I do not know if that would work with a DataGridView column but it works with ComboBoxes:</p>\n\n<pre><code>comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>MyEnum value = (MyEnum)comboBox1.SelectedValue;\n</code></pre>\n\n<p>UPDATE: It works with DataGridView columns too, just remember to set the value type.</p>\n\n<pre><code>DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();\ncol.Name = \"My Enum Column\";\ncol.DataSource = Enum.GetValues(typeof(MyEnum));\ncol.ValueType = typeof(MyEnum);\ndataGridView1.Columns.Add(col);\n</code></pre>\n"
},
{
"answer_id": 56613,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Or, if you need to do some filtering of the enumerator values, you can loop through <code>Enum.GetValues(typeof(EnumeratorName))</code> and add the ones you want using:</p>\n\n<pre><code>dataGridViewComboBoxColumn.Items.Add(EnumeratorValue)\n</code></pre>\n\n<p>As an aside, rather than using a DataTable, you can set the DataSource of the DataGridView to a BindingSource object, with the DataSource of the BindingSource object set to a <code>BindingList<Your Class></code>, which you populate by passing an <code>IList</code> into the constructor.</p>\n\n<p>Actually, I'd be interested to know from anyone if this is preferable to using a DataTable in situations where you don't already have one (i.e. it is returned from a database call).</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4660/"
] | I currently have a class and I'm trying to create an easy GUI to create a collection of this class. Most of the attributes of this class are strings. However, one of the attributes I want the user to be able to set is an Enum. Therefore, I would like the user interface, to have a dropdownlist for this enum, to restrict the user from entering a value that is not valid. Currently, I am taking the initial list of objects, adding them to a DataTable and setting the DataSource of my DataGridView to the table. Works nicely, even creates a checkbox column for the one Boolean property. But, I don't know how to make the column for the enum into a dropdownlist. I am using C# and .NET 2.0.
Also, I have tried assigning the DataSource of the DataGridView to the list of my objects, but when I do this, it doesn't help with the enum and I'm unable to create new rows in the DataGridView, but I am definitely not bound to using a DataTable as my DataSource, it was simply the option I have semi-working. | I do not know if that would work with a DataGridView column but it works with ComboBoxes:
```
comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
```
and:
```
MyEnum value = (MyEnum)comboBox1.SelectedValue;
```
UPDATE: It works with DataGridView columns too, just remember to set the value type.
```
DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
col.Name = "My Enum Column";
col.DataSource = Enum.GetValues(typeof(MyEnum));
col.ValueType = typeof(MyEnum);
dataGridView1.Columns.Add(col);
``` |
56,446 | <p>Although perhaps a bizare thing to want to do, I need to create an Array in .Net with a lower bound > 0. This at first seems to be possible, using:</p>
<pre><code>Array.CreateInstance(typeof(Object), new int[] {2}, new int[] {9});
</code></pre>
<p>Produces the desired results (an array of objects with a lower bound set to 9). However the created array instance can no longer be passed to other methods expecting <code>Object[]</code> giving me an error saying that:</p>
<p><code>System.Object[*]</code> can not be cast into a <code>System.Object[]</code>. What is this difference in array types and how can I overcome this?</p>
<p>Edit: test code = </p>
<pre><code>Object x = Array.CreateInstance(typeof(Object), new int[] {2}, new int[] {9});
Object[] y = (Object[])x;
</code></pre>
<p>Which fails with: "Unable to cast object of type 'System.Object[*]' to type 'System.Object[]'."</p>
<p>I would also like to note that this approach <strong>DOES</strong> work when using multiple dimensions:</p>
<pre><code>Object x = Array.CreateInstance(typeof(Object), new int[] {2,2}, new int[] {9,9});
Object[,] y = (Object[,])x;
</code></pre>
<p>Which works fine.</p>
| [
{
"answer_id": 56457,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure about why that can't be passed as Object[], but wouldn't be easy if you just create a real class to wrap an array and handle your \"weird logic\" in there?</p>\n\n<p>You'd get the benefits of using a real reference object were you could add \"intelligence\" to your class.</p>\n\n<p>Edit: How are you casting your Array, could you post some more code? Thanks.</p>\n"
},
{
"answer_id": 56495,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 2,
"selected": false,
"text": "<p>The reason why you can't cast from one to the other is that this is evil.</p>\n\n<p>Lets say you create an array of object[5..9] and you pass it to a function F as an object[].</p>\n\n<p>How would the function knows that this is a 5..9 ? F is expecting a general array but it's getting a constrained one. You could say it's possible for it to know, but this is still unexpected and people don't want to make all sort of boundary checks everytime they want to use a simple array.</p>\n\n<p>An array is the simplest structure in programming, making it too complicated makes it unsusable. You probably need another structure.</p>\n\n<p>What you chould do is a class that is a constrained collection that mimics the behaviour you want. That way, all users of that class will know what to expect.</p>\n\n<pre><code>class ConstrainedArray<T> : IEnumerable<T> where T : new()\n{\n public ConstrainedArray(int min, int max)\n {\n array = new T[max - min];\n }\n\n public T this [int index]\n {\n get { return array[index - Min]; }\n set { array[index - Min] = value; }\n }\n\n public int Min {get; private set;}\n public int Max {get; private set;}\n\n T[] array;\n\n public IEnumerator<T> GetEnumerator()\n {\n return array.GetEnumarator();\n }\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return array.GetEnumarator();\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 56529,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>Just store your lower bound in a const offset integer, and subtract that value from whatever your source returns as the index.</p>\n\n<p>Also: this is an old VB6 feature. I think there might be an attribute to help support it.</p>\n"
},
{
"answer_id": 57501414,
"author": "SoLaR",
"author_id": 1011436,
"author_profile": "https://Stackoverflow.com/users/1011436",
"pm_score": 0,
"selected": false,
"text": "<p>Know it's old question, but to fully explain it.</p>\n\n<p>If type (in this case a single-dimension array with lower bound > 0) can't be created by typed code, simply reflected type instance can't be consumed by typed code then.</p>\n\n<p>What you have noticed is already in documentation:</p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/specifying-fully-qualified-type-names\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/specifying-fully-qualified-type-names</a></p>\n\n<blockquote>\n <p>Note that from a runtime point of view, MyArray[] != MyArray[*], but\n for multidimensional arrays, the two notations are equivalent. That\n is, Type.GetType(\"MyArray [,]\") == Type.GetType(\"MyArray[*,*]\")\n evaluates to true.</p>\n</blockquote>\n\n<p>In c#/vb/... you can keep that reflected array in object, pass around as object, and use only reflection to access it's items. </p>\n\n<p>-</p>\n\n<p>Now you ask \"why is there LowerBound at all?\", well COM object aren't .NET, it could be written in old VB6 that actually had array object that has LowerBound set to 1 (or anything VB6 had such freedom or curse, depends whom you ask). To access first element of such object you would actually need to use 'comObject(1)' instead of 'comObject(0)'. So the reason to check lower bound is when you are performing enumeration of such object to know where to start enumeration, since element functions in COM object expects first element to be of LowerBound value, and not Zero (0), it was reasonable to support same logic on such instances. Imagine your get element value of first element at 0, and use some Com object to pass such element instance with index value of 1 or even with index value of 2001 to a method, code would be very confusing.</p>\n\n<p>To put it simply: it's mostly for legacy support only!</p>\n"
},
{
"answer_id": 69082566,
"author": "usr",
"author_id": 122718,
"author_profile": "https://Stackoverflow.com/users/122718",
"pm_score": 1,
"selected": false,
"text": "<p>The .NET CLR differentiates between two internal array object formats: <em>SZ arrays</em> and <em>MZ arrays</em>. MZ arrays can be multi-dimensional and store their lower bounds in the object.</p>\n<p>The reason for this difference is two-fold:</p>\n<ol>\n<li>Efficient code generation for single-dimensional arrays requires that there is no lower bound. Having a lower bound is incredibly uncommon. We would not want to sacrifice significant performance in the common case for this rarely used feature.</li>\n<li>Most code expects arrays with zero lower bound. We certainly don't want to pollute all of our code with checking the lower bound or adjusting loop bounds.</li>\n</ol>\n<p>These concerns are solved by making a separate CLR type for SZ arrays. This is the type that almost all practically occurring arrays are using.</p>\n"
}
] | 2008/09/11 | [
"https://Stackoverflow.com/questions/56446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111/"
] | Although perhaps a bizare thing to want to do, I need to create an Array in .Net with a lower bound > 0. This at first seems to be possible, using:
```
Array.CreateInstance(typeof(Object), new int[] {2}, new int[] {9});
```
Produces the desired results (an array of objects with a lower bound set to 9). However the created array instance can no longer be passed to other methods expecting `Object[]` giving me an error saying that:
`System.Object[*]` can not be cast into a `System.Object[]`. What is this difference in array types and how can I overcome this?
Edit: test code =
```
Object x = Array.CreateInstance(typeof(Object), new int[] {2}, new int[] {9});
Object[] y = (Object[])x;
```
Which fails with: "Unable to cast object of type 'System.Object[\*]' to type 'System.Object[]'."
I would also like to note that this approach **DOES** work when using multiple dimensions:
```
Object x = Array.CreateInstance(typeof(Object), new int[] {2,2}, new int[] {9,9});
Object[,] y = (Object[,])x;
```
Which works fine. | The reason why you can't cast from one to the other is that this is evil.
Lets say you create an array of object[5..9] and you pass it to a function F as an object[].
How would the function knows that this is a 5..9 ? F is expecting a general array but it's getting a constrained one. You could say it's possible for it to know, but this is still unexpected and people don't want to make all sort of boundary checks everytime they want to use a simple array.
An array is the simplest structure in programming, making it too complicated makes it unsusable. You probably need another structure.
What you chould do is a class that is a constrained collection that mimics the behaviour you want. That way, all users of that class will know what to expect.
```
class ConstrainedArray<T> : IEnumerable<T> where T : new()
{
public ConstrainedArray(int min, int max)
{
array = new T[max - min];
}
public T this [int index]
{
get { return array[index - Min]; }
set { array[index - Min] = value; }
}
public int Min {get; private set;}
public int Max {get; private set;}
T[] array;
public IEnumerator<T> GetEnumerator()
{
return array.GetEnumarator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return array.GetEnumarator();
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.