qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
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 cal...
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-&gt;db_connection = $db_connection; $this-&gt;page_title = ''; } public function get_page_title() { return $this-&gt;page_title; } public function set_page_title($page_title) { $this-&gt;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-&gt;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...
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 ...
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<...
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-configu...
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 ass...
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 va...
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 screen...
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>&lt;ItemTemplate&gt; &lt;tr&gt; &lt;td class="class1" align=center&gt;&lt;a href='url'&gt;&lt;img src="img.gif"&gt;&lt;/a&gt;&lt;/td&gt; &lt;td class="class1"&gt;&lt;%# DataBinder.Eval(Container.DataItem,"field1") %&gt;&lt;/td&gt; &lt;td class="class1"&gt;&lt;%# DataBinder.Eval(Container.DataItem,"field2") %&gt;&lt;/td&gt; &lt;td class="class1"&gt;&lt;%# DataBinder.Eval(Container.DataItem,"field3") %&gt;&lt;/td&gt; &lt;td class="class1"&gt;&lt;%# DataBinder.Eval(Container.DataItem,"field4") %&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/ItemTemplate&gt; </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>&lt;tr&gt; &lt;td class="class1" align=center&gt;&lt;a href='url'&gt;&lt;img src="img.gif"&gt;&lt;/a&gt;&lt;/td&gt; &lt;td class="class1"&gt;23&lt;/td&gt; &lt;td class="class1"&gt;1/1/2000&lt;/td&gt; &lt;td class="class1"&gt;-2&lt;/td&gt; &lt;td class="class1"&gt;11&lt;/td&gt; &lt;/tr&gt; </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 ce...
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 S...
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: &lt;chris@example.org&gt; X-Mailer: mail (GNU Mailutils 1.1) Message-Id: &lt;E1KdTJj-00025z-RK@localhost&gt; From: &lt;chris@localhost&gt; 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 th...
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-NHiber...
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 r...
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>&lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestWebApp.Default" %&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" &gt; &lt;head runat="server"&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;asp:TextBox ID="txtMultiLine" runat="server" Width="400px" Height="300px" TextMode="MultiLine"&gt;&lt;/asp:TextBox&gt; &lt;br /&gt; &lt;asp:Button ID="btnSubmit" runat="server" Text="Do A Postback" OnClick="btnSubmitClick" /&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </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 PDF...
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(ja...
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&lt;String&gt; output = new List&lt;String&gt;(); for (int i = 0; i &lt; tokens.Length; i++) { if (tokens[i].StartsWith("\"")) { string temp = tokens[i]; int k = 0; for (k = i + 1; k &lt; 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 spac...
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 &gt; ul").after("&lt;div id='xxx'&gt;&lt;/div&gt;").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 &gt; 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 \"#someotherd...
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&lt;String&gt;</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&lt;String&gt;</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" }, { ...
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&gt; chcp 65001 Activated code page: 65001 C:\Application&gt; start.bat C:\Application&gt; </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...
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 =&gt; x.FileName.Contains(ddlFileName.SelectedValue)); if (chkFileName.Checked) results = results.Where(x =&gt; x.FileName == null); if (!string.IsNullOrEmpty(ddlIPAddress.SelectedItem.Text)) results = results.Where(x =&gt; x.IpAddress.Contains(ddlIPAddress.SelectedValue)); if (chkIPAddress.Checked) results = results.Where(x =&gt; x.IpAddress == null); ...etc. </code></pre> <p><code>results</code> is an <code>IQueryable&lt;MyObject&gt;</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&lt;Func&lt;MyObject, bool&gt;&gt;</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 =&gt; \n (string.IsNullOrEmpty(ddlFileName.SelectedItem.Text) || x.FileName.Contains(d...
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...
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....
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 pro...
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/f...
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 ...
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....
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 df...
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\"><c...
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 ...
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. ![Screenshot of the Action registry key](https://i.stack.imgur.com/0k0b0.png) 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" }, { "answe...
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 encapsula...
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...
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...
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...
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 li...
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....
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, "aut...
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 t...
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&amp;AspxAutoDetectCookieSupport=1" rel="nofollow noreferrer">http://www.dotnetcurry.com/ShowArticle.aspx?ID=181&amp;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("&lt;%=HiddenField1.ClientID%&gt;"); if(elem.value != "0") { var temp = new Array(); temp = elem.value.split(';'); // set the position of the panel manually with the retrieve value $find('&lt;%=Panel1_DragPanelExtender.BehaviorID%&gt;').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("&lt;%=HiddenField1.ClientID%&gt;"); // store the value in the hidden field elem1.value = loc.x + ';' + loc.y; } &lt;asp:Button ID="Button1" runat="server" Text="Button"/&gt; &lt;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...
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 ...
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&amp;page...
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&amp;7 and it even works in Chrome??</p> <p>It's a simple asp:LinkButton with an OnClick event</p> <pre><code>&lt;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"&gt; </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 th...
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\"...
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>&lt;input type="hidden" name="fooId" value="12-3456789-1111111111" /&gt; </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>&lt;input type="hidden" name="fooId" value="**[id is here]**" /&gt; </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>/&lt;input type=\"hidden\" name=\"fooId\" value=\"([\\d-]+)\" \\/&gt;/\n</code></pre>\n" }, { "answer_id": 55401...
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" },...
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&lt;typename ImplemenationClass&gt; 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>&lt;? extends BaseClass&gt; </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 ...
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=\"http...
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-...
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&lt;string&gt; 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=\"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 ...
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 &lt;&gt; @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 &lt;&gt; @expects\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 alr...
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&lt;Matrix&amp;&gt;(array1)); api_func(reinterpret_cast&lt;Matrix&amp;&gt;(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 co...
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 rand...
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 ...
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>&lt;%# Eval(\"Name1\", \"{0} - \")%&gt; &lt;%#Eval(\"Name2\")...
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 ...
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 fair...
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...
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>cl...
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&lt;=N; i++)) ; do mv foo$i `printf foo%05d $i` ; done\n</code></pre>\...
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\" re...
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 _te...
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...
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, "aut...
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 i...
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=\"nofol...
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...
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\">RETUR...
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>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Wix xmlns="http://schemas.microsoft.com/wix/2003/01/wi"&gt; &lt;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"&gt; &lt;!-- Package information --&gt; &lt;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" /&gt; &lt;Upgrade Id='9071eacc-9b5a-48e3-bb90-8064d2b2c45d'&gt; &lt;UpgradeVersion Property="PATCHFOUND" OnlyDetect="no" Minimum="0.0.1" IncludeMinimum="yes" Maximum="1.0.0" IncludeMaximum="yes"/&gt; &lt;/Upgrade&gt; &lt;!-- Useless but necessary... --&gt; &lt;Media Id="1" Cabinet="MyCompany.cab" EmbedCab="yes" /&gt; &lt;!-- Precondition: .NET 2 must be installed --&gt; &lt;Condition Message='This setup requires the .NET Framework 2 or higher.'&gt; &lt;![CDATA[MsiNetAssemblySupport &gt;= "2.0.50727"]]&gt; &lt;/Condition&gt; &lt;Directory Id="TARGETDIR" Name="SourceDir"&gt; &lt;Directory Id="MyCompany" Name="MyCompany"&gt; &lt;Directory Id="INSTALLDIR" Name="Integrat" LongName="MyCompany Integration Framework"&gt; &lt;Component Id="MyCompanyDllComponent" Guid="4f362043-03a0-472d-a84f-896522ce7d2b" DiskId="1"&gt; &lt;File Id="MyCompanyIntegrationDll" Name="IbIntegr.dll" src="..\Build\MyCompany.Integration.dll" Vital="yes" LongName="MyCompany.Integration.dll" /&gt; &lt;File Id="MyCompanyServiceModelDll" Name="IbSerMod.dll" src="..\Build\MyCompany.ServiceModel.dll" Vital="yes" LongName="MyCompany.ServiceModel.dll" /&gt; &lt;/Component&gt; &lt;!-- More components --&gt; &lt;/Directory&gt; &lt;/Directory&gt; &lt;/Directory&gt; &lt;Feature Id="MyCompanyProductFeature" Title='MyCompany Integration Framework' Description='The complete package' Display='expand' Level="1" InstallDefault='local' ConfigurableDirectory="INSTALLDIR"&gt; &lt;ComponentRef Id="MyCompanyDllComponent" /&gt; &lt;/Feature&gt; &lt;!-- Task scheduler application. It has to be used as a property --&gt; &lt;Property Id="finaltaskexe" Value="MyCompany.Integration.Host.exe" /&gt; &lt;Property Id="WIXUI_INSTALLDIR" Value="INSTALLDIR" /&gt; &lt;InstallExecuteSequence&gt; &lt;!-- command must be executed: MyCompany.Integration.Host.exe /INITIALCONFIG parameters.xml --&gt; &lt;Custom Action='PropertyAssign' After='InstallFinalize'&gt;NOT Installed AND NOT PATCHFOUND&lt;/Custom&gt; &lt;Custom Action='LaunchFile' After='InstallFinalize'&gt;NOT Installed AND NOT PATCHFOUND&lt;/Custom&gt; &lt;RemoveExistingProducts Before='CostInitialize' /&gt; &lt;/InstallExecuteSequence&gt; &lt;!-- execute comand --&gt; &lt;CustomAction Id='PropertyAssign' Property='PathProperty' Value='[INSTALLDIR][finaltaskexe]' /&gt; &lt;CustomAction Id='LaunchFile' Property='PathProperty' ExeCommand='/INITIALCONFIG "[INSTALLDIR]parameters.xml"' Return='asyncNoWait' /&gt; &lt;!-- User interface information --&gt; &lt;UIRef Id="WixUI_InstallDir" /&gt; &lt;UIRef Id="WixUI_ErrorProgressText" /&gt; &lt;/Product&gt; &lt;/Wix&gt; </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-...
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...
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),...
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 mi...
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 nor...
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 &lt;html/&gt; element.</p>\n\n<p>HTML example:</p>\n\n<pre>\n&lt;!DOCTYPE HTM...
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...
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....
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&lt;string&gt;</code>, and that calls itself recursively to eventually return one big <code>Collection&lt;string&gt;</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&lt;T&gt;</co...
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&amp; str ) { cout &lt;&lt; "case 1:" &lt;&lt; str; return true; } bool CaseMethod2( int abc, const std::string&amp; str ) { cout &lt;&lt; "case 2:" &lt;&lt; str; return true; } bool CaseMethod3( int abc, const std::string&amp; str ) { cout &lt;&lt; "case 3:" &lt;&lt; str; return true; } public: bool TestSwitch( int num ) { bool ( MyClass::*CaseMethod )( int, const std::string&amp; ); switch ( num ) { case 1: CaseMethod = &amp;MyClass::CaseMethod1; break; case 2: CaseMethod = &amp;MyClass::CaseMethod2; break; case 3: CaseMethod = &amp;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 ...
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 &lt;- the one dealing with my data</li> <li>AuthenticationService.svc &lt;- 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...
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...
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. ![triangle](https://i.stack.imgur.com/B0nfz.jpg)
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&gt;0); //Precondition if (value&gt;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 &gt;= 0 ); //Precondition assert(value &lt;= 90); //Precondition if(value &lt; 0) //Just in case value = 0; if (value &gt; 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 wikipedi...
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&amp; inParameters, IWbemClassObjectFreeThreaded&amp; inParametersClass, IWbemClassObjectFreeThreaded&amp; 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...
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 ...
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...\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 &amp;aacute; letters'" body = ET.SubElement(root,'body') h1 = ET.SubElement(body,'h1') h1.text = "And I like the fact that 3 &gt; 1" tree = ET.ElementTree(root) tree.write('foo.xhtml') # more foo.xhtml &lt;html&gt;&lt;head&gt;&lt;script type="text/javascript"&gt;var a = 'I love &amp;amp;aacute; letters'&lt;/script&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;And I like the fact that 3 &amp;gt; 1&lt;/h1&gt; &lt;/body&gt;&lt;/html&gt; </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 = ....
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 &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> ```
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 &amp;aacute; letters' </script> </head> <body> <h1>And I like the fact that 3 &gt; 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 &amp;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>&lt;system.serviceModel&gt; &lt;service blah blah blah&gt; &lt;host&gt; &lt;baseAddresses&gt; &lt;add baseAddress="http://localhost/blah" /&gt; &lt;/baseAddresses&gt; &lt;/host&gt; &lt;/service&gt; &lt;/system.serviceModel&gt; </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 i...
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>&lt;system.web&gt; &lt;authentication mode="Forms"&gt; &lt;forms loginUrl="Default.aspx" path="/" protection="All" timeout="360" name="MyAppName" cookieless="UseCookies" /&gt; &lt;/authentication&gt; &lt;authorization &gt; &lt;allow users="*"/&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;location path="Admin"&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;allow roles="Admin"/&gt; &lt;deny users="*"/&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/location&gt; </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 shoul...
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 &lt; [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 &lt; convert(datetime, '01/...
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/ms...
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 (...
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 &lt; 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 (...
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&lt;String&gt; 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&lt;int&gt; vec; vector&lt;int&gt;::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 &lt;&lt; *i &lt;&lt; " "; //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 ...
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 &lt;- built binaries -/build &lt;- build time temporary object (eg. .obj, cmake intermediates) -/doc &lt;- 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 ...
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()</co...
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/\...
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 h...
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 Vi...
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.D...
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...
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(); } } ```