instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>What is the best way to design an interface so that very long drop down values that get trucated due to size limits do not create a very bad user experience. My question is for web applications.</p> <p>Could you please send your suggestions.</p> <p>Thanks.</p>
<p>One option is to use 'type-ahead' with postback (AJAX) to reduce the size of the list.</p>
<p>have a tooltip for each item in the dropdown list so when a user hovers his mouse pointer to an item, he'll still be able to see the full description of the item.</p> <p>or have your dropdown width auto-resize to the longest description in the list.</p>
16,021
<pre><code>string [] files = new string[2]; files[0] = "ThinkFarAhead.Example.Settings.Configuration_Local.xml"; files[1] = "ThinkFarAhead.Example.Settings.Configuration_Global.xml"; //Resharper complains this is an "access to modified closure" for (int i = 0; i &lt; files.Length; i++ ) { // Resharper disable AccessToModifiedClosure if(Array.Exists(Assembly.GetExecutingAssembly().GetManifestResourceNames(), delegate(string name) { return name.Equals(files[i]); })) return Assembly.GetExecutingAssembly().GetManifestResourceStream(files[i]); // ReSharper restore AccessToModifiedClosure } </code></pre> <p>The above seems to work fine though ReSharper complains that this is "access to modified closure". Can any one shed light on this?</p> <p>(this topic continued <a href="https://stackoverflow.com/questions/304258">here</a>)</p>
<p>In this case, it's okay, since you are actually executing the delegate <em>within</em> the loop.</p> <p>If you were saving the delegate and using it later, however, you'd find that all of the delegates would throw exceptions when trying to access files[i] - they're capturing the <em>variable</em> <code>i</code> rather than its value at the time of the delegates creation.</p> <p>In short, it's something to be aware of as a <em>potential</em> trap, but in this case it doesn't hurt you.</p> <p>See the <a href="http://jonskeet.uk/csharp/csharp2/delegates.html#captured.variables" rel="noreferrer">bottom of this page</a> for a more complex example where the results are counterintuitive.</p>
<p>"files" is a <strong>captured outer variable</strong> because it has been captured by the anonymous delegate function. Its lifetime is extended by the anonymous delegate function.</p> <blockquote> <p>Captured outer variables When an outer variable is referenced by an anonymous function, the outer variable is said to have been captured by the anonymous function. Ordinarily, the lifetime of a local variable is limited to execution of the block or statement with which it is associated (Local variables). However, the lifetime of a captured outer variable is extended at least until the delegate or expression tree created from the anonymous function becomes eligible for garbage collection.</p> </blockquote> <p><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/expressions#outer-variables" rel="nofollow noreferrer">Outer Variables on MSDN</a></p> <blockquote> <p>When a local variable or a value parameter is captured by an anonymous function, the local variable or parameter is no longer considered to be a fixed variable (Fixed and moveable variables), but is instead considered to be a moveable variable. Thus any unsafe code that takes the address of a captured outer variable must first use the fixed statement to fix the variable. Note that unlike an uncaptured variable, a captured local variable can be simultaneously exposed to multiple threads of execution.</p> </blockquote>
29,151
<p>I've created a MATLAB class, something like:</p> <pre><code>classdef myclass properties x_array = []; end methods function increment(obj,value) obj.x_array = [obj.x_array ; value); end end end </code></pre> <p>The problem is, the property <code>x_array</code> is never modified when I invoke the <code>increment()</code> function: ex:</p> <pre><code>&gt;&gt;s = myclass &gt;&gt;increment(s,5) &gt;&gt;s.x_array ans = [] </code></pre> <p>I did some research, and I reached a conclusion that this is because of MATLAB using Lazy Copy for objects, making my class inherit the HANDLE class should have solved this, but it didn't, does anybody know why this is happening? And if extending the handle class is indeen the solution, isn't this the right way to do it:</p> <pre><code>classdef myclass &lt; handle </code></pre> <p>or are there any extra steps?</p>
<p>This is similar to <a href="https://stackoverflow.com/questions/209005/object-oriented-matlab-properties">this question</a>. In short all you should have to do is inherit from handle class.</p> <p>Quick example </p> <p>Contents of file myclass.m</p> <pre><code>classdef myclass&lt;handle properties x_array = [] end methods function obj=increment(obj,val) obj.x_array=[obj.x_array val]; end end end </code></pre> <p>Now from the Matlab command prompt, you can do the following</p> <pre><code>&gt;&gt; s=myclass; &gt;&gt; s.increment(5) &gt;&gt; s.increment(6) &gt;&gt; s s = myclass handle properties: x_array: [5 6] lists of methods, events, superclasses </code></pre>
<p>There is an easier way. You only need to overwrite your initial instance <code>s</code> as follows:</p> <pre><code>s = increment(s,5); </code></pre> <p>More information <a href="https://www.mathworks.com/help/matlab/matlab_oop/matlab-vs-other-oo-languages.html" rel="nofollow noreferrer">in the documentation</a>.</p> <p>PS: While it is fine to use <em>handle</em>, the way copy function works is different and you should be careful about the way you use it. When you use <em>handle</em>, in fact you are making a new address/reference to an obj</p>
34,318
<p>When I try to execute the following code in IE:</p> <pre><code> &lt;script type="text/javascript"&gt; google.load("jquery", 1); google.load("jqueryui", "1.5.3"); $(document).ready(function() { $("#main-dialog").draggable(); }); &lt;/script&gt; &lt;div id="main-dialog"&gt; This is just some simple content &lt;/div&gt; </code></pre> <p>I get the following error message:</p> <blockquote> <p>Object doesn't support this property or method</p> </blockquote> <p>Why am I getting this error?</p>
<p>Essentially, yes, you need to at least be able to read and understand CAML. However you can probably get out of writing it. I've used these tools:</p> <p>U2U CAML Query Builder by U2U - <a href="http://www.u2u.be/res/Tools/CamlQueryBuilder.aspx" rel="nofollow noreferrer">download</a> and <a href="http://www.u2u.be/res/Tools/SharePointCamlQueryBuilder.aspx" rel="nofollow noreferrer">online</a></p> <p>Yet Another CAML Query Tool by Carlos Segura Sanz (good if you know SQL) - <a href="http://yacamlqt.codeplex.com/" rel="nofollow noreferrer">CodePlex</a></p>
<p>I depends on what you want to do.<br> You can also use the MOSS search engine to search for documents.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms544561.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms544561.aspx</a></p>
44,717
<p><a href="https://stackoverflow.com/questions/2262/aspnet-url-rewriting">So this post</a> talked about how to actually implement url rewriting in an ASP.NET application to get "friendly urls". That works perfect and it is great for sending a user to a specific page, but does anyone know of a good solution for creating "Friendly" URLs inside your code when using one of the tools referenced?</p> <p>For example listing a link inside of an asp.net control as ~/mypage.aspx?product=12 when a rewrite rule exists would be an issue as then you are linking to content in two different ways.</p> <p>I'm familiar with using DotNetNuke and FriendlyUrl's where there is a "NavigateUrl" method that will get the friendly Url code from the re-writer but I'm not finding examples of how to do this with UrlRewriting.net or the other solutions out there. </p> <p>Ideally I'd like to be able to get something like this.</p> <pre><code>string friendlyUrl = GetFriendlyUrl("~/MyUnfriendlyPage.aspx?myid=13"); </code></pre> <p><strong>EDIT:</strong> I am looking for a generic solution, not something that I have to implement for every page in my site, but potentially something that can match against the rules in the opposite direction.</p>
<p>See <a href="http://www.codethinked.com/post/2008/08/20/Exploring-SystemWebRouting.aspx" rel="nofollow noreferrer">System.Web.Routing</a></p> <p>Routing is a different from rewriting. Implementing this technique does require minor changes to your pages (namely, any code accessing querystring parameters will need to be modified), but it allows you to generate links based on the routes you define. It's used by ASP.NET MVC, but can be employed in any ASP.NET application.</p> <p>Routing is part of .Net 3.5 SP1</p>
<p>Create a UrlBuilder class with methods for each page like so:</p> <pre><code>public class UrlBuilder { public static string BuildProductUrl(int id) { if (true) // replace with logic to determine if URL rewriting is enabled { return string.Format("~/Product/{0}", id); } else { return string.Format("~/product.aspx?id={0}", id); } } } </code></pre>
11,273
<p>OK,</p> <p>Here is my problem, I have a master page with a HEAD section that contains my JS includes. I have one JS include </p> <pre><code>&lt;script src="Includes/js/browser.js" language="javascript" type="text/javascript"&gt;&lt;/script&gt; </code></pre> <p>In my page i consume it like this:</p> <pre><code>&lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; .... &lt;script type="text/javascript"&gt;registerBookmarkButton();&lt;/script&gt; .... &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p>And i get this error:</p> <pre><code>Line: 216 Error: Object expected </code></pre> <p>Please tell me i just missed something and it's a stupid mistake</p>
<p>If you can use Firefox, I would highly recommend installing and enabling the Firebug addon.</p> <p>Otherwise, see some of the following for tools that might help:</p> <ul> <li><a href="https://stackoverflow.com/questions/3404/javascript-troubleshooting-tools-in-ie">Javascript troubleshooting tools in IE</a></li> <li><a href="https://stackoverflow.com/questions/179054/is-there-any-good-or-reliable-way-to-figure-out-where-a-javascript-error-is-usi">Is there any good or reliable way to figure out where a JavaScript error is using only an Internet Explorer error message?</a> </li> <li><a href="https://stackoverflow.com/questions/313186/what-is-the-best-development-add-on-for-browsers-closed">What is the Best Development “add on” for Browsers [closed]</a></li> <li><a href="https://stackoverflow.com/questions/170164/debugging-javascript-in-ie">Debugging javascript in IE?</a></li> </ul>
<p>check if youre using a keyword as an identifier in yoru code</p> <hr> <p><a href="http://mattsnider.com/languages/javascript/reserved-words-in-javascript/" rel="nofollow noreferrer">http://mattsnider.com/languages/javascript/reserved-words-in-javascript/</a></p> <p><a href="http://bytes.com/groups/javascript/424640-error-object-expected" rel="nofollow noreferrer">http://bytes.com/groups/javascript/424640-error-object-expected</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/0779sbks.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/0779sbks.aspx</a></p>
42,334
<p>cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;</p> <p>in this method</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; </code></pre> <p>but I can only see it when I select that cell otherwise it's not visible.and it work perfectly when background is white. I am sure that I need to set a property, but I don't know which property I need to change to make this thing work.</p> <p>thanks in advance.</p> <p>cheers.</p>
<p>It would appear that the disclosure indicator is a gray, high-alpha image, so overlaying that over a black background makes it invisible. If you want to do this, you'll need to add your own UIImageView to the cell's contentView.</p>
<p>I made a solution where I added an ImageView with addSubView in the normal fashion, with an image that was not black (in my case, a grey filled circle) at the position where the accessory appears. </p> <p>That allows the arrow to be seen and still have a dark/black table cell background color.</p> <p>Maybe not the most kosher solution, but it makes the arrow visible, and I get notified of accessory clicks without subclassing or writing lots of code.</p>
30,951
<p>We have a SharePoint site on it's own domain and are debating using Forms Authentication or Active Directory. Really we would like the power of kerberos with the flexibility and transparancy of a forms authentication (like storing the users in sqlserver using sqlmembershipprovider in asp.net). Is there any way to force Active Directory to authenticate against our user store, or can we set up a kerberos authentication server that isn't active directory?</p> <p>Thanks!</p>
<p>Maybe ADAM might be helpful for your scenario: <a href="http://www.microsoft.com/windowsserver2003/adam/default.mspx" rel="nofollow noreferrer">http://www.microsoft.com/windowsserver2003/adam/default.mspx</a></p> <p>The problem with Forms authentication is that it misses some end user GUI controls like: change password, forgot password etc. We implemented it on a project and had to do a lot of coding to achieve good usability for the end users.</p>
<p>You might also consider using Forefront User Access Gateway (UAG). I have implemented multiple times and it works much better than ISA and in fact, bits are installed along with SharePoint for the User Profile Service - <a href="http://www.microsoft.com/en-us/server-cloud/forefront/unified-access-gateway.aspx" rel="nofollow">http://www.microsoft.com/en-us/server-cloud/forefront/unified-access-gateway.aspx</a>.</p> <p>UAG gives you better security and flexibility and it is 'SharePoint Aware'. Based on the technology developed by Whale Communications (purchased by MS), it provides a common gateway for all of your applications (in addition to SharePoint).</p> <p>There is one 'gotcha' in the way UAG logs out however but I have the fix for you here: <a href="http://davidmsterling.blogspot.com/2011/08/sharepoint-logout-with-uag.html" rel="nofollow">http://davidmsterling.blogspot.com/2011/08/sharepoint-logout-with-uag.html</a>.</p> <p>To date, 20 clients have moved from ISA to Forefront UAG and all love it.</p> <p>David Sterling - <a href="http://davidmsterling.blogspot.com" rel="nofollow">http://davidmsterling.blogspot.com</a> - <a href="http://www.sterling-consulting.com" rel="nofollow">http://www.sterling-consulting.com</a> - <a href="http://www.sharepoint-blog.com" rel="nofollow">http://www.sharepoint-blog.com</a></p>
14,220
<p>Can I use three-phase stepper motors with pololu style stepper drivers? If not, what kind of drivers support three-phase motors?</p>
<p>Three phase stepper motors are superior in several ways: <a href="http://www.fullingmotorusa.com/the-new-range-of-3-phase-stepper-motors/" rel="nofollow noreferrer">see this advertising literature.</a> Unfortunately for using this with simple stepper drivers, they have an extra coil of wire that simple drivers have no way to control. Two phase motors have two isolated coils, while three phase motors have three coils connected in a star configuration.</p> <p>Texas Instruments offers this design suggestion for using three-phase motors: <a href="http://www.ti.com/lit/ug/tiducn7/tiducn7.pdf" rel="nofollow noreferrer">TI White Paper</a>. Ultimately, it is driven by three synchronized PWM signals connected to three H-bridges, each driving one of the three motor wires. One could build a board with a micro-controller that accepted step and direction pulses and output the three-phase drive. At that level, you could substitute the micro-control-plus-H-bridge board for the Pololu-style driver in an existing 3D printer framework. You would need to configure the steps-per-mm correctly for the new drive system. </p> <p>If you did this, and the sales literature is correct, you should get quieter operation with higher torque. How that would affect operation would depend on the torque of the motor, the rotating mass of the motor, and the gearing or belt drive you use. </p> <p>Like two-phase motors, high torque at high speed requires driving the motor with a voltage much higher than the "specified" steady-state motor voltage.</p>
<p>3D printers typically use bipolar two-phase stepper motors, and it is possible that Pololu-style carriers for stepper-motor drivers only support such motors.</p> <p>Certainly, drivers for three-phase stepper motors exist, for example, the Trinamic TMC5062, but I cannot find any Pololu-style carriers for this chip. Even if a Pololu-style carrier can be sourced, it is not certain that existing 3D-printer firmware can be configured to control it.</p> <p>If you are thinking about re-purposing some three-phase motors, I would advise that you purchase standard bipolar motors, instead. Bipolar two-phase motors suitable for 3D printing are not that expensive.</p> <p><a href="http://www.trinamic.com/fileadmin/assets/Support/Appnotes/AN030-TMC5062_3_Phase_Motor.pdf" rel="nofollow noreferrer">Trinamic TMC5062</a></p>
1,324
<p>Here's some background on what I'm trying to do:</p> <ol> <li>Open a serial port from a mobile device to a Bluetooth printer.</li> <li>Send an EPL/2 form to the Bluetooth printer, so that it understands how to treat the data it is about to receive.</li> <li>Once the form has been received, send some data to the printer which will be printed on label stock.</li> <li>Repeat step 3 as many times as necessary for each label to be printed.</li> </ol> <p>Step 2 only happens the first time, since the form does not need to precede each label. My issue is that when I send the form, if I send the label data too quickly it will not print. Sometimes I get "Bluetooth Failure: Radio Non-Operational" printed on the label instead of the data I sent.</p> <p>I have found a way around the issue by doing the following:</p> <pre><code>for (int attempt = 0; attempt &lt; 3; attempt++) { try { serialPort.Write(labelData); break; } catch (TimeoutException ex) { // Log info or display info based on ex.Message Thread.Sleep(3000); } } </code></pre> <p>So basically, I can catch a TimeoutException and retry the write method after waiting a certain amount of time (three seconds seems to work all the time, but any less and it seems to throw the exception every attempt). After three attempts I just assume the serial port has something wrong and let the user know.</p> <p>This way seems to work ok, but I'm sure there's a better way to handle this. There are a few properties in the SerialPort class that I think I need to use, but I can't really find any good documentation or examples of how to use them. I've tried playing around with some of the properties, but none of them seem to do what I'm trying to achieve. </p> <p>Here's a list of the properties I have played with:</p> <ul> <li>CDHolding </li> <li>CtsHolding</li> <li>DsrHolding</li> <li>DtrEnable</li> <li>Handshake</li> <li>RtsEnable</li> </ul> <p>I'm sure some combination of these will handle what I'm trying to do more gracefully. </p> <p>I'm using C# (2.0 framework), a Zebra QL 220+ Bluetooth printer and a windows Mobile 6 handheld device, if that makes any difference for solutions.</p> <p>Any suggestions would be appreciated.</p> <p>[UPDATE]</p> <p>I should also note that the mobile device is using Bluetooth 2.0, whereas the printer is only at version 1.1. I'm assuming the speed difference is what's causing the printer to lag behind in receiving the data.</p>
<p>Flow control is the correct answer here, and it may not be present/implemented/applicable to your bluetooth connection.</p> <p>Check out the Zebra specification and see if they implement, or if you can turn on, software flow control (xon, xoff) which will allow you to see when the various buffers are getting full.</p> <p>Further, the bluetooth radio is unlikely to be capable of transmitting faster than 250k at the maximum. You might consider artificially limiting it to 9,600bps - this will allow the radio a lot of breathing room for retransmits, error correction, detection, and its own flow control.</p> <p>If all else fails, the hack you're using right now isn't bad, but I'd call Zebra tech support and find out what they recommend before giving up.</p> <p>-Adam</p>
<p>The issue is likely not with the serial port code, but with the underlying bluetooth stack. The port you're using is purely virtual, and it's unlikely that any of the handshaking is even implemented (as it would be largely meaningless). CTS/RTS DTR/DSR are simply non-applicable for what you're working on.</p> <p>The underlying issue is that when you create the virtual port, underneath it has to bind to the bluetooth stack and connect to the paired serial device. The port itself has no idea how long that might take and it's probably set up to do this asynchronously (though it would be purely up to the device OEM how that's done) to prevent the caller from locking up for a long period if there is no paired device or the paired device is out of range.</p> <p>While your code may feel like a hack, it's probably the best, most portable way to do what you're doing.</p> <p>You could use a bluetooth stack API to try to see if the device is there and alive before connecting, but there is no standardization of stack APIs, so the Widcom and Microsoft APIs differ on how you'd do that, and Widcom is proprietary and expensive. What you'd end up with is a mess of trying to discover the stack type, dynamically loading an appropriate verifier class, having it call the stack and look for the device. In light of that, your simple poll seems much cleaner, and you don't have to shell out a few $k for the Widcom SDK.</p>
27,444
<p>How do I implement this equality comparison is a sane java way? </p> <pre><code>boolean x = (a == b) || (a.equals(b)) </code></pre> <p>I want to make sure the content of both objects is equal but null is also ok, i.e. both can be null and are thus equal.</p> <p>Update: just to be clear, I have to implement this comparison several times and don't want to copy&amp;paste this stuff every time, especially with lenghty object names. With 'a' and 'b' it looks small and simple, but tends to grow... I'd like to know if I'm missing some existing Java feature for this.</p>
<p>What happens if a is null but b is not? I think you really want:</p> <pre><code>boolean x = (a == null &amp;&amp; b == null) || (a != null &amp;&amp; a.equals(b)) </code></pre> <p><strong>EDIT:</strong> You could implement a static NullEquals method for the class that takes two objects of that class and does the comparison as above to avoid rewriting and make the code a little cleaner.</p> <pre><code>public class MyClass { public static boolean NullEquals( MyClass a, MyClass b ) { return (a == null &amp;&amp; b == null) || (a != null &amp;&amp; a.equals(b)); } } if (MyClass.NullEquals(a,b)) { ... } </code></pre>
<p>Can not add comment, Treat this as comment to <a href="https://stackoverflow.com/users/22656/jon-skeet">Jon Skeet</a>'s answer.</p> <p>Does Null = Null true or false in Java. </p> <p>More specifically what should be Null = Null should be treated and How and why the different language treat this case ?</p>
43,727
<p>I want to simulate a 'Web 2.0' Lightbox style UI technique in a <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a> application. That is, to draw attention to some foreground control by 'dimming' all other content in the client area of a window. </p> <p>The obvious solution is to create a control that is simply a partially transparent rectangle that can be docked to the client area of a window and brought to the front of the Z-Order. It needs to act like a dirty pain of glass through which the other controls can still be seen (and therefore continue to paint themselves). Is this possible? </p> <p>I've had a good hunt round and tried a few techniques myself but thus far have been unsuccessful. If it is not possible, what would be another way to do it?</p> <p>See: <a href="http://www.useit.com/alertbox/application-design.html" rel="noreferrer">http://www.useit.com/alertbox/application-design.html</a> (under the Lightbox section for a screenshot to illustrate what I mean.)</p>
<p>Can you do this in .NET/C#? </p> <p>Yes you certainly can but it takes a little bit of effort. I would recommend the following approach. Create a top level Form that has no border or titlebar area and then give make sure it draws no client area background by setting the TransparencyKey and BackColor to the same value. So you now have a window that draws nothing...</p> <pre><code>public class DarkenArea : Form { public DarkenArea() { FormBorderStyle = FormBorderStyle.None; SizeGripStyle = SizeGripStyle.Hide; StartPosition = FormStartPosition.Manual; MaximizeBox = false; MinimizeBox = false; ShowInTaskbar = false; BackColor = Color.Magenta; TransparencyKey = Color.Magenta; Opacity = 0.5f; } } </code></pre> <p>Create and position this DarkenArea window over the client area of your form. Then you need to be able to show the window without it taking the focus and so you will need to platform invoke in the following way to show without it becoming active...</p> <pre><code>public void ShowWithoutActivate() { // Show the window without activating it (i.e. do not take focus) PlatformInvoke.ShowWindow(this.Handle, (short)SW_SHOWNOACTIVATE); } </code></pre> <p>You need to make it actually draw something but exclude drawing in the area of the control you want to remain highlighted. So override the OnPaint handler and draw in black/blue or whatever you want but excluding the area you want to remain bright...</p> <pre><code>protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); // Do your painting here be exclude the area you want to be brighter } </code></pre> <p>Last you need to override the WndProc to prevent the mouse interacting with the window if the user tries something crazy like clicking on the darkened area. Something like this...</p> <pre><code>protected override void WndProc(ref Message m) { if (m.Msg == (int)WM_NCHITTEST) m.Result = (IntPtr)HTTRANSPARENT; else base.WndProc(ref m); } </code></pre> <p>That should be enough to get the desired effect. When you are ready to reverse the effect you dispose of the DarkenArea instance and carry on.</p>
<p>Every form has "Opacity" property. Set it to 50% (or 0.5 from code) so will be half transparent. Remove borders and show it maximized before the form you want to have focus. You can change BackColor of the form or even set background image for different effects.</p>
9,860
<p>Ok, I asked a question earlier about Flex and ADO.NET Data Services but didn't get much response so I thought I'd rephrase. Does anyone have any experience building Adobe Flex applications with a .NET back-end? If so, what architecture did you use and what third-party tools if any did you employ. I've read a little about doing Flex remoting with WebORB but it seems more complicated than it should be, are web services an adequate alternative?</p>
<p>I've mainly used plain ASP.NET pages that return XML for situations that are mainly one-way (data from ASP.NET --> Flex/Flash) communication. The Flex side just uses a URLLoader to hit the ASP.NET page and loads the result as XML.</p> <p>If the communication needs to be a little more two-sided (sending more than a couple parameters to ASP.NET lets say), I have used standard ASP.NET webservices. </p> <p>I've never used WebOrb or Flex remoting because I've never really needed that type of interaction between the server and the SWF.</p> <p>Hope that helps.</p>
<p>I've mainly used plain ASP.NET pages that return XML for situations that are mainly one-way (data from ASP.NET --> Flex/Flash) communication. The Flex side just uses a URLLoader to hit the ASP.NET page and loads the result as XML.</p> <p>If the communication needs to be a little more two-sided (sending more than a couple parameters to ASP.NET lets say), I have used standard ASP.NET webservices. </p> <p>I've never used WebOrb or Flex remoting because I've never really needed that type of interaction between the server and the SWF.</p> <p>Hope that helps.</p>
6,688
<p>How to customize the color of the symbol inserted in the "glasses mode" in Emacs? I have not found the option for this. Can anyone suggest anything?</p>
<p>There's no option to set the face for the inserted separator (and from a brief study of the docs for emacs overlays, I don't think it's simple to add).</p> <p>You can customize the face used for the capital letters that glasses-mode splits on; it's called <code>glasses-face</code>.</p>
<p>The easiest way to see the customisations available for <code>glasses-mode</code> is to enter:</p> <pre><code>M-x customize-group </code></pre> <p>and then enter <code>glasses</code> at the <code>Customize group (default emacs):</code> prompt.</p> <p>However, you will need to set up a <a href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Saving-Customizations.html" rel="nofollow noreferrer">custom.el file</a> first.</p>
14,082
<p>I know that this should be easy but how do I export/save a DataGridView to excel?</p>
<p>You can use this library for more detailed formatting<br> <a href="http://www.carlosag.net/Tools/ExcelXmlWriter/" rel="nofollow noreferrer">http://www.carlosag.net/Tools/ExcelXmlWriter/</a></p> <p>There are samples in the page.</p>
<p>Here some code we use to do it across lots of our apps. We have a special method to clean up "not exportable" column. Additionally, we don't export cols without headers but you can adjust that logic to your needs.</p> <p>Edit: The code formatter doesn't love vb.net - you can copy/paste into visual studio and it will be fine.</p> <pre><code> Public Overloads Shared Function BuildExcel(ByVal gView As System.Web.UI.WebControls.GridView) As String PrepareGridViewForExport(gView) Dim excelDoc As New StringBuilder Dim startExcelXML As String = " " + _ " " + _ " " + _ " " + _ " " + _ " " + _ " " + _ " " + _ " " Dim endExcelXML As String = "" Dim rowCount As Int64 = 0 Dim sheetCount As Int16 = 1 excelDoc.Append(startExcelXML) excelDoc.Append("") excelDoc.Append("") ' write out column headers excelDoc.Append("") For x As Int32 = 0 To gView.Columns.Count - 1 'Only write out columns that have column headers. If Not gView.Columns(x).HeaderText = String.Empty Then excelDoc.Append("") excelDoc.Append(gView.Columns(x).HeaderText.ToString) excelDoc.Append("") End If Next excelDoc.Append("") For r As Int32 = 0 To gView.Rows.Count - 1 rowCount += rowCount If rowCount = 64000 Then rowCount = 0 sheetCount += sheetCount excelDoc.Append("") excelDoc.Append(" ") excelDoc.Append("") excelDoc.Append("") End If excelDoc.Append("") For c As Int32 = 0 To gView.Rows(r).Cells.Count - 1 'Don't write out a column without a column header. If Not gView.Columns(c).HeaderText = String.Empty Then Dim XMLstring As String = gView.Rows(r).Cells(c).Text XMLstring = XMLstring.Trim() XMLstring = XMLstring.Replace("&", "&") XMLstring = XMLstring.Replace(">", ">") XMLstring = XMLstring.Replace("" + "") excelDoc.Append(XMLstring) excelDoc.Append("") End If Next excelDoc.Append("") Next excelDoc.Append("") excelDoc.Append(" ") excelDoc.Append(endExcelXML) Return excelDoc.ToString End Function Shared Sub PrepareGridViewForExport(ByVal gview As System.Web.UI.Control) ' Cleans up grid for exporting. Takes links and visual elements and turns them into text. Dim lb As New System.Web.UI.WebControls.LinkButton Dim l As New System.Web.UI.WebControls.Literal Dim name As String = String.Empty For i As Int32 = 0 To gview.Controls.Count - 1 If TypeOf gview.Controls(i) Is System.Web.UI.WebControls.LinkButton Then l.Text = CType(gview.Controls(i), System.Web.UI.WebControls.LinkButton).Text gview.Controls.Remove(gview.Controls(i)) gview.Controls.AddAt(i, l) ElseIf TypeOf gview.Controls(i) Is System.Web.UI.WebControls.DropDownList Then l.Text = CType(gview.Controls(i), System.Web.UI.WebControls.DropDownList).SelectedItem.Text gview.Controls.Remove(gview.Controls(i)) gview.Controls.AddAt(i, l) ElseIf TypeOf gview.Controls(i) Is System.Web.UI.WebControls.CheckBox Then l.Text = CType(gview.Controls(i), System.Web.UI.WebControls.CheckBox).Checked.ToString gview.Controls.Remove(gview.Controls(i)) gview.Controls.AddAt(i, l) End If If gview.Controls(i).HasControls() Then PrepareGridViewForExport(gview.Controls(i)) End If Next End Sub </code></pre>
4,694
<p>I was reading <a href="https://stackoverflow.com/questions/144735/best-way-to-get-started-with-programming-other-things-than-your-computer#144843">this</a> answer previously and it got me interested in purchasing a Nintendo DS Lite for learning to program embedded devices. Before I go out and splurge on a DS I had a few questions:</p> <ol> <li><p>Are there any restrictions on what you can program? The post I indicated earlier seemed to say there weren't, but clarification would be nice.</p></li> <li><p>Would I be better off buying an arduino (or similar) and going that route? I like the DS because it already has a lot of hardware built in.</p></li> <li><p>I'm thinking of getting a CycloDS Evo card, is there a better option for homebrew? </p></li> <li><p>What are the best resources to learn about DS development?</p></li> </ol> <p>Thanks for your time, If you have a DS and program on it, I'd love you hear your opinion, or alternatively if you have a better idea, I'd like to hear it too.</p> <p>Thanks =]</p>
<ol> <li><p>No, there really isn't much of a limitation beyond that of the hardware, and even that can be overcome with enough effort. Quake has been ported to DS, for example, and particle games that utilize both processors have been made. There has also been discussion on how to make higher quality 3D scenes using a double pass renderer. There are multiple resources on the Nintendo DS section of the <a href="http://forum.gbadev.org" rel="nofollow noreferrer">GBADev forums</a>. </p></li> <li><p>I would say that the DS is an excellent route to embedded systems development; there is a large and active community that is willing to answer questions and give support, and there is so much hardware built straight into the thing. It saves you the time of building a system to test on. </p></li> <li><p>The CycloDS Evolution is a good card and is fairly common, so it shouldn't be difficult - if necessary at all - to make your homebrew compatable with other cards. However, be aware that other popular choices are the M3 line and the R4 line, which are pretty much the same thing. I have a TTDS, and it works well, but not out of the box. I would reccommend the other three mentioned. </p></li> <li><p>As for beginning DS devving, I would reccommend looking at the basic examples found in the <code>examples</code> folder of devkitPro and reading the <a href="http://www.coranac.com/tonc/text/" rel="nofollow noreferrer">GBA tutorial TONC</a>, which covers many of the concepts that are used in both GBA and DS development. A more DS oriented tutorial, <a href="http://www.patater.com/manual" rel="nofollow noreferrer">Patater's Introduction to Nintendo DS Programming</a>, will help beginners get on their way in the DS world. There is also a <a href="http://nocash.emubase.de/gbatek.htm" rel="nofollow noreferrer">very comprehensive documentation spec for the GBA and DS known as GBATek</a>.</p></li> </ol>
<p>Honestly, I found the Nintendo DS and the homebrew community while I was attending an Embedded Systems course in college, and I realized the similarities between the ATmega32-based kit I was programming for the class and the hardware-level development of the Nintendo DS via libnds, and I was hooked.</p> <p>Personally, I've come from a strong C++ background, but being able to walk around with something in my pocket that I've programmed has been a goal of mine since I first got my hands on a TI-83 Plus calculator... I'm now able to realize that goal due to the Nintendo DS.</p> <p>Anyway, I hope you have as much fun getting into DS development as I have over the past months, and I wish you luck on your endeavors.</p>
17,482
<p>I've been banging my head against for wall for a while with this one.</p> <p>I want to SSH into a set of machines and check whether they are available (accepting connections and not being used). I have created a small script, tssh, which does just that:</p> <pre><code>#!/bin/bash host=$1 timeout=${2:-1} ssh -qo "ConnectTimeout $timeout" $host "[ \`who | cut -f1 | wc -l \` -eq 0 ] &amp;&amp; exit 0 || exit 1" </code></pre> <p>This script works correctly. Returning 255 if there was a connection problem, 1 if the machine is busy and 0 if everything is good. If anyone knows a better way to do this please let me know.</p> <p>So next I try and call tssh on my set of machines using a while read loop, and this is where it all goes wrong. The loop exits as soon as tssh returns 0 and never completes the full set. </p> <pre><code>while read nu ; do tssh "MYBOXES$nu" ; done &lt; &lt;(ruby -e '(0..20).each { |i| puts i }') </code></pre> <p>At first I thought this was a subshell problem but apparently not. Any help, along with comments on style/content, would be much appreciated! I know I'm going to kick myself when I find out why...</p>
<p>Chris is correct. The source of the loop breaking was SSH using stdin, however guns is correct in is usage of a looping methodology.</p> <p>If you are looping through input (a file with a list of hostnames for example), and calling SSH, you need to pass the -n parameter, otherwise your loop based on input will fail.</p> <pre><code>while read host; do ssh -n $host "remote command" &gt;&gt; output.txt done &lt;&lt; host_list_file.txt </code></pre>
<p>I'm also unsure about why it fails, but i like <code>xargs</code> and <code>seq</code>:</p> <pre><code>seq 0 20 | xargs -n1 tssh MYBOXES </code></pre>
45,078
<p>Given an integer typedef:</p> <pre><code>typedef unsigned int TYPE; </code></pre> <p>or</p> <pre><code>typedef unsigned long TYPE; </code></pre> <p>I have the following code to reverse the bits of an integer:</p> <pre><code>TYPE max_bit= (TYPE)-1; void reverse_int_setup() { TYPE bits= (TYPE)max_bit; while (bits &lt;&lt;= 1) max_bit= bits; } TYPE reverse_int(TYPE arg) { TYPE bit_setter= 1, bit_tester= max_bit, result= 0; for (result= 0; bit_tester; bit_tester&gt;&gt;= 1, bit_setter&lt;&lt;= 1) if (arg &amp; bit_tester) result|= bit_setter; return result; } </code></pre> <p>One just needs first to run reverse_int_setup(), which stores an integer with the highest bit turned on, then any call to reverse_int(<em>arg</em>) returns <em>arg</em> with its bits reversed (to be used as a key to a binary tree, taken from an increasing counter, but that's more or less irrelevant).</p> <p>Is there a platform-agnostic way to have in compile-time the correct value for max_int after the call to reverse_int_setup(); Otherwise, is there an algorithm you consider <em>better/leaner</em> than the one I have for reverse_int()?</p> <p>Thanks.</p>
<pre><code>#include&lt;stdio.h&gt; #include&lt;limits.h&gt; #define TYPE_BITS sizeof(TYPE)*CHAR_BIT typedef unsigned long TYPE; TYPE reverser(TYPE n) { TYPE nrev = 0, i, bit1, bit2; int count; for(i = 0; i &lt; TYPE_BITS; i += 2) { /*In each iteration, we swap one bit on the 'right half' of the number with another on the left half*/ count = TYPE_BITS - i - 1; /*this is used to find how many positions to the left (and right) we gotta move the bits in this iteration*/ bit1 = n &amp; (1&lt;&lt;(i/2)); /*Extract 'right half' bit*/ bit1 &lt;&lt;= count; /*Shift it to where it belongs*/ bit2 = n &amp; 1&lt;&lt;((i/2) + count); /*Find the 'left half' bit*/ bit2 &gt;&gt;= count; /*Place that bit in bit1's original position*/ nrev |= bit1; /*Now add the bits to the reversal result*/ nrev |= bit2; } return nrev; } int main() { TYPE n = 6; printf("%lu", reverser(n)); return 0; } </code></pre> <p>This time I've used the 'number of bits' idea from TK, but made it somewhat more portable by not assuming a byte contains 8 bits and instead using the CHAR_BIT macro. The code is more efficient now (with the inner for loop removed). I hope the code is also slightly less cryptic this time. :)</p> <p>The need for using count is that the number of positions by which we have to shift a bit varies in each iteration - we have to move the rightmost bit by 31 positions (assuming 32 bit number), the second rightmost bit by 29 positions and so on. Hence count must decrease with each iteration as i increases. </p> <p>Hope that bit of info proves helpful in understanding the code... </p>
<p>How about:</p> <pre><code>long temp = 0; int counter = 0; int number_of_bits = sizeof(value) * 8; // get the number of bits that represent value (assuming that it is aligned to a byte boundary) while(value &gt; 0) // loop until value is empty { temp &lt;&lt;= 1; // shift whatever was in temp left to create room for the next bit temp |= (value &amp; 0x01); // get the lsb from value and set as lsb in temp value &gt;&gt;= 1; // shift value right by one to look at next lsb counter++; } value = temp; if (counter &lt; number_of_bits) { value &lt;&lt;= counter-number_of_bits; } </code></pre> <p>(I'm assuming that you know how many bits value holds and it is stored in number_of_bits)</p> <p>Obviously temp needs to be the longest imaginable data type and when you copy temp back into value, all the extraneous bits in temp should magically vanish (I think!). </p> <p>Or, the 'c' way would be to say :</p> <pre><code>while(value) </code></pre> <p>your choice</p>
8,922
<p>in XSLT processing, is there a performance difference between apply-template and call-template? In my stylesheets there are many instances where I can use either, which is the best choice?</p>
<p>As with all performance questions, the answer will depend on your particular configuration (in particular the XSLT processor you're using) and the kind of processing that you're doing.</p> <p><code>&lt;xsl:apply-templates&gt;</code> takes a sequence of nodes and goes through them one by one. For each, it locates the template with the highest priority that matches the node, and invokes it. So <code>&lt;xsl:apply-templates&gt;</code> is like a <code>&lt;xsl:for-each&gt;</code> with an <code>&lt;xsl:choose&gt;</code> inside, but more modular.</p> <p>In contrast, <code>&lt;xsl:call-template&gt;</code> invokes a template by name. There's no change to the context node (no <code>&lt;xsl:for-each&gt;</code>) and no choice about which template to use.</p> <p>So with exactly the same circumstances, you might imagine that <code>&lt;xsl:call-template&gt;</code> will be faster because it's doing less work. But if you're in a situation where either <code>&lt;xsl:apply-templates&gt;</code> or <code>&lt;xsl:call-template&gt;</code> could be used, you're probably going to be doing the <code>&lt;xsl:for-each&gt;</code> and <code>&lt;xsl:choose&gt;</code> yourself, in XSLT, rather than the processor doing it for you, behind the scenes. So in the end my guess it that it will probably balance out. But as I say it depends a lot on the kind of optimisation your processor has put into place and exactly what processing you're doing. Measure it and see.</p> <p>My rules of thumb about when to use matching templates and when to use named templates are:</p> <ul> <li>use <code>&lt;xsl:apply-templates&gt;</code> and matching templates if you're processing individual nodes to create a result; use modes if a particular node needs to be processed in several different ways (such as in the table of contents vs the body of a document)</li> <li>use <code>&lt;xsl:call-template&gt;</code> and a named template if you're processing something other than an individual node, such as strings or numbers or sets of nodes</li> <li>(in XSLT 2.0) use <code>&lt;xsl:function&gt;</code> if you're returning an atomic value or an existing node</li> </ul>
<p>It may depend on the xml parser you are using. I can't speak for anything but .NET 2003 parser where I did some informal performance tests on <a href="http://www.dpawson.co.uk/xsl/sect2/pushpull.html" rel="nofollow noreferrer">push vs pull</a> XSLT code. This is similar to what you are asking: apply-template = push and call-template = pull. I was convinced push would be faster, but that was not the case. It was about even. </p> <p>Sorry I don't have the exact tests now. I recommend trying it out with your parser of choice and see if there is any major difference. My bet is there won't be. </p>
11,001
<p>In java, when using SimpleDateFormat with the pattern:</p> <pre><code>yyyy-MM-dd'T'HH:mm:ss.SSSZ </code></pre> <p>the date is outputted as:</p> <pre><code>"2002-02-01T18:18:42.703-0700" </code></pre> <p>In xquery, when using the xs:dateTime function, it gives the error:</p> <pre><code>"Invalid lexical value [err:FORG0001]" </code></pre> <p>with the above date. In order for xquery to parse properly, the date needs to look like:</p> <pre><code>"2002-02-01T18:18:42.703-07:00" - node the ':' 3rd position from end of string </code></pre> <p>which is based on the ISO 8601, whereas Java date is based on the RFC 822 standard.</p> <p>I would like to be able to easily specify the timezone in Java so that it will output the way that xquery wants.</p> <p>Thanks!</p>
<p>OK, the linked to forum post DID help, thank you. I did however find a simpler solution, which I include below:</p> <p>1) Use Apache commons.lang java library<br> 2) Use the following java code: </p> <pre class="lang-java prettyprint-override"><code>//NOTE: ZZ on end is not compatible with jdk, but allows for formatting //dates like so (note the : 3rd from last spot, which is iso8601 standard): //date=2008-10-03T10:29:40.046-04:00 private static final String DATE_FORMAT_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ"; DateFormatUtils.format(new Date(), DATE_FORMAT_8601) </code></pre>
<p>Try this:</p> <pre><code>static public String formatISO8601(Calendar cal) { MessageFormat format = new MessageFormat("{0,time}{1,number,+00;-00}:{2,number,00}"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); df.setTimeZone(cal.getTimeZone()); format.setFormat(0, df); long zoneOff = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET) / 60000L; int zoneHrs = (int) (zoneOff / 60L); int zoneMins = (int) (zoneOff % 60L); if (zoneMins &lt; 0) zoneMins = -zoneMins; return (format.format(new Object[] { cal.getTime(), new Integer(zoneHrs), new Integer(zoneMins) })); } </code></pre>
20,122
<p>By default, copying from the command prompt will prompt you to overwrite files that already exist in the target location.</p> <p>You can add "/Y" to say "Yes to all" replacements.</p> <p>But how can you say "No to all" ?</p> <p>In other words, I want to copy everything from one directory that does <strong>not</strong> already exist in the target.</p> <p>The closest thing I see is the XCOPY argument to only copy things after a specific mod-datetime.</p>
<p>Unless there's a scenario where you'd <em>not</em> want to copy existing files in the source that have changed since the last copy, why not use XCOPY with /D without specifying a date?</p>
<p>We used "robocopy" through "invoke-command" to copy a huge amount of VMs in our environment. We've discovered that "robocopy" unexpectedly exits sometimes and the whole proccess goes to down. So we've decided to use "xcopy". Now we're checking it's work and to "create" "Not for all" option we use that function (powershell):</p> <p>function gen_long_no([string]$path) { $result = ""; Get-ChildItem $path -Recurse | ? { if ($_.PSIsContainer -eq $false) { $result += "n" } }; return $result }</p> <p>Maybe helps somebody.</p>
23,217
<p>C# doesn't require you to specify a generic type parameter if the compiler can infer it, for instance:</p> <pre><code>List&lt;int&gt; myInts = new List&lt;int&gt; {0,1,1, 2,3,5,8,13,21,34,55,89,144,233,377, 610,987,1597,2584,4181,6765}; //this statement is clunky List&lt;string&gt; myStrings = myInts. Select&lt;int,string&gt;( i =&gt; i.ToString() ). ToList&lt;string&gt;(); //the type is inferred from the lambda expression //the compiler knows that it's taking an int and //returning a string List&lt;string&gt; myStrings = myInts. Select( i =&gt; i.ToString() ). ToList(); </code></pre> <p>This is needed for anonymous types where you don't know what the type parameter would be (in intellisense it shows up as <code>'a</code>) because it's added by the compiler.</p> <p>Class-level type parameters don't let you do this:</p> <pre><code>//sample generic class public class GenericDemo&lt;T&gt; { public GenericDemo ( T value ) { GenericTypedProperty = value; } public T GenericTypedProperty {get; set;} } //why can't I do: int anIntValue = 4181; var item = new GenericDemo( anIntValue ); //type inference fails //however I can create a wrapper like this: public static GenericDemo&lt;T&gt; Create&lt;T&gt; ( T value ) { return new GenericDemo&lt;T&gt; ( value ); } //then this works - type inference on the method compiles var item = Create( anIntValue ); </code></pre> <p>Why doesn't C# support this class level generic type inference?</p>
<p>Actually, your question isn't bad. I've been toying with a generic programming language for last few years and although I've never come around to actually develop it (and probably never will), I've thought a lot about generic type inference and one of my top priorities has always been to allow the construction of classes without having to specify the generic type.</p> <p>C# simply lacks the set of rules to make this possible. I think the developers never saw the neccesity to include this. Actually, the following code would be very near to your proposition and solve the problem. All C# needs is an added syntax support.</p> <pre><code>class Foo&lt;T&gt; { public Foo(T x) { … } } // Notice: non-generic class overload. Possible in C#! class Foo { public static Foo&lt;T&gt; ctor&lt;T&gt;(T x) { return new Foo&lt;T&gt;(x); } } var x = Foo.ctor(42); </code></pre> <p>Since this code actually works, we've shown that the problem is not one of semantics but simply one of lacking support. I guess I have to take back my previous posting. ;-)</p>
<p>Thanks Konrad, that's a good response (+1), but just to expand on it.</p> <p>Let's pretend that C# has an explicit constructor function:</p> <pre><code>//your example var x = new Foo( 1 ); //becomes var x = Foo.ctor( 1 ); //your problem is valid because this would be var x = Foo&lt;T&gt;.ctor&lt;int&gt;( 1 ); //and T can't be inferred </code></pre> <p>You're quite right that the first constructor can't be inferred.</p> <p>Now let's go back to the class</p> <pre><code>class Foo&lt;T&gt; { //&lt;T&gt; can't mean anything else in this context public Foo(T x) { } } //this would now throw an exception unless the //typeparam matches the parameter var x = Foo&lt;int&gt;.ctor( 1 ); //so why wouldn't this work? var x = Foo.ctor( 1 ); </code></pre> <p>Of course, if I add your constructor back in (with its alternate type) we have an ambiguous call - exactly as if a normal method overload couldn't be resolved.</p>
6,753
<p>I am debugging with breakpoints and I realize the assert call? I thought it was only for unit tests. What does it do more than breakpoint? Since I can breakpoint, why should I use Assert?</p>
<p>In a debug compilation, <a href="https://msdn.microsoft.com/en-us/library/kssw4w7z.aspx" rel="noreferrer" title="MSDN Debug.Assert"><code>Assert</code></a> takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true. </p> <p>If you compile in Release, all <a href="https://msdn.microsoft.com/en-us/library/kssw4w7z(v=vs.110).aspx#Remarks" rel="noreferrer" title="MSDN Debug.Assert Remarks"><code>Debug.Assert</code></a>'s are automatically left out.</p>
<p>The way I think of it is Debug.Assert is a way to establish a contract about how a method is supposed to be called, focusing on specifics about the values of a paramter (instead of just the type). For example, if you are not supposed to send a null in the second parameter you add the Assert around that parameter to tell the consumer not to do that.</p> <p>It prevents someone from using your code in a boneheaded way. But it also allows that boneheaded way to go through to production and not give the nasty message to a customer (assuming you build a Release build).</p>
19,770
<p>What options / methods / software are available to convert a JAR file to a managed .NET assembly?<br> Please provide all commercial and non-commercial methods in the answer.<br> These don't include solutions which require Java to be installed on the host machine.</p>
<p>I could be wrong, but I'm pretty sure that's impossible. The java byte code is different to the code produced to run on the CLR.</p> <p><strong>Snarky answer</strong>: Get the source code, and port it.</p> <p>EDIT: A little poking comes up with <a href="http://sourceforge.net/projects/ikvm/" rel="noreferrer">http://sourceforge.net/projects/ikvm/</a>, a Java Virtual Machine implementation for .NET. Not quite what you asked for, but it's probably going to be the best you can do.</p>
<p>Confronted with this situation last year, I wrote a small wrapper (in java) that read the inputs from a temp file, invoked the jar and placed the output in anther temp file. The .NET project would create the input file, call the JVM and start the wrapper, wait for it to finish and read the output file. Quick and Dirty. at least in my case</p>
9,457
<p>Short of rolling your own. There has to be something out there. FlexLM/FlexNet is overpriced, and does not work for a company like ours. The same goes for RLM. There was one product I had hope in called LUM, but IBM no longer licenses the API. So what else is available? Or do you have any known way to get LUM?</p> <p>Please help, I have been reviewing and searching on and off for over a year, and just can't find the right solution. Maybe everyone just creates their own, we'd rather not.</p>
<p>There's also <a href="http://www.reprisesoftware.com/" rel="nofollow noreferrer">Reprise</a>, coded by the people who originally wrote FlexLM. It's touted as cheaper and better than the original.</p> <p>I haven't tried it yet, since I'm doing the same search as the OP.</p>
<p>Here's one product -- SoftwarePassport: <a href="http://www.siliconrealms.com/" rel="nofollow noreferrer">http://www.siliconrealms.com/</a> They purchased Armadillo, which used to be an inexpensive software protection and licensing scheme. The price is higher than it was back then but I'll bet it's still less than FlexLM.</p> <p>I do have one suggestion regarding licensing -- as a user and developer of licensed software. Implement a "soft cutoff", so that your customers are not dead in the water if the licensing mechanism fails (or if the license expires). Provide some way for them to keep running so that there's enough time to remedy the problem.</p>
37,976
<p>When a java based application starts to misbehave on a windows machine, you want to be able to kill the process in the task manager if you can't quit the application normally. Most of the time, there's more than one java based application running on my machine. Is there a better way than just randomly killing java.exe processes in hope that you'll hit the correct application eventually?</p> <p><strong>EDIT:</strong> Thank you to all the people who pointed me to Sysinternal's Process Explorer - Exactly what I'm looking for!</p>
<p>Download <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="noreferrer">Sysinternal's Process Explorer</a>. It's a task manager much more powerfull than Windows's own manager. </p> <p>One of it's features is that you can see all the resources that each process is using (like registry keys, hard disk directories, named pipes, etc). So, browsing the resources that each java.exe process holds might help you determine wich one you want to kill. I usually find out by looking for the one that's using a certain log file directory.</p>
<p>I'd suggest downloading Process Explorer from Sysinternals and looking at the different java.exe processes more closesly, that way you can get a better idea of which one to kill.</p> <p><a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx</a></p> <p>It's very intuitive and you can find the java.exe processes and right click and goto their properties, from there you can see their command line, time of creation, etc which can help you find the process you want to kill.</p> <p>Hope it helps.</p>
8,782
<p>How do you create a simple, custom rule using the jQuery Validate plugin (using <a href="http://jqueryvalidation.org/jQuery.validator.addMethod" rel="noreferrer"><code>addMethod</code></a>) that doesn't use a regex?</p> <p>For example, what function would create a rule that validates only if at least one of a group of checkboxes is checked?</p>
<p>You can create a simple rule by doing something like this:</p> <pre><code>jQuery.validator.addMethod("greaterThanZero", function(value, element) { return this.optional(element) || (parseFloat(value) &gt; 0); }, "* Amount must be greater than zero"); </code></pre> <p>And then applying this like so:</p> <pre><code>$('validatorElement').validate({ rules : { amount : { greaterThanZero : true } } }); </code></pre> <p>Just change the contents of the 'addMethod' to validate your checkboxes.</p>
<p><strong>Step 1</strong> Included the cdn like</p> <pre><code> &lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js&quot;&gt;&lt;/script&gt; </code></pre> <p><strong>Step 2</strong> Code Like</p> <pre><code> $(document).ready(function(){ $(&quot;#submit&quot;).click(function () { $('#myform').validate({ // initialize the plugin rules: { id: { required: true, email: true }, password: { required: true, minlength: 1 } }, messages: { id: { required: &quot;Enter Email Id&quot; }, password: { required: &quot;Enter Email Password&quot; } }, submitHandler: function (form) { // for demo alert('valid form submitted'); // for demo return false; // for demo } }); }): }); </code></pre>
29,845
<p>I have a Java application that launches another java application. The launcher has a watchdog timer and receives periodic notifications from the second VM. However, if no notifications are received then the second virtual machine should be killed and the launcher will perform some additional clean-up activities.</p> <p>The question is, is there any way to do this using only java? so far I have to use some native methods to perform this operation and it is somehow ugly.</p> <p>Thanks!</p>
<p>I may be missing something but can't you call the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Process.html#destroy()" rel="noreferrer"><code>destroy()</code></a> method on the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Process.html" rel="noreferrer"><code>Process</code></a> object returned by <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Runtime.html#exec(java.lang.String)" rel="noreferrer"><code>Runtime.exec()</code></a>?</p>
<p>You should be able to do that <code>java.lang.Runtime.exec</code> and shell commands.</p>
8,919
<p>The problem is very simple. An object needs to notify some events that might be of interest to observers.</p> <p>When I sat to validate a design that I cooked up now in Ruby just to validate it.. I find myself stumped as to how to implement the object events. In .Net this would be a one-liner.. .Net also does handler method signature verification,etc. e.g.</p> <pre><code>// Object with events public delegate void HandlerSignature(int a); public event HandlerSignature MyEvent; public event HandlerSignature AnotherCriticalEvent; // Client MyObject.MyEvent += new HandlerSignature(MyHandlerMethod); // MyHandlerMethod has same signature as delegate </code></pre> <p>Is there an EventDispatcher module or something that I am missing that I can strap on to a Ruby class ? Hoping for an answer that plays along with Ruby's principle of least surprise. <em>An event would be the name of the event plus a queue of [observer, methodName] objects that need to be invoked when the event takes place.</em></p>
<p>Firstly, in Ruby there are no method signatures. The closest would be checking the function's arity. Duck typing requires thinking differently (slightly).</p> <p>The Observable module is a start, but if you have a requirement to have multiple events from a single class it might not be enough.</p> <p>This is a quick sketch. It supports methods and blocks. Modify as necessary to adapt for your code, threading approach, etc. For example, you could use method_missing to have the event name in the method name rather than having it as a parameter.</p> <pre><code>class EventBase def initialize @listeners = Hash.new end def listen_event(name, *func, &amp;p) if p (@listeners[name] ||= Array.new) &lt;&lt; p else (@listeners[name] ||= Array.new) &lt;&lt; func[0] end end def ignore_event(name, func) return if !@listeners.has_key?(name) @listeners[name].delete_if { |o| o == func } end def trigger_event(name, *args) return if !@listeners.has_key?(name) @listeners[name].each { |f| f.call(*args) } end end class MyClass &lt; EventBase def raise_event1(*args) trigger_event(:event1, *args) end def raise_event2(*args) trigger_event(:event2, *args) end end class TestListener def initialize(source) source.listen_event(:event1, method(:event1_arrival)) source.listen_event(:event2) do |*a| puts "event 2 arrival, args #{a}" end end def event1_arrival(*a) puts "Event 1 arrived, args #{a}" end end s = MyClass.new l = TestListener.new(s) s.raise_event1("here is event 1") s.raise_event2("here is event 2") </code></pre>
<p>I wrote a gem just for this because I had exactly the same issue. Try this:</p> <pre><code>gem install ruby_events </code></pre> <p>Follow the instructions as on <a href="http://github.com/nathankleyn/ruby_events" rel="nofollow noreferrer">http://github.com/nathankleyn/ruby_events</a>, but in a nutshell:</p> <pre><code>require 'rubygems' require 'ruby_events' class Example def initialize events.listen(:test_event) do |event_data| puts 'Hai there!' puts event_data end end def call_me events.fire(:test_event, 'My name is Mr Test Man!') end end e = Example.new e.call_me # Fires the event, and our handler gets called! </code></pre>
30,535
<p>This semester, I took a course in computer graphics at my University. At the moment, we're starting to get into some of the more advanced stuff like heightmaps, averaging normals, tesselation etc.</p> <p>I come from an object-oriented background, so I'm trying to put everything we do into reusable classes. I've had good success creating a camera class, since it depends mostly on the one call to gluLookAt(), which is pretty much independent of the rest of the OpenGL state machine.</p> <p>However, I'm having some trouble with other aspects. Using objects to represent primitives hasn't really been a success for me. This is because the actual render calls depend on so many external things, like the currently bound texture etc. If you suddenly want to change from a surface normal to a vertex normal for a particular class it causes a severe headache.</p> <p>I'm starting to wonder whether OO principles are applicable in OpenGL coding. At the very least, I think that I should make my classes less granular.</p> <p>What is the stack overflow community's views on this? What are your best practices for OpenGL coding?</p>
<p>The most practical approach seems to be to ignore most of OpenGL functionality that is not directly applicable (or is slow, or not hardware accelerated, or is a no longer a good match for the hardware).</p> <p>OOP or not, to render some scene those are various types and entities that you usually have:</p> <p><strong>Geometry</strong> (meshes). Most often this is an array of vertices and array of indices (i.e. three indices per triangle, aka "triangle list"). A vertex can be in some arbitrary format (e.g. only a float3 position; a float3 position + float3 normal; a float3 position + float3 normal + float2 texcoord; and so on and so on). So to define a piece of geometry you need:</p> <ul> <li>define it's vertex format (could be a bitmask, an enum from a list of formats; ...), </li> <li>have array of vertices, with their components interleaved ("interleaved arrays")</li> <li>have array of triangles.</li> </ul> <p>If you're in OOP land, you could call this class a <em>Mesh</em>.</p> <p><strong>Materials</strong> - things that define how some piece of geometry <em>is rendered</em>. In a simplest case, this could be a color of the object, for example. Or whether lighting should be applied. Or whether the object should be alpha-blended. Or a texture (or a list of textures) to use. Or a vertex/fragment shader to use. And so on, the possibilities are endless. Start by putting things that <em>you need</em> into materials. In OOP land that class could be called (surprise!) a <em>Material</em>.</p> <p><strong>Scene</strong> - you have pieces of geometry, a collection of materials, time to define what is in the scene. In a simple case, each object in the scene could be defined by: - What geometry it uses (pointer to Mesh), - How it should be rendered (pointer to Material), - Where it is located. This could be a 4x4 transformation matrix, or a 4x3 transformation matrix, or a vector (position), quaternion (orientation) and another vector (scale). Let's call this a <em>Node</em> in OOP land.</p> <p><strong>Camera</strong>. Well, a camera is nothing more than "where it is placed" (again, a 4x4 or 4x3 matrix, or a position and orientation), plus some projection parameters (field of view, aspect ratio, ...).</p> <p>So basically that's it! You have a scene which is a bunch of Nodes which reference Meshes and Materials, and you have a Camera that defines where a viewer is.</p> <p>Now, where to put actual OpenGL calls is a design question only. I'd say, don't put OpenGL calls into Node or Mesh or Material classes. Instead, make something like <em>OpenGLRenderer</em> that can traverse the scene and issue all calls. Or, even better, make something that traverses the scene independent of OpenGL, and put lower level calls into OpenGL dependent class.</p> <p>So yes, all of the above is pretty much platform independent. Going this way, you'll find that glRotate, glTranslate, gluLookAt and friends are quite useless. You have all the matrices already, just pass them to OpenGL. This is how most of <em>real actual code</em> in real games/applications work anyway.</p> <p>Of course the above can be complicated by more complex requirements. Particularly, Materials can be quite complex. Meshes usually need to support lots of different vertex formats (e.g. packed normals for efficiency). Scene Nodes might need to be organized in a hierarchy (this one can be easy - just add parent/children pointers to the node). Skinned meshes and animations in general add complexity. And so on.</p> <p>But the main idea is simple: there is Geometry, there are Materials, there are objects in the scene. Then some small piece of code is able to render them.</p> <p>In OpenGL case, setting up meshes would most likely create/activate/modify VBO objects. Before any node is rendered, matrices would need to be set. And setting up Material would touch most of remaining OpenGL state (blending, texturing, lighting, combiners, shaders, ...).</p>
<p>I usually have a drawOpenGl() function, per class that can be rendered, that contains it's opengl calls. That function gets called from the renderloop. The class holds all info needed for its opengl function calls, eg. about position and orientation so it can do its own transformation. </p> <p>When objects are dependent on eachother, eg. they make a part of a bigger object, then compose those classes in a other class that represents that object. Which has its own drawOpenGL() function that calls all the drawOpenGL() functions of its children, so you can have surrounding position/orientation calls using push- and popmatrix.</p> <p>It has been some time, but i guess something similar is possible with textures.</p> <p>If you want to switch between surface normals or vertex normals, then let the object remember if its one or the other and have 2 private functions for each occasion that drawOpenGL() calls when needed. There are certainly other more elegant solutions (eg. using the strategy design pattern or something), but this one could work as far as I understand your problem</p>
20,093
<p>I have a table with a structure like the following:</p> <hr /> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>LocationID</th> <th>AccountNumber</th> </tr> </thead> <tbody> <tr> <td>long-guid-here</td> <td>12345</td> </tr> <tr> <td>long-guid-here</td> <td>54321</td> </tr> </tbody> </table> </div> <p>To pass into another stored procedure, I need the XML to look like this:</p> <pre><code>&lt;root&gt; &lt;clientID&gt;12345&lt;/clientID&gt; &lt;clientID&gt;54321&lt;/clientID&gt; &lt;/root&gt; </code></pre> <p>The best I've been able to do so far was getting it like this:</p> <pre><code>&lt;root clientID=&quot;10705&quot;/&gt; </code></pre> <p>I'm using this SQL statement:</p> <pre><code>SELECT 1 as tag, null as parent, AccountNumber as 'root!1!clientID' FROM Location.LocationMDAccount WHERE locationid = 'long-guid-here' FOR XML EXPLICIT </code></pre> <p>So far, I've looked at the documentation on <a href="http://msdn.microsoft.com/en-us/library/ms345137.aspx" rel="nofollow noreferrer">the MSDN page</a>, but I've not come out with the desired results.</p> <hr /> <p>@KG,</p> <p>Yours gave me this output actually:</p> <pre><code>&lt;root&gt; &lt;Location.LocationMDAccount&gt; &lt;clientId&gt;10705&lt;/clientId&gt; &lt;/Location.LocationMDAccount&gt; &lt;/root&gt; </code></pre> <p>I'm going to stick with the <code>FOR XML EXPLICIT</code> from Chris Leon for now.</p>
<p>try</p> <pre><code>SELECT 1 AS Tag, 0 AS Parent, AccountNumber AS [Root!1!AccountNumber!element] FROM Location.LocationMDAccount WHERE LocationID = 'long-guid-here' FOR XML EXPLICIT </code></pre>
<p>Try this, Chris:</p> <pre><code>SELECT AccountNumber as [clientId] FROM Location.Location root WHERE LocationId = 'long-guid-here' FOR XML AUTO, ELEMENTS </code></pre> <p>TERRIBLY SORRY! I mixed up what you were asking for. I prefer the XML AUTO just for ease of maintainance, but I believe either one is effective. My apologies for the oversight ;-)</p>
2,496
<p>Is there such a thing as too many stored procedures?</p> <p>I know there is not a limit to the number you can have but is this any performance or architectural reason not to create hundreds, thousands??</p>
<p>To me the biggest limitation to that hundreds or thousands store procedure is maintainability. Even though that is not a direct performance hit, it should be a consideration. That is an architectural stand point, you have to plan not just for the initial development of the application, but future changes and maintenance.</p> <p>That being said you should design/create as many as your application requires. Although with Hibernate, NHibernate, .NET LINQ I would try to keep as much store procedures logic in the code, and only put it in the database when speed is a factor.</p>
<p>You have to put all that code somewhere.<br> If you are going to have stored procedures at all (I personally do favour them, but many do not), then you might as well use them as much as you need to. At least all the database logic is in one place. The downside is that there isn't typically much structure to a bucket full of stored procs. </p> <p>Your call! :)</p>
16,431
<p>How do I maintain the scroll position of the parent page when I open new window using window.open()? The parent page returns to the top of the page.</p> <p>Here is my current code:</p> <pre><code>&lt;a href="#" onclick="javascript: window.open('myPage.aspx');"&gt; Open New Window &lt;/a&gt; </code></pre>
<pre><code>&lt;a href="#" onclick="window.open('myPage.aspx');return false;"&gt;Open New Window&lt;/a&gt; </code></pre> <ul> <li><code>javascript:</code> is not required in event attributes.</li> <li>You were not returning false from the event handler, so the link was being following, it was equivilent to <code>&lt;a href="#"&gt;Scroll to top&lt;/a&gt;</code>.</li> </ul>
<p>I think the problem is that your link is pointing to an empty # (<code>href="#"</code>), which the browser will interpret to mean "the top of the page".</p> <p>Try removing the href attribute from your anchor tag. The onclick attribute should be enough for what you need.</p>
48,753
<p>I need a programmatic way of creating a SQL Server ODBC Data Source. I can do this by directly accessing the Registry. It would be better if this could be done via an available (SQL Server/Windows) API to protect against changes in the registry keys or values with updated SQL Server drivers.</p> <p><strong>Accepted Answer Note:</strong> Using SQLConfigDataSource abstracts the code from the details of Registry keys etc. so this is more robust. I was hoping, however, that SQL Server would have wrapped this with a higher level function which took strongly typed attributes (rather than a delimited string) and exposed it through the driver.</p>
<p>SQLConfigDataSource() does the job.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ck4z6wwt.aspx?ppud=4" rel="noreferrer">MSDN article</a></p> <p>Just in case here is a VB6 example:</p> <pre><code>Const ODBC_ADD_DSN = 1 'user data source Const ODBC_ADD_SYS_DSN = 4 'system data source Private Declare Function SQLConfigDataSource Lib "ODBCCP32.DLL" (ByVal hwndParent As Long, ByVal fRequest As Long, ByVal lpszDriver As String, ByVal lpszAttributes As String) As Long strDriver = "SQL Server" strAttributes = "DSN=Sample" &amp; Chr$(0) _ &amp; "Database=Northwind" &amp; Chr$(0) _ &amp; "Description= Sample Data Source" &amp; Chr$(0) _ &amp; "Server=(local)" &amp; Chr$(0) _ &amp; "Trusted_Connection=No" &amp; Chr$(0) SQLConfigDataSource(0, ODBC_ADD_SYS_DSN, strDriver, strAttributes) </code></pre>
<p>I'd use odbcad32.exe which is located in your system32 folder.</p> <p>This will add your odbc data sources to the correcct location, which won't be effected by any patches.</p>
20,568
<p>I have a function which parses one string into two strings. In C# I would declare it like this:</p> <pre><code>void ParseQuery(string toParse, out string search, out string sort) { ... } </code></pre> <p>and I'd call it like this:</p> <pre><code>string searchOutput, sortOutput; ParseQuery(userInput, out searchOutput, out sortOutput); </code></pre> <p>The current project has to be done in C++/CLI. I've tried</p> <pre><code>using System::Runtime::InteropServices; ... void ParseQuery(String ^ toParse, [Out] String^ search, [Out] String^ sort) { ... } </code></pre> <p>but if I call it like this:</p> <pre><code>String ^ searchOutput, ^ sortOutput; ParseQuery(userInput, [Out] searchOutput, [Out] sortOutput); </code></pre> <p>I get a compiler error, and if I call it like this:</p> <pre><code>String ^ searchOutput, ^ sortOutput; ParseQuery(userInput, searchOutput, sortOutput); </code></pre> <p>then I get an error at runtime. How should I declare and call my function?</p>
<p>C++/CLI itself doesn't support a real 'out' argument, but you can mark a reference as an out argument to make other languages see it as a real out argument.</p> <p>You can do this for reference types as:</p> <pre><code>void ReturnString([Out] String^% value) { value = "Returned via out parameter"; } // Called as String^ result; ReturnString(result); </code></pre> <p>And for value types as:</p> <pre><code>void ReturnInt([Out] int% value) { value = 32; } // Called as int result; ReturnInt(result); </code></pre> <p>The % makes it a 'ref' parameter and the OutAttribute marks that it is only used for output values.</p>
<p>It's not supported. The closest you can get is ref</p> <p>Granted you can fake it, but you lose a compile time check.</p>
22,562
<p>I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table:</p> <pre><code>ID COMPANY_ID EMPLOYEE 1 1 Anna 2 1 Bill 3 2 Carol 4 2 Dave </code></pre> <p>and I wanted to group by company_id to get something like:</p> <pre><code>COMPANY_ID EMPLOYEE 1 Anna, Bill 2 Carol, Dave </code></pre> <p>There is a built-in function in mySQL to do this <a href="http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat" rel="noreferrer">group_concat</a></p>
<h3>PostgreSQL 9.0 or later:</h3> <p>Modern Postgres (since 2010) has the <a href="http://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE" rel="noreferrer"><code>string_agg(expression, delimiter)</code></a> function which will do exactly what the asker was looking for:</p> <pre><code>SELECT company_id, string_agg(employee, ', ') FROM mytable GROUP BY company_id; </code></pre> <p>Postgres 9 also added the ability to specify an <code>ORDER BY</code> clause <a href="https://www.postgresql.org/docs/current/static/sql-expressions.html#SYNTAX-AGGREGATES" rel="noreferrer">in any aggregate expression</a>; otherwise you have to order all your results or deal with an undefined order. So you can now write:</p> <pre><code>SELECT company_id, string_agg(employee, ', ' ORDER BY employee) FROM mytable GROUP BY company_id; </code></pre> <h3>PostgreSQL 8.4.x:</h3> <p>PostgreSQL 8.4 (in 2009) introduced <a href="http://www.postgresql.org/docs/8.4/interactive/functions-aggregate.html" rel="noreferrer" title="array_agg(expression)">the aggregate function <code>array_agg(expression)</code></a> which collects the values in an array. Then <code>array_to_string()</code> can be used to give the desired result:</p> <pre><code>SELECT company_id, array_to_string(array_agg(employee), ', ') FROM mytable GROUP BY company_id; </code></pre> <h3>PostgreSQL 8.3.x and older:</h3> <p>When this question was originally posed, there was no built-in aggregate function to concatenate strings. The simplest custom implementation (<a href="http://archives.postgresql.org/pgsql-novice/2003-09/msg00177.php" rel="noreferrer">suggested by Vajda Gabo in this mailing list post</a>, among many others) is to use the built-in <code>textcat</code> function (which lies behind the <code>||</code> operator):</p> <pre><code>CREATE AGGREGATE textcat_all( basetype = text, sfunc = textcat, stype = text, initcond = '' ); </code></pre> <p><a href="http://www.postgresql.org/docs/8.3/static/sql-createaggregate.html" rel="noreferrer">Here is the <code>CREATE AGGREGATE</code> documentation.</a></p> <p>This simply glues all the strings together, with no separator. In order to get a &quot;, &quot; inserted in between them without having it at the end, you might want to make your own concatenation function and substitute it for the &quot;textcat&quot; above. Here is one I put together and tested on 8.3.12:</p> <pre><code>CREATE FUNCTION commacat(acc text, instr text) RETURNS text AS $$ BEGIN IF acc IS NULL OR acc = '' THEN RETURN instr; ELSE RETURN acc || ', ' || instr; END IF; END; $$ LANGUAGE plpgsql; </code></pre> <p>This version will output a comma even if the value in the row is null or empty, so you get output like this:</p> <pre><code>a, b, c, , e, , g </code></pre> <p>If you would prefer to remove extra commas to output this:</p> <pre><code>a, b, c, e, g </code></pre> <p>Then add an <code>ELSIF</code> check to the function like this:</p> <pre><code>CREATE FUNCTION commacat_ignore_nulls(acc text, instr text) RETURNS text AS $$ BEGIN IF acc IS NULL OR acc = '' THEN RETURN instr; ELSIF instr IS NULL OR instr = '' THEN RETURN acc; ELSE RETURN acc || ', ' || instr; END IF; END; $$ LANGUAGE plpgsql; </code></pre>
<p>According to version PostgreSQL 9.0 and above you can use the aggregate function called string_agg. Your new SQL should look something like this:</p> <pre><code>SELECT company_id, string_agg(employee, ', ') FROM mytable GROUP BY company_id; </code></pre>
6,550
<p>Is this possible via CSS? </p> <p>I'm trying </p> <pre class="lang-css prettyprint-override"><code>tr.classname { border-spacing: 5em; } </code></pre> <p>to no avail. Maybe I'm doing something wrong?</p>
<p>In the parent table, try setting</p> <pre class="lang-css prettyprint-override"><code>border-collapse: separate; border-spacing: 5em; </code></pre> <p>Plus a border declaration, and see if this achieves your desired effect. Beware, though, that IE doesn't support the &quot;separated borders&quot; model.</p>
<p>Have you tried:</p> <pre><code>tr.classname { margin-bottom:5em; } </code></pre> <p>Alternatively, each td can be adjusted as well:</p> <pre><code>td.classname { margin-bottom:5em; } </code></pre> <p>or</p> <pre><code> td.classname { padding-bottom:5em; } </code></pre>
45,701
<p>Is there a way to query against exchange 2007 to distinguish who is either an active sync or blackberry user using powershell exchange addin? </p>
<p>BBES typically uses a service account that has access to ALL mailboxes in order to do it's thing. you will want to look at the BBES server itself to find out which users are active, not AD or Exchange. Because BBES is backed by a database, just dig into the dbo.UserStats table to see what's there.</p>
<p>You could query to see which mailboxes have the necessary permission enabled - just as you could see which mailboxes are OWA-enabled. That won't actually tell you who is USING the capability, merely who COULD.</p>
43,927
<p>I was wondering what people thought of using properties as object initializers in C#. For some reason it seems to break the fundamentals of what constructors are used for.</p> <p>An example...</p> <pre><code>public class Person { string firstName; string lastName; public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName= value; } } } </code></pre> <p>Then doing object intialization with.....</p> <pre><code>Person p = new Person{ FirstName = "Joe", LastName = "Smith" }; Person p = new Person{ FirstName = "Joe" }; </code></pre>
<p>What you see here is some syntatic sugar provided by the compiler. Under the hood what it really does is something like:</p> <p><strong>Person p = new Person( FirstName = "Joe", LastName = "Smith" );</strong></p> <pre><code>Person _p$1 = new Person(); _p$1.FirstName = "Joe"; _p$1.LastName = "Smith"; Person p = _p$1; </code></pre> <p>So IMHO you are not really breaking any constructor fundamentals but using a nice language artifact in order to ease readability and maintainability.</p>
<p>It's also quite necessary for projected classes returned from a language integrated query (linq) </p> <pre><code>var qry = from something in listofsomething select new { Firstname = something.FirstName, Lastname = something.Surname } </code></pre>
11,445
<p>By graphing I mean bar charts, pie charts, line graphs, that sort of thing. I've used a couple over the years, but what is your favourite and why?</p> <p>One tool per answer please (to make the voting easier :o)</p>
<p>I like <a href="http://zedgraph.org/wiki/index.php?title=Main_Page" rel="noreferrer">ZedGraph</a> it is a free library and produces quality output. You can tweak the anti-aliasing to work the way it looks best to you and it supports a variety of charts and graphs.</p>
<p><a href="http://www.steema.com/products/teechart/whatsnew.html" rel="nofollow noreferrer">TeeChart</a>. I've been using this tool for a few years now, although it is not free (~500€) it is packed with features.<br></p> <p>What I prefer:</p> <ul> <li>axes scale automatically</li> <li>automatic colours for different series</li> <li>zoom by selecting an area with the mouse</li> <li>delivered with excellent code examples of all the features</li> <li>and web support for ASP.NET</li> </ul>
9,529
<p>I am using the following method to browse for a file:</p> <pre><code> OpenFileDialog.ShowDialog() PictureNameTextEdit.Text = OpenFileDialog.FileName </code></pre> <p>Is there a way get ONLY the file name?</p> <p>The <strong>FileName</strong> method returns the entire path and file name.</p> <p>i.e. I want Foo.txt instead of C:\SomeDirectory\Foo.txt</p>
<p>Use <a href="http://msdn.microsoft.com/en-us/library/system.io.path.getfilename.aspx" rel="noreferrer"><code>Path.GetFileName(fullPath)</code></a> to get just the filename part, like this:</p> <pre><code>OpenFileDialog.ShowDialog() PictureNameTextEdit.Text = System.IO.Path.GetFileName(OpenFileDialog.FileName) </code></pre>
<pre><code>//Following code return file name only string[] FileFullPath; string FileName; objOpenFileDialog.Title = "Select Center Logo"; objOpenFileDialog.ShowDialog(); FileFullPath = objOpenFileDialog.FileNames[0].ToString().Split('\\'); FileName = FileFullPath[FileFullPath.Length - 1]; //return only File Name //Use following code if u want save other folder , // following code save file to CenterLogo folder which inside bin folder// System.IO.File.Copy(OFD.FileName, Application.StartupPath + "/CenterLogo/" + FileName, true); </code></pre>
44,493
<p>I have an application that is built against OpenSceneGraph (2.6.1) and therefore indirectly OpenGL. The application initializes and begins to run, but then I get the following exception "attempt was made to execute an invalid lock sequence" in OpenGL32.dll. When I re-run it, I sometimes get this exception, and sometimes an exception about a "privileged instruction". The call stack looks like it is corrupted, so I can't really tell exactly where the exception is being thrown from. I ran the app quite a bit a couple of days ago and never saw this behavior. Since then I have added an else clause to a couple of ifs, and that is all. My app is a console application, is built with Visual Studio 2008, and it sets OpenScenGraph to SingleThreaded mode. Anybody seen this before? Any debugging tips? </p>
<p>Can you reproduce it with one of the standard examples?<br> Can you create a minimal app that causes this?<br> Do you have a machine with a different brand video card you can test it on (eg Nvidia vs. ATI) there are some issues with openscenegraph and bad OpenGL drivers.</p> <p>Have you tried posting to osg-users@lists.openscenegraph.org</p>
<p>The problem turned out to be our app was picking up an incorrect version of the OpenGL DLL , instead of the one installed in System32.</p>
35,291
<p>Is there a pattern using Linq to dynamically create a filter?</p> <p>I have the need to create custom filtering on a list, in the past I would just dynamically create the SQL...it doesn't seem like this is possible with Linq.</p>
<p>Check out the <a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx" rel="noreferrer">Dynamic Linq Library</a> from ScottGu's blog:</p> <p>For example, below is a standard type-safe LINQ to SQL VB query that retrieves data from a Northwind database and displays it in a ASP.NET GridView control:</p> <pre><code>Dim Northwind As New NorthwindDataContext Dim query = From q In Northwind.Products Where p.CategoryID = 2 And p.UnitPrice &gt; 3 Order By p.SupplierID Select p Gridview1.DataSource = query GridView1.DataBind() </code></pre> <p>Using the LINQ DynamicQuery library I could re-write the above query expression instead like so</p> <pre><code>Dim Northwind As New NorthwindDataContext Dim query = Northwind.Products .where("CategoryID=2 And UnitPrice&gt;3") . OrderBy("SupplierId") Gridview1.DataSource = query GridView1.DataBind() </code></pre> <p>Notice how the conditional-where clause and sort-orderby clause now take string expressions instead of code expressions. Because they are late-bound strings I can dynamically construct them. For example: I could provide UI to an end-user business analyst using my application that enables them to construct queries on their own (including arbitrary conditional clauses).</p>
<p>something like this?</p> <pre><code>var myList = new List&lt;string&gt; { "a","b","c" }; var items = from item in db.Items where myList.Contains(item.Name) select item; </code></pre> <p>that would create a sql statement like</p> <pre><code>SELECT * FROM Items [t0] where Name IN ('a','b','c') </code></pre>
5,074
<p>Does anybody know of a good media framework for Flex?<br/> I'd like to be able to create apps that can play not only those formats that the Flex framework provides support for, but other formats as well (like wav, wma, ogg and other...).</p> <p><strong>EDIT 13.10.2008.:</strong> It was recently pointed out to me in the answers section that I should perhaps rephrase the question, so here goes: What I'm really looking for is a way to play various media formats in a Flex/Air app. Onekidney posted a nice answer about Ogg/Vorbis. Does anybody know of a way to play other media formats? Never mind about the portability to different platforms now. Portability would be nice, but if I can't get it, I can live without it :-).<br/> Thanks for the answers!</p>
<p>is there a reason you're trying to put a <code>&lt;p&gt;</code> within <code>&lt;textarea&gt;</code>? as you found out it's not valid. if it's for display purposes (ie, showing code) it should be translated:</p> <pre><code>&lt;textarea&gt;&amp;lt;p&amp;gt;text&amp;lt;/p&amp;gt;&lt;/textarea&gt; </code></pre> <p>beyond validation issues, allowing arbitrary tags (which are not properly encoded as above) to display can be a huge security issue. it's paramount to make sure any user supplied input has been properly sanitized before it is displayed.</p>
<p>You can leave out the tags in the text area, and when you need new lines use \n Otherwise use <code>&amp;lt;p&amp;gt;</code> and <code>&amp;lt;/p&amp;gt;</code> in the place of your tags.</p>
23,831
<p>We are running MOSS 2007 with profiles coming from our active directory. One feature we use is "Audiences" which get compiled based on specific AD groups. We have problems with very few of the accounts where they do not get included in the audience. We have for example AD group of "Procurement" where 15 out of 16 users get included in the audience that uses membership in the "Procurement" group as its criteria.</p> <p>It seems to be something specific to that account, but I can't see anything about the account that is distinct from any other. The AD accesss is being done by an account with full rights to read and write to AD.</p> <p>Any ideas on what could be the cause? I'm not sure where even to look as the audience compliation doesn't throw any errors.</p>
<p>I didn't find a good solution, but I did find this very good posting on issues around this stuff:</p> <p><a href="http://www.moss2007.be/blogs/vandest/archive/2008/12/11/add-a-new-security-group-to-an-audience.aspx" rel="nofollow noreferrer">http://www.moss2007.be/blogs/vandest/archive/2008/12/11/add-a-new-security-group-to-an-audience.aspx</a></p>
<p>I would check the log files (in the \12 hive) to see is there is more information related to the compilation of audiences. </p> <p>If necessary you can log more for this component by configuring the logging in the Central Administration site.</p>
21,444
<p>Using the ClearCase find command, how do I find all files in a directory that do not have the name pom.xml? </p> <p>I'd like to pass other selection options to the ClearCase find command so I'd prefer not to execute another command.</p> <p>I am using a RedHat linux version of ClearCase. I have tried "cleartool find ! -name pom.xml -print" and that does not work.</p> <p>PS: I do not use ClearCase by choice, it's mandated on my project. This is one of the reasons I hate it. I've read the man pages several times and see no clear way to do this that works!</p>
<p>You seem to forget the <strong><em>-exec</em></strong> option of the cleartool find command. </p> <p>It actually does allow you to execute other commands than cleartool ones, including system ones (like a sh or DOS script). </p> <p>I know you would "prefer not to execute another command", but if that other system script is part of the exec option of a find command... it can be argued it is still <em>one</em> command ;)</p> <p>So create a simple script like:</p> <p>(Unix 'print.sh')</p> <pre><code>#!/bin/sh if [ $1 != $2 ] ; then echo $1 fi </code></pre> <p>(windows 'print.bat')</p> <pre><code>@echo off if not "%1"=="%2" echo "%1" </code></pre> <p>Put that script either in your search directory, or add the script path to your %PATH% or $PATH environment.</p> <p>And finally, use the find command (with all the <a href="http://www.samecs.com/commands/cleartool%20commands/find/find.htm" rel="nofollow noreferrer">other options</a> regarding date filtering, branch filtering and so on)</p> <p>(Unix)</p> <pre><code>cleartool find . -nrec -type f -exec './print.sh $CLEARCASE_PN ./pom.xml' </code></pre> <p>(windows)</p> <pre><code>cleartool find . -nrec -type f -exec "print.bat %CLEARCASE_PN% .\pom.xml" </code></pre> <p>And here you go: "all files in a directory that do not have the name pom.xml".</p> <p>Note: the '-type f' option of the find command allows you to restrict the search to file names only (not directory names).</p>
<p>ClearCase wildcards doesn't have inversion (AFAIR) but you can use grep for this - </p> <pre><code>cleartool ls -short -nxname | grep -v pom.xml </code></pre>
26,901
<p>I understand that heater blocks act as kind of “low-pass-filter” on the temperature change of the hotend, but why do we need that?</p> <p>Wouldn’t it be better to have as little metal as possible in order to be able to control temperature changes quickly and precisely (using PID, PWM plus maybe some predictions based on printed G-code)?</p>
<p>Let's look at the elements and what they do:</p> <p>The <em>Heater Cartridge</em> (blue) is the device that converts electric to thermal energy to melt the plastic. 30 and 40 W are common.</p> <p>The <em>Thermosensor</em> (red) is there to give feedback to the mainboard.</p> <p>The <em>Filament Path</em> (gold) in this area is made up of the <em>nozzle</em> and the <em>heatbreak</em>, it contains the <em>meltzone</em>.</p> <p>The <em>Heater Block</em> (transparent green) is the mounting for all parts. It also acts as the medium to transfer the thermal energy from the <em>Heater Cartidge</em> to the <em>Thermo Sensor</em> and the <em>Filament Path</em>. It also acts as a dampener for the control circuit.</p> <p>Now, let's put things together and omit the wires and cold end (and internal geometry of the filament path, cause I am lazy):</p> <p><a href="https://i.stack.imgur.com/b0nE1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b0nE1.png" alt="Mock up of a hotend assembly" /></a></p> <p>Now, the construction gives us several reasons for the shape of the heater block:</p> <ul> <li>Ease of construction. Taking a simple block and adding a couple of holes and one cut allows very fast production.</li> <li>Maximum contact surface. To get the maximum contact surface to the heater cartrige, the heater block has to make contact along its whole length, dictating a minimum size in 2 direction. The same is true for the thermosensor.</li> <li>The heater block transmits temperature pretty much radially from the heater cartridge. Because it is metal, the gradient between areas is very low, but it is measureable. These would be the thermal equivalent lines on heating up:</li> </ul> <p><a href="https://i.stack.imgur.com/LL01Q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LL01Q.png" alt="Heating lines around the Heater Cartridge" /></a></p> <p>You may easily notice that the temperature lines appear more straight as they come closer to the filament path and thermosensor. This helps to give the filament in the heatbreak and nozzle more even heating and better printing.</p> <p>The mockup I made has a deliberate flaw though: a change in temperature first affects the filament and then shows up on the sensor, making the temperature in the filament path wobble to the extreme. The Heater Block acts pretty much as a transmitter just as much as a time dilation between the heating command and the pickup.</p> <p>Because this arrangement is not very good, let's swap sensor and filament path around and look at the same lines.</p> <p><a href="https://i.stack.imgur.com/cTqqo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cTqqo.png" alt="Arrangement 2 of a Hotend assembly" /></a></p> <p>Now we have a much shorter feedback loop, allowing our printer to react quicker to temperature changes and the filament path also gets heated more evenly. The temperature inside the filament path does change less around the target temperature. The whole block now acts mostly as a distribution medium but also as a storage for heat energy:</p> <p>Up to this point, we did not take into account a very simple fact: the hotend drains thermal energy via two areas:</p> <ul> <li>The outer surface of the heater block emits heat to the air.</li> <li>Filament gets molten and extruded.</li> </ul> <p>Factor 1 is simple and here a bigger heater block actually is positive: The thermal 'storage' capacity is dependant on the volume, so goes with <span class="math-container">$xyz \approx a^3$</span>. The surface to emit heat from goes with <span class="math-container">$2\times(xy+xz+yz)\approx 6\times a^2$</span>. Plotting a graph of that shows us the square-cube law: the capacity increase for one unit does increase the surface just by a fraction of that, so the storage gets better the larger the heater block is.</p> <p>Factor 2 is why we need to have a storage of thermal energy in the first place: the flow of filament is not exactly the same all the time. Of course, we have moments of even flow, but we also have moments of low or no flow when the printer moves between parts of the print. This alteration of the drain of thermal energy from the heater block means that if we would go down to a bare minimum size, we'd heat up the block fast whenever we are on a move action and cool as the extrusion starts till equilibrium is achieved again. The more thermal capacity is there to store energy, the less the lack of extrusion will immediately affect the print and the more even the temperature will be in the filament path.</p> <h2>Fast printing?!</h2> <p>How is faster printing achieved with a special hotend? Well, 4 factors are used in hotends meant for very fast or very hot printing:</p> <ul> <li>Longer, more powerful heater cartridge.</li> <li>Longer filament path.</li> <li>Extra large Heater Block to even out the temperature changes under extrusion more.</li> <li>Insulating the Heater Block to the air.</li> </ul> <p>One of the prime examples would be an e3D-Volcano.</p>
<p>I think the idea is to <em>not</em> change the temperature fast. You want it to maintain a certain temperature so you have consistent flow. The extra mass at the hot end provides the mass which is needed to maintain the heat. If you don't maintain the heat while you print, you'll have inconsistent filament flow, which will screw up your print.</p>
1,335
<p>I am writing a script at the moment that will grab certain information from HTML using dom4j.</p> <p>Since Python/Jython does not have a native <strong>switch</strong> statement I decided to use a whole bunch of <strong>if</strong> statements that call the appropriate method, like below:</p> <pre><code>if type == 'extractTitle': extractTitle(dom) if type == 'extractMetaTags': extractMetaTags(dom) </code></pre> <p>I will be adding more depending on what information I want to extract from the HTML and thought about taking the dictionary approach which I found elsewhere on this site, example below:</p> <pre><code>{ 'extractTitle': extractTitle, 'extractMetaTags': extractMetaTags }[type](dom) </code></pre> <p>I know that each time I run the script the dictionary will be built, but at the same time if I were to use the <strong>if</strong> statements the script would have to check through all of them until it hits the correct one. What I am really wondering, which one performs better or is generally better practice to use?</p> <p><strong>Update:</strong> @Brian - Thanks for the great reply. I have a question, if any of the extract methods require more than one object, e.g.</p> <pre><code>handle_extractTag(self, dom, anotherObject) # Do something </code></pre> <p>How would you make the appropriate changes to the <strong>handle</strong> method to implemented this? Hope you know what I mean :)</p> <p>Cheers</p>
<p>To avoid specifying the tag and handler in the dict, you could just use a handler class with methods named to match the type. Eg</p> <pre><code>class MyHandler(object): def handle_extractTitle(self, dom): # do something def handle_extractMetaTags(self, dom): # do something def handle(self, type, dom): func = getattr(self, 'handle_%s' % type, None) if func is None: raise Exception("No handler for type %r" % type) return func(dom) </code></pre> <p>Usage:</p> <pre><code> handler = MyHandler() handler.handle('extractTitle', dom) </code></pre> <p><strong>Update:</strong> </p> <p>When you have multiple arguments, just change the handle function to take those arguments and pass them through to the function. If you want to make it more generic (so you don't have to change both the handler functions and the handle method when you change the argument signature), you can use the *args and **kwargs syntax to pass through all received arguments. The handle method then becomes:</p> <pre><code>def handle(self, type, *args, **kwargs): func = getattr(self, 'handle_%s' % type, None) if func is None: raise Exception("No handler for type %r" % type) return func(*args, **kwargs) </code></pre>
<p>It depends on how many if statements we're talking about; if it's a very small number, then it will be more efficient than using a dictionary.</p> <p>However, as always, I strongly advice you to do whatever makes your code look cleaner until experience and profiling tell you that a specific block of code needs to be optimized.</p>
35,090
<p>Suppose I have a SELECT statement that returns some set of results. Is there some way I can number my results in the following way:</p> <blockquote> <p>SELECT TOP 3 Name FROM PuppyNames ORDER BY NumberOfVotes</p> </blockquote> <p>would give me...</p> <blockquote> <p>Fido</p> <p>Rover</p> <p>Freddy Krueger</p> </blockquote> <p>...but I want...</p> <blockquote> <p>1, Fido</p> <p>2, Rover</p> <p>3, Freddy Krueger</p> </blockquote> <p>where of course the commas signify that the numbers are in their own column. [I am using SQL Server 2000.]</p>
<p>In Microsoft SQL Server 2005, you have the <code>ROW_NUMBER()</code> function which does exactly what you want. </p> <p>If you are stuck with SQL Server 2000, the typical technique was to create a new temporary table to contain the result of your query, plus add an <code>IDENTITY</code> column and generate incremental values. See an article that talks about this technique here: <a href="http://www.databasejournal.com/features/mssql/article.php/3572301/RowNumber-function-in-SQL-Server-2005.htm" rel="noreferrer">http://www.databasejournal.com/features/mssql/article.php/3572301/RowNumber-function-in-SQL-Server-2005.htm</a></p>
<p>SQL 2005, 2008:</p> <p>SELECT TOP 3 ROW_NUMBER() OVER(ORDER BY NumberOfVotes DESC) AS VoteRank, Name FROM PuppyNames </p> <p>EDIT: Sorry - just saw you specified 2000.</p>
35,751
<p>Every time I create a new excel sheet, I have to go in and change it's cell reference mode to the familiar A1, B1, etc. I can't seem to find a way to permanently set it to A1 style.</p> <p>Is there a macro I can write or a way to use templates or something, so that I don't have to keep changing the R1C1 setting?</p>
<p>In Office 2007, Click the Office button and click Excel Options which you will find at the end near Exit Excel.</p> <p>Go to Formulas tab and under Working with formulas, Check or uncheck R1C1 reference style to use it or to change it to A1 reference style.</p> <p><a href="https://i.stack.imgur.com/hfZTf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hfZTf.jpg" alt=""></a><br> <sub>(source: <a href="http://www.lytebyte.com/wp-content/uploads/2008/05/r1c1-reference-style-in-excel-2007.jpg" rel="nofollow noreferrer">lytebyte.com</a>)</sub> </p> <p>If it doesn't stick you have some problem with a <code>personal.xls</code> or the default template or something I guess...</p> <p>EDIT:</p> <p><strong>Try this first:</strong> Close all spreadsheets down. Assuming you have created one previously, unhide your <code>Personal.xls</code> workbook (Window>Unhide; In Excel 2007 and newer,View,Unhide) and then uncheck the R1C1 reference style. Save your Personal.xls, rehide &amp; close down Excel (clicking Yes to save changes to Personal.xls). With any luck you should now have your default A1 style back. You will have to repeat the above with any other workbooks in your XLSTART directory and/or the start up location in Tools>Options>General tab.</p> <p><strong>Then this:</strong> Help > Detect &amp; Repair.<br /> If no good, try <a href="http://support.microsoft.com/kb/291288" rel="nofollow noreferrer">http://support.microsoft.com/kb/291288</a></p> <p><strong>Last resort:</strong> Use Start > Run <code>excel /regserver</code> <br /> NOTE the space after "excel"</p>
<p>I suppose the template has been saved with the R1C1 option. Maybe you can open it, change the option and overwrite the original template?</p>
48,588
<p>Is there any way, in any language, to hook my program when a user renames a file?</p> <p>For example: A user renames a file and presses enter (or clicks away) to confirm the rename action. BEFORE the file is actually renamed, my program "listens" to this event and pops up a message saying "Are you sure you want to rename C:\test\file.txt to C:\test\test.txt?".</p> <p>I'm thinking/hoping this is possible with C++, C# or .NET.. But I don't have any clue where to look for.</p>
<p>You can probably solve this by using the <a href="http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx" rel="noreferrer">FileSystemWatcher class</a> in .NET framework.</p> <p>From the class remarks:</p> <blockquote> <p>You can watch for renaming, deletion, or creation of files or directories. For example, to watch for renaming of text files, set the Filter property to "*.txt" and call the WaitForChanged method with a Renamed specified for its parameter.</p> </blockquote>
<p>My guess is that this is <em>not</em> possible, I did find <a href="http://msdn.microsoft.com/en-us/library/bb776794(VS.85).aspx" rel="nofollow noreferrer">this</a> which is for monitoring operations (including rename) on a folder, but there does not appear to be a similar method for files.</p> <p>@Richard, FileSystemWatcher is good if you only need to monitor changes, but he needs to interrupt them which it cannot do.</p>
4,430
<p>I'm using SqlServer for the first time, and in every single one of our create procedure scripts there is a block of code like below to remove the procedure if it already exists:</p> <pre><code>IF EXISTS (SELECT * FROM information_schema.routines WHERE routine_name = 'SomeProcedureName' AND routine_type = 'PROCEDURE' BEGIN DROP PROCEDURE SomeProcedureName END //then the procedure definition </code></pre> <p>To stop cutting and pasting this boilerplate code in every file I would like to put this code in its own stored procedure so that instead the scripts would look like this:</p> <pre><code>DropIfRequired('SomeProcedureName') //then the procedure definition </code></pre> <p>My attempt at a solution is:</p> <pre><code>CREATE PROCEDURE DropIfRequired ( @procedureName varchar ) AS IF EXISTS (SELECT * FROM information_schema.routines WHERE routine_name = @procedureName AND routine_type = 'PROCEDURE') BEGIN DROP PROCEDURE @procedureName END </code></pre> <p>But I then get the following error:</p> <p>Msg 102, Level 15, State 1, Procedure DeleteProcedure, Line 10 Incorrect syntax near '@procedureName'.</p> <p>Any ideas how to do what I want?</p>
<p>The full answer is: <PRE> DECLARE @SQL VARCHAR(8000) SELECT @SQL = 'USE ' + DB_NAME() + CHAR(10) SET @SQL = @SQL + 'DROP PROCEDURE ' + @procName --PRINT @SQL EXEC(@SQL) </PRE></p> <p>The one given by Andrew will only work if the default database for your login is set to the database you want. When using dynamic sql you get a new database context. So if you do not have a default database set you will execute the command from master.</p>
<p>its missing quotes, try adding them in with an exec statement.</p> <pre><code>EXEC( 'DROP PROCEDURE ''' + @procName + '''') ( all single quotes) </code></pre>
23,286
<p>I need to store log files and configuration files for my application. Where is the best place to store them?</p> <p>Right now, I'm just using the current directory, which ends up putting them in the Program Files directory where my program lives.</p> <p>The log files will probably be accessed by the user somewhat regularly, so <code>%APPDATA%</code> seems a little hard to get to.</p> <p>Is a directory under <code>%USERPROFILE%\My Documents</code> the best? It needs to work for all versions of Windows, from 2000 forward.</p>
<p>If you're not using <code>ConfigurationManager</code> to manage your application and user settings, you should be. The configuration toolkit in the .NET Framework is remarkably well thought out, and the Visual Studio tools that interoperate with it are too. </p> <p>The default behavior of <code>ConfigurationManager</code> puts both invariant (application) and modifiable (user) settings in the right places: the application settings go in the application folder, and the user settings go in <code>System.Environment.SpecialFolder.LocalApplicationData</code>. It works properly under all versions of Windows that support .NET.</p> <p>As for log files, <code>System.Environment.SpecialFolder.LocalApplicationData</code> is generally the place that you want to put them, because it's guaranteed to be user-writeable. </p> <p>There are certainly cases where you wouldn't - for instance, if you want to write files to a network share so that you easily can access them remotely. There's a pretty wide range of ways to implement that, but most of them start with creating an application setting that contains the path to the shared folder. All of them involve administration.</p> <p>I have a couple of complaints about <code>ConfigurationManager</code> and the VS tools: there needs to be better high-level documentation than there is, and better documentation of the VS-generated <code>Settings</code> class. The mechanism by which the <code>app.config</code> file turns into the application configuration file in the target build directory is opaque (and the source of one of the most frequently asked questions of all: "what happened to my connection string?"). And if there's a way of creating settings that don't have default values, I haven't found it.</p>
<p>I use the <strong>Isolation Storage</strong> for configuration. You can also use the <strong>Temp</strong> folder to store temporary information like log.</p>
33,915
<p>Why would a stored procedure that returns a table with 9 columns, 89 rows using this code take 60 seconds to execute (.NET 1.1) when it takes &lt; 1 second to run in SQL Server Management Studio? It's being run on the local machine so little/no network latency, fast dev machine</p> <pre><code>Dim command As SqlCommand = New SqlCommand(procName, CreateConnection()) command.CommandType = CommandType.StoredProcedure command.CommandTimeout = _commandTimeOut Try Dim adapter As new SqlDataAdapter(command) Dim i as Integer For i=0 to parameters.Length-1 command.Parameters.Add(parameters(i)) Next adapter.Fill(tableToFill) adapter.Dispose() Finally command.Dispose() End Try </code></pre> <p>my paramter array is typed (for this SQL it's only a single parameter)</p> <pre><code>parameters(0) = New SqlParameter("@UserID", SqlDbType.BigInt, 0, ParameterDirection.Input, True, 19, 0, "", DataRowVersion.Current, userID) </code></pre> <p>The Stored procedure is only a select statement like so:</p> <pre><code>ALTER PROC [dbo].[web_GetMyStuffFool] (@UserID BIGINT) AS SELECT Col1, Col2, Col3, Col3, Col3, Col3, Col3, Col3, Col3 FROM [Table] </code></pre>
<p>First, make sure you are profiling the performance properly. For example, run the query twice from ADO.NET and see if the second time is much faster than the first time. This removes the overhead of waiting for the app to compile and the debugging infrastructure to ramp up.</p> <p>Next, check the default settings in ADO.NET and SSMS. For example, if you run <code>SET ARITHABORT OFF</code> in SSMS, you might find that it now runs as slow as when using ADO.NET.</p> <p>What I found once was that <code>SET ARITHABORT OFF</code> in SSMS caused the stored proc to be recompiled and/or different statistics to be used. And suddenly both SSMS and ADO.NET were reporting roughly the same execution time. Note that <code>ARITHABORT</code> is not <em>itself</em> the cause of the slowdown, it's that it causes a recompilation, and you are ending up with two different plans <a href="http://www.sommarskog.se/query-plan-mysteries.html" rel="nofollow noreferrer">due to parameter sniffing</a>. It is likely that parameter sniffing is the actual problem needing to be solved.</p> <p>To check this, look at the execution plans for each run, specifically the <code>sys.dm_exec_cached_plans</code> table. They will probably be different.</p> <p>Running 'sp_recompile' on a specific stored procedure will drop the associated execution plan from the cache, which then gives SQL Server a chance to create a possibly more appropriate plan at the next execution of the procedure.</p> <p>Finally, you can try the &quot;<a href="http://knowyourmeme.com/memes/nuke-it-from-orbit" rel="nofollow noreferrer">nuke it from orbit</a>&quot; approach of cleaning out the entire procedure cache and memory buffers using SSMS:</p> <pre><code>DBCC DROPCLEANBUFFERS DBCC FREEPROCCACHE </code></pre> <p>Doing so before you test your query prevents usage of cached execution plans and previous results cache.</p>
<p>I don't know "Why" it's so slow per se - but as Marcus is pointing out - comparing Mgmt Studio to filling a dataset is apples to oranges. Datasets contain a LOT of overhead. I hate them and NEVER use them if I can help it.</p> <p>You may be having issues with mismatches of old versions of the SQL stack or some such (esp given you are obviously stuck in .NET 1.1 as well) The Framework is likely trying to do database equivilant of "Reflection" to infer schema etc etc etc</p> <p>One thing to consider try with your unfortunate constraint is to access the database with a datareader and build your own dataset in code. You should be able to find samples easily via google.</p>
31,202
<p>I myself am convinced that in a project I'm working on signed integers are the best choice in the majority of cases, even though the value contained within can never be negative. (Simpler reverse for loops, less chance for bugs, etc., in particular for integers which can only hold values between 0 and, say, 20, anyway.)</p> <p>The majority of the places where this goes wrong is a simple iteration of a std::vector, often this used to be an array in the past and has been changed to a std::vector later. So these loops generally look like this:</p> <pre><code>for (int i = 0; i &lt; someVector.size(); ++i) { /* do stuff */ } </code></pre> <p>Because this pattern is used so often, the amount of compiler warning spam about this comparison between signed and unsigned type tends to hide more useful warnings. Note that we definitely do not have vectors with more then INT_MAX elements, and note that until now we used two ways to fix compiler warning:</p> <pre><code>for (unsigned i = 0; i &lt; someVector.size(); ++i) { /*do stuff*/ } </code></pre> <p>This usually works but might silently break if the loop contains any code like 'if (i-1 >= 0) ...', etc.</p> <pre><code>for (int i = 0; i &lt; static_cast&lt;int&gt;(someVector.size()); ++i) { /*do stuff*/ } </code></pre> <p>This change does not have any side effects, but it does make the loop a lot less readable. (And it's more typing.)</p> <p>So I came up with the following idea:</p> <pre><code>template &lt;typename T&gt; struct vector : public std::vector&lt;T&gt; { typedef std::vector&lt;T&gt; base; int size() const { return base::size(); } int max_size() const { return base::max_size(); } int capacity() const { return base::capacity(); } vector() : base() {} vector(int n) : base(n) {} vector(int n, const T&amp; t) : base(n, t) {} vector(const base&amp; other) : base(other) {} }; template &lt;typename Key, typename Data&gt; struct map : public std::map&lt;Key, Data&gt; { typedef std::map&lt;Key, Data&gt; base; typedef typename base::key_compare key_compare; int size() const { return base::size(); } int max_size() const { return base::max_size(); } int erase(const Key&amp; k) { return base::erase(k); } int count(const Key&amp; k) { return base::count(k); } map() : base() {} map(const key_compare&amp; comp) : base(comp) {} template &lt;class InputIterator&gt; map(InputIterator f, InputIterator l) : base(f, l) {} template &lt;class InputIterator&gt; map(InputIterator f, InputIterator l, const key_compare&amp; comp) : base(f, l, comp) {} map(const base&amp; other) : base(other) {} }; // TODO: similar code for other container types </code></pre> <p>What you see is basically the STL classes with the methods which return size_type overridden to return just 'int'. The constructors are needed because these aren't inherited.</p> <p><strong>What would you think of this as a developer, if you'd see a solution like this in an existing codebase?</strong></p> <p>Would you think 'whaa, they're redefining the STL, what a huge WTF!', or would you think this is a nice simple solution to prevent bugs and increase readability. Or maybe you'd rather see we had spent (half) a day or so on changing all these loops to use std::vector&lt;>::iterator?</p> <p>(In particular if this solution was combined with banning the use of unsigned types for anything but raw data (e.g. unsigned char) and bit masks.)</p>
<h2>I made this community wiki... Please edit it. I don't agree with the advice against "int" anymore. I now see it as not bad.</h2> <p>Yes, i agree with Richard. You should never use <code>'int'</code> as the counting variable in a loop like those. The following is how you might want to do various loops using indices (althought there is little reason to, occasionally this can be useful).</p> <h2>Forward</h2> <pre><code>for(std::vector&lt;int&gt;::size_type i = 0; i &lt; someVector.size(); i++) { /* ... */ } </code></pre> <h2>Backward</h2> <p>You can do this, which is perfectly defined behaivor:</p> <pre><code>for(std::vector&lt;int&gt;::size_type i = someVector.size() - 1; i != (std::vector&lt;int&gt;::size_type) -1; i--) { /* ... */ } </code></pre> <p>Soon, with c++1x (next C++ version) coming along nicely, you can do it like this:</p> <pre><code>for(auto i = someVector.size() - 1; i != (decltype(i)) -1; i--) { /* ... */ } </code></pre> <p>Decrementing below 0 will cause i to wrap around, because it is unsigned. </p> <h2>But unsigned will make bugs slurp in</h2> <p>That should never be an argument to make it the wrong way (using <code>'int'</code>). </p> <h2>Why not use std::size_t above?</h2> <p>The C++ Standard defines in <code>23.1 p5 Container Requirements</code>, that <code>T::size_type</code> , for <code>T</code> being some <code>Container</code>, that this type is some implementation defined unsigned integral type. Now, using <code>std::size_t</code> for <code>i</code> above will let bugs slurp in silently. If <code>T::size_type</code> is less or greater than <code>std::size_t</code>, then it will overflow <code>i</code>, or not even get up to <code>(std::size_t)-1</code> if <code>someVector.size() == 0</code>. Likewise, the condition of the loop would have been broken completely.</p>
<p><code>vector.size()</code> returns a <code>size_t</code> var, so just change <code>int</code> to <code>size_t</code> and it should be fine.</p> <p>Richard's answer is more correct, except that it's a lot of work for a simple loop.</p>
34,770
<p>How do I initialize an automatic download of a file in Internet Explorer?</p> <p>For example, in the download page, I want the download link to appear and a message: "If you download doesn't start automatically .... etc". The download should begin shortly after the page loads.</p> <p>In Firefox this is easy, you just need to include a meta tag in the header, <code>&lt;meta http-equiv="Refresh" content="n;url"&gt;</code> where n is the number of seconds and <code>url</code> is the download URL. This does not work in Internet Explorer. How do I make this work in Internet Explorer browsers?</p>
<p><a href="http://en.wikipedia.org/wiki/SourceForge" rel="noreferrer">SourceForge</a> uses an <code>&lt;iframe&gt;</code> element with the <code>src=""</code> attribute pointing to the file to download.</p> <pre><code>&lt;iframe width="1" height="1" frameborder="0" src="[File location]"&gt;&lt;/iframe&gt; </code></pre> <p>(Side effect: no redirect, no JavaScript, original URL remains unchanged.)</p>
<p>Nice jquery solution:</p> <pre><code>jQuery('a.auto-start').get(0).click(); </code></pre> <p>You can even set different file name for download inside <code>&lt;a&gt;</code> tag:</p> <pre><code>Your download should start shortly. If not - you can use &lt;a href="/attachments-31-3d4c8970.zip" download="attachments-31.zip" class="download auto-start"&gt;direct link&lt;/a&gt;. </code></pre>
18,954
<p>This is an adapted version of a question from someone in my office. She's trying to determine how to tell what ports MSDE is running on for an application we have in the field.</p> <p>Answers to that narrower question would be greatly appreciated. I'm also interested in a broader answer that could be applied to any networked applications.</p>
<pre><code>netstat -b </code></pre> <p>from the command line will display the application name, process owner, address, and port number used for all running applications.</p>
<p>Download currports from <a href="http://www.nirsoft.net/utils/cports.html" rel="nofollow noreferrer">here</a>.</p> <p>It will show you which ports are open and which processes are associated with each port.</p> <p>Scroll down to: Download CurrPorts</p>
6,354
<p>In Microsoft Oslo SDK CTP 2008 (using Intellipad) the following code compiles fine:</p> <pre><code>module T { type A { Id : Integer32 = AutoNumber(); } where identity Id; As : A*; type B { Id : Integer32 = AutoNumber(); // A : A; // } where A in As &amp;&amp; identity Id; } where identity Id; Bs : B*; type C { Id : Integer32 = AutoNumber(); B : B; } where B in Bs &amp;&amp; identity Id; Cs : C*; } </code></pre> <p>and results in the following Reach SQL output:</p> <pre><code>set xact_abort on; go begin transaction; go set ansi_nulls on; go create schema [T]; go create table [T].[As] ( [Id] int not null identity, constraint [PK_As] primary key clustered ([Id]) ); go create table [T].[Bs] ( [Id] int not null identity, constraint [PK_Bs] primary key clustered ([Id]) ); go create table [T].[Cs] ( [Id] int not null identity, [B] int not null, constraint [PK_Cs] primary key clustered ([Id]), constraint [FK_Cs_B_T_Bs] foreign key ([B]) references [T].[Bs] ([Id]) ); go commit transaction; go </code></pre> <p>But after changing the commented line in module T as follows</p> <pre><code> A : A; } where A in As &amp;&amp; identity Id; // } where identity Id; </code></pre> <p>the error message "M2037: SQL Generation Internal Error: Missing generator for variable 'A'" is displayed (in Intellipad's Reach SQL Window).</p> <p>Any Ideas?</p> <p>Regards, tamberg</p>
<p>I think what you want is:</p> <pre><code>type A { Id : Integer32 = AutoNumber(); } where identity Id; As : A*; type B { Id : Integer32 = AutoNumber(); A : A; } where identity Id; Bs : (B where value.A in As)*; type C { Id : Integer32 = AutoNumber(); B : B; } where identity Id &amp;&amp; B in Bs; Cs : (C where value.B in Bs)*; </code></pre> <p>Note that the constraints are on the externs, not the types here. I was able to get similar code when the constraints where on the types but not able to go more than one relationship deep. Moving them to the externs seems correct and generates the expected Reach SQL.</p>
<p><a href="http://social.msdn.microsoft.com/Forums/en-US/oslo/thread/05103bf8-4e0f-4976-bcdd-2c724cb08738/" rel="nofollow noreferrer">http://social.msdn.microsoft.com/Forums/en-US/oslo/thread/05103bf8-4e0f-4976-bcdd-2c724cb08738/</a></p>
31,633
<p>I am trying to have an element fade in, then in 5000 ms fade back out again. I know I can do something like:</p> <pre><code>setTimeout(function () { $(".notice").fadeOut(); }, 5000); </code></pre> <p>But that will only control the fade out, would I add the above on the callback?</p>
<p><strong>Update:</strong> As of jQuery 1.4 you can use the <code>.delay( n )</code> method. <a href="http://api.jquery.com/delay/" rel="noreferrer">http://api.jquery.com/delay/</a></p> <pre><code>$('.notice').fadeIn().delay(2000).fadeOut('slow'); </code></pre> <p><strong>Note</strong>: <code>$.show()</code> and <code>$.hide()</code> by default are not queued, so if you want to use <code>$.delay()</code> with them, you need to configure them that way:</p> <pre><code>$('.notice') .show({duration: 0, queue: true}) .delay(2000) .hide({duration: 0, queue: true}); </code></pre> <hr> <p>You could possibly use the Queue syntax, this might work: </p> <pre><code>jQuery(function($){ var e = $('.notice'); e.fadeIn(); e.queue(function(){ setTimeout(function(){ e.dequeue(); }, 2000 ); }); e.fadeOut('fast'); }); </code></pre> <p>or you could be really ingenious and make a jQuery function to do it.</p> <pre><code>(function($){ jQuery.fn.idle = function(time) { var o = $(this); o.queue(function() { setTimeout(function() { o.dequeue(); }, time); }); }; })(jQuery); </code></pre> <p>which would ( in theory , working on memory here ) permit you do to this: </p> <pre><code>$('.notice').fadeIn().idle(2000).fadeOut('slow'); </code></pre>
<p>This can be done with only a few lines of jQuery:</p> <pre><code>$(function(){ // make sure img is hidden - fade in $('img').hide().fadeIn(2000); // after 5 second timeout - fade out setTimeout(function(){$('img').fadeOut(2000);}, 5000); });​ </code></pre> <hr> <p>see the fiddle below for a working example...</p> <h2><a href="http://jsfiddle.net/eNxuJ/78/" rel="nofollow">http://jsfiddle.net/eNxuJ/78/</a></h2>
40,836
<p>I'm looking at creating a server in python that I can run, and will work as an SSH server. This will then let different users login, and act as if they'd logged in normally, but only had access to one command.</p> <p>I want to do this so that I can have a system where I can add users to without having to create a system wide account, so that they can then, for example, commit to a VCS branch, or similar.</p> <p>While I can work out how to do this with conch to get it to a "custom" shell... I can't figure out how to make it so that the SSH stream works as if it were a real one (I'm preferably wanting to limit to /bin/bzr so that bzr+ssh will work.</p> <p>It needs to be in python (which i can get to do the authorisation) but don't know how to do the linking to the app. </p> <p>This needs to be in python to work within the app its designed for, and to be able to be used for those without access to add new users</p>
<p>When you write a Conch server, you can control what happens when the client makes a shell request by implementing <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/conch/interfaces.py?rev=24441#L62" rel="noreferrer"><code>ISession.openShell</code></a>. The Conch server will request <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/conch/interfaces.py?rev=24441#L6" rel="noreferrer"><code>IConchUser</code></a> from your realm and then adapt the resulting avatar to <code>ISession</code> to call <code>openShell</code> on it if necessary.</p> <p><code>ISession.openShell</code>'s job is to take the transport object passed to it and associate it with a protocol to interpret the bytes received from it and, if desired, to write bytes to it to be sent to the client.</p> <p>In an unfortunate twist, the object passed to <code>openShell</code> which represents the transport is actually an <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/internet/interfaces.py?rev=24441#L1028" rel="noreferrer"><code>IProcessProtocol</code></a> provider. This means that you need to call <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/internet/interfaces.py?rev=24441#L1033" rel="noreferrer"><code>makeConnection</code></a> on it, passing an <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/internet/interfaces.py?rev=24441#L1261" rel="noreferrer"><code>IProcessTransport</code></a> provider. When data is received from the client, the <code>IProcessProtocol</code> will call <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/internet/interfaces.py?rev=24441#L1282" rel="noreferrer"><code>writeToChild</code></a> on the transport you pass to <code>makeConnection</code>. When you want to send data to the client, you should call <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/internet/interfaces.py?rev=24441#L1043" rel="noreferrer"><code>childDataReceived</code></a> on it.</p> <p>To see the exact behavior, I suggest reading <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/conch/ssh/session.py?rev=24441#L173" rel="noreferrer">the implementation of the <code>IProcessProtocol</code> that is passed in</a>. Don't depend on anything that's not part of <code>IProcessProtocol</code>, but seeing the implementation can make it easier to understand what's going on.</p> <p>You may also want to look at <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/conch/unix.py?rev=24441#L174" rel="noreferrer">the implementation of the normal shell-creation</a> to get a sense of what you're aiming for. This will give you a clue about how to associate the stdio of the bzr child process you launch with the SSH channel.</p>
<p>While Python really is my favorite language, I think you need not create you own server for this. When you look at the <a href="http://www.openbsd.org/cgi-bin/man.cgi?query=sshd&amp;sektion=8" rel="nofollow noreferrer">OpenSSH Manualpage for sshd</a> you'll find the "command" options for the authorized keys file that lets you define a specific command to run on login.</p> <p>Using keys, you can use one system account to allow many user to log in, just put their public keys in the account's authorized keys file.</p> <p>We are using this to create SSH tunnels for SVN and it works just great.</p>
22,542
<p>I am working on a web page that is using jQuery. I have an Ajax call that gets data from the server and updates a div. Inside that data there is a jQuery function, but the function is not being called after the data is loaded into the page. I have the proper js files included in the page already.</p> <p>This is what is returned from the Ajax call and placed into a div:</p> <pre><code>&lt;script type="text/javascript"&gt; $(function() { $('input').myFunction('param'); }); &lt;/script&gt; &lt;p&gt; other html &lt;/p&gt; </code></pre> <p>How do I get the returned javascript to run after the html is inserted into the page?</p> <p>(I am using Rails with the jRails plugin )</p>
<p>If you want JavaScript tag evaluation, with html content, you should set the dataType option of the ajax call to "html":</p> <pre><code>$.ajax({ type: "GET", url: "yourPage.htm", dataType: "html" }); </code></pre> <p>Or dataType "script", if you want to load and execute a .js file:</p> <pre><code>$.ajax({ type: "GET", url: "test.js", dataType: "script" }); </code></pre> <p>more info here: <a href="http://docs.jquery.com/Ajax/jQuery.ajax#options" rel="noreferrer">Ajax/jQuery.ajax</a></p>
<p>have you tried Sys.WebForms.PageRequestManager.add_endRequest method?</p> <pre><code> $(document).ready(function() { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler); } ); function endRequestHandler(sender, args) { // whatever } </code></pre>
29,201
<p>I'm looking for a Web UI toolkit for a Rails-based application. I have an experience with YUI but not in a Rails context. I have many questions I wish you could help me to answer.</p> <ol> <li>Do you use a web UI toolkit like <code>YUI</code>, <code>ExtJS</code> or <code>JxLib</code> within your Rails application ?</li> <li>Which UI toolkit is the most Rails-friendly ? Since most are not based on Prototype, is the co-existence of Prototype and another Javascript library (<code>MooTools</code>, <code>JQuery</code>, ...) easy and safe ?</li> <li>Do you mix usual 'traditional' Rails view development (<code>rhtml</code>, <code>rjs</code>) with a UI toolkit-based development ? In the same application ? In the same view ?</li> <li>Do you use a Rails plugin or do you code <code>plain Javascript</code> ?</li> </ol> <p>Thanks all for your answers.</p> <p>Laurent</p>
<p>If you're okay with Leopard-only, The new NSCollectionView supports horizontal display. Just set the collection view's number of rows to 1 in Interface Builder; it'll even handle the horizontal scroll bar for you. The <a href="http://developer.apple.com/samplecode/IconCollection/index.html" rel="noreferrer">IconCollection</a> sample code provides a simple demonstration of how it works. It's bindings work similarly to a table view's, except instead of rows and columns, each object represented gets an 'item' (an object of type NSCollectionViewItem) that displays it, and those items will be laid out in a grid. The sample code above demonstrates how to set up these 'items' in Interface Builder, which is definitely the easiest way.</p>
<p>With a table view? No. If I'm understanding correctly what you want, in the past I've created my own NSView subclass for this type of control. Define a data source protocol similar to NSTableView, and in your NSView drawRect method, draw the elements in order one by one from left to right. You can either keep track of paging in your control, or put it in a scroll view and resize yourself whenever the number of items changes.</p> <p>Usually this type of thing starts off pretty simple, and gets a bit complex once you start handling caching, paging, selection, mouse and keyboard input and so on. My advice, start as simple as possible and add new features one by one, only after you've finished the previous task.</p>
48,933
<p>Suppose I have a set of commits in a repository folder...</p> <pre><code>123 (250 new files, 137 changed files, 14 deleted files) 122 (150 changed files) 121 (renamed folder) 120 (90 changed files) 119 (115 changed files, 14 deleted files, 12 added files) 118 (113 changed files) 117 (10 changed files) </code></pre> <p>I want to get a working copy that includes all changes from revision 117 onward but does NOT include the changes for revisions 118 and 120.</p> <p>EDIT: To perhaps make the problem clearer, I want to undo the changes that were made in 118 and 120 while retaining all other changes. The folder contains thousands of files in hundreds of subfolders.</p> <p>What is the best way to achieve this?</p> <p><strong>The answer</strong>, thanks to Bruno and Bert, is the command (in this case, for removing 120 after the full merge was performed)</p> <pre><code>svn merge -c -120 . </code></pre> <p>Note that the revision number must be specified with a leading minus. '-120' not '120'</p>
<p>To undo revisions 118 and 120:</p> <pre><code>svn up -r HEAD # get latest revision svn merge -c -120 . # undo revision 120 svn merge -c -118 . # undo revision 118 svn commit # after solving problems (if any) </code></pre> <p>Also see the description in <a href="http://svnbook.red-bean.com/en/1.5/svn.branchmerge.basicmerging.html#svn.branchmerge.basicmerging.undo" rel="noreferrer">Undoing changes</a>.</p> <p>Note the minus in the <code>-c -120</code> argument. The <code>-c</code> (or <code>--change</code>) switch is supported since Subversion 1.4, older versions can use <code>-r 120:119</code>.</p>
<p>I suppose you could create a branch from revision 117, then merge everything except 118 and 120.</p> <pre><code>svn copy -r 117 source destination </code></pre> <p>Then checkout this branch and from there do <code>svnmerge.py merge -r119,120-123</code></p> <p><strong>EDIT:</strong> This doesn't undo the revisions in the branch/trunk. Use <code>svn merge</code> instead.</p>
15,363
<p>When creating a UserControl in WPF, I find it convenient to give it some arbitrary Height and Width values so that I can view my changes in the Visual Studio designer. When I run the control, however, I want the Height and Width to be undefined, so that the control will expand to fill whatever container I place it in. How can I acheive this same functionality without having to remove the Height and Width values before building my control? (Or without using DockPanel in the parent container.)</p> <p>The following code demonstrates the problem:</p> <pre><code>&lt;Window x:Class="ExampleApplication3.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:loc="clr-namespace:ExampleApplication3" Title="Example" Height="600" Width="600"&gt; &lt;Grid Background="LightGray"&gt; &lt;loc:UserControl1 /&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>The following definition of <code>UserControl1</code> displays reasonably at design time but displays as a fixed size at run time:</p> <pre><code>&lt;UserControl x:Class="ExampleApplication3.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="300" Width="300"&gt; &lt;Grid Background="LightCyan" /&gt; &lt;/UserControl&gt; </code></pre> <p>The following definition of <code>UserControl1</code> displays as a dot at design time but expands to fill the parent <code>Window1</code> at run time:</p> <pre><code>&lt;UserControl x:Class="ExampleApplication3.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;Grid Background="LightCyan" /&gt; &lt;/UserControl&gt; </code></pre>
<p>For Blend, a little known trick is to add these attributes to your usercontrol or window:</p> <pre><code> xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignHeight="500" d:DesignWidth="600" </code></pre> <p>This will set the design height and width to 500 and 600 respectively. However this will only work for the blend designer. Not the Visual Studio Designer. </p> <p>As far as the Visual Studio Designer your technique is all that works. Which is why I don't use the Visual Studio Designer. ;)</p>
<p>I do it similar, but my solution assures that if you add your control to an container in design mode, it will appear reasonably.</p> <pre><code>protected override void OnVisualParentChanged(DependencyObject oldParent) { if (this.Parent != null) { this.Width = double.NaN; this.Height = double.NaN; } } </code></pre> <p>what do you think?</p>
10,113
<p>In subclipse, the Team > Update menu option performs an "svn update -r HEAD".</p> <p>I want to run "svn update -r [revision number]" but can't find a menu option which will let me update to anything besides the HEAD revision.</p>
<p>It is the "Replace With" menu option. It is not under "Team", but on the same level.</p>
<p>It is the "Replace With" menu option. It is not under "Team", but on the same level.</p>
10,910
<p>I have a form with a default OK button, and a Cancel button. I have a treeview with nodes that can be edited, i.e. you can double-click them or press F2 to open another form.</p> <p>Now, I've never liked that F2 shortcut, and now that I'm enabling treeview label edition, it's even worse. My first reaction when testing the form was to press "Enter" to edit the selected node, but doing this would go against the normal default button behavior.</p> <p>Your opinion: Should an application always enforce the default button being triggered with the Enter key? If so what kind of shortcut should an application use to "edit the selected item"?</p>
<p>Definitely not... Confuses our users no end that enter doesn't select what they have highlighted.</p>
<p>Definitely not... Confuses our users no end that enter doesn't select what they have highlighted.</p>
16,206
<p>In Delphi 2007, in a mouse move event, I try to change the mouse cursor with:</p> <pre><code>procedure TFr_Board_Display.PaintBox_Proxy_BoardMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if left_mouse_button_down then begin if some_condition then begin Cursor := crDrag; end else begin Cursor := crNoDrop; end; end else begin if some_other_condition then begin Cursor := crHandPoint; end else begin Cursor := crDefault; end; end; end; </code></pre> <p>for example. However, when the left mouse button is down, and I move the mouse, the cursor doesn't change to either crDrag or crNoDrop. The code is executed (e.g. Cursor := crDrag;) but the cursor does not change. When the left mouse button is up, and I move the mouse, the cursor changes no problem. </p> <p>(I originally tried to use some Drag &amp; Drop events and properties, but couldn't get everything to work the way I wanted.)</p> <p>Edit: Clarified desired behavior, and formatted code.</p> <p>Edit: Thank you, Gamecat, but I want the cursor to change when the left mouse button is down and the while the mouse is moving the cursor should change back and forth between crDrag and crNoDrop.</p>
<p>If you set the mouse cursor in the OnMouseDown and reset it in the OnMouseUp, anything works fine:</p> <pre><code>procedure TForm4.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Cursor := crCross; end; procedure TForm4.FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Cursor := crDefault; // Or you can restore a saved cursor. end; </code></pre> <p>If you want the mousecursor to react at the mouse move, use the following:</p> <pre><code>procedure TForm4.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if ssLeft in Shift then begin if X&lt;100 then Screen.Cursor := crCross else Screen.Cursor := crHourGlass; end else Screen.Cursor := crDefault; // Or you can restore a saved cursor. end; procedure TForm4.FormMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Screen.Cursor := crDefault; // Or you can restore a saved cursor. end; </code></pre> <p>The MouseUp is needed, else the cursor won't change back if it hovers above a control.</p> <p>Be sure to use Screen.Cursor everywhere.</p>
<p>Slightly off-topic, but perhaps useful to you.</p> <p>I created a global stack to allow nested cursor changes. It lets any piece of code set the mouse cursor to what they want without worrying about what their caller or callee's set it to.</p> <p>For example:</p> <pre><code>procedure AskUserWhatToDo; begin PushMouseCursor(crArrow); try if MessageDlg('Abort?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then SysUtils.Abort; finally PopMouseCursor; end; end; procedure LongProcess; begin PushMouseCursor(crHourglass); try // do something if QuestionableState then AskUserWhatToDo; // do something finally PopMouseCursor; end; end; </code></pre> <p>Neither procedure has to worry about what state the other needs or leaves the mouse cursor.</p> <pre><code>//=============================================================== // in a universal utility module (mine is called CraftWindows.pas) function SetMouseCursor(ACursor : TCursor) : TCursor; begin Result := Screen.Cursor; Screen.Cursor := ACursor; end; var GlobalMouseCursorStack : TList = nil; procedure PushMouseCursor(ACursor : TCursor); begin if GlobalMouseCursorStack = nil then GlobalMouseCursorStack := TList.Create; GlobalMouseCursorStack.Add(Pointer(SetMouseCursor(ACursor))); end; procedure PopMouseCursor; begin if (GlobalMouseCursorStack &lt;&gt; nil) and (GlobalMouseCursorStack.Count &gt; 0) then begin SetMouseCursor(TCursor(GlobalMouseCursorStack.Last)); GlobalMouseCursorStack.Delete(GlobalMouseCursorStack.Count - 1); end; end; ... finalization GlobalMouseCursorStack.Free; </code></pre>
49,374
<p>Lots of frameworks let me expose an ejb as a webservice. </p> <p>But then 2 months after publishing the initial service I need to change the ejb or any part of its interface. I still have clients that need to access the old interface, so I obviously need to have 2 webservices with different signatures.</p> <p>Anyone have any suggestions on how I can do this, preferably letting the framework do the grunt work of creating wrappers and copying logic (unless there's an even smarter way).</p> <p>I can choose webservice framework on basis of this, so suggestions are welcome.</p> <p>Edit: I know my change is going to break compatibility,and I am fully aware that I will need two services with different namespaces at the same time. But how can I do it in a simple manner ?</p>
<p>I don't think, you need any additional frameworks to do this. Java EE lets you directly expose the EJB as a web service (since <a href="http://www.jcp.org/en/jsr/detail?id=153" rel="nofollow noreferrer">EJB 2.1</a>; see <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/doc/Session3.html#wp79822" rel="nofollow noreferrer">example for J2EE 1.4</a>), but with EE 5 it's even simpler:</p> <pre><code>@WebService @SOAPBinding(style = Style.RPC) public interface ILegacyService extends IOtherLegacyService { // the interface methods ... } @Stateless @Local(ILegacyService.class) @WebService(endpointInterface = "...ILegacyService", ...) public class LegacyServiceImpl implements ILegacyService { // implementation of ILegacyService } </code></pre> <p>Depending on your application server, you should be able to provide <code>ILegacyService</code> at any location that fits. As jezell said, you should try to put changes that do not change the contract directly into this interface. If you have additional changes, you may just provide another implementation with a different interface. Common logic can be pulled up into a superclass of <code>LegacyServiceImpl</code>.</p>
<p>I'm not an EBJ guy, but I can tell you how this is generally handled in the web service world. If you have a non-breaking change to the contract (for instance, adding a property that is optional), then you can simply update the contract and consumers should be fine.</p> <p>If you have a breaking change to a contract, then the way to handle it is to create a new service with a new namespace for it's types. For instance, if your first service had a namespace of:</p> <p><a href="http://myservice.com/2006" rel="nofollow noreferrer">http://myservice.com/2006</a></p> <p>Your new one might have:</p> <p><a href="http://myservice.com/2009" rel="nofollow noreferrer">http://myservice.com/2009</a></p> <p>Expose this contract to new consumers.</p> <p>How you handle the old contract is up to you. You might direct all the requests to an old server and let clients choose when to upgrade to the new servers. If you can use some amount of logic to upgrade the requests to the format that the new service expects, then you can rip out the old service's logic and replace it with calls to the new. Or, you might just deprecate it all together and fail all calls to the old service.</p> <p>PS: This is much easier to handle if you create message class objects rather than reusing domain entities.</p>
27,382
<p>How can I find out the decorated name that will be asigned to each method name ? I'm trying to find out what the decorated name is , so that I may export it , in a DLL .</p>
<p>This question is pretty similar: <a href="https://stackoverflow.com/questions/186232/exporting-dll-c-class-question-about-def-file">Exporting DLL C++ Class , question about .def file</a>. The quick summary is that you probably want to use <code>__declspec(dllexport)</code> to let the compiler do the work of exporting your methods for you.</p> <p>Microsoft changes the way they do function name mangling (or "decorated names" as they call them) with every compiler version, so you would probably run into future maintenance troubles if you try to manually export the mangled names. If you google for "msvc decorated names" there are some links that might help, but no guarantees.</p>
<p>I think you should take the advice of the previous 2 respondants <a href="https://stackoverflow.com/users/893/greg-hewgill">Greg Hewgill</a> and <a href="https://stackoverflow.com/users/12711/mike-b">Mike B</a>, but if you are using the Microsoft tool chain and you really want to know the decorated name(s)... <p></p> <ol> <li>Create your .lib and .dll files using <em>__declspec(dllexport)</em></li> <li>Inspect the names exported by the dll using dumpbin /exports</li> <li>Now you can remove the <em>__declspec(dllexport)</em> and export the symbols manually in the <em>.def</em> file</li> </ol>
23,095
<p>Cura has a layer view feature that lets you watch a simulation of the extruder head as it lays down material at each layer. Is it possible to get Cura to show a time stamp as it does this? That would let me set reminders to check a print just at certain critical times.</p>
<p>These estimates tend to be very approximate, even if Cura has the accurate acceleration values for your firmware. An error of 100% is not unusual.</p> <p>What you probably want is an alarm at a specific layer (a few before the critical ones). You might be able to add this to Octoprint fairly easily - it does support plugins which can provide (for example) pushbullet notifications.</p> <p>I'm not sure that 'critical' points are much more likely to fail than other less predictable things (like bed adheesion failure, extruder jams, filament breaks) - unless you're testing features (and then hopefully you can print only a slice of the part).</p>
<p>If I may interpret your question a bit, and add alternatives to Sean H's suggestions. I agree that any attempt to estimate elapsed time per layer is doomed. </p> <p>Perhaps you should just look at the LayerView to determine the critical layers of interest. Then edit the gcode file in a text editor. Locate the start of the layer in question, and insert a PAUSE command (as well as whatever other actions your firmware supports, in case you can actually send an audible alarm or something). </p> <p>If you really just want to print a subsection of the item, you're better off removing the unwanted parts in MeshMixer/MeshLab/whateverCAD , and slicing just the part you want to produce. </p>
1,001
<p>While LOC (# lines of code) is a problematic measurement of a code's complexity, it is the most popular one, and when used very carefully, can provide a rough estimate of at least relative complexities of code bases (i.e. if one program is 10KLOC and another is 100KLOC, written in the same language, by teams of roughly the same competence, the second program is almost certainly much more complex).</p> <p>When counting lines of code, do you prefer to count comments in ? What about tests? </p> <p>I've seen various approaches to this. Tools like cloc and sloccount allow to either include or exclude comments. Other people consider comments part of the code and its complexity. </p> <p>The same dilemma exists for unit tests, that can sometimes reach the size of the tested code itself, and even exceed it.</p> <p>I've seen approaches all over the spectrum, from counting only "operational" non-comment non-blank lines, to "XXX lines of tested, commented code", which is more like running "wc -l on all code files in the project".</p> <p>What is your personal preference, and why?</p>
<p>A wise man once told me 'you get what you measure' when it comes to managing programmers.</p> <p>If you rate them in their LOC output amazingly you tend to get a lot of lines of code.</p> <p>If you rate them on the number of bugs they close out, amazingly you get a lot of bugs fixed.</p> <p>If you rate them on features added, you get a lot of features.</p> <p>If you rate them on cyclomatic complexity you get ridiculously simple functions.</p> <p>Since one of the major problems with code bases these days is how quickly they grow and how hard they are to change once they've grown, I tend to shy away from using LOC as a metric at all, because it drives the wrong fundamental behavior.</p> <p>That said, if you have to use it, count sans comments and tests and require a consistent coding style.</p> <p>But if you really want a measure of 'code size' just tar.gz the code base. It tends to serve as a better rough estimate of 'content' than counting lines which is susceptible to different programming styles.</p>
<p>Depends on what you are using the LOC for.</p> <p>As a complexity measure - not so much. Maybe the 100KLOC are mostly code generated from a simple table, and the 10KLOC kas 5KLOC regexps.</p> <p>However, I see every line of code associated with a running cost. You pay for every line as long as the program lives: it needs to be read when maintained, it might contain an error that needs to be fixed, it increases compile time, get-from-source-control and backup times, before you change or remove it you may need to find out if anyone relies on it etc. The average cost may be nanopennies per line and day, but it's stuff that adds up. </p> <p>KLOC can be a first shot indicator of how much infrastructure a project needs. In that case, I would include comments and tests - even though the running cost of a comment line is much lower than one of the regexp's in the second project.</p> <p>[edit] [someone with a similar opinion about code size]<a href="http://steve-yegge.blogspot.com/2007/12/codes-worst-enemy.html" rel="nofollow noreferrer">1</a></p>
34,591
<p>What happens if I use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb762181%28v=vs.85%29.aspx" rel="nofollow noreferrer">SHGetFolderPath</a> api call in a 32 bit system with CSIDL_PROGRAM_FILESx86 folder id instead of the CSIDL_PROGRAM_FILES id?</p> <p>Theoretically CSIDL_PROGRAM_FILESx86 should map to <code>C:\program files (x86)</code> in a 64 bit system but what does it map to in a 32 bit system where this path doesn't exist?</p>
<p>The different scenarios are described in <a href="http://msdn.microsoft.com/en-us/library/bb762584(VS.85).aspx" rel="nofollow noreferrer">this article on MSDN</a>.</p> <p>Scroll down to remarks, &quot;FOLDERID_ProgramFiles&quot;</p> <pre><code>The interpretation of certain KNOWNFOLDERID values depends on whether the folder is part of a 32-bit or 64-bit application and whether that application is running on a 32-bit or 64-bit operating system. If your application needs to distinguish between, for example, Program Files and Program Files (x86), you must use the right KNOWNFOLDERID for the situation. The following tables summarize the KNOWNFOLDERID use in those cases. FOLDERID_ProgramFiles OS Application KNOWNFOLDERID Default Path CSIDL Equivalent 32 bit 32 bit FOLDERID_ProgramFiles %SystemDrive%\Program Files CSIDL_PROGRAM_FILES 32 bit 32 bit FOLDERID_ProgramFilesX86 %SystemDrive%\Program Files CSIDL_PROGRAM_FILESX86 32 bit 32 bit FOLDERID_ProgramFilesX64 (undefined) Not applicable Not applicable 64 bit 64 bit FOLDERID_ProgramFiles %SystemDrive%\Program Files CSIDL_PROGRAM_FILES 64 bit 64 bit FOLDERID_ProgramFilesX86 %SystemDrive%\Program Files (x86) CSIDL_PROGRAM_FILESX86 64 bit 64 bit FOLDERID_ProgramFilesX64 %SystemDrive%\Program Files None 64 bit 32 bit FOLDERID_ProgramFiles %SystemDrive%\Program Files (x86) CSIDL_PROGRAM_FILES 64 bit 32 bit FOLDERID_ProgramFilesX86 %SystemDrive%\Program Files (x86) CSIDL_PROGRAM_FILESX86 64 bit 32 bit FOLDERID_ProgramFilesX64 %SystemDrive%\Program Files None </code></pre> <p>Summary: It will point to %SystemDrive%\Program Files</p>
<p>Try this:</p> <pre><code>GetEnvironmentVariable("ProgramW6432", szBuffer, nBufferSize); </code></pre> <p>YMMV</p>
16,753
<p>In actionscript 3 is it possible to allow a user to upload an image into a flash movie at runtime without POSTing to a PHP script? I dont want to export the image or save it anywhere I just want to be able to display the image in the flash movie</p> <p><em>fingers crossed</em></p>
<p>Yes, you can if you are targeting Flash Player 10. Use the FileReference.load() method. Once the file is loaded, you can access to the raw data as a ByteArray, using the data property. In flex you can pass that to an Image component. In plain Actionscript, you can use the Loader.loadBytes() method to the display the loaded image.</p>
<p>The flash developer at work, seems to believe that it is not possible. That said you don't have to use PHP, you could use any server side technology that allows uploading (ASP.NET, Python, etc) </p>
39,681
<p>I'm working in two different Oracle schemas on two different instances of Oracle. I've defined several types and type collections to transfer data between these schemas. The problem I'm running into is that even though the type have exactly the same definitions (same scripts used to create both sets in the schemas) Oracle sees them as different objects that are not interchangeable.</p> <p>I thought about casting the incoming remote type object as the same local type but I get an error about referencing types across dblinks.</p> <p>Essentially, I'm doing the following:</p> <pre><code>DECLARE MyType LocalType; -- note, same definition as the RemoteType (same script) BEGIN REMOTE_SCHEMA.PACKAGE.PROCEDURE@DBLINK( MyType ); -- MyType is an OUT param LOCAL_SCHEMA.PACKAGE.PROCEDURE( MyType ); -- IN param END; </code></pre> <p>That fails because the REMOTE procedure call can't understand the MyType since it treats LocalType and RemoteType as different object types.</p> <p>I tried DECLARING MyType as follows as well:</p> <pre><code> MyType REMOTE_SCHEMA.RemoteType@DBLINK; </code></pre> <p>but I get another error about referencing types across dblinks. CASTing between types doesn't work either because in order to cast, I need to reference the remote type across the dblink - same issue, same error. I've also tried using SYS.ANYDATA as the object that crosses between the two instance but it gets a similar error.</p> <p>Any ideas?</p> <p><strong>UPDATE:</strong> Tried declaring the object type on both sides of the DBLINK using the same OID (retrieved manually using <code>SYS_OP_GUID()</code>) but Oracle still "sees" the two objects as different and throws a "wrong number or types of arguements" error.</p>
<p>I have read the Oracle Documentation and it is not very difficult. </p> <p>You need to add an OID to your type definitions in both databases. </p> <p>You can use a GUID as OID.</p> <pre><code>SELECT SYS_OP_GUID() FROM DUAL; SYS_OP_GUID() -------------------------------- AE34B912631948F0B274D778A29F6C8C </code></pre> <p>Now create your UDT in both databases with the <strong>SAME</strong> OID. </p> <pre><code>create type testlinktype oid 'AE34B912631948F0B274D778A29F6C8C' as object ( v1 varchar2(10) , v2 varchar2(20) ); / </code></pre> <p>Now create a table:</p> <pre><code>create table testlink ( name testlinktype); insert into testlink values (testlinktype ('RC','AB')); commit; </code></pre> <p>Now you can select from the table via the dblink in the other database:</p> <pre><code>select * from testlink@to_ora10; NAME(V1, V2) -------------------------- TESTLINKTYPE('RC', 'AB') </code></pre> <p>If you get error ORA-21700 when you try to select via the dblink the first time, just reconnect. </p>
<p>I think the underlying issue is that Oracle doesn't know how to automatically serialize/deserialize your custom type over the wire, so to speak.</p> <p>Your best bet is probably to pass an XML (or other) representation over the link.</p>
49,546
<p>How can I find out the folder where the windows service .exe file is installed dynamically?</p> <pre><code>Path.GetFullPath(relativePath); </code></pre> <p>returns a path based on <code>C:\WINDOWS\system32</code> directory.</p> <p>However, the <code>XmlDocument.Load(string filename)</code> method appears to be working against relative path inside the directory where the service .exe file is installed to.</p>
<p>Try</p> <pre><code>System.Reflection.Assembly.GetEntryAssembly().Location </code></pre>
<p>This should give you the path that the executable resides in:</p> <pre><code>Environment.CurrentDirectory; </code></pre> <p>If not, you could try:</p> <pre><code>Directory.GetParent(Assembly.GetEntryAssembly().Location).FullName </code></pre> <p>A more hacky, but functional way:</p> <pre><code>Path.GetFullPath("a").TrimEnd('a') </code></pre> <p>:)</p>
24,384
<p>Is there a function like <code>document.getElementById("FirstDiv").clear()</code>?</p>
<p>To answer the original question - there are various ways to do this, but the following would be the simplest.</p> <p>If you already have a handle to the child node that you want to remove, i.e. you have a JavaScript variable that holds a reference to it:</p> <pre><code>myChildNode.parentNode.removeChild(myChildNode); </code></pre> <p>Obviously, if you are not using one of the numerous libraries that already do this, you would want to create a function to abstract this out:</p> <pre><code>function removeElement(node) { node.parentNode.removeChild(node); } </code></pre> <hr> <p>EDIT: As has been mentioned by others: if you have any event handlers wired up to the node you are removing, you will want to make sure you disconnect those before the last reference to the node being removed goes out of scope, lest poor implementations of the JavaScript interpreter leak memory.</p>
<p>You should be able to use the .RemoveNode method of the node or the .RemoveChild method of the parent node.</p>
3,470
<p>I have one std::list&lt;> container and these threads:</p> <ul> <li><p>One writer thread which adds elements indefinitely.</p></li> <li><p>One reader/writer thread which reads and removes elements while available.</p></li> <li><p>Several reader threads which access the SIZE of the container (by using the size() method)</p></li> </ul> <p>There is a normal mutex which protects the access to the list from the first two threads. My question is, do the size reader threads need to acquire this mutex too? should I use a read/write mutex?</p> <p>I'm in a windows environment using Visual C++ 6.</p> <p><strong>Update</strong>: It looks like the answer is not clear yet. To sum up the main doubt: Do I still need to protect the SIZE reader threads even if they only call size() (which returns a simple variable) taking into account that I don't need the exact value (i.e. I can assume a +/- 1 variation)? How a race condition could make my size() call return an invalid value (i.e. one totally unrelated to the good one)?</p> <p><strong>Answer</strong>: In general, the reader threads must be protected to avoid race conditions. Nevertheless, in my opinion, some of the questions stated above in the update haven't been answered yet.</p> <p>Thanks in advance! </p> <p>Thank you all for your answers!</p>
<p>Yes, the read threads will need some sort of mutex control, otherwise the write will change things from under it.</p> <p>A reader/writer mutex should be enough. But strictly speaking this is an implmentation-specific issue. It's possible that an implementation may have mutable members even in const objects that are read-only in your code.</p>
<p>Yes. I would suggest wrapping your STL library with a class that enforces serial access. Or find a similar class that's already been debugged.</p>
22,724
<p>Does anyone of you know, if and if so, how can I check, with my application code, if a server has ssl enabled or not?</p>
<p><a href="http://mail.python.org/pipermail/python-list/2003-May/203039.html" rel="nofollow noreferrer">"It's easier to ask forgiveness than permission"</a></p> <p>For example, to read <code>stackoverflow.com</code> via SSL, don't ask whether <code>stackoverflow.com</code> supports it, just do it. In Python:</p> <pre><code>&gt;&gt;&gt; import urllib2 &gt;&gt;&gt; urllib2.urlopen('https://stackoverflow.com') Traceback (most recent call last): ... urllib2.URLError: &lt;urlopen error (10060, 'Operation timed out')&gt; &gt;&gt;&gt; html = urllib2.urlopen('http://stackoverflow.com').read() &gt;&gt;&gt; len(html) 146271 &gt;&gt;&gt; </code></pre> <p>It shows that <code>stackoverflow.com</code> doesn't support SSL (2008).</p> <hr> <p><strong>Update:</strong> <code>stackoverflow.com</code> supports https now.</p>
<p>You need to specify what protocol you're working with -- there are SSL versions of HTTP, IMAP, POP, etc.</p> <p>Assuming it's HTTPS you're interested in, you could check to see if something is listening on port 443 on the server and go from there... </p>
42,182
<p>I'm playing with <a href="http://www.dncompute.com/blog/2007/03/19/seed-based-pseudorandom-number-generator-in-actionscript.html" rel="nofollow noreferrer">this ActionScript</a> which generates a random 'squiggle'.</p> <p>Each time a 'squiggle' is placed, it appears within a sprite with a white background.</p> <p>If I change the background colour of the flash file to pink for example, it would still show up as white.</p> <p>Does anybody know how I might make the sprite background transparent? Thanks.</p>
<p>In RandomSquiggle.as change line 76 from</p> <pre><code>bitmapData = new BitmapData(width,height,false,0xfafafa); </code></pre> <p>to</p> <pre><code>bitmapData = new BitmapData(width,height,true,0x000000); </code></pre> <p>the third param is for transparency</p>
<p>That is not an actual Sprite (Sprite is an AS3 datatype) it's just a MovieClip that's called 'sprite'. I see that in the code the squiggles are actually being drawn to a MovieClip called 'paintSurface', then when it's done a Bitmap of 'paintSurface' is captured via this line:</p> <pre><code>bitmapData.draw(paintSurface); </code></pre> <p>then it is attached to the 'sprite' MovieClip here:</p> <pre><code>sprite.attachBitmap(bitmapData, 3); </code></pre> <p>That is probably why you are getting the white background. </p> <p>I assume the bitmap is being captured for the sake of processing speed. </p> <p>Perhaps you could see what happens if you do not capture a bitmap, but instead just attach 'paintSurface' to 'sprite' instead.</p>
38,311
<p>I'm used to the Java model where you can have one public class per file. Python doesn't have this restriction, and I'm wondering what's the best practice for organizing classes.</p>
<p>A Python file is called a "module" and it's one way to organize your software so that it makes "sense". Another is a directory, called a "package".</p> <p>A module is a distinct thing that may have one or two dozen closely-related classes. The trick is that a module is something you'll import, and you need that import to be perfectly sensible to people who will read, maintain and extend your software.</p> <p>The rule is this: <strong>a module is the unit of reuse</strong>. </p> <p>You can't easily reuse a single class. You should be able to reuse a module without any difficulties. Everything in your library (and everything you download and add) is either a module or a package of modules.</p> <p>For example, you're working on something that reads spreadsheets, does some calculations and loads the results into a database. What do you want your main program to look like?</p> <pre><code>from ssReader import Reader from theCalcs import ACalc, AnotherCalc from theDB import Loader def main( sourceFileName ): rdr= Reader( sourceFileName ) c1= ACalc( options ) c2= AnotherCalc( options ) ldr= Loader( parameters ) for myObj in rdr.readAll(): c1.thisOp( myObj ) c2.thatOp( myObj ) ldr.laod( myObj ) </code></pre> <p>Think of the import as the way to organize your code in concepts or chunks. Exactly how many classes are in each import doesn't matter. What matters is the overall organization that you're portraying with your <code>import</code> statements.</p>
<p>I would say to put as many classes as can be logically grouped in that file without making it too big and complex.</p>
13,247
<p>I'm thinking floats. For the record I'm also using NHibernate.</p>
<p><code>decimal</code></p> <p>You won't lose precision due to rounding.</p>
<p>It depends on what you are using them for.</p> <p>if it's for display, an int would do just fine, and be faster than a float. If it's for infrequent mathematics, an int would still do fine (or even a short, in either case).</p> <p>If you're doing a lot of math, then a float would probably be best, performance-wise.</p> <p>Of course, unless you're doing a LOT of manipulation of the percentages, it won't really matter in the end, performance-wise, given modern processor speed.</p> <p>EDIT: Of course, 'int' assumes you are just using strict, whole-number percents. If you aren't, you'd ALWAYS be better with float or dec.</p>
19,231
<p>I have an XML feed (which I don't control) and I am trying to figure out how to detect the volume of certain attribute values within the document.</p> <p>I am also parsing the XML and separating attributes into Arrays (for other functionality) </p> <p>Here is a sample of my XML</p> <pre><code>&lt;items&gt; &lt;item att1="ABC123" att2="uID" /&gt; &lt;item att1="ABC345" att2="uID" /&gt; &lt;item att1="ABC123" att2="uID" /&gt; &lt;item att1="ABC678" att2="uID" /&gt; &lt;item att1="ABC123" att2="uID" /&gt; &lt;item att1="XYZ123" att2="uID" /&gt; &lt;item att1="XYZ345" att2="uID" /&gt; &lt;item att1="XYZ678" att2="uID" /&gt; &lt;/items&gt; </code></pre> <p>I want to find the volume nodes based on each att1 value. Att1 value will change. Once I know the frequency of att1 values I need to pull the att2 value of that node.</p> <p>I need to find the TOP 4 items and pull the values of their attributes.</p> <p>All of this needs to be done in C# code behind.</p> <p>If I was using Javascript I would create an associative array and have att1 be the key and the frequency be the value. But since I'm new to c# I don't know how to duplicate this in c#.</p> <p>So I believe, first I need to find all unique att1 values in the XML. I can do this using:</p> <pre><code>IEnumerable&lt;string&gt; uItems = uItemsArray.Distinct(); // Where uItemsArray is a collection of all the att1 values in an array </code></pre> <p>Then I get stuck on how I compare each unique att1 value to the whole document to get the volume stored in a variable or array or whatever data set. </p> <p>Here is the snippet I ended up using:</p> <pre><code> XDocument doc = XDocument.Load(@"temp/salesData.xml"); var topItems = from item in doc.Descendants("item") select new { name = (string)item.Attribute("name"), sku = (string)item.Attribute("sku"), iCat = (string)item.Attribute("iCat"), sTime = (string)item.Attribute("sTime"), price = (string)item.Attribute("price"), desc = (string)item.Attribute("desc") } into node group node by node.sku into grp select new { sku = grp.Key, name = grp.ElementAt(0).name, iCat = grp.ElementAt(0).iCat, sTime = grp.ElementAt(0).sTime, price = grp.ElementAt(0).price, desc = grp.ElementAt(0).desc, Count = grp.Count() }; _topSellers = new SalesDataObject[4]; int topSellerIndex = 0; foreach (var item in topItems.OrderByDescending(x =&gt; x.Count).Take(4)) { SalesDataObject topSeller = new SalesDataObject(); topSeller.iCat = item.iCat; topSeller.iName = item.name; topSeller.iSku = item.sku; topSeller.sTime = Convert.ToDateTime(item.sTime); topSeller.iDesc = item.desc; topSeller.iPrice = item.price; _topSellers.SetValue(topSeller, topSellerIndex); topSellerIndex++; } </code></pre> <p>Thanks for all your help!</p>
<p>If you have the values, you should be able to use LINQ's GroupBy...</p> <pre><code> XDocument doc = XDocument.Parse(xml); var query = from item in doc.Descendants("item") select new { att1 = (string)item.Attribute("att1"), att2 = (string)item.Attribute("att2") // if needed } into node group node by node.att1 into grp select new { att1 = grp.Key, Count = grp.Count() }; foreach (var item in query.OrderByDescending(x=&gt;x.Count).Take(4)) { Console.WriteLine("{0} = {1}", item.att1, item.Count); } </code></pre>
<p>You can use LINQ/XLINQ to accomplish this. Below is a sample console application I just wrote, so the code might not be optimized but it works.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using System.Text; namespace FrequencyThingy { class Program { static void Main(string[] args) { string data = @"&lt;items&gt; &lt;item att1=""ABC123"" att2=""uID"" /&gt; &lt;item att1=""ABC345"" att2=""uID"" /&gt; &lt;item att1=""ABC123"" att2=""uID"" /&gt; &lt;item att1=""ABC678"" att2=""uID"" /&gt; &lt;item att1=""ABC123"" att2=""uID"" /&gt; &lt;item att1=""XYZ123"" att2=""uID"" /&gt; &lt;item att1=""XYZ345"" att2=""uID"" /&gt; &lt;item att1=""XYZ678"" att2=""uID"" /&gt; &lt;/items&gt;"; XDocument doc = XDocument.Parse(data); var grouping = doc.Root.Elements().GroupBy(item =&gt; item.Attribute("att1").Value); foreach (var group in grouping) { var groupArray = group.ToArray(); Console.WriteLine("Group {0} has {1} element(s).", groupArray[0].Attribute("att1").Value, groupArray.Length); } Console.ReadKey(); } } } </code></pre>
49,194
<p>Comparing LinkedLists and Arrays while also comparing their differences with sorted and unsorted data</p> <ul> <li>Adding </li> <li>Removing</li> <li>Retrieving </li> <li>Sorting</li> <li>Overall speed</li> <li>Overall memory usage</li> </ul> <p>Actual questions</p> <blockquote> <p>Discuss the feasibility of implementing an unsorted data set as a linked list rather than an array. What would the tradeoffs be in terms of insertion, removal, retrieval, computer memory, and speed of the application?</p> <p>Discuss the feasibility of implementing a sorted data set as a linked list rather than an array. What would the tradeoffs be in terms of insertion, removal, retrieval, computer memory, and speed of the application? </p> <p>Based on your answers to the previous questions, summarize the costs and benefits of using linked lists in an application.</p> </blockquote> <p>My answers/input:</p> <blockquote> <p>LinkedLists have to allocate memory everytime a new Node is added, useful when adding many Nodes and size keeps changing but generally slower when adding few elements</p> <p>Arrays allocated memory at the beggining of the program run, resizing list slow (adding many elements slow if have to resize)</p> <p>Retrieval is faster in array due to indexing</p> <p>Adding/removing faster in LinkedList due to pointers</p> </blockquote>
<p>On unsorted vs. sorted. I'll do one, then you really do need to do your homework</p> <p>Stackoverflow markup really needs tables to do this one. You want to say how "expensive" the operation is for the unsorted/array, sorted/array, unsorted/linked-list, sorted/linked-list</p> <p>One final point: "speed of the application" is a hint to consider more than just the speed of the individual operations. </p> <pre><code>* Adding </code></pre> <p>Unsorted: Array adding is O(1) unless resizing needed - just add it to the end. You might want to discuss a resizing strategy that minimises the overhead (hint: don't just increase the size by one)</p> <p>Sorted: Array adding is O(n) - finding the place to add it is O(log(n)), but you need to move half the elements up (on average) to make romm for the new one</p> <p>Unsorted: Linked list is O(1) - add it to the start or end of the list.</p> <p>Sorted: Linked list is O(n) - although you can again add the element in O(1), you need to scan through half the list on average to find the place to put it.</p> <p>So, over to you for the rest. Post an answer, and we'll critique it, but to get the most from your (presumably) expensive educatiom, you really need to do some work on this :)</p> <pre><code>* Removing * Retrieving * Sorting * Overall speed * Overall memory usage </code></pre>
<p>@Paul: Thanks</p> <blockquote> <ul> <li>Removing</li> </ul> </blockquote> <p>Unsorted &amp; sorted: Array removing is O(n) - have to move all element over to fill 'hole'</p> <p>Unsorted &amp; sorted: Linked list is O(1) - Change pointers as needed</p>
34,836
<p>On <strong>Linux/NPTL</strong>, threads are created as some kind of process.</p> <p>I can see some of my process have a weird cmdline:</p> <pre><code>cat /proc/5590/cmdline hald-addon-storage: polling /dev/scd0 (every 2 sec) </code></pre> <p>Do you have an idea how I could do that for each thread of my process? That would be very helpful for debugging.</p> <p><em>/me now investigating in HAL source</em></p>
<p>If you want to do this in a portable way, something that will work across multiple Unix variations, there are very few options available.</p> <p>What you have to do is that your caller process must call exec with the <code>argv [0]</code> argument pointing to the name that you would like to see in the process output, and the filename pointing to the actual executable.</p> <p>You can try this behavior from the shell by using:</p> <pre><code>exec -a "This is my cute name" bash </code></pre> <p>That will replace the current bash process with one named <code>"This is my cute name"</code>.</p> <p>For doing this in C, you can look at the source code of <code>sendmail</code> or any other piece of software that has been ported extensively and find all the variations that are needed across operating systems to support this.</p> <p>Some operating systems have a <code>setproctitle(3)</code> API, some others allow you to override the contents of <code>argv [0]</code> and show that result.</p>
<p>Bah.. the code is not that nice, the trick is to reuse the environ (here argv_buffer) pointer:</p> <pre><code>memset (argv_buffer[0] + len, 0, argv_size - len); argv_buffer[1] = NULL; </code></pre> <p>Any better idea?</p> <p>Is that working for different threads?</p>
16,919
<p>From basic things likes page views per second to more advanced stuff like cpu or memory usage. Any ideas?</p>
<p>I think someone has asked the same type of question before <a href="https://stackoverflow.com/questions/18080/best-traffic-performance-usage-monitoring-module#19502">here</a>? Though I'm not too sure how helpful it is.</p> <p>For CPU usage, etc, I would try <a href="http://oss.oetiker.ch/rrdtool/" rel="nofollow noreferrer">RRDTool</a>, or maybe something like <a href="http://www.cacti.net/" rel="nofollow noreferrer">Cacti</a>.</p>
<p>I've been using monit (<a href="http://www.tildeslash.com/monit/" rel="nofollow noreferrer">http://www.tildeslash.com/monit/</a>) for years. It monitors CPU and memory usage as well as downtime for apache/mysql/etc... you can also configure it to notify you of outages and automatically restart services in real time.</p> <p>I also use munin for reporting: <a href="http://munin.projects.linpro.no/" rel="nofollow noreferrer">http://munin.projects.linpro.no/</a></p> <p>If you want reports on pageviews and whatnot, <a href="http://awstats.sourceforge.net/" rel="nofollow noreferrer">AWStats</a> is the best I've used.</p>
13,183
<p>I want to use <a href="http://jmockit.dev.java.net" rel="nofollow noreferrer">JMockit</a>'s incremental test runner instead of the standard JUnit test runners from within Eclipse. Is there a way to do this?</p> <p><strong>Edit</strong> Received the following answer to my email to the JMockit dev:</p> <blockquote> <p>You would need to start the JVM with a command line such as "-javaagent:jmockit.jar=incjunit4", where "incjunit4" specifies that the external tool for incremental JUnit tests be loaded. The coverage tool must also be used, because it provides the necessary runtime information to the incremental test tool. In fact, there is no documentation about that, mainly because this feature is not fully developed yet.</p> </blockquote> <p>Unfortunately this still doesn't work for me. Has anyone gotten the incremental test runner to work?</p>
<p>Reporting Services does not have an event based model that would allow you to hook in custom code in order to dynamically create report objects. Using expressions to hide and show objects is the correct way of achieving this sort of functionality. </p>
<p>I don't think the default report viewer control that comes with SSRS supports this. You may have to build your own report viewer interface that calls the reporting services manually.</p>
26,016
<p>I want to use jQuery with asp.net webfoms. Do I need to get a special toolkit so the .net controls spit out friendly Control ID's?</p> <p>Reason being, I don't want to write javascript referencing my html ID's like control_123_asdfcontrol_234.</p> <p>Has this been addressed in version 3.5? (I remember reading you have to get some special dll that makes ID's friendly).</p>
<p>The easiest way I've found is just to match on the end of the mangled ID for most controls. The exceptions that Know of are radiobutton lists and checkbox lists - you have to be a little trickier with them.</p> <p>But if you have this in your .aspx page:</p> <pre><code>&lt;asp:TextBox ID="txtExample" runat="server" /&gt; </code></pre> <p>Then your jQuery can easily find that control, even if it's mangled by the master page rendering, like this:</p> <pre><code>$("[id$=txtExample]") </code></pre> <p>The <code>$=</code> operator matches the end of the string and the name mangling is always on the front. Once you've done that, you can get the actual mangled ID like this:</p> <pre><code>$("[id$=txtExample]").attr("id") </code></pre> <p>and then parse that anyway you see fit. </p> <p>EDIT: This is an easy way, but it may be more of a performance hit than just giving each control a class the same as its old ID.</p> <p>See this article that Jeff posted a link to on another jQuery optimization question:</p> <p><strong><a href="http://www.componenthouse.com/article-19" rel="noreferrer">jQuery: Performance Analysis of Selectors</a></strong></p>
<p>You can attach a unique attribute to your controls (I'm not sure if you can do this without extending the base web controls; a quick search <a href="http://www.codeproject.com/KB/webforms/customhtmlattributes.aspx" rel="nofollow noreferrer">revealed only this</a>) and then use the "element[attribute:value]" selector.</p>
32,753
<p>The original bed surface of my Ender 3 has become brittle and finally cracked, requiring replacement. I'm trying to figure out what the cause might have been to avoid it happening again. It seems to have started after using "flex PLA", which involves both high temperatures (225&nbsp;&deg;C) and plasticizers mixed in the PLA. Could either of these have contributed to the problem? I'm not sure what material the bed surface is - it's the new one that's removable and held on by clips. If it's PEI, the glass transition temperature is supposedly 217&nbsp;&deg;C, just above what I use for normal PLA but well below what I'm using for the flex, so perhaps that's the cause?</p> <p>Image of the damage: <img src="https://i.stack.imgur.com/wXWW4.jpg" alt="Image of the damage"></p>
<p>The build surface on the Ender3 is a BuildTak clone. The picture is a bit unclear, but given my experience with BuildTak (clones) this certainly damage because of heat. You can, as suggested before, replace the bed surface, but I do not think it is necessary at this stage. </p> <p>Normally these surfaces do not get damaged that easily but to prolong the life try to keep the following points in mind:</p> <ul> <li>Correct height between nozzle and bed.</li> <li>Don't let the nozzle heat up/cool down close to the bed (for example after a failed first layer).</li> <li>When using sharp tools to remove prints be careful nut to dig into the surface.</li> <li>Don't use too high of a bed temperature (my BuildTak clone once had bubbles forming because the layers separated)</li> <li>Clean/degrease the bed, although this is more to ensure proper bed adhesion.</li> <li>I found out that if the bed stops sticking you can revive it by sanding it a bit.</li> </ul>
<p>The material used for the Build surface is not PEI but a BuildTak Clone that offers adhesion through a rough surface texture. I do not know what exactly is in the composition of the polymer, but I can say that my bed surface needed replacement about 9 months after purchase after I vigorously removed a piece I printed. As a matter of fact, most build surfaces - even PEI - are pretty much going to wear out over time and need occasional replacement. Luckily, a build surface isn't expensive usually.</p> <p>To prolong the life of the bed surface, I suggest:</p> <ul> <li>check the nozzle distance to the bed, as printing too close can make plastic residue extremely hard to remove.</li> <li>be very careful when using sharp tools to remove parts - don't let a corner bite into the surface!</li> <li>don't use a soldering iron or hot air gun on the build platform to remove stuck parts, you'll melt the surface and degrade it</li> <li>clean the surface at times.</li> </ul> <p>However, replacing the bed is easy enough, as I found out <a href="https://3dprinting.stackexchange.com/questions/7960/how-to-clean-up-my-buildpate-for-a-new-build-surface">here</a>.</p>
1,295
<p>When you create a new content type in Drupal using the Content Creation Kit, you automatically get Title and Body fields in the generated form. Is there a way to remove them?</p>
<p>If you're not a developer (or you want to shortcut the development process), another possible solution is to utilize the auto_nodetitle module. Auto nodetitle will let you create rules for generating the title of the node. These can be programmatic rules, tokens that are replaced, or simply static text. Worth a look if nothing else.</p>
<p>The initial answers are all good. Just as another idea for the title part... how about creating a custom template file for the cck node type. You would copy node.tpl.php to node-TYPE.tpl.php, and then edit the new file and remove where the title is rendered. (Dont forget to clear your cache).</p> <p>Doing it this way means that every node still has a title, so for content management you aren't left with blank titles or anything like that.</p> <p>HTH!</p>
11,516
<p>What's the difference between <code>TRUNCATE</code> and <code>DELETE</code> in SQL?</p> <p>If your answer is platform specific, please indicate that.</p>
<p>Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below.</p> <p><hr></p> <h1>General Overview</h1> <p>If you want to quickly delete all of the rows from a table, and you're really sure that you want to do it, and you do not have foreign keys against the tables, then a TRUNCATE is probably going to be faster than a DELETE.</p> <p>Various system-specific issues have to be considered, as detailed below.</p> <p><hr></p> <h1>Statement type</h1> <p>Delete is DML, Truncate is DDL (<a href="https://stackoverflow.com/q/2578194/276052">What is DDL and DML?</a>)</p> <p><hr></p> <h1>Commit and Rollback</h1> <p>Variable by vendor</p> <p><strong>SQL*Server</strong></p> <p>Truncate can be rolled back.</p> <p><strong>PostgreSQL</strong></p> <p>Truncate can be rolled back.</p> <p><strong>Oracle</strong></p> <p>Because a TRUNCATE is DDL it involves two commits, one before and one after the statement execution. Truncate can therefore not be rolled back, and a failure in the truncate process will have issued a commit anyway.</p> <p>However, see Flashback below.</p> <p><hr></p> <h1>Space reclamation</h1> <p>Delete does not recover space, Truncate recovers space</p> <p><strong>Oracle</strong></p> <p>If you use the REUSE STORAGE clause then the data segments are not de-allocated, which can be marginally more efficient if the table is to be reloaded with data. The high water mark is reset.</p> <p><hr></p> <h1>Row scope</h1> <p>Delete can be used to remove all rows or only a subset of rows. Truncate removes all rows.</p> <p><strong>Oracle</strong></p> <p>When a table is partitioned, the individual partitions can be truncated in isolation, thus a partial removal of all the table's data is possible.</p> <p><hr></p> <h1>Object types</h1> <p>Delete can be applied to tables and tables inside a cluster. Truncate applies only to tables or the entire cluster. (May be Oracle specific)</p> <p><hr></p> <h1>Data Object Identity</h1> <p><strong>Oracle</strong></p> <p>Delete does not affect the data object id, but truncate assigns a new data object id <em>unless</em> there has never been an insert against the table since its creation Even a single insert that is rolled back will cause a new data object id to be assigned upon truncation.</p> <p><hr></p> <h1>Flashback (Oracle)</h1> <p>Flashback works across deletes, but a truncate prevents flashback to states prior to the operation.</p> <p>However, from 11gR2 the FLASHBACK ARCHIVE feature allows this, except in Express Edition</p> <p><a href="https://stackoverflow.com/questions/25950145/use-of-flashback-in-oracle">Use of FLASHBACK in Oracle</a> <a href="http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638" rel="noreferrer">http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638</a></p> <p><hr></p> <h1>Privileges</h1> <p>Variable</p> <p><strong>Oracle</strong></p> <p>Delete can be granted on a table to another user or role, but truncate cannot be without using a DROP ANY TABLE grant.</p> <p><hr></p> <h1>Redo/Undo</h1> <p>Delete generates a small amount of redo and a large amount of undo. Truncate generates a negligible amount of each.</p> <p><hr></p> <h1>Indexes</h1> <p><strong>Oracle</strong></p> <p>A truncate operation renders unusable indexes usable again. Delete does not.</p> <p><hr></p> <h1>Foreign Keys</h1> <p>A truncate cannot be applied when an enabled foreign key references the table. Treatment with delete depends on the configuration of the foreign keys.</p> <p><hr></p> <h1>Table Locking</h1> <p><strong>Oracle</strong></p> <p>Truncate requires an exclusive table lock, delete requires a shared table lock. Hence disabling table locks is a way of preventing truncate operations on a table.</p> <p><hr></p> <h1>Triggers</h1> <p>DML triggers do not fire on a truncate.</p> <p><strong>Oracle</strong></p> <p>DDL triggers are available.</p> <p><hr></p> <h1>Remote Execution</h1> <p><strong>Oracle</strong></p> <p>Truncate cannot be issued over a database link.</p> <p><hr></p> <h1>Identity Columns</h1> <p><strong>SQL*Server</strong></p> <p>Truncate resets the sequence for IDENTITY column types, delete does not.</p> <p><hr></p> <h1>Result set</h1> <p>In most implementations, a <code>DELETE</code> statement can return to the client the rows that were deleted.</p> <p>e.g. in an Oracle PL/SQL subprogram you could:</p> <pre><code>DELETE FROM employees_temp WHERE employee_id = 299 RETURNING first_name, last_name INTO emp_first_name, emp_last_name; </code></pre>
<p>TRUNCATE is fast, DELETE is slow.</p> <p>Although, TRUNCATE has no accountability.</p>
16,889
<p>Using the Windows API, how can I get a list of domains on my network?</p>
<p>Answered my own question:</p> <p>Use the <a href="http://msdn.microsoft.com/en-us/library/aa370623(VS.85).aspx" rel="nofollow noreferrer">NetServerEnum</a> function, passing in the <code>SV_TYPE_DOMAIN_ENUM</code> constant for the "servertype" argument.</p> <p>In Delphi, the code looks like this:</p> <pre><code>&lt;snip&gt; type NET_API_STATUS = DWORD; PSERVER_INFO_100 = ^SERVER_INFO_100; SERVER_INFO_100 = packed record sv100_platform_id : DWORD; sv100_name : PWideChar; end; function NetServerEnum( //get a list of pcs on the network (same as DOS cmd "net view") const servername : PWideChar; const level : DWORD; const bufptr : Pointer; const prefmaxlen : DWORD; const entriesread : PDWORD; const totalentries : PDWORD; const servertype : DWORD; const domain : PWideChar; const resume_handle : PDWORD ) : NET_API_STATUS; stdcall; external 'netapi32.dll'; function NetApiBufferFree( //memory mgmt routine const Buffer : Pointer ) : NET_API_STATUS; stdcall; external 'netapi32.dll'; const MAX_PREFERRED_LENGTH = DWORD(-1); NERR_Success = 0; SV_TYPE_ALL = $FFFFFFFF; SV_TYPE_DOMAIN_ENUM = $80000000; function TNetwork.ComputersInDomain: TStringList; var pBuffer : PSERVER_INFO_100; pWork : PSERVER_INFO_100; dwEntriesRead : DWORD; dwTotalEntries : DWORD; i : integer; dwResult : NET_API_STATUS; begin Result := TStringList.Create; Result.Clear; dwResult := NetServerEnum(nil,100,@pBuffer,MAX_PREFERRED_LENGTH, @dwEntriesRead,@dwTotalEntries,SV_TYPE_DOMAIN_ENUM, PWideChar(FDomainName),nil); if dwResult = NERR_SUCCESS then begin try pWork := pBuffer; for i := 1 to dwEntriesRead do begin Result.Add(pWork.sv100_name); inc(pWork); end; //for i finally NetApiBufferFree(pBuffer); end; //try-finally end //if no error else begin raise Exception.Create('Error while retrieving computer list from domain ' + FDomainName + #13#10 + SysErrorMessage(dwResult)); end; end; &lt;snip&gt; </code></pre>
<p>Answered my own question:</p> <p>Use the <a href="http://msdn.microsoft.com/en-us/library/aa370623(VS.85).aspx" rel="nofollow noreferrer">NetServerEnum</a> function, passing in the <code>SV_TYPE_DOMAIN_ENUM</code> constant for the "servertype" argument.</p> <p>In Delphi, the code looks like this:</p> <pre><code>&lt;snip&gt; type NET_API_STATUS = DWORD; PSERVER_INFO_100 = ^SERVER_INFO_100; SERVER_INFO_100 = packed record sv100_platform_id : DWORD; sv100_name : PWideChar; end; function NetServerEnum( //get a list of pcs on the network (same as DOS cmd "net view") const servername : PWideChar; const level : DWORD; const bufptr : Pointer; const prefmaxlen : DWORD; const entriesread : PDWORD; const totalentries : PDWORD; const servertype : DWORD; const domain : PWideChar; const resume_handle : PDWORD ) : NET_API_STATUS; stdcall; external 'netapi32.dll'; function NetApiBufferFree( //memory mgmt routine const Buffer : Pointer ) : NET_API_STATUS; stdcall; external 'netapi32.dll'; const MAX_PREFERRED_LENGTH = DWORD(-1); NERR_Success = 0; SV_TYPE_ALL = $FFFFFFFF; SV_TYPE_DOMAIN_ENUM = $80000000; function TNetwork.ComputersInDomain: TStringList; var pBuffer : PSERVER_INFO_100; pWork : PSERVER_INFO_100; dwEntriesRead : DWORD; dwTotalEntries : DWORD; i : integer; dwResult : NET_API_STATUS; begin Result := TStringList.Create; Result.Clear; dwResult := NetServerEnum(nil,100,@pBuffer,MAX_PREFERRED_LENGTH, @dwEntriesRead,@dwTotalEntries,SV_TYPE_DOMAIN_ENUM, PWideChar(FDomainName),nil); if dwResult = NERR_SUCCESS then begin try pWork := pBuffer; for i := 1 to dwEntriesRead do begin Result.Add(pWork.sv100_name); inc(pWork); end; //for i finally NetApiBufferFree(pBuffer); end; //try-finally end //if no error else begin raise Exception.Create('Error while retrieving computer list from domain ' + FDomainName + #13#10 + SysErrorMessage(dwResult)); end; end; &lt;snip&gt; </code></pre>
3,036
<p>I'd like to get a feel for what people are using for IoC containers. I've read some good things about Castle Windsor, but I know a lot of people use StructureMap, Unity, Ninject, etc. </p> <p>What are some of the differences amongst those mentioned (and any I neglected). Strengths? Weaknesses? Better fit (like StructureMap is great for ABC but not so good for XYZ)?</p>
<p>"Best" will always be subjective.</p> <p>That said, I favor Castle Windsor because its XML is simpler. I've only tried Windsor and Spring.NET, by the way, so I couldn't say much about the others.</p>
<p>I like StructureMap. The latest version allows you to declare inline too without having to resort to XML configuration files.</p>
16,646
<p>I want to do this, but haven't figured it quite out yet...</p> <pre><code> $(document).ready(function() { $("a.whateverclass").click(function() { $("div.whateverclass").show(); return false; }); </code></pre> <p>Basically when a link with a certain class is clicked all divs with that class are shown. The classes can be any class. And I won't know the name(s) of the classes in the application.js file so I need to match equal classes.</p>
<p>I like @Eran's answer, but in event that you have some links that don't fit this pattern, you may want to make sure that you only apply this to links that do.</p> <pre><code>$('a[class]').click(function() { $('div.' + $(this).attr('class')).show(); return false; }); </code></pre> <p>And in the case where links may have other classes applied to them, you may want to use a naming scheme such as:</p> <pre><code>$('a[class^=div-]').click(function() { $('div.' + $(this).attr('class')).show(); return false; }); &lt;div class='div-mydiv'&gt;&lt;/div&gt; &lt;a href='javascript:void(0);' class='div-mydiv'&gt;Show&lt;/a&gt; &lt;a href='mailto:nobody@nowhere.com' class='mail-link'&gt;Contact Us&lt;/a&gt; </code></pre>
<pre><code>$("a").click(function() { $("div." + $(this).attr('class')).show(); }); </code></pre>
41,781
<p>After maintaining lots of code littered with #region (in both C# and VB.NET), it seems to me that this construct is just a bunch of "make work" for the programmer. It's work to PUT the dang things into the code, and then they make searching and reading code very annoying.</p> <p>What are the benefits? Why do coders go to the extra trouble to put this in their code.</p> <p>Make me a believer!</p>
<p>A <a href="https://stackoverflow.com/questions/5916/how-do-you-feel-about-code-folding">similar question</a> has already been asked.</p> <p>but...</p> <p>I would say <strong>not anymore</strong>. It was originally intended to hide <em>generated code</em> from WinForms in early versions of .NET. With partial classes the need seems to go away. IMHO it gets way overused now as an organizational construct and has no compiler value whatsoever. It's all for the IDE.</p>
<p>My working day starts with opening files in editor and clicking on "Expand All" to hide all regions. After that I can begin to work.</p>
20,433
<p>I’m selecting data on an old database which has an abused status column. The status column has multiple pieces of information in it. Values are like ‘New Contact YYYY’, ‘Online YYYY’, ‘Updated YYYY’, ‘Withdrawn YYYY’, etc…. As you may have guessed, YYYY represents the year … which I need.</p> <p>In the past I’ve done something similar to </p> <pre><code>Rtrim( ltrim( Replace(Replace(Replace(Replace(Replace( … </code></pre> <p>Basically, replacing all text values with an empty string, so the only thing that still exists is the year. I can still do this, but I’m thinking this is ridiculous, and there’s got to be a better way.</p> <p>Does anybody know of a better way to do this?</p>
<p>If you simply want to extract a four digit year from the string, you could use PATINDEX</p> <pre><code>SELECT SUBSTRING(FieldName, PATINDEX('%[0-9][0-9][0-9][0-9]%', FieldName), 4) FROM TableName </code></pre>
<p>If the year allways are the last 4:</p> <pre><code>SELECT right(FieldName,4) from table </code></pre>
44,032
<p>As most of you probably noticed, when uninstalling an MSI package Windows will ask for the original <code>.msi</code> file. Why is that?</p> <p>I can only see disadvantages to that:</p> <ul> <li>not resilient to network changes.</li> <li>not resilient to local disk changes.</li> <li>unexpected by users.</li> <li>typically requires users to leave their desk and start a crusade to get the correct CD.</li> <li>kind of proves installations are not self-contained.</li> <li>promotes the use of unsafe tools such as msizap.</li> <li>which in turn promotes the "next time I'll just use a zip file" mentality.</li> </ul> <p>Could someone shed some light on this?</p>
<blockquote> <p><strong><em>Fix Broken Uninstall</em></strong>: You can try the newest <a href="https://support.microsoft.com/en-us/help/17588/fix-problems-that-block-programs-from-being-installed-or-removed" rel="nofollow noreferrer">FixIt Uninstall tool from Microsoft</a> if you have problems uninstalling an MSI. And one more link: <a href="https://stackoverflow.com/questions/450027/uninstalling-an-msi-file-from-the-command-line-without-using-msiexec/1055933#1055933">Uninstalling an MSI file from the command line without using msiexec</a> (a plethora of different ways to uninstall an MSI).</p> </blockquote> <hr> <p><strong>UPDATE</strong>:</p> <p><del><a href="http://support2.microsoft.com/default.aspx?scid=kb;en-us;290301" rel="nofollow noreferrer"><strong>This new support tool</strong></a></del> (this tool is now also deprecated) can be tried on recent Windows versions if you have <strong>defunct MSI packages needing uninstall</strong> (rather than the outdated, deprecated, unsupported <del>msizap.exe</del>).</p> <p>Some have suggested to use the tool linked to here by saschabeaumont: <strong><a href="https://stackoverflow.com/questions/334490/uninstall-without-an-msi-file/11058378#11058378">Uninstall without an MSI file</a></strong>. If you try it and it works, please be sure to let us know. Feedback in that answer indicates that it works (I don't have any stuck setups to test with as of now).</p> <hr> <p><strong><em>Why are you asked for the original installation media?</em></strong>:</p> <ul> <li><strong>The original MSI is not needed for uninstall unless the MSI itself is badly designed - or the cached MSI is missing</strong> (see details below).</li> <li>All installed MSI files are cached in <strong>%SystemRoot%\Installer\*.*</strong> using a <strong>random hex name</strong>.</li> <li>The cached MSI file is used for any <strong>maintenance</strong>, <strong>repair</strong> and <strong>uninstall</strong> operations - and it is sufficient for uninstall in the vast majority of cases.</li> <li><em>In some cases <strong>this cached file can be missing</strong>, and then uninstall is not possible at all in some cases</em> (<a href="https://stackoverflow.com/questions/50475550/powershell-silent-uninstall-microsoft-report-viewer-runtime-2012/50478416#50478416">some theories as to why this can happen</a> - <strong><code>MSI design errors</code></strong>, <strong><code>anti-virus quarantining</code></strong>, <strong><code>system restore</code></strong>, <strong><code>tinkering</code></strong>, <strong><code>developer system in erroneous state from development work</code></strong>, <strong><code>etc...</code></strong>). See more info below - and links to force uninstall or unregistration of the product.</li> <li><strong>The original source</strong> is only needed if files need to be copied to disk (for a maintenance install), or the MSI does an <strong>explicit request</strong> to resolve the original source via the standard action <strong>ResolveSource</strong> or via a custom action (which <strong>shouldn't be done in a properly authored package</strong> - I think the MS Office package contained this ResolveSource error back in the day, causing everyone to go looking for their installation CDs/DVDs).</li> <li>In previous editions of Windows this cached MSI was stripped of all cabs, and hence contained the installer structure only, and no files.</li> <li>Starting with Windows 7 (<strong>MSI version 5</strong>) the <strong>MSI files are now cached full size</strong> to avoid breaking the file signature which affects the UAC prompt on setup launch (a known Vista problem). This may cause a tremendous increase in disk space consumption (several gigabytes for some systems). <a href="https://www.symantec.com/connect/forums/caching-msi-windowsinstaller-folder" rel="nofollow noreferrer">Check this article and especially the discussion at the bottom for more intel</a>.</li> <li>To prevent caching a huge MSI file, you can run an <strong>admin-install</strong> of the package before installing. This is how a company with proper deployment in a managed network would do things, and it will strip out the cab files and make a network install point with a small MSI file and files besides it. <em>Note that this may yield a <strong>UAC prompt</strong> is some cases since the extracted MSI file is no longer signed - this must be tested with your SOE / desktop configuration</em>.</li> <li>Read my answer in this thread for the full description of admin installs: <a href="https://stackoverflow.com/questions/5564619/what-is-the-purpose-of-administrative-installation-initiated-using-msiexec-a">What is the purpose of administrative installation initiated using msiexec /a?</a> or this similar but perhaps more accessible answer: <a href="https://stackoverflow.com/questions/1547809/extract-msi-from-exe/24987512#24987512"><strong>admin install and its uses</strong></a></li> <li><em>In some rare cases the cached MSI (with the random name) can be erroneously missing, and uninstall will then ask for the original MSI in order to complete the uninstall.</em> This does not happen often. It used to be the case that one could use <del><strong>MsiZap.exe</strong></del> to clean out such an install, but this tool is <strong>outdated</strong>, <strong>deprecated</strong> and <strong>unsupported</strong>. Don't use it - there are too many incompatibilities with newer Windows versions and you create new problems. Perhaps try <del><a href="http://support2.microsoft.com/default.aspx?scid=kb;en-us;290301" rel="nofollow noreferrer"><strong>this support tool</strong></a></del> instead (also deprecated). The only option I can suggest now is <a href="https://stackoverflow.com/questions/334490/uninstall-without-an-msi-file/11058378#11058378"><strong>this answer from saschabeaumont</strong></a>. <em>If you try this tool, please let us know if it works for yo</em>u. If you want to figure out what could have caused the cached MSI to be missing, try to read section 12 here: <a href="https://stackoverflow.com/questions/450027/uninstalling-an-msi-file-from-the-command-line-without-using-msiexec/1055933#1055933">Uninstalling an MSI file from the command line without using msiexec</a> (in short potential causes range from interference with system restore, anti virus and cleanup scripts, to erronous manual tweaking, low disk space, power outages, developer box debugging errors, badly designed MSI files with duplicate package codes, failed patches, etc... Many theories, few certainties I am afraid).</li> <li>As a <strong>last resort</strong> you can try <strong><a href="http://en.wikipedia.org/wiki/System_Restore" rel="nofollow noreferrer">system restore</a></strong> (unless it has been disabled entirely or partly) to go back to a previous installation state and see if this solves your uninstall problem (you can find video demos of this on youtube or a similar site).</li> <li>Be aware that system restore might affect Windows Update that must then be re-applied - as well as many other system settings. I have seen new, unsolvable installation problems resulting from a system restore, but normally it works OK. Obviously don't use the feature for fun, <strong>it's a last resort</strong> and is best used for <strong>rollback of new drivers</strong> or setups that have just been installed and are found to cause immediate problems and such issues. The longer you go back the more rework you will create for yourself. A lot of self-evident stuff, but I guess it needs to be mentioned.</li> <li>Since I mentioned system restore I suppose I should mention <a href="http://support.microsoft.com/kb/307852" rel="nofollow noreferrer">the Last Known Good Configuration feature</a>. This feature has nothing to do with uninstall or system restore, but is the last boot configuration that worked or resulted in a running system. It can be used to get your system running again if it bluescreens or halts during booting. This often happens after driver installs. This will do nothing to fix your failing uninstall though (or I would be <strong>very</strong> surprised).</li> </ul> <p>Related answer: </p> <ul> <li><a href="https://stackoverflow.com/questions/334490/uninstall-without-msi-file/1061570#1061570">Uninstall without an MSI file</a></li> </ul> <hr> <p>In addition to this answer, perhaps this article on various ways of uninstalling MSI packages is of interest. It is a <strong>rather popular article</strong> with a <strong>high number of views</strong>: </p> <ul> <li><strong><a href="https://stackoverflow.com/questions/450027/uninstalling-an-msi-file-from-the-command-line-without-using-msiexec/1055933#1055933">Uninstalling an MSI file from the command line without using msiexec</a></strong>. </li> </ul>
<p>There are a few reasons for keeping the original msi:</p> <ul> <li>The uninstaller uses it to know what files and registry keys were installed and make sure they are all cleaned up.</li> <li>The msi may contain special uninstall actions that need to be performed.</li> <li>It allows you do to a 'repair' operation from the Add/Remove Programs menu, regardless of whether or not you saved the install file yourself.</li> </ul> <p>The normal way of things is for Windows to keep the file cached for you, so you don't have to think about it. See your <code>%WINDIR%\Installer\</code> folder. The only reason it would ask your for the original msi is if something is wrong with the saved file. This addresses most of your concerns, though it does raise a new one (disk-space).</p>
25,585
<p>I have a templated class defined (in part) as</p> <pre><code>template &lt;class T&gt; MyClass { public: void DoSomething(){} }; </code></pre> <p>If I want to call DoSomething from another class, but be able to do this for multiple 'T' types in the same place, I am stuck for an idea as method functions pointers are uniquely constrained to the class type. Of course, each MyClass is a different type, so I can not store function pointers to MyClassDoSomething() in a 'polymorphic' way.</p> <p>My use-case is I want to store, in a holding class, a vector of function pointers to 'DoSomething' such that I can issue a call to all stored classes from one place.</p> <p>Has anyone any suggestions?</p>
<p>Ok, so the functor solution doesn't work as you need. Perhaps you should have your template class inherit from a common base "Interface" class. And then you use a vector of those.</p> <p>Something like this:</p> <pre><code>class Base { public: virtual ~Base(){} virtual void DoSomething() = 0; } template &lt;class T&gt; class MyClass : public Base { public: void DoSomething(){} }; std::vector&lt;Base *&gt; objects; objects.push_back(new MyClass&lt;int&gt;); objects.push_back(new MyClass&lt;char&gt;); </code></pre>
<p>You know, that is just what I needed to do. Bizzarly I had discounted it as a solution valid for my usecase early on, for reasons that now escape me. I think I was blinded by some metaprogramming stuff I'm doing in the same place for compile-time dispatch (i.e. confusing compile time and runtime in my addled brain).</p> <p>Thanks for the jolts!</p>
17,616
<p>Quite a few comments to answers in a different post, <em><a href="https://stackoverflow.com/questions/191609/where-are-the-best-locations-to-write-an-error-log-in-windows">Where are the best locations to write an error log in Windows?</a></em>, gave me the impression that a lot of things regarding standard folders (<code>%APPDATA%</code>; <code>%TEMP%</code>) in Windows&nbsp;Vista are different from Windows&nbsp;XP, which should of course be taken into account when developing software that will have to run under Windows&nbsp; at some point. </p> <p>But in my company, I do not see that happen in this decade, and maybe not in the next either. I mean, the central IT deployed SP2 only eight months ago, and any question about SP3 is met with disregard (well, if you're lucky...) </p> <p>So what is your advice? Should I rewrite two modules in my current project to make them ready for Windows&nbsp;Vista, or should I not bother about it at all, until it is really needed?</p>
<p>Make them Vista-ready, if only for the fact that Windows 7 will have the same changes. Better to future-proof now when you have the chance, than later when time is critical.</p>
<p>Is your company going to upgrade to Windows&nbsp;Vista at all? A lot of companies are ignoring Windows&nbsp;Vista and are planning to upgrade to the next Windows version when it comes out in the hopes that it will suck less than Windows&nbsp;Vista. If this is the case, it would be a complete waste of time. Who knows what will change in the next version of Windows. It is better to rewrite once for the new Windows than to rewrite once for Windows&nbsp;Vista and then again for the next Windows version.</p>
23,295
<p>Where can I find a good sample of Asynchronous IO on files with thread hooping?</p> <p>Thanks</p>
<p>In this video cast <a href="http://channel9.msdn.com/pdc2008/TL11/" rel="nofollow noreferrer">http://channel9.msdn.com/pdc2008/TL11/</a> Luca Bolognese explain F#, including async file reading and parallel map reduce. </p> <p>I hope it helps. </p>
<p>Here is an example: <a href="http://through-the-interface.typepad.com/through_the_interface/2008/01/harnessing-f-as.html" rel="nofollow noreferrer">Using F# Asynchronous Workflows to simplify concurrent programming in AutoCAD</a>.</p>
44,707
<p>Is there any way in Python to determine what exceptions a (built-in) function might raise? For example, the documentation (<a href="http://docs.python.org/lib/built-in-funcs.html" rel="nofollow noreferrer">http://docs.python.org/lib/built-in-funcs.html</a>) for the built-in int(s) says nothing about the fact that it might raise a ValueError if s is not a validly formatted int.</p> <hr> <p>This is a duplicate of <a href="https://stackoverflow.com/questions/58119/does-recompile-or-any-given-python-library-call-throw-an-exception">Does re.compile() or any given Python library call throw an exception?</a></p>
<p>The only way to tell what exceptions something can raise is by looking at the documentation. The fact that the int() documentation doesn't say it may raise ValueError is a bug in the documentation, but easily explained by ValueError being exactly for that purpose, and that being something "everybody knows".</p> <p>To belabour the point, though, documentation is the only way to tell what exceptions you should care about; in fact, any function can potentially raise any exception, even if it's just because signals may arrive and signal handlers may raise exceptions. You should not anticipate or handle those errors, however; you should just handle the errors you expect.</p>
<p>I don't know of any definitive source, apart from the source.</p>
18,175