instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>A friend of mine is now building a web application with J2EE and Struts, and it's going to be prepared to display pages in several languages.</p> <p>I was told that the best way to support a multi-language site is to use a properties file where you store all the strings of your pages, something like:</p> <pre><cod...
<p>They way I have designed the database before is to have an News-table containing basic info like NewsID (int), NewsPubDate (datetime), NewsAuthor (varchar/int) and then have a linked table NewsText that has these columns: NewsID(int), NewsText(text), NewsLanguageID(int). And at last you have a Language-table that ha...
<p>@Auron</p> <p>thats what we apply it to. Our apps are all PHP, but gettext has a long heritage. </p> <p>Looks like there is a <a href="http://www.gnu.org/software/autoconf/manual/gettext/Java.html" rel="nofollow noreferrer">good Java implementation</a></p>
6,065
<p>Maybe I should further qualify this - Is there a way to specify which direction a ComboBox will open without copying and pasting the entire ComboBox class and ripping out the code where it determines which direction it will open in...</p> <p>I'm my specific case - I need it to open upwards - always.</p> <p>UPDATE:...
<p>If you build up the Menu object yourself, you can place the menu anywhere you want by simply setting the x,y coordinates of the menu object. You'll need to calculate those coordinates, but you might be able to do this easily without subclassing ComboBox.</p> <p>I am doing something similar with PopUpButton; you mi...
<p>I doubt it - you'd need to subclass the control (which isn't <em>that</em> big a deal.)</p> <p>Maybe you could mess with the real estate so it's placed in such a fashion (e.g. crowded into the lower right corner) that up is naturally coerced?</p>
33,369
<p>We have a project that generates a code snippet that can be used on various other projects. The purpose of the code is to read two parameters from the query string and assign them to the "src" attribute of an iframe.</p> <p>For example, the page at the URL <a href="http://oursite/Page.aspx?a=1&amp;b=2" rel="nofollo...
<p>Upadte Sep 2022: Most JS runtimes now have a <em>URL</em> type which exposes query parameters via the <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams" rel="nofollow noreferrer"><em>searchParams</em></a> property. You need to supply a base URL even if you just want to get URL parameters fro...
<p>Several things you should be doing:</p> <ul> <li>Strictly whitelist your accepted values, according to type, format, range, etc</li> <li>Explicitly blacklist certain characters (even though this is usually bypassable), IF your whitelist cannot be extremely tight.</li> <li>Encode the values before output, if youre u...
15,582
<p>I have a COM dll written in vb6. When I try to create a new object of a class module from this dll I get a Run timer error 430: Class does not support automation or does not support expected interface. The interesting thing is that this happens only from outside the IDE, when I am debugging from within the IDE there...
<p>If this project is entirely in VB6. The likely cause of this is that the EXE has a copy of the DLL binary in it's directory. When you fire it uses that copy instead of the compiled copy. When you ADD methods or classes that EXE becomes incompatible with the old DLL. If you did a bug fix or just worked with the insid...
<p>This is almost certainly a versioning problem, sometimes known as "DLL hell".</p> <p>The background is that the .NET world is explicitly designed to let interfaces evolve while keeping the same name. But in the COM world, interfaces are considered to be immutable. </p> <p>When you're working within the IDE, Visual...
35,453
<p>I have a Java server that accepts SSL connections using JSSE and uses a simple XML message format inside the stream. I would like the server to read a complete message and then send a reply. This turns out to be quite difficult because org.xml.sax.XMLReader wants to read the entire stream and then call close(). I...
<p>I'm guessing that you are already doing dynamic assembly resolution and loading? If so, then you could try substituting a fake assembly name in place of the real assembly name i n the Xaml - you can then use that in your assembly resolution code to load up and return the right assembly. e.g. if your original source ...
<p>I haven't confirmed if this would work, but I believe that it may. You could use the XmlnsDefinitionAttribute (at assembly level). E.g.</p> <p>Assembly V1 -> AssemblyInfo.cs</p> <pre><code>[assembly: XmlnsDefinition( "http://schema.mycompany.com/myproject/v1", "MyCompany.MyProject" )] </code></pre> <p>Assembly V2...
32,980
<p>Following on from this question <a href="https://stackoverflow.com/questions/150814/how-to-handle-an-activex-event-in-javascript">here</a></p> <p>I have a custom ActiveX control which raises an event "BeforePageValidated" which has a parameter "args" which is an object which contains a boolean. The purpose of this ...
<p>Worked it out for myself.</p> <p>The problem was that the event was being passed down from another dll used by the activeX control, and this is where the args class was declared.</p> <p>Fixed it by creating a copy of the args class in the activeX object and using this when raising the event.</p> <p>Unfortunately ...
<p><code>args</code> also needs to register as com object.</p> <pre><code>[ComVisible(true)] [GuidAttribute("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")] public class args { } </code></pre> <p>Hope this will help.</p>
27,929
<p>I am using windows authentication within an ASP.NET application. I am wondering how to best get the objectGuid from the currently logged in user?</p> <p>Regards, Egil.</p>
<p>The suggest solutions are rather expensive. Rather than searching by domain and username, a better solution is to use the SID to lookup the account:</p> <pre><code>// using System.Security.Principal; IPrincipal userPrincipal = HttpContext.Current.User; WindowsIdentity windowsId = userPrincipal.Identity as WindowsId...
<p>You need to use <a href="http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.nativeguid.aspx" rel="nofollow noreferrer">NativeGuid</a> property. C# code:</p> <pre><code>string login = HttpContext.Current.User.Identity.Name; string domain = login.Substring(0, login.IndexOf('\\')); string ...
40,716
<p>Is it possible to run both debuggers within the same PHP installation simultaneously. They both use different ports so communication with the client IDEs/other apps wouldn't be an issue.</p> <p>I ask only because using the Zend Debugger with ZendStudio has proven to be much easier (fewer steps to start/stop debuggi...
<p><a href="http://www.suspekt.org/2008/08/04/xdebug-203-stealth-patch/" rel="noreferrer">http://www.suspekt.org/2008/08/04/xdebug-203-stealth-patch/</a> (in particular the last comment) seems to indicate that the profiling parts of Xedebug will work fine alongside Zend Debugger, with the patch installed.</p>
<p>So, XDebug is known not to work with many Zend tools (I know Zend Optimizer for certain, I don't know about Zend Debugger but I wouldn't be surprised if XDebug has a built-in check for that).</p> <p>Since you're running the debugger and profiler on a dev machine, I don't see why you can't maintain two separate ini ...
23,356
<p>In the <a href="http://www.boost.org/doc/html/signals.html" rel="noreferrer" title="Boost Signals documentation">Boost Signals</a> library, they are overloading the () operator.</p> <p>Is this a convention in C++? For callbacks, etc.?</p> <p>I have seen this in code of a co-worker (who happens to be a big Boost fa...
<p>One of the primary goal when overloading operator() is to create a functor. A functor acts just like a function, but it has the advantages that it is stateful, meaning it can keep data reflecting its state between calls.</p> <p>Here is a simple functor example :</p> <pre><code>struct Accumulator { int counter ...
<p>Overloading operator() can make the class object calling convention easier. <code>Functor</code> is one of the applications of operator() overloading.</p> <p>It is easy to get confused between <code>Functor</code> and <code>user-defined conversion function</code>.</p> <p>Below 2 examples show the difference between<...
41,007
<p>How does it work, what is it used for and when should one use it?</p>
<p>Let's explain the strategy pattern the easy way:</p> <p>You have a class <code>Car()</code> with a method <code>run()</code>, so you use it this way in a pseudo language:</p> <pre><code>mycar = new Car() mycar.run() </code></pre> <p>Now, you may want to change the <code>run()</code> behavior on the fly, while the...
<p>Directly from the <a href="http://en.wikipedia.org/wiki/Strategy_pattern" rel="nofollow noreferrer">Strategy Pattern Wikipedia article</a>:</p> <blockquote> <p>The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application. The strategy pattern is int...
11,739
<p>I'd like to force Klipper to perform power on (using <code>M80</code>) before homing. For this purpose I'm trying to override <code>G28</code>:</p> <pre><code>[gcode_macro G28] rename_existing: G28_BASE gcode: M80 G28_BASE { rawparams } </code></pre> <p>But for some reason this does not work, I'm getting the fol...
<p>Because of the way parameters work differently (<code>Sx</code> vs <code>NAME=x</code>) for gcode style commands vs Klipper extended ones, the rename has to be to the &quot;same type&quot; of command. <code>G28_BASE</code> does not fit the pattern to be considered a &quot;gcode style&quot; one. Use <code>G9028</code...
<p>Besides using a different macro, it is also possible to use <a href="https://www.klipper3d.org/Config_Reference.html#homing_override" rel="nofollow noreferrer">[homing_override]</a> which allows you to redefine the homing sequence.</p> <p>You can write a simple homing_override like (untested!)</p> <pre><code>[homing...
2,108
<p>I like using WCF callbacks when I can because to me it is better than the client having to poll the server and its more real time than polling. The question I have is when I subscribe to a WCF service event is there any kind of heart beat that keeps the connection alive between the client and the server. I starting ...
<p>There is a good short description of the Duplex contract (WCF callbacks) in this <a href="http://msdn.microsoft.com/en-us/library/ms731184.aspx" rel="nofollow noreferrer">link</a>. The duplex contract is basically two one-way channels and there is no implied message correlation. You are right, there are no "heartbea...
<p>I went ahead and created a recurring heartbeat to the subscribed clients (basically a call to a function they're hosting).</p> <p>I've run this for hours and it works, this helps ensure the connection.</p>
30,835
<p>My understanding is that you have to write unit tests that isolate functionality. So given a repository class that has this method:</p> <pre><code>Entity GetById(Guid id) </code></pre> <p>and a <em>fake</em> implementation (using a Dictionary for storage), how would you write a test without first <em>adding</em> a...
<p>Yes, using a fake implementation of an object/interface with a fixed list of items that can be queried from the fake instance is a valid practice. </p> <p>Obviously, without adding an entry first, one can only test what's returned when the Guid can't be found in the repository. </p> <p>In C# allows it, one also ca...
<p>Yes, you could use known test ids in your test - that is what I would do. Although I have become a fan of <a href="http://en.wikibooks.org/wiki/How_to_Use_Rhino_Mocks/Introduction" rel="nofollow noreferrer">Rhino Mocks</a> which lets you put more directly in the test about what you'd expect to the mock object to do...
40,499
<p>After encountering extreme under extrusion on my Anycubic i3 Mega, I first cleaned the nozzle and ended up replacing the entire hotend + nozzle. Since that did not help and I couldn't see any issues with it, I went on to check my E-steps. It seems that this is the root cause of the issue.</p> <p>I removed the Bowden...
<p>The raft still needs to fit on the bed, and it counts as a print, because, it is printed. You want the raft for better adhesion, so that means that you need more contact with the bed. If you’re not, your basically wasting filament. Its kinda logical actually.</p>
<h2>Adjusted model Dimensions</h2> <p>The model has the size determined by the base area of the bounding box, in this case, <span class="math-container">$\pu{190 \times 200 mm }$</span>. The raft as told by OP adds 15mm on <strong>all</strong> sides of the model, and thus adds 30 mm in total on both the X and Y dimensi...
2,225
<p>Just wondering why people like case sensitivity in a programming language? I'm not trying to start a flame war just curious thats all.<br> Personally I have never really liked it because I find my productivity goes down when ever I have tried a language that has case sensitivity, mind you I am slowly warming up/gett...
<p>Consistency. Code is more difficult to read if "foo", "Foo", "fOO", and "fOo" are considered to be identical.</p> <p>SOME PEOPLE WOULD WRITE EVERYTHING IN ALL CAPS, MAKING EVERYTHING LESS READABLE.</p> <p>Case sensitivity makes it easy to use the "same name" in different ways, according to a capitalization conven...
<p>It's useful for distinguishing between types in code.</p> <p>For example in Java: If it begins with a capital letter, then its probably a class. if its ALL_CAPS its probably a constant.</p> <p>It gives more versatility. </p>
19,987
<p>I'm looking for something that will show me the size of each folder within my main folder recursively.</p> <p>This is a <a href="http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29" rel="nofollow noreferrer">LAMP</a> server with a CGI-Bin so most any PHP script should work or anything that will work in the CGI-...
<p>Strange, I came up on Google with <a href="http://www.google.com.au/search?hl=en&amp;q=php+directory+size&amp;btnG=Google+Search&amp;meta=" rel="nofollow noreferrer">many relevant results</a> and <a href="http://www.go4expert.com/forums/showthread.php?t=290" rel="nofollow noreferrer">this one</a> is probably the mos...
<h1>number_files_and_size.php</h1> <pre><code>&lt;?php if (isset($_POST["nivel"])) { $mostrar_hasta_nivel = $_POST["nivel"]; $comenzar_nivel_inferior = $_POST["comenzar_nivel_inferior"]; // $mostrar_hasta_nivel = 3; global $nivel_directorio_raiz; global $nivel_directorio; ...
4,951
<p>I know enough to know that we need to get our application to deploy with a single user action. However, I <strong>don't</strong> know:</p> <ol> <li>What are some good tools to use in a .NET shop?</li> <li>How do you manage config changes for each of your environments?</li> </ol> <p>Can someone point me to some goo...
<p>I wrote a blog post that may be helpful:</p> <p><a href="http://murrayon.net/2008/02/visual-studio-web-deployment-projects.html" rel="nofollow noreferrer">Visual Studio Web Deployment Projects</a></p> <p>It is a year and a half old, but talked about some new (at that time) project templates for VS and also a comma...
<p>I see two different questions:</p> <ul> <li>For the deployment thing: The ClickOnce deployment should do it. You just publish your desktop application by going in VS.net at Build menu > Publish. VS.net then compiles a web page and a setup.exe. When users with IE or Firefox and .net 3.5 SP1 click on the link, it run...
28,629
<p>I have a mysql table with albums. Each album can be a top level album, or a child album of another album. Each album has a foldername which is the name of the folder its pictures are in. Each album also has a field called parent which is the id of the parent album. So, if I have a path to an image like this:</p> <p...
<p>I'm not sure storing a tree in Database is a good idea...</p> <p>To keep your problem simple maybe just store the full path of an album in a column of your table...</p> <pre><code>id parent path foldername 1 NULL / root 2 1 /root/ album1 3 2 /root/album1/ album2 </cod...
<p>Totally untested and typed off the top of my head...</p> <pre><code>DECLARE @FOLDER VARCHAR(200) DECLARE @TOPID AS INT DECLARE @MYID As int CREATE TABLE #tmp ( [id] INT, [path] VARCHAR(50) ) DECLARE tempCursor CURSOR FOR SELECT id FROM albums ORDER BY id OPEN tempCursor FETCH NEXT FROM tempCursor INTO @T...
22,324
<p>When I have entities in my domain with lists of things, should they be exposed as ILists or IEnumerables? E.g. Order has a bunch of OrderLines. </p>
<p><a href="https://msdn.microsoft.com/en-us/library/9eekhta0.aspx" rel="noreferrer" title="MSDN documentation"><code>IEnumerable&lt;T&gt;</code></a> represents a series of items that you can iterate over (using foreach, for example), whereas <a href="https://msdn.microsoft.com/en-us/library/5y536ey6.aspx" rel="norefer...
<p>Most of the time I end up going with IList over IEnumerable because IEnumerable doesn't have the Count method and you can't access the collection through an index (although if you are using LINQ you can get around this with extension methods).</p>
49,314
<p>I know it is not recommended, but is it at all possible to pass the user's password to scp?</p> <p>I'd like to copy a file via scp as part of a batch job and the receiving server does, of course, need a password and, no, I cannot easily change that to key-based authentication.</p>
<p>Use <a href="http://sshpass.sourceforge.net/" rel="noreferrer">sshpass</a>:</p> <pre><code>sshpass -p "password" scp -r user@example.com:/some/remote/path /some/local/path </code></pre> <p>or so the password does not show in the bash history</p> <pre><code>sshpass -f "/path/to/passwordfile" scp -r user@example.co...
<p>An alternative would be add the public half of the user's key to the authorized-keys file on the target system. On the system you are initiating the transfer from, you can run an ssh-agent daemon and add the private half of the key to the agent. The batch job can then be configured to use the agent to get the privat...
7,271
<p>I am looking at some code and it has this statement: </p> <pre><code>~ConnectionManager() { Dispose(false); } </code></pre> <p>The class implements the <code>IDisposable</code> interface, but I do not know if that is part of that the tilde(~) is used for.</p>
<p><strong>~ is the destructor</strong></p> <ol> <li>Destructors are invoked automatically, and cannot be invoked explicitly.</li> <li>Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.</li> <li>Destructors are not inherited. Thus, a class has no destructors other than the one, which ma...
<p>~ usually represents a deconstructor. which is run right before a object dies. </p> <p><a href="http://www.ondotnet.com/pub/a/dotnet/2002/02/11/csharp_traps.html" rel="nofollow noreferrer">Here is a description of C# deconstructors i found</a></p>
22,881
<p>I want to emulate the delete confirmation page behavior before saving certain models in the admin. In my case if I change one object, certain others should be deleted as they depend upon the object's now out-of-date state. </p> <p>I understand where to implement the actual cascaded updates (inside the parent m...
<p>You could overload the <code>get_form</code> method of your model admin and add an extra checkbox to the generated form that has to be ticket. Alternatively you can override <code>change_view</code> and intercept the request.</p>
<p>Have you considered overriding the administrative templates for the models in question? This <a href="http://www.unessa.net/en/hoyci/2006/12/custom-admin-templates/" rel="nofollow noreferrer">link</a> provides an excellent overview of the process. In this particular situation, having a finer-grained level of contr...
13,958
<p>I wonder if anyone could suggest the best way of looping through all the <code>&lt;option&gt;</code> s in a <code>&lt;select&gt;</code> element with jQuery, and building an array.</p> <p>Eg.</p> <p>Instead of the following, whereby a string ins passed to the autoCompleteArray(),</p> <pre><code>$("#CityLocal").au...
<p>This should work:</p> <pre><code>$(document).ready(function(){ // array of option elements' values var optionValues = []; // array of option elements' text var optionTexts = []; // iterate through all option elements $('#sel &gt; option').each(function() { // get value/text and push it into respect...
<p>All you need to do is pass the array as the first parameter without the brackets. Brackets create a new array, but you don't need to do that because you are already passing an array. Just do:</p> <pre><code>$("#CityLocal").autocompleteArray( MyBigArrayOfOptions, { ...
28,675
<p>Using C#</p> <p>How do you remove a specific node from an XMLDocument using XPATH?</p>
<p>If you want to delete nodes, that are not direct children of the documents root, you can do this:</p> <pre><code>XmlDocument doc = new XmlDocument(); // ... fill or load the XML Document XmlNode childNode = doc.SelectSingleNode("/rootnode/childnode/etc"); // apply your xpath here childNode.ParentNode.RemoveChild(ch...
<p>Here you go. ChildNodeName, could be just the node name or an XPath query.</p> <pre><code>XmlDocument doc = new XmlDocument(); // Load you XML Document XmlNode childNode = doc.SelectSingleNode(childNodeName); // Remove from the document doc.RemoveChild(childNode); </code></pre> <p>There is a different way usi...
19,664
<p>I want to add an item into the Desktop context menu (the menu you see when you right-click on an empty space on the Windows Desktop). </p> <p>Something like Catalyst Control Center in this screenshot:<br> <img src="https://i361.photobucket.com/albums/oo51/Stark3000/ContextMenuExample.png" alt="Embedded Example"></...
<p>Such a handler must be registered in HKCR\Directory\Background, instead of usual locations like HKCR\Directory, HKCR\Folder, etc.</p> <p>Check out <a href="http://msdn.microsoft.com/en-us/library/cc144067(VS.85).aspx" rel="nofollow noreferrer">Creating Shell Extension Handlers</a> in MSDN.</p>
<p>There's a series of articles on CodeProject that details writing Shell Extensions and is very good:</p> <p><a href="http://www.codeproject.com/KB/shell/shellextguide1.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/shell/shellextguide1.aspx</a></p>
10,218
<p>Specifically I'd like to detect when a query has been executing for over 5 minutes and then cause it to rollback, I could no doubt do this at an application level but am investigating if SQL Server has any built in mechanism to do this for me.</p> <p>Note, for clarification, I'm sadly still running SQL Server 2000....
<p>It is not possible in Eclipse 3.4.1. It is a <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=163194" rel="noreferrer">known issue</a>. See this bug report page for more information.</p>
<p>Maybe I'm missing something but interface methods are already required to be implemented by implementation classes.</p> <p>The compiler will generate an error if the interface is not completely implemented.</p>
27,804
<p>I need to copy a set of rows from one tab to another tab of the same Excel document by just clicking a button. </p> <p>Also, can I also get information on how can I copy a set of rows that are hidden and paste it in the same tab without copying the "hidden" format?</p>
<p>If 'Copystart' is your original rows, and 'Copyend' is where you want to paste them, then using named ranges:</p> <pre><code>Sub Copybutton_Click() Range("Copyend").value = Range("Copystart").value Range("Copyend").visible = True End Sub </code></pre> <p>If you have multiple named ranges with the same name, then...
<p>There are no native functions in Excel that will allow you to do this. You will need to write a macro and assign that to a button control (which you can drop onto your worksheet by using the Control Toolbox toolbar - View > Toolbars > Control Toolbox).</p> <p>You would usually then assign the macro to that button ...
33,588
<p>I have my sources split up in several directories, so for each directory I get back a DLL. Is it possible to create a DLL from several other DLL's ?</p> <p><strong>EDIT:</strong> I'm using C++ with Windows CE Platform Builder 6.0 ( it's not managed )</p>
<p>There is no tool that will do this automatically for native code DLLs. You would have create a new DLL and add the existing source code to that project. However, doing this is likely to require changes to the source code.</p>
<p>You can't create one DLL from multiple DLLs. Any such tool would be awkward since each DLL could have it's own DllMain.</p> <p>You CAN create a DLL from multiple static libraries though. It shouldn't be too hard to reconfigure your setup that way.</p>
31,501
<p>I have an ActiveRecord model that I would like to convert to xml, but I do not want all the properties rendered in xml. Is there a parameter I can pass into the render method to keep a property from being rendered in xml? </p> <p>Below is an example of what I am talking about.</p> <pre><code>def show @person = P...
<p>You can pass an array of model attribute names to the <code>:only</code> and <code>:except</code> options, so for your example it would be:</p> <pre><code>def show @person = Person.find(params[:id]) respond_to do |format| format.xml { render :text =&gt; @person.to_xml, :except =&gt; [:phone] } end end </c...
<p>The except is good, but you have to remember to put it everywhere. If you're putting this in a controller, every method needs to have an except clause. I overwrite the serializable_hash method in my models to exclude what I don't want to show up. This has the benefits of not having t put it every place you're goi...
27,422
<p>I'm developing a piece in VB.NET. Inside my primary form, I'm creating a new form to use as a dialog. I was wondering if there was a way to, upon the close of the new dialog, save it's size settings for each user (probably in a file on their machine, through XML or something?)</p>
<p>you can save it to the settings file, and update it on the 'onclosing' event.</p> <p>to make a setting goto Project Properties ->settings -> then make a setting like 'dialogsize' of type system.drawing.size.</p> <p>then do this in your dialog form:</p> <pre><code>Public Sub New() InitializeComponent() End Sub...
<p>You can also do this using the UI provided by the VB.NET IDE itself. In the properties pane for a form, look under the item called "(Application Settings)" and then under "Property Binding." You can bind just about every property of the form (including size and location) to a settings value for that application. </p...
27,915
<p>I want to make a schedule for many pastors. The conditions are:</p> <ol> <li>Every month, each pastor must must go to another church, </li> <li>The pastor must not go to same church where he came</li> <li>In 1 year he must go to 12 different churches</li> <li>There is 13 churches and 13 pastors and every church acc...
<p>Your conditions don't require that the next church for a given pastor be randomly selected. Couldn't you just iterate through the church list?</p> <p>That is, assign each pastor a number, 0-12. Assign each church a number, 0-12. The first month:</p> <blockquote> <p>Month 0:<br> pastor-0 --> church-0<br> past...
<p>Given that you have the same number of pastors and churches, here's a really simple algorithm:</p> <ol> <li><p>Number each church from 0 to 12</p></li> <li><p>Construct an array with the elements 0 to 12 in it.</p></li> <li><p>Perform a Knuth Shuffle (see below) on the array, producing a randomly shuffled list of c...
42,839
<p>I'm implementing a search algorithm (let's call it MyAlg) in a python package. Since the algorithm is super-duper complicated, the package has to contain an auxiliary class for algorithm options. Currently I'm developing the entire package by myself (and I'm not a programmer), however I expect 1-2 programmers to joi...
<p>I suggest you read <a href="http://www.python.org/dev/peps/pep-0008/" rel="noreferrer">PEP8</a> (styleguide for Python code).</p>
<p>Just naming it <code>Options</code> should be fine. The Python standard library generally takes the philosophy that namespaces make it easy and manageable for different packages to have identically named things. For example, <code>open</code> is both a builtin and a function in the <code>os</code> module, several ...
20,292
<p>and to spice things a bit , what is the best approach for globalization in Asp.net Mvc App </p>
<p><strong>Globalization</strong> is about producing a map from strings or identifiers to translations in other languages, while <strong>Localization</strong> is about using that map to find the correct translation. Globalization happens during development, localization happens at runtime.</p> <p>I'm not very experie...
<blockquote> <p>The <strong>System.Globalization</strong> namespace contains classes that define culture-related information, including the language, the country/region, the calendars in use, the format patterns for dates, currency, and numbers, and the sort order for strings.</p> </blockquote> <p>As for...
35,118
<p>I'm running into an unusual problem in my unit tests. The class I'm testing creates a dependency property dynamically at runtime and the type of that dependency property can vary depending on the circumstances. While writing my unit tests, I need to create the dependency property with different types and that leads ...
<p>I had similar issue just yesterday when trying to test my own DependencyProperty creating class. I came across this question, and noticed there was no real solution to unregister dependency properties. So I did some digging using <a href="http://www.red-gate.com/products/reflector/" rel="noreferrer">Red Gate .NET Re...
<p>If we register name for a Label like this :</p> <pre><code>Label myLabel = new Label(); this.RegisterName(myLabel.Name, myLabel); </code></pre> <p>We can easily unregister the name by using :</p> <pre><code>this.UnregisterName(myLabel.Name); </code></pre>
17,671
<p>There is a need from a customer to log every data change to a logging table with the actual user who made the modification. The application is using one SQL user to access the database, but we need to log the "real" user id.</p> <p>We can do this in t-sql by writing triggers for every table insert and update, and u...
<p>How about handling Context.<a href="http://msdn.microsoft.com/en-us/library/cc716714.aspx" rel="noreferrer">SavingChanges</a>?</p>
<p>I had somewhat similar scenario, which I resolved through following steps:</p> <ol> <li><p>First create a generic repository for all CRUD operations like following, which is always a good approach. public class GenericRepository : IGenericRepository where T : class</p></li> <li><p>Now write your actions like "publi...
37,802
<p>I'm slowly moving all of my <code>LAMP websites</code> from <code>mysql_</code> functions to <code>PDO</code> functions and I've hit my first brick wall. I don't know how to loop through results with a parameter. I am fine with the following:</p> <pre><code>foreach ($database-&gt;query("SELECT * FROM widgets") as...
<p>Here is an example for using PDO to connect to a DB, to tell it to throw Exceptions instead of php errors (will help with your debugging), and using parameterised statements instead of substituting dynamic values into the query yourself (highly recommended):</p> <pre><code>// connect to PDO $pdo = new PDO(&quot;mysq...
<p>If you like the foreach syntax, you can use the following class:</p> <pre><code>// Wrap a PDOStatement to iterate through all result rows. Uses a // local cache to allow rewinding. class PDOStatementIterator implements Iterator { public $stmt, $cache, $next; public function __const...
19,341
<p>I want my controller to return the right HTTP response code when the user lacks permission to view a particular page.</p>
<p>Create an Exception annotated with <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ResponseStatus.html">@ResponseStatus</a> e.g. like this:</p> <pre class="lang-java prettyprint-override"><code>@ResponseStatus(HttpStatus.FORBIDDEN) public class ForbiddenExcepti...
<p>Use this: <code>response.setStatus(403)</code>.</p>
6,747
<p>BITS, the Windows background intelligent transfer service.</p> <p>Looks like there are a few C# wrappers around that manage the interop to BITS, does anybody have any opinions on the best one?</p>
<p>I found problems with using the Managed_BITS codeproject article and I found an even better wrapper:</p> <p><a href="http://www.codeplex.com/sharpbits" rel="nofollow noreferrer">http://www.codeplex.com/sharpbits</a><br> <a href="http://nuget.org/packages/SharpBITS" rel="nofollow noreferrer">http://nuget.org/package...
<p>Check out the following:</p> <ol> <li><p><a href="http://www.codeproject.com/KB/cs/Managed_BITS.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/Managed_BITS.aspx</a></p></li> <li><p><a href="http://www.simple-talk.com/dotnet/.net-tools/using-bits-to-upload-files-with-.net/" rel="nofollow noreferrer...
13,010
<p>How do you get the name and/or description of an <a href="http://msdn.microsoft.com/en-us/library/ms680657(VS.85).aspx" rel="noreferrer">SEH</a> exception <strong>without</strong> having to hard-code the strings into your application?</p> <p>I tried to use <code>FormatMessage()</code>, but it truncates the message ...
<p>Structured exception codes are defined through NTSTATUS numbers. Although someone from MS <a href="https://support.microsoft.com/en-us/kb/259693" rel="nofollow noreferrer">suggests</a> using <a href="https://msdn.microsoft.com/en-us/library/ms679351(v=vs.85).aspx" rel="nofollow noreferrer">FormatMessage()</a> to con...
<p>Does this apply?</p> <p><a href="http://www.winehq.org/pipermail/wine-devel/2001-May/000801.html" rel="nofollow noreferrer">http://www.winehq.org/pipermail/wine-devel/2001-May/000801.html</a></p>
41,669
<p>In eclipse developing a java app, there are several class files that are generated by a custom ant script. This happens automatically, and it is set up as an export/publish dependency for /WEB-INF/classes. With publishing it happens alright, however on exporting to .WAR these files just got missing. Is there a way...
<p>I'd suggest generating your war file using Ant.</p> <p>I like my deliverables to be easy to generate using a simple toolchain, i.e. not need to fire up Eclipse to generate them; this way things are easier to automate and document.</p> <p>six years after edit: I was an Ant man when I wrote this- today I'd probably ...
<p>Maybe you can try to add an extra builder. Go to project properties, and then "builders". You can add your own commands which will be run after the eclipse building process runs.</p> <p>It's not an ideal solution, but maybe it works.</p>
27,864
<p>I've recently installed the MVC CTP5 and VS is now crashing on me when I try to open an aspx, I get the following error in event viewer:</p> <pre><code>.NET Runtime version 2.0.50727.3053 - Fatal Execution Engine Error (7A035E00) (80131506) </code></pre> <p>I was able to find <a href="http://forums.asp.net/t/1313452...
<p>I had a problem with Power Commands and Preview 5. If you have Power Commands installed, try updating or uninstalling it to fix the issue.</p>
<p>Have same problem, on vista x64 and vs2008 sp1. Have to do probably something with cleaning bin folder and system.web.routing/abstraction, because it crashes even on webforms project with (mvc) routing in it. When I delete all files from bin, and add references again, it works fine.<br> Really annoying bug in vs2008...
16,240
<p>Am I correct to say the difference between a signed and unsigned integer is:</p> <ol> <li>Unsigned can hold a larger positive value and no negative value.</li> <li>Unsigned uses the leading bit as a part of the value, while the signed version uses the left-most-bit to identify if the number is positive or negative.<...
<blockquote> <p>Unsigned can hold a larger positive value and no negative value.</p> </blockquote> <p>Yes.</p> <blockquote> <p>Unsigned uses the leading bit as a part of the value, while the signed version uses the left-most-bit to identify if the number is positive or negative.</p> </blockquote> <p>There are different...
<p>The only <em>guaranteed</em> difference between a signed and an unsigned value in C is that the signed value can be negative, 0 or positive, while an unsigned can only be 0 or positive. The problem is that C doesn't define the format of types (so you don't <em>know</em> that your integers are in two's complement). S...
30,793
<p>I've been playing with the .NET built in localization features and they seem to all rely on putting data in resx files. </p> <p>But most systems can't rely on this because they are database driven. So how do you solve this issue? Is there a built in .NET way, or do you create a translations table in SQL and do it a...
<p>In my opinion, localizing dynamic content (e.g., your FAQ) should be done by you in your database. Depending on how your questions are stored, I would probably create a "locale" column and use that when selecting the FAQ questions from the database. I'm not sure if this would scale very well when you started locali...
<p>Currently, translation is not something that can be done automatically. The best way is to get a person to translate and use Nick's methods to show the proper language.</p>
19,390
<p>I want to be able to get a list of all differences between two JavaScript object graphs, with the property names and values where the deltas occur. </p> <p>For what it is worth, these objects are usually retrieved from the server as JSON and typically are no more than a handful of layers deep (i.e. it may be an arr...
<p>After reviewing the existing answers, I noticed that the <a href="https://github.com/flitbit/diff">https://github.com/flitbit/diff</a> library was not yet listed as a solution.</p> <p>From my research, this library seems to be the best in terms of active development, contributions and forks for solving the challeng...
<p>you can do'it with filter and indexOf</p> <pre><code>var first = [ 1, 2, 3, 4, 5 ]; var second = [ 4, 5, 6 ]; var difference = first.filter(x =&gt; second.indexOf(x) === -1); console.log(difference); </code></pre>
33,123
<p>I'm having an issue with a Flash/Flex erroring in Firefox but not IE. I need to see the error that the Flash/Flex app is getting from the ASP.NET app. Is there any way to debug the response that Flash/Flex is getting?</p>
<p>Install the Debug version of the FlashPlayer for Firefox. Maybe this is already enough and an Error might pop up.</p> <p>If not use the FlexBuilder and debug the Flex application. If you don't have a license for the FlexBuilder you may also use the Evaluation licence.</p>
<p>Depending on how you are making calls to your ASP.net app - you could use something like <a href="http://livehttpheaders.mozdev.org/" rel="nofollow noreferrer">LiveHTTPHeaders</a> to see the url that your flex app is call and see what response is being sent back from the server (i.e. 200, 404, 503, etc...)</p> <p>A...
18,537
<p>Know of an OCAML/CAML IDE? Especially one that runs on Linux?</p>
<p>Emacs in <a href="http://www.cs.jhu.edu/~scott/pl/caml/emacs.html" rel="noreferrer">Caml mode</a>, or <a href="https://who.rocq.inria.fr/Albert.Cohen/tuareg/index.html.en" rel="noreferrer">Tuareg mode</a>, or <a href="http://www.typerex.org/" rel="noreferrer">TypeRex mode</a>. TypeRex adds auto-completion to Taureg...
<p>You can try to edit, compile and run simple Ocaml codes even online with <a href="http://ideone.com/YNQhz" rel="nofollow">ideone</a>. There are also apps for mobile devices, which allows you to program/experiment with your smartphone.</p>
14,472
<p>How do I get today's date in C# in mm/dd/yyyy format?</p> <p>I need to set a string variable to today's date (preferably without the year), but there's got to be a better way than building it month-/-day one piece at a time.</p> <p>BTW: I'm in the US so M/dd would be correct, e.g. September 11th is 9/11.</p> <p><...
<pre><code>DateTime.Now.ToString("M/d/yyyy"); </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx</a></p>
<p>Or without the year:</p> <pre><code>DateTime.Now.ToString("M/dd") </code></pre>
5,275
<p>Does anyone know a good online resource for example of R code?</p> <p>The programs do not have to be written for illustrative purposes, I am really just looking for some places where a bunch of R code has been written to give me a sense of the syntax and capabilities of the language?</p> <p><strong>Edit:</strong> ...
<p>I just found this question and thought I would add a few resources to it. I really like the Quick-R site: </p> <p><a href="http://www.statmethods.net/" rel="noreferrer">http://www.statmethods.net/</a></p> <p>Muenchen has written a book about using R if you come from SAS or SPSS. Originally it was an 80 page online...
<p>Steve McIntyre at <a href="http://www.climateaudit.org/" rel="nofollow noreferrer">http://www.climateaudit.org/</a> is a big fan of R and often posts working code.</p> <p>There is a <a href="http://www.climateaudit.org/?cat=57" rel="nofollow noreferrer">scripts category</a>, and the <a href="http://www.climateaudit...
15,471
<p>I'm getting an error message when I try to build my project in eclipse:</p> <p><code>The type weblogic.utils.expressions.ExpressionMap cannot be resolved. It is indirectly referenced from required .class files</code></p> <p>I've looked online for a solution and cannot find one (except for those sites that make y...
<p>How are you adding your Weblogic classes to the classpath in Eclipse? Are you using WTP, and a server runtime? If so, is your server runtime associated with your project?</p> <p>If you right click on your project and choose build <code>path-&gt;configure</code> build path and then choose the libraries tab. You s...
<p>I was getting this error:</p> <blockquote> <p>The type com.ibm.portal.state.exceptions.StateException cannot be resolved. It is indirectly referenced from required .class files</p> </blockquote> <p>Doing the following fixed it for me:</p> <p>Properties -> Java build path -> Libraries -> Server Library[wps.base....
14,133
<p>When I'm joining three or more tables together by a common column, I'd write my query like this:</p> <pre><code>SELECT * FROM a, b, c WHERE a.id = b.id AND b.id = c.id </code></pre> <p>a colleague recently asked my why I didn't do explicit <em>Join Transitive Closure</em> in my queries like this:</p> <pre><...
<p>You don't need to do this in todays database engines, but there was a time when things like that would give the query optimizer more hints as to possible index paths and thus to speedier results.</p> <p>These days that entire syntax is going out anyway.</p>
<p>That syntax has its uses though ... there are times when you find you need to join two tables on more than one field</p>
3,221
<p>I am having problems when connecting to my SQL server 2008 and think it might be a problem related to MDAC. Is there a download to re-install these?</p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=78cac895-efc2-4f8e-a9e0-3a1afbd5922e&amp;DisplayLang=en" rel="nofollow noreferrer">MDAC 2.8 SP1</a></p> <p>Remember, MDAC is client software that should not be installed on the server.</p> <p>Your problem is more likely a protocol or firewall error....
<p>Use the MDAC checker first, it will tell you if there's a problem with your MDAC:</p> <p><a href="http://support.microsoft.com/kb/307255" rel="nofollow noreferrer">http://support.microsoft.com/kb/307255</a></p>
38,806
<p>So in a .NET app , i got about 2 million items that i need to hold them in memory for processing , 1 by 1, would holding these items in a Stack collection , is better than holding them in a List collection, assuming that the memory used by the stack object will be keep minimizing every time an item is poped out of t...
<p>No difference. The "Pop" method of a Stack never reduces the size of the internal array. The "Push" method doubles the size when the limit is hit.</p> <p>I used <a href="http://en.wikipedia.org/wiki/.NET_Reflector" rel="nofollow noreferrer">.NET Reflector</a> to discover this.</p>
<p>Popping an object out of a stack will remove the reference to the object from the stack. Then, it's up to the garbage collector to decide when to free up the memory. However, depending on the object, you could call .Dispose() after each loop iteration in order to release any <em>unamanged</em> resources the object...
29,808
<p>We're using Mercurial where I work and I want to have a setup similar to how I used SVN:</p> <ul> <li>Trunk</li> <li>Tags <ul> <li>Production</li> </ul></li> <li>Branches</li> </ul> <p>Since Mercurial supports branches natively, I know how to create a named branch, but I can't find any documentation on how to rep...
<p>As the previous poster mentioned, the transplant extension can be used for cherry-picking individual changes from one branch to another. If, however, you always want to pull <em>all</em> the latest changes, the <code>hg merge</code> command will get you there.</p> <p>The simplest case is when you're using clones t...
<p>Something like <a href="http://www.selenic.com/mercurial/wiki/index.cgi/TransplantExtension" rel="nofollow noreferrer"><code>hg transplant</code></a>? That's what we use on our dev and prod branches.</p>
7,294
<p>I have always thought that the .equals() method in java should be overridden to be made specific to the class you have created. In other words to look for equivalence of two different instances rather than two references to the same instance. However I have encountered other programmers who seem to think that the de...
<p>Overriding the equals method is necessary if you want to test equivalence in standard library classes (for example, ensuring a java.util.Set contains unique elements or using objects as keys in java.util.Map objects).</p> <p>Note, if you override equals, ensure you honour the API contract as described in the docume...
<p>The Equals method is intended to compare references. So it should not be overriden to change its behaviour.</p> <p>You should create a new method to test for equivalence in different instances if you need to (or use the CompareTo method in some .NET classes)</p>
3,728
<p>Here at work, we are working on a newsletter system that our clients can use. As an intern one of my jobs is to help with the smaller pieces of the puzzle. In this case what I need to do is scan the logs of the email server for bounced messages and add the emails and the reason the email bounced to a "bad email data...
<p>Something like this would work:</p> <pre><code>while(&lt;STDIN&gt;) { my $line = $_; chomp($line); my ($email,$reason) = split(/\|/, $line); print "Email: $email\n"; print "Reason: $reason"; my $sth = $dbh-&gt;prepare(qq{INSERT INTO bademails VALUES(?, ?)}); $sth-&gt;execute($email, $reason); ...
<pre><code>my(@list) = split /\|/, $line; </code></pre> <p>This will generate more than two entries in @list if you have extra pipe symbols in the tail of the line. To avoid that, use:</p> <pre><code>$line =~ m/^([^|]+)\|(.*)$/; my(@list) = ($1, $2); </code></pre> <p>The dollar in the regex is arguably superfluous,...
19,927
<p>I have been wondering what are best practices when it comes to referencing 3rd party assemblies. A while ago I asked a question "<a href="https://stackoverflow.com/questions/268214/dependencies-and-references-what-exactly-should-i-reference">Dependencies and references: what exactly should I reference</a>" and recei...
<p>If i have to deal with libraries that aren't registered in the GAC, I use the following method:</p> <ul> <li>Make a folder "Libs" with all third party libraries and their dependencies in it</li> <li>Reference the ones I need</li> <li>Create a post-build action that copies all the files in the "Libs" folder to the "...
<p>You can also use <a href="http://www.NDepend.com" rel="nofollow noreferrer">NDepend</a> to know and control exactly what you use from tiers library. I wrote an article about this <a href="http://codebetter.com/blogs/patricksmacchia/archive/2008/10/20/controlling-the-usage-of-libraries.aspx" rel="nofollow noreferrer"...
39,203
<p>I'd like to make a simple html form where a person can upvote or downvote an item. However I don't like the default look of a <code>&lt;input type="submit"&gt;</code> . What other options do I have to send a POST request than a bulky, default button?</p>
<p>You can also make pretty buttons with just css, here's a nice article:</p> <p><a href="http://particletree.com/features/rediscovering-the-button-element/" rel="noreferrer">http://particletree.com/features/rediscovering-the-button-element/</a></p>
<p>Like above mentioned techniques, I would recommend either image buttons or designing boxes with to create a nice and simple css-button.</p> <p>Simplicity can be very well used.</p> <p>CSS power: <a href="http://www.zengarden.com" rel="nofollow noreferrer">http://www.zengarden.com</a></p>
47,808
<p>I know it is not strictly a programmer question, on the other hand, I would really like to be able to do a simple <code>svn up</code> on the production servers, which would save us a lot of hassle.</p> <p>Or production servers are within a corporate network, and access is only allowed through a gateway server. From...
<p>Okay, not wanting this to remain unsolved, I posted the following on the usenet in alt.os.citrix:</p> <blockquote> <p>G'day everyone</p> <p>Someone asked me this question. I haven't a clue. Any ideas?</p> <p>&quot;the connection I have is PC -&gt; Citrix Access Gateway -&gt; actual Server. My question is, if it is p...
<p><a href="http://www.boran.com/security/sp/ssh-part1.html#Doing%20even%20more%20with%20SSH" rel="nofollow noreferrer">Citrix over SSH</a>, <a href="http://support.citrix.com/article/CTX109009" rel="nofollow noreferrer">How to Create a Key Pair for SSH Authentication Using PuTTYgen</a>, <a href="http://www.codeplex.co...
28,341
<p>Has anybody here succeeded in running Eclipse under <a href="http://valgrind.org/" rel="noreferrer">Valgrind</a>? I'm battling a particularly hairy crash involving JNI code, and was hoping that Valgrind perhaps could (again) prove its excellence, but when I run Eclipse under Valgrind, the JVM terminates with an erro...
<p>Does it work if you <A HREF="http://valgrind.org/docs/manual/faq.html#faq.java" rel="nofollow noreferrer">run valgrind with --smc-check=all</A>?</p> <p>Also -- valgrind increases a program's memory requirements pretty dramatically. With something as large as Eclipse, there's plenty of room for trouble; hopefully yo...
<p>Does it work if you <A HREF="http://valgrind.org/docs/manual/faq.html#faq.java" rel="nofollow noreferrer">run valgrind with --smc-check=all</A>?</p> <p>Also -- valgrind increases a program's memory requirements pretty dramatically. With something as large as Eclipse, there's plenty of room for trouble; hopefully yo...
22,951
<p>Question so easy that fitted in the title :) Eclipse (pydev): Is it possible to assign a shortcut to send selection to the python console?</p>
<p>One browser accesses your server via 127.0.0.1, and another via your external IP.</p> <p>Make sure virtualhost works with all network interfaces.</p>
<p>Perhaps your browsers have different locals set , only guessing as I have not used IIS7</p>
41,891
<p>Is it possible to run a ruby application as a Windows Service? I see that there is a related question which discusses running a <a href="https://stackoverflow.com/questions/25530/best-method-to-run-a-java-application-as-a-nix-daemon-or-windows-service">Java Application as a Windows Service</a>, how can you do this ...
<p>Check out the following library: <a href="http://win32utils.rubyforge.org/" rel="nofollow noreferrer">Win32Utils</a>. You can create a simple service that you can start/stop/restart at your leisure. I'm currently using it to manage a Mongrel instance for a Windows hosted Rails app and it works flawlessly.</p>
<p>You can write (or download) a wrapper service. The wrapper can call the ruby.exe to execute your program. Same trick works for Java, VB, etc.</p>
19,763
<p>Is it possible to create a list that can be access by either an index or a key?</p> <p><em>I am looking for a Collection type that already exists but has this facility, I want to avoid redefining the indexers</em> </p>
<p>System.Collections.Specialized.NameValueCollection can do this, but it can only store strings as values.</p> <pre><code> System.Collections.Specialized.NameValueCollection k = new System.Collections.Specialized.NameValueCollection(); k.Add("B", "Brown"); k.Add("G", "Green"); Console.WriteL...
<p>You can add an indexer by adding the following property to your collection:</p> <pre><code>public object this[int index] { get { /* return the specified index here */ } set { /* set the specified index to value here */ } } </code></pre> <p>This can be quickly added in Visual Studio by typing <em>indexer</e...
38,175
<p>I create a TextArea in actionscript:</p> <pre><code>var textArea:TextArea = new TextArea(); </code></pre> <p>I want it to have a black background. I've tried</p> <pre><code>textArea.setStyle("backgroundColor", 0x000000); </code></pre> <p>and I've tried</p> <pre><code>textArea.opaqueBackground = 0x000000; </cod...
<p>TextArea is a UI component built from TextField and other Flash built-in classes and UIComponents. As with most of the Adobe UI components, nothing is as it seems when setting properties. To set the color of the area behind the text in the TextArea, you need to actually set the opaque background of its internal Text...
<p>Here is what worked for me, which I discovered on my own after reviewing updated AC3 documentation</p> <p><strong>TextArea - Background Color, 2011 AC3</strong></p> <p>Took me forever to realize that in AC3, as of now (2011), they officially tell you to use spark TextArea instead of mx </p> <p>(<code>s:TextArea</...
21,100
<p>I'm using an image component that has a FromBinary method. Wondering how do I convert my input stream into a byte array</p> <pre><code>HttpPostedFile file = context.Request.Files[0]; byte[] buffer = new byte[file.ContentLength]; file.InputStream.Read(buffer, 0, file.ContentLength); ImageElement image = ImageElemen...
<p>Use a BinaryReader object to return a byte array from the stream like:</p> <pre><code>byte[] fileData = null; using (var binaryReader = new BinaryReader(Request.Files[0].InputStream)) { fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength); } </code></pre>
<p>in your question, both buffer and byteArray seem to be byte[]. So:</p> <pre><code>ImageElement image = ImageElement.FromBinary(buffer); </code></pre>
46,960
<p>What is the best way to copy a list? I know the following ways, which one is better? Or is there another way?</p> <pre><code>lst = ['one', 2, 3] lst1 = list(lst) lst2 = lst[:] import copy lst3 = copy.copy(lst) </code></pre>
<p>If you want a shallow copy (elements aren't copied) use:</p> <pre><code>lst2=lst1[:] </code></pre> <p>If you want to make a deep copy then use the copy module:</p> <pre><code>import copy lst2=copy.deepcopy(lst1) </code></pre>
<p>You can also do this:</p> <pre><code>import copy list2 = copy.copy(list1) </code></pre> <p>This should do the same thing as Mark Roddy's shallow copy.</p>
22,325
<p>Here is the scenario. There is content loaded in iframe from other site. I click to some link inside the iframe.</p> <p>Is it possible to catch somehow outside the iframe what is that link? </p> <p>UPDATE Since I recieved question if my intentions are pure, I would explain more on the use case. May be I started in...
<p>If the pages are not located on the same domain then there is no way to do this. Your scripts cannot see across domains.</p>
<p>If your iframe is in the same domain, it's a simple matter of adding an event listener to the onclick event of your links.</p> <p>Example: </p> <pre><code>&lt;a href="javascript:void(0)" onclick="top.harvestLink(this)" title="Item=foo" alt=""&gt;Foo&lt;/a&gt; </code></pre> <p>Then in the page hosting the iframe y...
33,133
<p>One of our unit tests is to populate properties within our business objects with random data.</p> <p>These properties are of different intrinsic types and therefore we would like to use the power of generics to return data of the type you pass in. Something along the lines of:</p> <pre><code>public static T GetDat...
<p>You could keep the "easy to use" GetData interface you've got there, but internally have a Dictionary&lt;Type, object> where each value is a Func&lt;T> for the relevant type. GetData would then have an implementation such as:</p> <pre><code>public static T GetData&lt;T&gt;() { object factory; if (!factories...
<p>I would use <a href="http://autopoco.codeplex.com/" rel="nofollow">AutoPoco</a> to generate the needed data for testing.</p>
21,430
<p>I shudder to ask, but my client might offer no other SQL (or SQL-like) solution. I know Access has some SQL hooks; are they enough for basic ActiveRecord?</p> <p><em>Later:</em></p> <p>I appreciate all the suggestions to use other databases, but trust me: I've tried convincing them. There is an "approved" list, ...
<p>It's a long shot but there's an <a href="http://odbc-rails.rubyforge.org/" rel="nofollow noreferrer">ODBC adapter for ActiveRecord</a> that might work.</p>
<p>You should really talk them into allowing SQLite. It is super-simple to setup, and operates like Access would (as a file sitting next to the app on the same server).</p>
4,039
<p>What version control systems have you used with MS Excel (2003/2007)? What would you recommend and Why? What limitations have you found with your top rated version control system?</p> <p>To put this in perspective, here are a couple of use cases:</p> <ol> <li>version control for VBA modules </li> <li>more than one...
<p>I've just setup a spreadsheet that uses Bazaar, with manual checkin/out via TortiseBZR. Given that the topic helped me with the save portion, I wanted to post my solution here.</p> <p><em>The solution for me was to create a spreadsheet that exports all modules on save, and removes and re-imports the modules on open...
<p>It depends on what level of integration you want, I've used Subversion/TortoiseSVN which seems fine for simple usage. I have also added in keywords but there seems to be a risk of file corruption. There's an option in Subversion to make the keyword substitutions fixed length and as far as I understand it will work i...
15,969
<p>I've got a dump of a .Net process that has hung due to a deadlock (the gui thread is no longer responding, and my logs show that some threads have stopped responding). I have taken a snapshot and am now looking through it in windbg, and all threads bar one are waiting for the last one. Looking at that one thread's s...
<p>I'm not absolutely sure but you might be able to use !SyncBlk to look at the sync block objects, if you invoke it without any arguments I think you should see the sync blocks that are owned by a thread.</p> <p>If you have a sync block deadlock, the extension <a href="http://www.stevestechspot.com/SOSEXANewDebugging...
<p>An approach that would provide traceability is to wrap your locks into an IDisposable interface and replace:</p> <p>lock( mylock) { ... }</p> <p>with </p> <p>using( new DisposeableLock() ) { ... }</p> <p>You can log the constructor and Dispose() methods either to the console, or log4net, or some other mechanism....
40,922
<p>Every time I start in deep in a C# project, I end up with lots of events that really just need to pass a single item. I stick with the <code>EventHandler</code>/<code>EventArgs</code> practice, but what I like to do is have something like:</p> <pre><code>public delegate void EventHandler&lt;T&gt;(object src, Event...
<p>Delegate of the following form has been added since .NET Framework 2.0 </p> <pre><code>public delegate void EventHandler&lt;TArgs&gt;(object sender, TArgs args) where TArgs : EventArgs </code></pre> <p>You approach goes a bit further, since you provide out-of-the-box implementation for EventArgs with single data i...
<p>I do believe that the recent versions of .NET have just such an event handler defined in them. That's a big thumbs up as far as I'm concerned.</p> <p>/EDIT</p> <p>Didn't get the distinction there originally. As long as you are passing back a class that inherits from EventArgs, which you are, I don't see a proble...
15,742
<p>I came across this class while reading a C# book and have some questions.</p> <ul> <li>Why is this added into System.Linq namespace and not into usuall Collections namespace?</li> <li>What the intention behind this class is</li> <li>Why this class is not intended for direct instantiation? This is available through ...
<p>Purpose of the class: a dictionary where a key can map to multiple values. Think of it as being for grouping rather than one-to-one mapping.</p> <p>Only through ToLookup decision: Pass. Again, seems like a bad call to me. On the other hand, it means that the result is immutable to the outside world, which is quite ...
<p>As an aside, note that <a href="http://www.pobox.com/~skeet/csharp/miscutil/" rel="noreferrer">MiscUtil</a> also includes a <code>MiscUtil.Linq.EditableLookup&lt;,&gt;</code> class, that is similar; it implements the regular <code>ILookup&lt;,&gt;</code> interface, but is fully mutable - so you can create it and add...
23,994
<p>I would like to hear from you guys on how do you decide when you should be using concrete parameterized type vs. bounded parameterized type when designing API, esp. (that I care most) of defining a class/interface.</p> <p>For instance,</p> <pre><code>public interface Event&lt;S&gt;{ void setSource(S s); } publi...
<p>I think your commented-out <code>UserEvent&lt;S extends User&gt;</code> approach is the right one -- then you can declare <code>AdminUserEvent extends UserEvent&lt;AdminUser&gt;</code>. Is that all you need?</p>
<p>If I understand right this does not have much to do with generics in itself, but rather to do with parallel hierarchy. <code>B extends A</code>, <code>BHandler extends AHandler</code> and <code>AHandler.handle(A)</code> but <code>BHandler.handle(B)</code>.</p> <p>Yes, I believe this can be made typesafe with the us...
39,691
<p>Would it be posible to design something that is as flexible and that can be printed with PLA that would work as a cloth? I did some research and found that there was a company named Electroloom but that didn't make it. I'm not looking for anything fine, just something that would work for wiping</p>
<p>Maybe you would be better off with TPU or some other type of flexible material...</p> <p>I have been able to print PLA and have it flex quite a bit, but that was an ~0.2mm single layer print, I guess maybe up to 0.3-0.4mm should still be a little bit flexible, but not much. Also since you want it to wipe things, ma...
<p>You can not 3D print that because there is no nozzle or method for producing filaments of the required size. A few microns at least. You might be able to spin molten pla like cotton candy and it might absorb; but I doubt it.</p> <p><a href="https://phys.org/news/2010-05-cotton-candy-machine-tiny-nanofibers.html" re...
1,626
<p>How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?</p>
<p>Several connectors are configured, and each connector has an optional "address" attribute where you can set the IP address.</p> <ol> <li>Edit <code>tomcat/conf/server.xml</code>.</li> <li>Specify a bind address for that connector: <pre> &lt;Connector port="8080" protocol="HTTP/1.1" address="127.0.0.1...
<p>It may be worth mentioning that running tomcat as a non root user (which you should be doing) will prevent you from using a port below 1024 on *nix. If you want to use TC as a standalone server -- as its performance no longer requires it to be fronted by Apache or the like -- you'll want to bind to port 80 along wit...
3,916
<p>What is the best way to store string data across postback. I need to store an ID and name for multiple entities. I was thinking of using a datatable in viewstate, but would that make viewstate grow too large? I can't use a database yet because I'll be inserting a record that those other records need to be related...
<p>You actually have a lot of options - the one you choose will entirely depend on the requirements of your own application.</p> <ol> <li><p>ViewState - you can add the data to the page's viewstate. The advantages of this is that the data <em>will</em> live only for the lifetime of the user being on the page and posti...
<p>you could just store them to a cookie, this would allow you to access them from Javascript too. Alternatively you could store a simple string array to the view state. A lot depends on what and how much information you wish to store. </p>
12,069
<p>I'm wondering if there are any architectural frameworks out there to create desktop or standalone applications, in Java or C# for instance. It seems that there are tons of them available for web applications but I can't find many good resources on frameworks or architectural best-practices for desktop development.</...
<p>While not directly related to desktop applications if you are looking for decent source code for well written projects I asked a similar question: </p> <p><a href="https://stackoverflow.com/questions/143088/open-source-c-projects-that-have-extremely-high-code-quality-to-learn-from">Open source C# projects that hav...
<p>We develop in .NET technologies here.</p> <p>Our friends here working on client applications develop their software to the Model View Presenter design pattern that is often associated with Web Development. For them they find it works very well, I believe it may be worth checking out. </p> <p>The Smart Client Fac...
18,123
<p>Has anyone been successful in getting the grails plugin for eclipse to work? How about grails plugin with netbeans?</p>
<p>Unfortunately, there hasn't been much progress on the Eclipse plugin for Grails, we have started using <a href="http://www.jetbrains.com/idea/" rel="nofollow noreferrer">IntelliJ IDEA</a> for Grails development, the <a href="http://www.jetbrains.com/idea/features/groovy_grails.html" rel="nofollow noreferrer">JetGroo...
<p>I haven't had any problems getting the Eclipse grails plugin "to work" insofar as it's installed and providing all the features advertised. The problem is that this set of features is minimal, and light years behind IntelliJ. I understand that switching from a free IDE to a commercial IDE isn't at all possible, but ...
14,767
<p>Put differently:</p> <p>Is there a good reason to choose a loosely-typed collection over a type-safe one (HashTable vs. Dictionary)? Are they still there only for compatibility?</p> <p>As far as I understand, generic collections not only are type-safe, but their performance is better.</p> <hr> <p>Here's a compre...
<p>The non-generic collections are so obsolete that they've been removed from the CoreCLR used in Silverlight and Live Mesh.</p>
<p>Yes, as far as I understand they are only there for compatibility with existing products. You should always use the type safe version (i.e. use System.Collections.Generic over System.Collections).</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms379564.aspx" rel="nofollow noreferrer">http://msdn.microsoft....
8,030
<p>I have read several documentations about building custom ErrorHandler (by inheriting from IErrorHandler). Unfortunately, I have several doubts about how doing it.</p> <p>The problem is that I don't exactly understand the meaning of the two methods of IErorrHandler (i.e. ProvideFault and HandleError). For me, the Ha...
<p>Based on the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx" rel="nofollow noreferrer">MSDN documentation</a>, the boolean is to return a success or failure of performing the needed behavior. </p> <p>You are correct in that the ProviderFault method is where you c...
<p>Based on the <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx" rel="nofollow noreferrer">MSDN documentation</a>, the boolean is to return a success or failure of performing the needed behavior. </p> <p>You are correct in that the ProviderFault method is where you c...
33,289
<p>As the title says: What is the difference between a non-secure random number generator and a secure random number generator?</p>
<p>No computationally feasible algorithm should:</p> <ul> <li>recover the seed, or</li> <li>predict the "next bit"</li> </ul> <p>for a secure random number generator.</p> <p>Example: a linear feedback shift register produces lots of random numbers out there, but given enough output, the seed can be discovered and al...
<p>It probably depends on the context, but when you are comparing them like this, I'd say "random number" is a <a href="http://en.wikipedia.org/wiki/Pseudorandomness" rel="nofollow noreferrer">pseduo random number</a> and a "secure random number" is truly random. The former gives you a number based on a seed and an alg...
12,680
<p>I would like to build and deploy a database application for Windows based systems, but need to live within the following constraints:</p> <ol><li>Cannot run as a server (i.e., have open ports);</li> <li>Must be able to share database files with other instances of the program (running on other machines);</li> <li>Mu...
<p>I'd go with SQLite. There are SQLite bindings for everything, and it's very widely used as a embedded database for a large number of applications. </p>
<p>If you've got VStudio sitting around, how about SQL Server 3.5 Compact edition? MSSQL running in-proc.</p> <p><a href="http://www.microsoft.com/sql/editions/compact/downloads.mspx" rel="nofollow noreferrer">http://www.microsoft.com/sql/editions/compact/downloads.mspx</a></p>
13,250
<p>I am trying to solve the current problem using GPU capabilities: "given a point cloud P and an oriented plane described by a point and a normal (Pp, Np) return the points in the cloud which lye at a distance equal or less than EPSILON from the plane".</p> <p>Talking with a colleague of mine I converged toward the f...
<p>It's simple: Let n be the normal of the plane and x be the point.</p> <pre><code>n_u = n/norm(n) //this is a normal vector of unit length d = scalarprod(n,x) //this is the distance of the plane to the origin for each point p_i d_i = abs(scalarprod(p_i,n) - d) //this is the distance of the point to...
<p>Ok first as a little disclaimer: I know nothing about 3D programming.</p> <p>Now my purely mathematical idea:</p> <p>Given a plane by a normal N (of unit length) and a distance L of the plane to the center (the point [0/0/0]). The distance of a point X to the plane is given by the scalar product of N and X minus L...
10,282
<p>What is copyright licence type to select in order to make the code free for the public in all possible ways.</p> <p>Is "The MIT License" the best option?</p>
<p>Releasing your code as <a href="http://en.wikipedia.org/wiki/Public_domain" rel="nofollow noreferrer">public domain</a> is the best way to make it free for <em>all</em> possible ways. <a href="http://sqlite.org" rel="nofollow noreferrer">SQLite</a> is a well-known public domain library (they have <a href="http://sql...
<p>Check out some of the summarizes of licenses on line (see this <a href="https://stackoverflow.com/questions/23098/why-the-proliferation-of-open-source-licenses">question</a> for links). Just don't write your own!</p>
34,459
<p>I have come across the following type of code many a times, and I wonder if this is a good practice (from Performance perspective) or not:</p> <pre><code>try { ... // some code } catch (Exception ex) { ... // Do something throw new CustomException(ex); } </code></pre> <p>Basically, what the coder is do...
<p>@Brad Tutterow</p> <p>The exception is not being lost in the first case, it is being passed in to the constructor. I will agree with you on the rest though, the second approach is a very bad idea because of the loss of stack trace. When I worked with .NET, I ran into many cases where other programmers did just th...
<p>The throw in your first example has the overhead of the creation of a new CustomException object.</p> <p>The re-throw in your second example will throw an exception of type Exception.</p> <p>The re-throw in your third example will throw an exception of the same type that was thrown by your "some code".</p> <p>So ...
2,857
<p>How can I project the row number onto the linq query result set.</p> <p>Instead of say:</p> <p>field1, field2, field3</p> <p>field1, field2, field3</p> <p>I would like:</p> <p>1, field1, field2, field3</p> <p>2, field1, field2, field3</p> <p>Here is my attempt at this:</p> <pre><code>public List&lt;ScoreWith...
<p>Well, the easiest way would be to do it at the client side rather than the database side, and use the overload of Select which provides an index as well:</p> <pre><code>public List&lt;ScoreWithRank&gt; GetHighScoresWithRank(string gameId, int count) { Guid guid = new Guid(gameId); using (PPGEntities entitie...
<p>You could also make just a slight adjustment to your original code to get it working. Word of caution, if you databind or access the object again, the Rank will increment each time. In those cases the top answer is better.</p> <pre><code>let Rank = i++ </code></pre> <p>and</p> <pre><code>Rank.ToString() </code>...
47,661
<p>So here's what I'm looking to achieve. I would like to give my users a single google-like textbox where they can type their queries. And I would like them to be able to express semi-natural language such as</p> <pre><code>"view all between 1/1/2008 and 1/2/2008" </code></pre> <p>it's ok if the syntax has to be f...
<p>You are describing a programming language. Granted it's a small language (often called a little language, or Domain Specific Language (DSL)). If you've never heard the term recursive descent parser, you are probably better off following Paul's advice and using drop down boxes of some description.</p> <p>However, ag...
<p>Trying to parse that stuff would be a disaster, and ultimatley very limiting to the user, thus frustrating them more then helping them. I would suggest using pre-defined Query clasues, with some kind of query builder tool that has all the available options in drop down form. You can have different boolean operators ...
45,808
<p>If you were running a news site that created a list of 10 top news stories, and you wanted to make tweaks to your algorithm and see if people liked the new top story mix better, how would you approach this? </p> <p>Simple Click logging in the DB associated with the post entry? </p> <p>A/B testing where you would s...
<p>Thirding <a href="https://github.com/mono/taglib-sharp" rel="noreferrer">TagLib Sharp</a>.</p> <pre><code>TagLib.File f = TagLib.File.Create(path); f.Tag.Album = "New Album Title"; f.Save(); </code></pre>
<p>I wrapped mp3 decoder library and made it available for .net developers. You can find it here:</p> <p><a href="http://sourceforge.net/projects/mpg123net/" rel="nofollow noreferrer">http://sourceforge.net/projects/mpg123net/</a></p> <p>Included are the samples to convert mp3 file to PCM, and read ID3 tags.</p>
9,379
<p>I'm interested in learning C. I have read <a href="http://en.wikipedia.org/wiki/The_C_Programming_Language_(book)" rel="nofollow noreferrer">K &amp; R</a>, and I have even done some simple C extension work in R and Python. What's a worthwhile project idea for doing something more substantial with C? Any good onli...
<p>Have a look at <a href="https://stackoverflow.com/questions/803522/after-kr-what-book-to-use-to-learn-programming-in-plain-c">After K&amp;R what book to use to learn programming in plain C?</a></p>
<p>Find or define a problem in your day-to-day work and force yourself to solve it using C instead of Python. That will force you to learn the language while keeping the problem relevent to what you normally do.</p>
22,332
<p>I have a class:</p> <pre><code>class MyClass: def __init__(self, foo): if foo != 1: raise Error("foo is not equal to 1!") </code></pre> <p>and a unit test that is supposed to make sure the incorrect arg passed to the constructor properly raises an error:</p> <pre><code>def testInsufficientArgs(self): ...
<p>'Error' in this example could be any exception object. I think perhaps you have read a code example that used it as a metasyntatic placeholder to mean, "The Appropriate Exception Class".</p> <p>The baseclass of all exceptions is called 'Exception', and most of its subclasses are descriptive names of the type of err...
<p>I think you're thinking of <a href="http://docs.python.org/lib/module-exceptions.html" rel="nofollow noreferrer">Exception</a>s. Replace the word Error in your description with Exception and you should be good to go :-)</p>
11,392
<p>I'm looking to create a virtual printer that passes data to my .NET application. I want to then create an installer that installs both the printer and the .NET application. It would we really nice to be able to write it all in C#, but I have a feeling that this will require a printer driver to be written is unmanag...
<p>Did exactly what you are asking using the Github project: Microsoft/Windows-driver-samples/print/XPSDrvSmpl</p> <p><a href="https://github.com/Microsoft/Windows-driver-samples/tree/master/print/XPSDrvSmpl" rel="nofollow noreferrer">https://github.com/Microsoft/Windows-driver-samples/tree/master/print/XPSDrvSmpl</a>...
<p>If I remember correctly Microsoft does not support .NET within printer driver development. I have yet to come across a pure .NET printer driver. You will be a very brave man to do so! The website "Printer Driver Resource Toolkit" does not say that the driver has been written in .NET</p>
32,168
<p>After reading the answers to the question <a href="https://stackoverflow.com/questions/60394/calculate-code-metrics" title="Calculate Code Metrics">"Calculate Code Metrics"</a> I installed the tool <a href="http://www.campwoodsw.com/sm20.html" rel="nofollow noreferrer" title="SourceMonitor">SourceMonitor</a> and cal...
<p>SourceMonitor is an awesome tool. </p> <p>"Methods Per Class" is useful to those who wish to ensure their classes follow good OO principles (too many methods indicates that a class could be taking on more than it should). </p> <p>"Average Statements per Method" is useful for a general feel of how big each method ...
<p>As a general rule of thumb, a cyclomatic complexity of 10 or less is where you want to be. A CC from 11 to 20 is about as high as you want to get in most cases: once you get above 20, you're more likely to encounter problems finding and fixing defects, and once you get above 50, you're usually looking at a method th...
16,255
<p>I'm about to start on a large Qt application, which is made up of smaller components (groups of classes that work together). For example, there might be a dialog that is used in the project, but should be developed on its own before being integrated into the project. Instead of working on it in another folder somewh...
<p>Here is what I would do. Let's say I want the following folder hierarchy :</p> <pre><code>/MyWholeApp </code></pre> <p>will contain the files for the whole application.</p> <pre><code>/MyWholeApp/DummyDlg/ </code></pre> <p>will contain the files for the standalone dialogbox which will be eventually part of the w...
<p>For Qt on Windows you can create DLLs for every subproject you want. No problem with using them from the main project (exe) after that. You'll have to take care of dependencies but it's not very difficult.</p>
8,663
<ol> <li><p>Consider:</p> <pre><code>char *p=NULL; free(p) // or delete p; </code></pre> <p>What will happen if I use <code>free</code> and <code>delete</code> on <code>p</code>?</p></li> <li><p>If a program takes a long time to execute, say 10 minutes, is there any way to reduce its running time to 5 minutes?</p></l...
<p>Some performance notes about new/delete and malloc/free:</p> <p>malloc and free <strong>do not</strong> call the constructor and deconstructor, respectively. This means your classes won't get initalized or deinitialized automatically, which could be bad (e.g. uninitalized pointers)! This doesn't matter for POD da...
<p>Good answers all.</p> <p>On the performance issue, <a href="https://stackoverflow.com/questions/266373/one-could-use-a-profiler-but-why-not-just-halt-the-program">this</a> provides a method that most can't imagine will work, but a few know it does, surprisingly well.</p> <p>The 90/10 rule is true. In my experience...
42,609
<p>I have observed some occasional delamination in horizontal layers of my resin prints — see two examples:</p> <p><a href="https://i.stack.imgur.com/DxGPD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DxGPD.png" alt="downward" /></a> <a href="https://i.stack.imgur.com/BZEoF.png" rel="nofollow nore...
<p>With the information provided my thought is that your layers are underexposed for their thickness. Each layer is just barely bonding to the layer above it. After being pulled on by layers below eventually one of the layers fails. This is especially likely to happen on a thin part of the print any may need more suppo...
<p><a href="https://3dprinting.stackexchange.com/a/14947/8884">Besides the options of underexposure or bad FEP film</a>, there's also the option of the print being in a bad orientation for printing. Often, the quality gets better if you tilt the model some degrees. You do have to clean up some places, but the stresses ...
1,780
<p>Here's my PS1 variable:</p> <pre><code>PS1='\u:\W$(__git_ps1 "\e[32m\][%s]\e[0m\]")$ ' </code></pre> <p>Works great for picking up my Git branch, but it has the unfortunate side-effect of wrapping the lines when the colours are active, so that they overlap when you use long commands.</p> <p>Can anyone with magic ...
<p>Got it, needed to escape the colours properly.</p> <p>Fix:</p> <pre><code>PS1='\u:\W$(__git_ps1 "\[\e[32m\][%s]\[\e[0m\]")$ ' </code></pre>
<p>These are the color functions I use regularly... wrote them years ago and have gotten so used to them that they're a regular part of my scripting. Just stick this code block into your .bashrc file, start a new session, and you're set!<BR></p> <p>I use these as colorful/stylish printf replacements:<BR> <PRE><code>##...
44,463
<p>How do I read a time value and then insert it into a TimeSpan variables?</p>
<p>If I understand you correctly you're trying to get some user input in the form of "08:00" and want to store the time in a timespan variable?</p> <p>So.. something like this?</p> <pre><code>string input = "08:00"; DateTime time; if (!DateTime.TryParse(input, out time)) { // invalid input return; } TimeSpan...
<p>Perhaps using:</p> <pre><code>var span = new TimeSpan(hours, minutes, seconds); </code></pre> <p>If you mean adding two timespans together use:</p> <pre><code>var newSpan = span.Add(new TimeSpan(hours, minutes, seconds)); </code></pre> <p>For more information see <a href="http://msdn.microsoft.com/en-us/library/...
16,003
<p>I need to add unit testing to some old scripts, the scripts are all basically in the following form:</p> <pre><code>#!/usr/bin/perl # Main code foo(); bar(); # subs sub foo { } sub bar { } </code></pre> <p>If I try to 'require' this code in a unit test, the main section of the code will run, where as I want to...
<p>Another common trick for unit testing scripts is to wrap the body of their code into a 'caller' block:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; unless (caller) { # startup code } sub foo { ... } </code></pre> <p>When run from the command line, cron, a bash script, etc., it runs normally. Ho...
<p>Assuming you have no security concerns, wrap it in a sub { ... } and eval it:</p> <pre><code>use File::Slurp "read_file"; eval "package Script; sub {" . read_file("script") . "}"; is(Script::foo(), "foo"); </code></pre> <p>(taking care that the eval isn't in scope of any lexicals that would be closed over by the ...
28,766
<p>Considering this code, can I be <em>absolutely sure</em> that the <code>finally</code> block always executes, no matter what <code>something()</code> is?</p> <pre><code>try { something(); return success; } catch (Exception e) { return failure; } finally { System.out.println("I don't...
<p>Yes, <code>finally</code> will be called after the execution of the <code>try</code> or <code>catch</code> code blocks.</p> <p>The only times <code>finally</code> won't be called are:</p> <ol> <li>If you invoke <code>System.exit()</code></li> <li>If you invoke <code>Runtime.getRuntime().halt(exitStatus)</code></li...
<p>I am terribly late to answer here, but I am surprised that no one mentioned the Java debugger option to drop a stack frame. I am a heavy user of this feature in IntelliJ. (I am <em>sure</em> Eclipse and NetBeans has support for the same feature.)</p> <p>If I drop stack frame from a the try or catch block that is f...
9,074
<p>I like to use static functions in C++ as a way to categorize them, like C# does.</p> <pre><code>Console::WriteLine("hello") </code></pre> <p>Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory?</p> <p>What about <code>static const</code>?</p>
<blockquote> <p>but is it good or bad </p> </blockquote> <p>The first adjective that comes to mind is "unnecessary". C++ has free functions and namespaces, so why would you need to make them static functions in a class?</p> <p>The use of static methods in uninstantiable classes in C# and Java <em>is a workaround</...
<p>For organization, use namespaces as already stated. </p> <p>For global data I like to use the <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow noreferrer">singleton</a> pattern because it helps with the problem of the unknown initialization order of static objects. In other words, if you use...
5,086