source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
21,715 | Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable IE: public class CollectionBase : IEnumerable and then would derive their Business Object collections from that. public class BusinessObjectCollection : CollectionBase Now with the generic list class, does anyone just use that instead? I've found that I use a compromise of the two techniques: public class BusinessObjectCollection : List<BusinessObject> I do this because I like to have strongly typed names instead of just passing Lists around. What is your approach? | I am generally in the camp of just using a List directly, unless for some reason I need to encapsulate the data structure and provide a limited subset of its functionality. This is mainly because if I don't have a specific need for encapsulation then doing it is just a waste of time. However, with the aggregate initializes feature in C# 3.0, there are some new situations where I would advocate using customized collection classes. Basically, C# 3.0 allows any class that implements IEnumerable and has an Add method to use the new aggregate initializer syntax. For example, because Dictionary defines a method Add(K key, V value) it is possible to initialize a dictionary using this syntax: var d = new Dictionary<string, int>{ {"hello", 0}, {"the answer to life the universe and everything is:", 42}}; The great thing about the feature is that it works for add methods with any number of arguments. For example, given this collection: class c1 : IEnumerable{ void Add(int x1, int x2, int x3) { //... } //...} it would be possible to initialize it like so: var x = new c1{ {1,2,3}, {4,5,6}} This can be really useful if you need to create static tables of complex objects. For example, if you were just using List<Customer> and you wanted to create a static list of customer objects you would have to create it like so: var x = new List<Customer>{ new Customer("Scott Wisniewski", "555-555-5555", "Seattle", "WA"), new Customer("John Doe", "555-555-1234", "Los Angeles", "CA"), new Customer("Michael Scott", "555-555-8769", "Scranton PA"), new Customer("Ali G", "", "Staines", "UK")} However, if you use a customized collection, like this one: class CustomerList : List<Customer>{ public void Add(string name, string phoneNumber, string city, string stateOrCountry) { Add(new Customer(name, phoneNumber, city, stateOrCounter)); }} You could then initialize the collection using this syntax: var customers = new CustomerList{ {"Scott Wisniewski", "555-555-5555", "Seattle", "WA"}, {"John Doe", "555-555-1234", "Los Angeles", "CA"}, {"Michael Scott", "555-555-8769", "Scranton PA"}, {"Ali G", "", "Staines", "UK"}} This has the advantage of being both easier to type and easier to read because their is no need to retype the element type name for each element. The advantage can be particularly strong if the element type is long or complex. That being said, this is only useful if you need static collections of data defined in your app. Some types of apps, like compilers, use them all the time. Others, like typical database apps don't because they load all their data from a database. My advice would be that if you either need to define a static collection of objects, or need to encapsulate away the collection interface, then create a custom collection class. Otherwise I would just use List<T> directly. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/21715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
]
} |
21,725 | What are your favorite (G)Vim plugins/scripts? | Nerdtree The NERD tree allows you to explore your filesystem and to open files anddirectories. It presents the filesystem to you in the form of a tree which youmanipulate with the keyboard and/or mouse. It also allows you to performsimple filesystem operations. The tree can be toggled easily with :NERDTreeToggle which can be mapped to a more suitable key. The keyboard shortcuts in the NERD tree are also easy and intuitive. Edit: Added synopsis | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/21725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2386/"
]
} |
21,817 | The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface? public interface ITest { public static String test();} The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only public & abstract are permitted". | There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between public interface Foo { public static int bar();} and public interface Foo { public static int bar() { ... }} The first is impossible for the reasons that Espo mentions: you don't know which implementing class is the correct definition. Java could allow the latter; and in fact, starting in Java 8, it does! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/21817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2238/"
]
} |
21,848 | There may be more than one way to ask this question, so here's a desciption of the problem. I was working on master and committed some stuff and then decided I wanted to put that work on hold. I backed up a few commits and then branched from before I started my crap work. Practically this works fine, I just now have a different branch as my main development branch. I'm wondering how I could change things around so I'm working on master again but it doesn't have my junk work and said work is on a different branch. Some ways this could be asked/solved:How do I rename my master branch to something else and then rename something else to master?How do I back up master and then cause all commits I've backed up past to be on a different branch? Thanks for all the (quick) answers! They're all good. | In addition to the other comments, you may find the -m (move) switch to git-branch helpful. You could rename your old master to something else, then rename your new branch to master: git branch -m master crap_workgit branch -m previous_master master | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/21848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2427/"
]
} |
21,870 | For a .NET component that will be used in both web applications and rich client applications, there seem to be two obvious options for caching: System.Web.Caching or the Ent. Lib. Caching Block. What do you use? Why? System.Web.Caching Is this safe to use outside of web apps? I've seen mixed information, but I think the answer is maybe-kind-of-not-really. a KB article warning against 1.0 and 1.1 non web app use The 2.0 page has a comment that indicates it's OK: http://msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx Scott Hanselman is creeped out by the notion The 3.5 page includes a warning against such use Rob Howard encouraged use outside of web apps I don't expect to use one of its highlights, SqlCacheDependency , but the addition of CacheItemUpdateCallback in .NET 3.5 seems like a Really Good Thing. Enterprise Library Caching Application Block other blocks are already in use so the dependency already exists cache persistence isn't necessary; regenerating the cache on restart is OK Some cache items should always be available, but be refreshed periodically. For these items, getting a callback after an item has been removed is not very convenient. It looks like a client will have to just sleep and poll until the cache item is repopulated. Memcached for Win32 + .NET client What are the pros and cons when you don't need a distributed cache? | These are the items that I consider for the topic of Caching: MemCached Win32Velocity.net CacheEnterprise Library Caching Application Block MemCached Win32: Up until recently I have used MemCached Win32. This is a akin to a web farm (many servers serving the same content for high availability) but it is a cache farm. This means that you can install it locally on your web server initially if you don't have the resources to go bigger. Then as you go down the road you can scale horizontally (more servers) or vertically (more hardware). This is a product that was ported from the original MemCached to work on Windows. This product has been used extensively in very high traffic sites. http://lineofthought.com/tools/memcached Velocity: This is Microsofts answer to products such as MemCached. MemCached has been out for quite some time, Velocity is in CTP mode. I must say that from what I have read so far this product will certainly turn my head once it is out. But I can't bring myself to run big production projects on a CTP product with zero track record. I have started playing with it though as once it gains momentum MemCached won't even compare for those locked in the windows world! http://blogs.msdn.com/velocity/ .NET Cache: There is no reason to discount the standard .NET Cache. It is built in and ready to use for free and with no (major) set up required. It offers flexibility by way of offering mechanisms for storing items in local memory, a SINGLE state server, or a centralized database. Where Velocity steps in is when you need more than a single state server (cache in memory) and don't want to use a slow database for holding your cache. Enterprise Application Block: I stay away from all of the Enterprise Application Blocks. They are heavy frameworks that give more than I generally require! As long as you remember to wrap everything that touches code that is not your own and follow simple rules for coding, stick to any of the other methods over this one! (just my opinion of course - MySpace leverages as much as they can out of Enterprise Application Blocks!) You don't have to choose up front! I generally create a cache wrapper that I communicate with in my code for methods such as Get, Set, Exists, Remove, ListKeys, etc. This then points to an underlying level of cache abstraction that can point to MemCached, Velocity, or .NET cache. I use StructureMap (or choose another IoC container) to inject which form of cache I want to use for a given environment. In my local dev box I might use .NET cache in the session. In production I generally use MemCached Win 32. But regardless of how it is set up you can easily swap things around to try each system out to see what works best for you. You just need to make sure that you application knows as little as possible about how things are cached! Once this layer of abstraction is in place you can then do things such as run a compression algorithm (gzip) for all the data that is going in and out of cache which would allow you to store 10 times the amount of data in cache. - transparently . I cover .NET Cache, MemCached Win32, StructureMap, and the appropriate abstractions in my book if you are interested! ASP.NET 3.5 Social Networking ( http://www.amazon.com/ASP-NET-3-5-Social-Networking-Enterprise-ready/dp/1847194788/ref=sr_1_1?ie=UTF8&s=books&qid=1225408005&sr=8-1 )Andrew Siemer www.andrewsiemer.com blog.andrewsiemer.com www.socialnetworkingin.net Update Changed the link that lists sites using memcached. Thank you David for noticing that it was broken! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/21870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/150/"
]
} |
21,877 | What I want to achieve is this. I want to give the user the ability to upload an image file, store the image in BLOB in SQL Server, and then use this image as a logo in other pages of the site. I have done this by using Response.Clear(); Response.ContentType = "image/pjpeg"; Response.BinaryWrite(imageConents); Response.End(); but to do this, I use a User control in the place where I want to show the image. I want to do it if possible using an asp:Image control, or even a pure old html image control. Is this possible? | Add a 'Generic Handler' to your web project, name it something like Image.ashx. Implement it like this: public class ImageHandler : IHttpHandler{ public void ProcessRequest(HttpContext context) { using(Image image = GetImage(context.Request.QueryString["ID"])) { context.Response.ContentType = "image/jpeg"; image.Save(context.Response.OutputStream, ImageFormat.Jpeg); } } public bool IsReusable { get { return true; } }} Now just implement the GetImage method to load the image with the given ID, and you can use <asp:Image runat="server" ImageUrl="~/Image.ashx?ID=myImageId" /> to display it. You might want to think about implementing some form of caching in the handler too. And remember if you want to change the image format to PNG, you need to use an intermediate MemoryStream (because PNGs require a seekable stream to be saved). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/21877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/932/"
]
} |
21,908 | I'm working on a web application that needs to prints silently -- that is without user involvement. What's the best way to accomplish this? It doesn't like it can be done with strictly with Javascript, nor Flash and/or AIR. The closest I've seen involves a Java applet. I can understand why it would a Bad Idea for just any website to be able to do this. This specific instance is for an internal application, and it's perfectly acceptable if the user needs to add the URL to a trusted site list, install an addon, etc. | Here’s what you need to do to enable Firefox immediately print without showing the print preferences dialog box. Type about:config at Firefox’s location bar and hit Enter. Right click at anywhere on the page and select New > Boolean Enter the preference name as print.always_print_silent and click OK. I found that somewhere and it helped me | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/21908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/181/"
]
} |
21,934 | Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed. But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time. Why does Java choose this strategy and what is the benefit from this? Is this better than the Python approach? | There are drawbacks of using reference counting. One of the most mentioned is circular references: Suppose A references B, B references C and C references B. If A were to drop its reference to B, both B and C will still have a reference count of 1 and won't be deleted with traditional reference counting. CPython (reference counting is not part of python itself, but part of the C implementation thereof) catches circular references with a separate garbage collection routine that it runs periodically... Another drawback: Reference counting can make execution slower. Each time an object is referenced and dereferenced, the interpreter/VM must check to see if the count has gone down to 0 (and then deallocate if it did). Garbage Collection does not need to do this. Also, Garbage Collection can be done in a separate thread (though it can be a bit tricky). On machines with lots of RAM and for processes that use memory only slowly, you might not want to be doing GC at all! Reference counting would be a bit of a drawback there in terms of performance... | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/21934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1556/"
]
} |
21,938 | Whilst analysing some legacy code with FXCop, it occurred to me is it really that bad to catch a general exception error within a try block or should you be looking for a specific exception. Thoughts on a postcard please. | Obviously this is one of those questions where the only real answer is "it depends." The main thing it depends on is where your are catching the exception. In general libraries should be more conservative with catching exceptions whereas at the top level of your program (e.g. in your main method or in the top of the action method in a controller, etc) you can be more liberal with what you catch. The reason for this is that e.g. you don't want to catch all exceptions in a library because you may mask problems that have nothing to do with your library, like "OutOfMemoryException" which you really would prefer bubbles up so that the user can be notified, etc. On the other hand, if you are talking about catching exceptions inside your main() method which catches the exception, displays it and then exits... well, it's probably safe to catch just about any exception here. The most important rule about catching all exceptions is that you should never just swallow all exceptions silently... e.g. something like this in Java: try { something(); } catch (Exception ex) {} or this in Python: try: something()except: pass Because these can be some of the hardest issues to track down. A good rule of thumb is that you should only catch exceptions that you can properly deal with yourself. If you cannot handle the exception completely then you should let it bubble up to someone who can. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/21938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1731/"
]
} |
21,965 | Could somebody please do a rundown of how to programmatically encrypt a config-file in .NET, preferably in C#. What I would like to do is do some kind of check on an application's startup to see if a section is unprotected, and if it is, then encrypt it. This for both settings and connection-strings. Also if anyone could list the types of encryption-providers and what is the difference between them. I don't know if the code for doing this in a normal WinForms-application is transparent to doing this in ASP.NET. | To summarize the answers and what I've found so far, here are some good links to answer this question: Encrypting Configuration Information in ASP.NET 2.0 Applications - 4GuysFromRolla.com How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI - MSDN Please feel free to complement with other links, maybe some to WinForms- or WPF-applications. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/21965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429/"
]
} |
22,000 | I've created a map system for a game that runs on the principle of drawing the picture of the map from tiles. There are many reasons for this which I won't go into here but if you really want to know then I'm sure you can find out how to contact me ;) I have made the latest version live so you can see exactly where the problem lies and the source. The issue is the line between the top 2 tiles and the bottom 2 tiles, I can't figure out why it's gone like this and any help would be appreciated. In the source is a marker called "stackoverflow", if you search for "stackoverflow" when viewing source then it should take you to the table in question. I have also uploaded an image of the issue . | I think you need to use display: block on your images. When images are inline there's a little extra space for the line spacing. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/22000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
22,012 | My application dynamically loads assemblies at runtime from specific subfolders. These assemblies are compiled with dependencies to other assemblies. The runtime trys to load these from the application directory. But I want to put them into the modules directory. Is there a way to tell the runtime that the dlls are in a seperate subfolder? | One nice approach I've used lately is to add an event handler for the AppDomain's AssemblyResolve event. AppDomain currentDomain = AppDomain.CurrentDomain;currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler); Then in the event handler method you can load the assembly that was attempted to be resolved using one of the Assembly.Load, Assembly.LoadFrom overrides and return it from the method. EDIT: Based on your additional information I think using the technique above, specifically resolving the references to an assembly yourself is the only real approach that is going to work without restructuring your app. What it gives you is that the location of each and every assembly that the CLR fails to resolve can be determined and loaded by your code at runtime... I've used this in similar situations for both pluggable architectures and for an assembly reference integrity scanning tool. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/22012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2374/"
]
} |
22,084 | I'm getting into ASP.NET (C# - I know it doesn't matter for this particular question, but full disclosure and all that), and while I love that the asp: -style controls save me a lot of tedious HTML-crafting, I am often frustrated with certain behaviors. I encountered one last night when working with Master Pages: my <asp:BulletedList ID="nav"> , when converted into HTML, became <ul id="ct100_nav"> . There are other issues--I noticed that when you auto-populate a DataGrid, it adds attributes to the resulting table that I don't necessarily want there. I know that there is a certain amount of "convention over configuration" that you have to accept when you rely on a framework to take over some of your tedious duties, but the "conventions" in these cases aren't so much any established conventions, but rather unnecessary extras. I know why the ID adds the prefix, but I should be able to tweak and turn things like this off, especially since, as a bit of a web standards evangelist, I don't duplicated HTML id's in a single page anyway. So the question here is for those ASP.NET devs more seasoned than I: in your experiences in developing and deploying apps, how do you leverage these controls? Do you find yourself resorting back to hard-coded HTML? Do you use a blend? I don't want to design my HTML around idiosyncratic quirks in these controls, but, if possible, I'd like to leverage them when possible. What's a boy to do? | Personally, I think the standard ASP.NET controls are fine for inhouse stuff - quick and dirty is good in that scenario. But, I once worked with a web developer who was also a designer and he refused to use the ASP.NET controls and only code in HTML and add runat="server" tags when needed. This was more because he wanted to know exactly how his HTML was going to be rendered, and at the time anyway, some of the ASP.NET controls wouldn't render to standards compliance. I sit somewhere in the middle - use HTML where appropriate and not when not. You can sort of best of both worlds with the CSS control Adapters | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/22084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1344/"
]
} |
22,115 | I am writing a Java utility that helps me to generate loads of data for performance testing. It would be really cool to be able to specify a regex for Strings so that my generator spits out things that match this. Is something out there already baked that I can use to do this? Or is there a library that gets me most of the way there? | Edit: Complete list of suggested libraries on this question: Xeger * - Java Generex * - Java Rgxgen - Java rxrdg - C# * - Depends on dk.brics.automaton Edit: As mentioned in the comments, there is a library available at Google Code to achieve this: https://code.google.com/archive/p/xeger/ See also https://github.com/mifmif/Generex as suggested by Mifmif Original message: Firstly, with a complex enough regexp, I believe this can be impossible. But you should be able to put something together for simple regexps. If you take a look at the source code of the class java.util.regex.Pattern, you'll see that it uses an internal representation of Node instances. Each of the different pattern components have their own implementation of a Node subclass. These Nodes are organised into a tree. By producing a visitor that traverses this tree, you should be able to call an overloaded generator method or some kind of Builder that cobbles something together. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/22115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2455/"
]
} |
22,145 | I am working on a project where I produce an aluminium extrusion cutting list. The aluminium extrusions come in lengths of 5m. I have a list of smaller lengths that need to be cut from the 5m lengths of aluminium extrusions. The smaller lengths need to be cut in the order that produces the least amount of off cut waste from the 5m lengths of aluminium extrusions. Currently I order the cutting list in such a way that generally the longest of the smaller lengths gets cut first and the shortest of smaller lengths gets cut last. The exception to this rule is whenever a shorter length will not fit in what is left of the 5m length of aluminium extrusion, I use the longest shorter length that will fit. This seems to produce a very efficient (very little off cut waste) cutting list and doesn't take long to calculate. I imagine, however, that even though the cutting list is very efficient, it is not necessarily the most efficient. Does anyone know of a way to calculate the most efficient cutting list which can be calculated in a reasonable amount of time? EDIT: Thanks for the answers, I'll continue to use the "greedy" approach as it seems to be doing a very good job (out performs any human attempts to create an efficient cutting list) and is very fast. | This is a classic, difficult problem to solve efficiently. The algorithm you describe sounds like a Greedy Algorithm . Take a look at this Wikipedia article for more information: The Cutting Stock Problem | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/22145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1142/"
]
} |
22,149 | I stumbled over this passage in the Django tutorial : Django models have a default str () method that calls unicode () and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8. Now, I'm confused because afaik Unicode is not any particular representation, so what is a "Unicode string" in Python? Does that mean UCS-2? Googling turned up this "Python Unicode Tutorial" which boldly states Unicode is a two-byte encoding which covers all of the world's common writing systems. which is plain wrong, or is it? I have been confused many times by character set and encoding issues, but here I'm quite sure that the documentation I'm reading is confused. Does anybody know what's going on in Python when it gives me a "Unicode string"? | what is a "Unicode string" in Python? Does that mean UCS-2? Unicode strings in Python are stored internally either as UCS-2 (fixed-length 16-bit representation, almost the same as UTF-16) or UCS-4/UTF-32 (fixed-length 32-bit representation). It's a compile-time option; on Windows it's always UTF-16 whilst many Linux distributions set UTF-32 (‘wide mode’) for their versions of Python. You are generally not supposed to care: you will see Unicode code-points as single elements in your strings and you won't know whether they're stored as two or four bytes. If you're in a UTF-16 build and you need to handle characters outside the Basic Multilingual Plane you'll be Doing It Wrong, but that's still very rare, and users who really need the extra characters should be compiling wide builds. plain wrong, or is it? Yes, it's quite wrong. To be fair I think that tutorial is rather old; it probably pre-dates wide Unicode strings, if not Unicode 3.1 (the version that introduced characters outside the Basic Multilingual Plane). There is an additional source of confusion stemming from Windows's habit of using the term “Unicode” to mean, specifically, the UTF-16LE encoding that NT uses internally. People from Microsoftland may often copy this somewhat misleading habit. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/22149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
]
} |
22,239 | (I'm using Visual C++ 2008) I've always heard that main() is required to return an integer, but here I didn't put in return 0; and and it compiled with 0 errors and 0 warnings! In the debug window it says the program has exited with code 0. If this function is named anything other than main(), the compiler complains saying 'blah' must return a value. Sticking a return; also causes the error to appear. But leaving it out completely, it compiles just fine. #include <iostream>using namespace std;int main(){ cout << "Hey look I'm supposed to return an int but I'm not gonna!\n";} Could this be a bug in VC++? | 3.6.1 Main function .... 2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int , but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main: int main() { /* ... */ } and int main(int argc, char* argv[]) {/* ... */} .... and it continues to add ... 5 A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing return 0 ; attempting to find an online copy of the C++ standard so I could quote this passage I found a blog post that quotes all the right bits better than I could. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/22239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2222/"
]
} |
22,245 | I have multiple projects in a couple of different workspaces. However, it seems like I can never figure out how to change my current workspace. The result is that files that I have checked out on my machine are shown to be checked out by somebody else and are not accessible. | I'm going to assume you mean "workspace", not "workstation", as your question doesn't quite make sense to me otherwise. In Visual Studio, go to the Source Control Explorer (View->Other Windows->Source Control Explorer). At the top of the source control explorer window you should have a toolbar with a few buttons. Somewhere on that toolbar (for me it's at the right) there should be a Workspace dropdown. Just select the workspace you want to use from that dropdown. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/22245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
22,259 | I want to allow users to upload avatar-type images in a variety of formats ( GIF, JPEG, and PNG at least ), but to save them all as PNG database BLOBs . If the images are oversized, pixelwise, I want to resize them before DB-insertion. What is the best way to use GD to do the resizing and PNG conversion? Edit: Sadly, only GD is available on the server I need to use, no ImageMagick . | <?php /*Resizes an image and converts it to PNG returning the PNG data as a string*/function imageToPng($srcFile, $maxSize = 100) { list($width_orig, $height_orig, $type) = getimagesize($srcFile); // Get the aspect ratio $ratio_orig = $width_orig / $height_orig; $width = $maxSize; $height = $maxSize; // resize to height (orig is portrait) if ($ratio_orig < 1) { $width = $height * $ratio_orig; } // resize to width (orig is landscape) else { $height = $width / $ratio_orig; } // Temporarily increase the memory limit to allow for larger images ini_set('memory_limit', '32M'); switch ($type) { case IMAGETYPE_GIF: $image = imagecreatefromgif($srcFile); break; case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($srcFile); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($srcFile); break; default: throw new Exception('Unrecognized image type ' . $type); } // create a new blank image $newImage = imagecreatetruecolor($width, $height); // Copy the old image to the new image imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); // Output to a temp file $destFile = tempnam(); imagepng($newImage, $destFile); // Free memory imagedestroy($newImage); if ( is_file($destFile) ) { $f = fopen($destFile, 'rb'); $data = fread($f); fclose($f); // Remove the tempfile unlink($destFile); return $data; } throw new Exception('Image conversion failed.');} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/22259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820/"
]
} |
22,269 | I'm trying to build a C# console application to automate grabbing certain files from our website, mostly to save myself clicks and - frankly - just to have done it. But I've hit a snag that for which I've been unable to find a working solution. The website I'm trying to which I'm trying to connect uses ASP.Net forms authorization, and I cannot figure out how to authenticate myself with it. This application is a complete hack so I can hard code my username and password or any other needed auth info, and the solution itself doesn't need to be something that is viable enough to release to general users. In other words, if the only possible solution is a hack, I'm fine with that. Basically, I'm trying to use HttpWebRequest to pull the site that has the list of files, iterating through that list and then downloading what I need. So the actual work on the site is fairly trivial once I can get the website to consider me authorized. | <?php /*Resizes an image and converts it to PNG returning the PNG data as a string*/function imageToPng($srcFile, $maxSize = 100) { list($width_orig, $height_orig, $type) = getimagesize($srcFile); // Get the aspect ratio $ratio_orig = $width_orig / $height_orig; $width = $maxSize; $height = $maxSize; // resize to height (orig is portrait) if ($ratio_orig < 1) { $width = $height * $ratio_orig; } // resize to width (orig is landscape) else { $height = $width / $ratio_orig; } // Temporarily increase the memory limit to allow for larger images ini_set('memory_limit', '32M'); switch ($type) { case IMAGETYPE_GIF: $image = imagecreatefromgif($srcFile); break; case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($srcFile); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($srcFile); break; default: throw new Exception('Unrecognized image type ' . $type); } // create a new blank image $newImage = imagecreatetruecolor($width, $height); // Copy the old image to the new image imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); // Output to a temp file $destFile = tempnam(); imagepng($newImage, $destFile); // Free memory imagedestroy($newImage); if ( is_file($destFile) ) { $f = fopen($destFile, 'rb'); $data = fread($f); fclose($f); // Remove the tempfile unlink($destFile); return $data; } throw new Exception('Image conversion failed.');} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/22269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/111/"
]
} |
22,326 | I am trying to replace the current selection in Word (2003/2007) by some RTF string stored in a variable. Here is the current code: Clipboard.SetText(strRTFString, TextDataFormat.Rtf)oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) Is there any way to do the same thing without going through the clipboard. Or is there any way to push the clipboard data to a safe place and restore it after? | Put the RTF in a file instead of the clipboard, then insert from the file, e.g. Selection.InsertFile FileName:="myfile.rtf", Range :="", _ ConfirmConversions:=False, Link:=False, Attachment:=False | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/22326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1508/"
]
} |
22,338 | I flatter myself that I'm a good programmer, and can get away with graphic design. But something I'm incapable of doing is coming up with good names - and it seems neither are the people I work with. We're now in the slightly ludicrous situation that the product we've been working on for a couple of years is being installed to customers, is well received and is making money - but doesn't yet have a name. We're too small a company to have anything like a proper marketing division to do this thing. So how have people tended to choose names, logos and branding? | When it's for something that "matters", I plop down the $50 and have the folks at PickyDomains.com help out. That also results in a name that's available as a .com. For guidelines, here's an extract from my own guide on naming open source projects: If the name you're thinking of is directly pulled from a scifi or fantasy source, don't bother. These sources are WAY overrepresented as naming sources in software. Not only are your chances of coming up with something original pretty small, most of the names of characters and places in scifi are trademarked and you run the risk of being sued. If the name you're thinking of comes straight from Greek, Roman or Norse mythology, try again. We've got more than enough mail related software called variations of "Mercury". Run your proposed name through Google. The fewer results you get the better. If you get down to no results, you're there. Don't try to get a unique name by just slightly misspelling something. Calling your new Windows filesystem program Phat32 is just going to end up with users getting frustrated looking at the results of "fat32" in a search engine. If your name couldn't be said on TV in the 50s or 60s, you're probably on the wrong track. This is particularly true if you would like anyone to use your product in a work environment. No one is going to recommend a product to their co-workers if they can get sued for sexual harassment just for uttering its name. If your product name can't be pronounced at all, you'll get no word of mouth benefit at all. Similarly, if no one knows how to pronounce it, they will not be very likely to try to say it out loud to ask questions about it, etc. How do YOU say MySQL? PostgreSQL? GNU? Almost all spoken languages on Earth are based on consonant/vowel syllables of some sort. Alternating between consonants and vowels is a pretty good way to ensure that someone can pronounce it. The shorter the better. See if the .com domain is available. If it's not, it's a pretty good indicator that someone has already thought of it and is using it or closer to using it than you are. Do this even if you don't intend to use the domain. Don't build inherent limitations on your product into the name. Calling your product LinProduct or WinProduct precludes you from ever releasing any sort of cross-platform edition. Don't use your own name for open source products. If the project lives on beyond your involvement, the project will either have to be renamed or your name may be used in ways you didn't intend. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/22338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1000/"
]
} |
22,356 | I find that the .NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is. Based on the community suggestions, I've used this: // earlier in the codemCoolObject.CoolEvent+= new CoolObjectEventHandler(mCoolObject_CoolEvent);// thenprivate void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args){ if (InvokeRequired) { CoolObjectEventHandler cb = new CoolObjectEventHandler( mCoolObject_CoolEvent); Invoke(cb, new object[] { sender, args }); return; } // do the dirty work of my method here} | A couple of observations: Don't create simple delegates explicitly in code like that unless you're pre-2.0 so you could use: BeginInvoke(new EventHandler<CoolObjectEventArgs>(mCoolObject_CoolEvent), sender, args); Also you don't need to create and populate the object array because the args parameter is a "params" type so you can just pass in the list. I would probably favor Invoke over BeginInvoke as the latter will result in the code being called asynchronously which may or may not be what you're after but would make handling subsequent exceptions difficult to propagate without a call to EndInvoke . What would happen is that your app will end up getting a TargetInvocationException instead. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/22356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1490/"
]
} |
22,358 | Is there any way to tinker with the iPhone SDK on a Windows machine? Are there plans for an iPhone SDK version for Windows? The only other way I can think of doing this is to run a Mac VM image on a VMWare server running on Windows, although I'm not too sure how legal this is. | It's certainly possible to develop on a Windows machine, in fact, my first application was exclusively developed on the old Dell Precision I had at the time :) There are three routes; Install OSx86 (aka iATKOS / Kalyway) on a second partition/disk and dual boot. Run Mac OS X Server under VMWare (Mac OS X 10.7 (Lion) onwards, read the update below). Use a framework and/or toolset, which allows developing on Windows, like Delphi XE4 with the mac-in-cloud service, which can build without MacOS device need. This is a commercial toolset, but the component and lib support is growing. Other honorable mentions are Flutter , Xamarin and similar; which may at end need actual MacOS device for final build (but you can test on Android till then, as they're cross-platform). The first route requires modifying (or using a pre-modified) image of Leopard that can be installed on a regular PC. This is not as hard as you would think, although your success/effort ratio will depend upon how closely the hardware in your PC matches that in Mac hardware - e.g. if you're running a Core 2 Duo on an Intel Motherboard, with an NVidia graphics card you are laughing. If you're running an AMD machine or something without SSE3 it gets a little more involved. If you purchase (or already own) a version of Leopard then this is a gray area since the Leopard EULA states you may only run it on an "Apple Labeled" machine. As many point out if you stick an Apple sticker on your PC you're probably covered. The second option is more costly. The EULA for the workstation version of Leopard prevents it from being run under emulation and as a result, there's no support in VMWare for this. Leopard server, however, CAN be run under emulation and can be used for desktop purposes. Leopard server and VMWare are expensive, however. If you're interested in option 1) I would suggest starting at Insanelymac and reading the OSx86 sections. I do think you should consider whether the time you will invest is going to be worth the money you will save though. It was for me because I enjoy tinkering with this type of stuff and I started during the early iPhone betas, months before their App Store became available. Alternatively, you could pick up a low-spec Mac Mini from eBay. You don't need much horsepower to run the SDK and you can always sell it on later if you decide to stop development or buy a better Mac. Update: You cannot create a Mac OS X Client virtual machine for OS X 10.6 and earlier. Apple does not allow these Client OSes to be virtualized. With Mac OS X 10.7 (Lion) onwards, Apple has changed its licensing agreement in regards to virtualization. Source: VMWare KnowledgeBase | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/22358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2454/"
]
} |
22,401 | I'm looking at the PHP Manual , and I'm not seeing a section on data structures that most languages have, such as lists and sets. Am I just blind or does PHP not have anything like this built in? | The only native data structure in PHP is array. Fortunately, arrays are quite flexible and can be used as hash tables as well. http://www.php.net/array However, there is SPL which is sort of a clone of C++ STL. http://www.php.net/manual/en/book.spl.php | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/22401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
]
} |
22,444 | I have this gigantic ugly string: J0000000: Transaction A0001401 started on 8/22/2008 9:49:29 AMJ0000010: Project name: E:\foo.pfJ0000011: Job name: MBiek Direct Mail TestJ0000020: Document 1 - Completed successfully I'm trying to extract pieces from it using regex. In this case, I want to grab everything after Project Name up to the part where it says J0000011: (the 11 is going to be a different number every time). Here's the regex I've been playing with: Project name:\s+(.*)\s+J[0-9]{7}: The problem is that it doesn't stop until it hits the J0000020: at the end. How do I make the regex stop at the first occurrence of J[0-9]{7} ? | Make .* non-greedy by adding ' ? ' after it: Project name:\s+(.*?)\s+J[0-9]{7}: | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/22444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
]
} |
22,459 | I'm getting some strange, intermittent, data aborts (< 5% of the time) in some of my code, when calling memset() . The problem is that is usually doesn't happen unless the code is running for a couple days, so it's hard to catch it in the act. I'm using the following code: char *msg = (char*)malloc(sizeof(char)*2048);char *temp = (char*)malloc(sizeof(char)*1024);memset(msg, 0, 2048);memset(temp, 0, 1024);char *tempstr = (char*)malloc(sizeof(char)*128);sprintf(temp, "%s %s/%s %s%s", EZMPPOST, EZMPTAG, EZMPVER, TYPETXT, EOL);strcat(msg, temp);//Add Datamemset(tempstr, '\0', 128);wcstombs(tempstr, gdevID, wcslen(gdevID));sprintf(temp, "%s: %s%s", "DeviceID", tempstr, EOL);strcat(msg, temp); As you can see, I'm not trying to use memset with a size larger that what's originally allocated with malloc() Anyone see what might be wrong with this? | malloc can return NULL if no memory is available. You're not checking for that. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/22459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
]
} |
22,466 | We've got a page with a ton of jQuery (approximately 2000 lines) that we want to trim down b/c it is a maintenance nightmare, and it might be easier to maintain on the server. We've thought about using UpdatePanel for this. However, we don't like the fact that the UpdatePanel is sending the whole page back to the server. | Don't move to UpdatePanels. After coming from jQuery, the drop in performance would be untenable. Especially on a page as complex as yours sounds. If you have 2,000 lines of JavaScript code, the solution is to refactor that code. If you put 2,000 lines of C# code in one file, it would be difficult to maintain too. That would be difficult to manage effectively with any language or tool. If you're using 3.5 SP1, you can use the ScriptManager's new script combining to separate your JavaScript into multiple files with no penalty. That way, you can logically partition your code just as you would with server side code. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/22466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1446/"
]
} |
22,469 | I'm going to be working on some iPhone apps so I've been given a golden ticket to buy a Mac. However the golden ticket isn't worth that much, and I'm thinking iMac. Now, Macs are great, I love 'em and use 'em at home, but I know that the iMac is geared more towards the average consumer than the professional. Is an iMac going to be powerful enough to do iPhone development on? If it helps any, the only thing I envision doing on the Mac is running XCode and maybe a web browser. Is there anybody out there doing iPhone development and having trouble running the required tools on their machine? If so, what do you have? | Any modern Mac will be fine. I work on a two year old MacBook (2GHz) with 2Gb of memory and its perfectly usable. The biggest constraint I find it screen real-estate. I am way more productive on my 22" external screen. Go big if you get an iMac or consider adding an external monitor to the base model. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/22469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/543/"
]
} |
22,500 | The Wikipedia article on ANSI C says: One of the aims of the ANSI C standardization process was to produce a superset of K&R C (the first published standard), incorporating many of the unofficial features subsequently introduced. However, the standards committee also included several new features, such as function prototypes (borrowed from the C++ programming language), and a more capable preprocessor. The syntax for parameter declarations was also changed to reflect the C++ style. That makes me think that there are differences. However, I didn't see a comparison between K&R C and ANSI C. Is there such a document? If not, what are the major differences? EDIT: I believe the K&R book says "ANSI C" on the cover. At least I believe the version that I have at home does. So perhaps there isn't a difference anymore? | There may be some confusion here about what "K&R C" is. The term refers to the language as documented in the first edition of "The C Programming Language." Roughly speaking: the input language of the Bell Labs C compiler circa 1978. Kernighan and Ritchie were involved in the ANSI standardization process. The "ANSI C" dialect superceded "K&R C" and subsequent editions of "The C Programming Language" adopt the ANSI conventions. "K&R C" is a "dead language," except to the extent that some compilers still accept legacy code. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/22500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
]
} |
22,528 | I would like to have a reference for the pros and cons of using include files vs objects(classes) when developing PHP applications. I know I would benefit from having one place to go for this answer...I have a few opinions of my own but I look forward to hearing others. A Simple Example: Certain pages on my site are only accessible to logged in users. I have two options for implementation (there are others but let's limit it to these two) Create an authenticate.php file and include it on every page. It holds the logic for authentication. Create a user object, which has an authenticate function, reference the object for authentication on every page. Edit I'd like to see some way weigh the benefits of one over the other. My current (and weak reasons) follow: Includes - Sometimes a function is just easier/shorter/faster to callObjects - Grouping of functionality and properties leads for longer term maintenance. Includes - Less code to write (no constructor, no class syntax) call me lazy but this is true. Objects - Force formality and a single approach to functions and creation. Includes - Easier for a novice to deal withObjects - Harder for novices, but frowned upon by professionals. I look at these factors at the start of a project to decide if I want to do includes or objects.Those are a few pros and cons off the top of my head. | These are not really opposite choices. You will have to include the checking code anyway. I read your question as procedural programming vs. OO programming. Writing a few lines of code, or a function, and including it in your page header was how things were done in PHP3 or PHP4. It's simple, it works (that's how we did it in osCommerce , for example, an eCommerce PHP application). But it's not easy to maintain and modify, as many developers can confirm. In PHP5 you'd write a user object which will carry its own data and methods for authentication. Your code will be clearer and easier to maintain as everything having to do with users and authentication will be concentrated in a single place. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/22528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2490/"
]
} |
22,566 | How do I get Perl to read the contents of a given directory into an array? Backticks can do it, but is there some method using 'scandir' or a similar term? | opendir(D, "/path/to/directory") || die "Can't open directory: $!\n";while (my $f = readdir(D)) { print "\$f = $f\n";}closedir(D); EDIT: Oh, sorry, missed the "into an array" part: my $d = shift;opendir(D, "$d") || die "Can't open directory $d: $!\n";my @list = readdir(D);closedir(D);foreach my $f (@list) { print "\$f = $f\n";} EDIT2: Most of the other answers are valid, but I wanted to comment on this answer specifically, in which this solution is offered: opendir(DIR, $somedir) || die "Can't open directory $somedir: $!";@dots = grep { (!/^\./) && -f "$somedir/$_" } readdir(DIR);closedir DIR; First, to document what it's doing since the poster didn't: it's passing the returned list from readdir() through a grep() that only returns those values that are files (as opposed to directories, devices, named pipes, etc.) and that do not begin with a dot (which makes the list name @dots misleading, but that's due to the change he made when copying it over from the readdir() documentation). Since it limits the contents of the directory it returns, I don't think it's technically a correct answer to this question, but it illustrates a common idiom used to filter filenames in Perl , and I thought it would be valuable to document. Another example seen a lot is: @list = grep !/^\.\.?$/, readdir(D); This snippet reads all contents from the directory handle D except '.' and '..', since those are very rarely desired to be used in the listing. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/22566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
]
} |
22,570 | Here is the issue I am having: I have a large query that needs to compare datetimes in the where clause to see if two dates are on the same day. My current solution, which sucks, is to send the datetimes into a UDF to convert them to midnight of the same day, and then check those dates for equality. When it comes to the query plan, this is a disaster, as are almost all UDFs in joins or where clauses. This is one of the only places in my application that I haven't been able to root out the functions and give the query optimizer something it can actually use to locate the best index. In this case, merging the function code back into the query seems impractical. I think I am missing something simple here. Here's the function for reference. if not exists (select * from dbo.sysobjects where id = object_id(N'dbo.f_MakeDate') and type in (N'FN', N'IF', N'TF', N'FS', N'FT')) exec('create function dbo.f_MakeDate() returns int as begin declare @retval int return @retval end')goalter function dbo.f_MakeDate( @Day datetime, @Hour int, @Minute int)returns datetimeas/*Creates a datetime using the year-month-day portion of @Day, and the @Hour and @Minute provided*/begindeclare @retval datetimeset @retval = cast( cast(datepart(m, @Day) as varchar(2)) + '/' + cast(datepart(d, @Day) as varchar(2)) + '/' + cast(datepart(yyyy, @Day) as varchar(4)) + ' ' + cast(@Hour as varchar(2)) + ':' + cast(@Minute as varchar(2)) as datetime)return @retvalendgo To complicate matters, I am joining on time zone tables to check the date against the local time, which could be different for every row: where dbo.f_MakeDate(dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), 0, 0) = @activityDateMidnight [Edit] I'm incorporating @Todd's suggestion: where datediff(day, dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, t.TheDateINeedToCheck), @ActivityDate) = 0 My misconception about how datediff works (the same day of year in consecutive years yields 366, not 0 as I expected) caused me to waste a lot of effort. But the query plan didn't change. I think I need to go back to the drawing board with the whole thing. | This is much more concise: where datediff(day, date1, date2) = 0 | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/22570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1219/"
]
} |
22,607 | I’m thinking about trying some development for the iPhone, is it possible to install Leopard inside VMWare? I already have a pretty high spec PC with a comfy setup that I’d like to use, or do I need to buy a real Mac? | It is legal to run Mac OS X Server in a virtual machine on Apple hardware . All other forms of Mac OS X virtualization are currently forbidden. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/22607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1367/"
]
} |
22,617 | I need to find out how to format numbers as strings. My code is here: return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm". Bottom line, what library / function do I need to do this for me? | Starting with Python 3.6, formatting in Python can be done using formatted string literals or f-strings : hours, minutes, seconds = 6, 56, 33f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}' or the str.format function starting with 2.7: "{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am") or the string formatting % operator for even older versions of Python, but see the note in the docs: "%02d:%02d:%02d" % (hours, minutes, seconds) And for your specific case of formatting time, there’s time.strftime : import timet = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)time.strftime('%I:%M:%S %p', t) | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/22617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2504/"
]
} |
22,623 | What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the Exception object's InnerException and stack trace are preserved. Is there a difference between the following code blocks in the way they handle this? try{ //some code}catch (Exception ex){ throw ex;} Vs: try{ //some code}catch{ throw;} | The way to preserve the stack trace is through the use of the throw; This is valid as well try { // something that bombs here} catch (Exception ex){ throw;} throw ex; is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the throw ex; statement. Mike is also correct, assuming the exception allows you to pass an exception (which is recommended). Karl Seguin has a great write up on exception handling in his foundations of programming e-book as well, which is a great read. Edit: Working link to Foundations of Programming pdf. Just search the text for "exception". | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/22623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
]
} |
22,674 | From a desktop application developer point of view, is there any difference between developing for Windows XP and developing for Windows Vista? | User Interface Looking at the Windows Vista User Experience Guidelines you can see that they have changed many UI elements, which you should be aware of. Some major things to take note of: Larger icons New font (Which affects some custom UI constistency) New dialog box features ( task dialogs ) Altered common dialogs (like File Open, Save As, etc.) Dialog text style and tone , and look and feel New Aero Wizards Redesigned toolbars Better notification UI New recommended method of including a search control Glass 64-bit Vista has a 64-bit edition, and although XP did too, your users are more likely to use Vista 64 than XP 64. Now you have to deal with: Registry virtualization Registry redirection ( Wow6432Node ) Registry reflection Digital signatures for kernel modules MSI installers have new properties to deal with UAC User Account Control vastly affects the default permissions that your application has when interacting with the OS. How UAC works and affects your application (also see the requirements doc ) Installers have to deal with UAC New APIs There are new APIs which are targeted at either new methods of application construction or allowing new functionality: Cryptography API: Next Generation (CNG) Extensible Application Markup Language (XAML) Windows Communication Foundation (WCF) Windows Workflow Foundation (WF) And many more smaller ones Installers Because installations can only use common runtimes they install after a transaction has completed, custom actions will fail if your custom action dll requires the Visual C++ runtimes above the VS 2005 CRT (non-SP1). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/22674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
22,676 | I have a small utility that I use to download an MP3 file from a website on a schedule and then builds/updates a podcast XML file which I've added to iTunes. The text processing that creates/updates the XML file is written in Python. However, I use wget inside a Windows .bat file to download the actual MP3 file. I would prefer to have the entire utility written in Python. I struggled to find a way to actually download the file in Python, thus why I resorted to using wget . So, how do I download the file using Python? | Use urllib.request.urlopen() : import urllib.requestwith urllib.request.urlopen('http://www.example.com/') as f: html = f.read().decode('utf-8') This is the most basic way to use the library, minus any error handling. You can also do more complex stuff such as changing headers. On Python 2, the method is in urllib2 : import urllib2response = urllib2.urlopen('http://www.example.com/')html = response.read() | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/22676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2109/"
]
} |
22,697 | What's the best framework for creating mock objects in Java? Why? What are the pros and cons of each framework? | I've had good success using Mockito . When I tried learning about JMock and EasyMock, I found the learning curve to be a bit steep (though maybe that's just me). I like Mockito because of its simple and clean syntax that I was able to grasp pretty quickly. The minimal syntax is designed to support the common cases very well, although the few times I needed to do something more complicated I found what I wanted was supported and easy to grasp. Here's an (abridged) example from the Mockito homepage: import static org.mockito.Mockito.*;List mockedList = mock(List.class);mockedList.clear();verify(mockedList).clear(); It doesn't get much simpler than that. The only major downside I can think of is that it won't mock static methods. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/22697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2030/"
]
} |
22,708 | How would you determine the column name (e.g. "AQ" or "BH") of the nth column in Excel? Edit: A language-agnostic algorithm to determine this is the main goal here. | I once wrote this function to perform that exact task: public static string Column(int column){ column--; if (column >= 0 && column < 26) return ((char)('A' + column)).ToString(); else if (column > 25) return Column(column / 26) + Column(column % 26 + 1); else throw new Exception("Invalid Column #" + (column + 1).ToString());} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/22708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940/"
]
} |
22,732 | I am trying to do some string concatenation/formatting, but it's putting all the parameters into the first placeholder. Code function CreateAppPoolScript([string]$AppPoolName, [string]$AppPoolUser, [string]$AppPoolPass){ # Command to create an IIS application pool $AppPoolScript = "cscript adsutil.vbs CREATE ""w3svc/AppPools/$AppPoolName"" IIsApplicationPool`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserName"" ""$AppPoolUser""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserPass"" ""$AppPoolPass""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/AppPoolIdentityType"" 3" return $AppPoolScript}$s = CreateAppPoolScript("name", "user", "pass")write-host $s Output cscript adsutil.vbs CREATE "w3svc/AppPools/name user pass" IIsApplicationPoolcscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserName" ""cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserPass" ""cscript adsutil.vbs SET "w3svc/AppPools/name user pass/AppPoolIdentityType" 3 | Lose the parentheses and commas. Calling your function as: $s = CreateAppPoolScript "name" "user" "pass" gives: cscript adsutil.vbs CREATE "w3svc/AppPools/name" IIsApplicationPoolcscript adsutil.vbs SET "w3svc/AppPools/name/WamUserName" "user"cscript adsutil.vbs SET "w3svc/AppPools/name/WamUserPass" "pass"cscript adsutil.vbs SET "w3svc/AppPools/name/AppPoolIdentityType" 3 | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/22732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
]
} |
22,792 | I'm working on an open source project that uses SQL Server 2005 as the data store. We need a DB compare tool to generate diff scripts to be able to upgrade a DB from one version to another. Is there an open source or free SQL Server DB diff tool out there that generates a convert script? | I think that Open DBiff does a good job.It's simple and I works with SQL Server 2005/2008. But only generate the change script. Nothing more and nothing less. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/22792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
]
} |
22,814 | I need to see the contents of the viewstate of an asp.net page. I looked for a viewstate decoder, found Fridz Onion's ViewState Decoder but it asks for the url of a page to get its viewstate. Since my viewstate is formed after a postback and comes as a result of an operation in an update panel, I cannot provide a url. I need to copy & paste the viewstate string and see what's inside. Is there a tool or a website exist that can help viewing the contents of viewstate? | Use Fiddler and grab the view state in the response and paste it into the bottom left text box then decode. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/22814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
]
} |
22,816 | I know the following libraries for drawing charts in an SWT/Eclipse RCP application: Eclipse BIRT Chart Engine (Links to an article on how to use it) JFreeChart Which other libraries are there for drawing pretty charts with SWT? Or charts in Java generally? After all, you can always display an image... | I have not used BIRT or JGraph, however I use JFreeChart in my SWT application. I have found the best way to use JFreeChart in SWT is by making a composite an AWT frame and using the AWT functionality for JFreeChart. The way to do this is by creating a composite Composite comp = new Composite(parent, SWT.NONE | SWT.EMBEDDED);Frame frame = SWT_AWT.new_Frame(comp);JFreeChart chart = createChart();ChartPanel chartPanel = new ChartPanel(chart);frame.add(chartPanel); There are several problems in regards to implementations across different platforms as well as the SWT code in it is very poor (in its defense Mr. Gilbert does not know SWT well and it is made for AWT). My two biggest problems are as AWT events bubble up through SWT there are some erroneous events fired and due to wrapping the AWT frame JFreeChart becomes substantially slower. @zvikico The idea of putting the chart into a web page is probably not a great way to go. There are a few problems first being how Eclipse handles integrating the web browser on different platforms is inconsistent. Also from my understanding of a few graphing packages for the web they are server side requiring that setup, also many companies including mine use proxy servers and sometimes this creates issues with the Eclipse web browsing. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/22816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1793/"
]
} |
22,836 | In Perl, what is a good way to perform a replacement on a string using a regular expression and store the value in a different variable, without changing the original? I usually just copy the string to a new variable then bind it to the s/// regex that does the replacement on the new string, but I was wondering if there is a better way to do this? $newstring = $oldstring;$newstring =~ s/foo/bar/g; | This is the idiom I've always used to get a modified copy of a string without changing the original: (my $newstring = $oldstring) =~ s/foo/bar/g; In perl 5.14.0 or later, you can use the new /r non-destructive substitution modifier : my $newstring = $oldstring =~ s/foo/bar/gr; NOTE: The above solutions work without g too. They also work with any other modifiers. SEE ALSO: perldoc perlrequick : Perl regular expressions quick start | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/22836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
]
} |
22,873 | It wasn't that long ago that I was a beginning coder, trying to find good books/tutorials on languages I wanted to learn. Even still, there are times I need to pick up a language relatively quickly for a new project I am working on. The point of this post is to document some of the best tutorials and books for these languages. I will start the list with the best I can find, but hope you guys out there can help with better suggestions/new languages. Here is what I found: Since this is now wiki editable, I am giving control up to the community. If you have a suggestion, please put it in this section. I decided to also add a section for general be a better programmer books and online references as well. Once again, all recommendations are welcome. General Programming Online Tutorials Foundations of Programming By Karl Seguin - From Codebetter, its C# based but the ideas ring true across the board, can't believe no-one's posted this yet actually. How to Write Unmaintainable Code - An anti manual that teaches you how to write code in the most unmaintable way possible. It would be funny if a lot of these suggestions didn't ring so true. The Programming Section of Wiki Books - suggested by Jim Robert as having a large amount of books/tutorials on multiple languages in various stages of completion Just the Basics To get a feel for a language. Books Code Complete - This book goes without saying, it is truely brilliant in too many ways to mention. The Pragmatic Programmer - The next best thing to working with a master coder, teaching you everything they know. Mastering Regular Expressions - Regular Expressions are an essential tool in every programmer's toolbox. This book, recommended by Patrick Lozzi is a great way to learn what they are capable of. Algorithms in C , C++ , and Java - A great way to learn all the classic algorithms if you find Knuth's books a bit too in depth. C Online Tutorials This tutorial seems to pretty consise and thourough, looked over the material and seems to be pretty good. Not sure how friendly it would be to new programmers though. Books K&R C - a classic for sure. It might be argued that all programmers should read it. C Primer Plus - Suggested by Imran as being the ultimate C book for beginning programmers. C: A Reference Manual - A great reference recommended by Patrick Lozzi. C++ Online Tutorials The tutorial on cplusplus.com seems to be the most complete. I found another tutorial here but it doesn't include topics like polymorphism, which I believe is essential. If you are coming from C, this tutorial might be the best for you. Another useful tutorial, C++ Annotation . In Ubuntu family you can get the ebook on multiple format(pdf, txt, Postscript, and LaTex) by installing c++-annotation package from Synaptic(installed package can be found in /usr/share/doc/c++-annotation/ . Books The C++ Programming Language - crucial for any C++ programmer. C++ Primer Plus - Orginally added as a typo, but the amazon reviews are so good, I am going to keep it here until someone says it is a dud. Effective C++ - Ways to improve your C++ programs. More Effective C++ - Continuation of Effective C++. Effective STL - Ways to improve your use of the STL. Thinking in C++ - Great book, both volumes. Written by Bruce Eckel and Chuck Ellison. Programming: Principles and Practice Using C++ - Stroustrup's introduction to C++. Accelerated C++ - Andy Koenig and Barbara Moo - An excellent introduction to C++ that doesn't treat C++ as "C with extra bits bolted on", in fact you dive straight in and start using STL early on. Forth Books FORTH, a text and reference. Mahlon G. Kelly and Nicholas Spies. ISBN 0-13-326349-5 / ISBN 0-13-326331-2. 1986 Prentice-Hall. Leo Brodie's books are good but this book is even better. For instance it covers defining words and the interpreter in depth. Java Online Tutorials Sun's Java Tutorials - An official tutorial that seems thourough, but I am not a java expert. You guys know of any better ones? Books Head First Java - Recommended as a great introductory text by Patrick Lozzi. Effective Java - Recommended by pek as a great intermediate text. Core Java Volume 1 and Core Java Volume 2 - Suggested by FreeMemory as some of the best java references available. Java Concurrency in Practice - Recommended by MDC as great resource for concurrent programming in Java. The Java Programing Language Python Online Tutorials Python.org - The online documentation for this language is pretty good. If you know of any better let me know. Dive Into Python - Suggested by Nickola. Seems to be a python book online. Perl Online Tutorials perldoc perl - This is how I personally got started with the language, and I don't think you will be able to beat it. Books Learning Perl - a great way to introduce yourself to the language. Programming Perl - greatly referred to as the Perl Bible. Essential reference for any serious perl programmer. Perl Cookbook - A great book that has solutions to many common problems. Modern Perl Programming - newly released, contains the latest wisdom on modern techniques and tools, including Moose and DBIx::Class. Ruby Online Tutorials Adam Mika suggested Why's (Poignant) Guide to Ruby but after taking a look at it, I don't know if it is for everyone.Found this site which seems to offer several tutorials for Ruby on Rails. Books Programming Ruby - suggested as a great reference for all things ruby. Visual Basic Online Tutorials Found this site which seems to devote itself to visual basic tutorials. Not sure how good they are though. PHP Online Tutorials The main PHP site - A simple tutorial that allows user comments for each page, which I really like. PHPFreaks Tutorials - Various tutorials of different difficulty lengths. Quakenet/PHP tutorials - PHP tutorial that will guide you from ground up. JavaScript Online Tutorials Found a decent tutorial here geared toward non-programmers. Found another more advanced one here . Nickolay suggested A reintroduction to javascript as a good read here. Books Head first JavaScript JavaScript: The Good Parts (with a Google Tech Talk video by the author) C# Online Tutorials C# Station Tutorial - Seems to be a decent tutorial that I dug up, but I am not a C# guy. C# Language Specification - Suggested by tamberg. Not really a tutorial, but a great reference on all the elements of C# Books C# to the point - suggested by tamberg as a short text that explains the language in amazing depth ocaml Books nlucaroni suggested the following: OCaml for Scientists Introduction to ocaml Using Understand and unraveling ocaml: practice to theory and vice versa Developing Applications using Ocaml - O'Reilly The Objective Caml System - Official Manua Haskell Online Tutorials nlucaroni suggested the following: Explore functional programming with Haskell Books Real World Haskell Total Functional Programming LISP/Scheme Books wfarr suggested the following: The Little Schemer - Introduction to Scheme and functional programming in general The Seasoned Schemer - Followup to Little Schemer. Structure and Interpretation of Computer Programs - The definitive book on Lisp (also available online ). Practical Common Lisp - A good introduction to Lisp with several examples of practical use. On Lisp - Advanced Topics in Lisp How to Design Programs - An Introduction to Computing and Programming Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp - an approach to high quality Lisp programming What about you guys? Am I totally off on some of there? Did I leave out your favorite language? I will take the best comments and modify the question with the suggestions. | I know this is going to seem old-fashioned, but I don't think much of using online tutorials to learn programming languages or platforms. These generally give you no more than a little taste of the language. To really learn a language, you need the equivalent of a "book", and in many cases, this means a real dead-tree book. If you want to learn C, read K&R. If you want to learn C++, read Stroustrup. If you want to learn Lisp/Scheme, read SICP. Etc. If you're not willing to spend more than $30 and a few hours to learn a language, you probably aren't going to learn it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/22873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2328/"
]
} |
22,880 | Specifically this is regarding when using a client session cookie to identify a session on the server. Is the best answer to use SSL/HTTPS encryption for the entire web site, and you have the best guarantee that no man in the middle attacks will be able to sniff an existing client session cookie? And perhaps second best to use some sort of encryption on the session value itself that is stored in your session cookie? If a malicious user has physical access to a machine, they can still look at the filesystem to retrieve a valid session cookie and use that to hijack a session? | Encrypting the session value will have zero effect. The session cookie is already an arbitrary value, encrypting it will just generate another arbitrary value that can be sniffed. The only real solution is HTTPS. If you don't want to do SSL on your whole site (maybe you have performance concerns), you might be able to get away with only SSL protecting the sensitive areas. To do that, first make sure your login page is HTTPS. When a user logs in, set a secure cookie (meaning the browser will only transmit it over an SSL link) in addition to the regular session cookie. Then, when a user visits one of your "sensitive" areas, redirect them to HTTPS, and check for the presence of that secure cookie. A real user will have it, a session hijacker will not. EDIT : This answer was originally written in 2008. It's 2016 now, and there's no reason not to have SSL across your entire site. No more plaintext HTTP! | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/22880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1341/"
]
} |
22,907 | Assuming you can't use LINQ for whatever reason, is it a better practice to place your queries in stored procedures, or is it just as good a practice to execute ad hoc queries against the database (say, SQL Server for argument's sake)? | In my experience writing mostly WinForms Client/Server apps these are the simple conclusions I've come to: Use Stored Procedures: For any complex data work. If you're going to be doing something truly requiring a cursor or temp tables it's usually fastest to do it within SQL Server. When you need to lock down access to the data. If you don't give table access to users (or role or whatever) you can be sure that the only way to interact with the data is through the SP's you create. Use ad-hoc queries: For CRUD when you don't need to restrict data access (or are doing so in another manner). For simple searches. Creating SP's for a bunch of search criteria is a pain and difficult to maintain. If you can generate a reasonably fast search query use that. In most of my applications I've used both SP's and ad-hoc sql, though I find I'm using SP's less and less as they end up being code just like C#, only harder to version control, test, and maintain. I would recommend using ad-hoc sql unless you can find a specific reason not to. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/22907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
22,976 | I've got a JavaScript "object", built this way: function foo(){ this.length = 0;}foo.prototype.getLength = function(){ return this.length;}... I know how to emulate namespaces with singleton JavaScript objects, but what is the best way to "namepace" an object such as that above that will intanced? I know that several JavaScript libraries have namepacing capabilities, but I'm using jQuery and would rather not add another library to the mix. I'd like to be able to provide my own, perhaps by exploiting jQuery, intrinsic namespacing scheme for the JS objects of mine that need to be instanced. Thanksrp | Simple: if(!MyNamespace) MyNamespace = {};MyNamespace.foo = function() { this.length = 0;};MyNamespace.foo.prototype.getLength = function() { return this.length;}; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/22976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2536/"
]
} |
23,082 | Did you ever have to choose between WISA or LAMP at the beginning of a web project? While pros and cons are littered around the net, it would be helpful to know about your real experience in coming up w/ criteria, evaluating, deciding, and reflecting upon your decision to go w/ either platform. | I think the first part is your Application. If you decide to go PHP, you almost automatically end up with LAMP, as WIMP or WISP stacks are quite rare (I think blog.stackoverflow.com runs on WIMP), and with .net you definitely want to go WISA. So normally, it boils down to .net vs. PHP. (Ignoring Ruby, Python and all the other stuff for a moment). When you made that decision, the rest comes naturally or adapts into your environment (i.e. if all your admins in the company are windows admins, maybe WAMP works better for you) I switched from PHP to .net about a year ago and I never looked back at PHP, but I never had to look at the bill for Windows and SQL Server licenses to be fair. Deployment on WISA has a much higher initial cost due to the licenses involved, whereas a LAMP Stack is free (Yes, MySQL is also free for commercial use). Addendum: All the funny acronyms stand for the combination of technologies: (L)inux or (W)indows, (A)pache or (I)IS, (M)ySQL or (S)QL Server, (P)hp or (A)SP.net. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/23082",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
23,083 | In the Windows applications I work on, we have a custom framework that sits directly above Win32 (don't ask). When we create a window, our normal practice is to put this in the window's user data area via SetWindowLong(hwnd, GWL_USERDATA, this) , which allows us to have an MFC-like callback or a tightly integrated WndProc , depending. The problem is that this will not work on 64-bit Windows, since LONG is only 32-bits wide. What's a better solution to this problem that works on both 32- and 64-bit systems? | SetWindowLongPtr was created to replace SetWindowLong in these instances. It's LONG_PTR parameter allows you to store a pointer for 32-bit or 64-bit compilations. LONG_PTR SetWindowLongPtr( HWND hWnd, int nIndex, LONG_PTR dwNewLong); Remember that the constants have changed too, so usage now looks like: SetWindowLongPtr(hWnd, GWLP_USERDATA, this); Also don't forget that now to retrieve the pointer, you must use GetWindowLongPtr : LONG_PTR GetWindowLongPtr( HWND hWnd, int nIndex); And usage would look like (again, with changed constants): LONG_PTR lpUserData = GetWindowLongPtr(hWnd, GWLP_USERDATA);MyObject* pMyObject = (MyObject*)lpUserData; | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/23083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2354/"
]
} |
23,102 | I'm pretty green still when it comes to web programming, I've spent most of my time on client applications. So I'm curious about the common exploits I should fear/test for in my site. | OWASP keeps a list of the Top 10 web attacks to watch our for, in addition to a ton of other useful security information for web development. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/23102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
]
} |
23,166 | I like to study languages outside my comfort zone, but I've had a hard time finding a place to start for functional languages. I heard a lot of good things about Structure and Interpretations of Computer Programs , but when I tried to read through it a couple of years ago it just seemed to whiz over my head. I do way better with books than web sites, but when I visit the local book store the books on LISP look kind of scary. So what's a good starting point? My goal is to be able to use a functional programming language to solve simple problems in 6 months or so, and the ability to move to more advanced topics, recognize when a functional language is the right tool for the job, and use the language to solve more problems over the course of 2-3 years. I like books that are heavy on examples but also include challenges to work through. Does such a thing exist for functional languages? | The Little Schemer teaches recursion really well, and it's fun and simple to read. I also liked The Scheme Programming Language for a broader introduction into the language. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/23166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2547/"
]
} |
23,217 | I've been making a concerted effort to improve my javascript skills lately by reading as much javascript code as I can. In doing this I've sometimes seen the javascript: prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciable difference between: onchange="javascript: myFunction(this)" and onchange="myFunction(this)" ? | Probably nothing in your example. My understanding is that javascript: is for anchor tags (in place of an actual href ). You'd use it so that your script can execute when the user clicks the link, but without initiating a navigation back to the page (which a blank href coupled with an onclick will do). For example: <a href="javascript:someFunction();">Blah</a> Rather than: <a href="" onclick="someFunction();">Blah</a> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/23217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1680/"
]
} |
23,228 | Compare String.Format("Hello {0}", "World"); with "Hello {0}".Format("World"); Why did the .Net designers choose a static method over an instance method? What do you think? | Because the Format method has nothing to do with a string's current value. That's true for all string methods because .NET strings are immutable. If it was non-static, you would need a string to begin with. It does: the format string. I believe this is just another example of the many design flaws in the .NET platform (and I don't mean this as a flame; I still find the .NET framework superior to most other frameworks). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/23228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2361/"
]
} |
23,250 | I was curious about how other people use the this keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples: In a constructor: public Light(Vector v){ this.dir = new Vector(v);} Elsewhere public void SomeMethod(){ Vector vec = new Vector(); double d = (vec * vec) - (this.radius * this.radius);} | There are several usages of this keyword in C#. To qualify members hidden by similar name To have an object pass itself as a parameter to other methods To have an object return itself from a method To declare indexers To declare extension methods To pass parameters between constructors To internally reassign value type (struct) value . To invoke an extension method on the current instance To cast itself to another type To chain constructors defined in the same class You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using auto-implemented properties . | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/23250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2016/"
]
} |
23,277 | I've read the Wikipedia articles for both procedural programming and functional programming , but I'm still slightly confused. Could someone boil it down to the core? | A functional language (ideally) allows you to write a mathematical function, i.e. a function that takes n arguments and returns a value. If the program is executed, this function is logically evaluated as needed. 1 A procedural language, on the other hand, performs a series of sequential steps. (There's a way of transforming sequential logic into functional logic called continuation passing style .) As a consequence, a purely functional program always yields the same value for an input, and the order of evaluation is not well-defined; which means that uncertain values like user input or random values are hard to model in purely functional languages. 1 As everything else in this answer, that’s a generalisation. This property, evaluating a computation when its result is needed rather than sequentially where it’s called, is known as “laziness”. Not all functional languages are actually universally lazy, nor is laziness restricted to functional programming. Rather, the description given here provides a “mental framework” to think about different programming styles that are not distinct and opposite categories but rather fluid ideas. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/23277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
]
} |
23,287 | What is the best approach to calculating the largest prime factor of a number? I'm thinking the most efficient would be the following: Find lowest prime number that divides cleanly Check if result of division is prime If not, find next lowest Go to 2. I'm basing this assumption on it being easier to calculate the small prime factors. Is this about right? What other approaches should I look into? Edit: I've now realised that my approach is futile if there are more than 2 prime factors in play, since step 2 fails when the result is a product of two other primes, therefore a recursive algorithm is needed. Edit again: And now I've realised that this does still work, because the last found prime number has to be the highest one, therefore any further testing of the non-prime result from step 2 would result in a smaller prime. | Actually there are several more efficient ways to find factors of big numbers (for smaller ones trial division works reasonably well). One method which is very fast if the input number has two factors very close to its square root is known as Fermat factorisation . It makes use of the identity N = (a + b)(a - b) = a^2 - b^2 and is easy to understand and implement. Unfortunately it's not very fast in general. The best known method for factoring numbers up to 100 digits long is the Quadratic sieve . As a bonus, part of the algorithm is easily done with parallel processing. Yet another algorithm I've heard of is Pollard's Rho algorithm . It's not as efficient as the Quadratic Sieve in general but seems to be easier to implement. Once you've decided on how to split a number into two factors, here is the fastest algorithm I can think of to find the largest prime factor of a number: Create a priority queue which initially stores the number itself. Each iteration, you remove the highest number from the queue, and attempt to split it into two factors (not allowing 1 to be one of those factors, of course). If this step fails, the number is prime and you have your answer! Otherwise you add the two factors into the queue and repeat. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/23287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1951/"
]
} |
23,288 | Where can I get some decent looking free ASP.Net or CSS themes? | I wouldn't bother looking for ASP.NET stuff specifically (probably won't find any anyways). Finding a good CSS theme easily can be used in ASP.NET. Here's some sites that I love for CSS goodness: http://www.freecsstemplates.org/ http://www.oswd.org/ http://www.openwebdesign.org/ http://www.styleshout.com/ http://www.freelayouts.com/ | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/23288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1287/"
]
} |
23,310 | What would be the best version control system to learn as a beginner to source control? | Anything but Visual Source Safe; preferably one which supports the concepts of branching and merging. As others have said, Subversion is a great choice, especially with the TortoiseSVN client. Be sure to check out (pardon the pun) Eric Sink's classic series of Source Control HOWTO articles . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/23310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453046/"
]
} |
23,373 | I have a simple little test app written in Flex 3 (MXML and some AS3). I can compile it to a SWF just fine, but I'd like to make it into an EXE so I can give it to a couple of my coworkers who might find it useful. With Flash 8, I could just target an EXE instead of a SWF and it would wrap the SWF in a projector, and everything worked fine. Is there an equivalent to that using the Flex 3 SDK that doesn't end up requiring AIR? Note: I don't have Flex Builder, I'm just using the free Flex 3 SDK. | In your Flex SDK folders you should see a 'runtimes\player\win\FlashPlayer.exe' which is a stand alone Flash player. Open your SWF with that and you'll see a 'Create Projector...' menu item in the File menu which will create the stand-alone EXE. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/23373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1409/"
]
} |
23,445 | I have two collections of the same object, Collection<Foo> oldSet and Collection<Foo> newSet . The required logic is as follow: if foo is in(*) oldSet but not newSet , call doRemove(foo) else if foo is not in oldSet but in newSet , call doAdd(foo) else if foo is in both collections but modified, call doUpdate(oldFoo, newFoo) else if !foo.activated && foo.startDate >= now , call doStart(foo) else if foo.activated && foo.endDate <= now , call doEnd(foo) (*) "in" means the unique identifier matches, not necessarily the content. The current (legacy) code does many comparisons to figure out removeSet , addSet , updateSet , startSet and endSet , and then loop to act on each item. The code is quite messy (partly because I have left out some spaghetti logic already) and I am trying to refactor it. Some more background info: As far as I know, the oldSet and newSet are actually backed by ArrayList Each set contains less than 100 items, most likely max out at 20 This code is called frequently (measured in millions/day), although the sets seldom differ My questions: If I convert oldSet and newSet into HashMap<Foo> (order is not of concern here), with the IDs as keys, would it made the code easier to read and easier to compare? How much of time & memory performance is loss on the conversion? Would iterating the two sets and perform the appropriate operation be more efficient and concise? | Apache's commons.collections library has a CollectionUtils class that provides easy-to-use methods for Collection manipulation/checking, such as intersection, difference, and union. The org.apache.commons.collections.CollectionUtils API docs are here . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/23445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2551/"
]
} |
23,566 | On IIS 6, what does an IIS reset do? Please compare to recycling an app pool and stopping and starting an ASP.NET web site. If you replace a DLL or edit/replace the web.config on an ASP.NET web site is that the same as stopping and starting that web site? | IISReset stops and restarts the entire web server (including non-ASP.NET apps) Recycling an app pool will only affect applications running in that app pool. Editing the web.config in a web application only affects that web application (recycles just that app). Editing the machine.config on the machine will recycle all app pools running. IIS will monitor the /bin directory of your application. Whenever a change is detected in those dlls, it will recycle the app and re-load those new dlls. It also monitors the web.config & machine.config in the same way and performs the same action for the applicable apps. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/23566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
]
} |
23,569 | How do you calculate the distance between 2 cities? | If you need to take the curvature of the earth into account, the Great-Circle distance is what you're looking for. The Wikipedia article probably does a better job of explaining how the formula works than me, and there's also this aviation formulary page that covers that goes into more detail. The formulas are only the first part of the puzzle though, if you need to make this work for arbitrary cities, you'll need a location database to get the lat/long from. Luckily you can get this for free from Geonames.org , although there are commercial db's available (ask google). So, in general, look up the two cities you want, get the lat/long co-orinates and plug them into the formula as in the Wikipedia Worked Example . Other suggestions: For a full commercial solution,there's PC Miler which is usedby many trucking companies tocalculate shipping rates. Make calls to the Google Maps (or other) api. If you need to do many requests per day, consider caching the results on the server. Also very important is to consider building an equivalence database for cities, suburbs, towns etc. if you think you'll ever need to group your data. This gets really complicated though, and you may not find a one-size-fits-all solution for your problem. Last but not least, Joel wrote an article about this problem a while back, so here you go: New Feature: Job Search | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/23569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2141/"
]
} |
23,578 | And on top of that, are there cases where one has to use the global assembly cache or where one cannot use it? | Loading assemblies from GAC mean less overhead and security that your application will always load correct version of .NET library You shouldn't ngen assemblies that are outside of GAC, because there will be almost no performance gain, in many cases even loss in performance. You're already using GAC, because all standard .NET assemblies are actually in GAC and ngened (during installation). Using GAC for your own libraries adds complexity into deployment, I would try to avoid it at all costs. Your users need to be logged as administrators during installation if you want to put something into GAC, quite a problem for many types of applications. So to sum it all, start simple and if you later see major performance gains if you put your assemblies into GAC and NGEN them, go for it, otherwise don't bother. GAC is more suitable for frameworks where there is expectation for library to be shared among more applications, in 99% of cases, you don't need it. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/23578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2374/"
]
} |
23,689 | Does anyone know of a .NET date/time parser similar to Chronic for Ruby (handles stuff like "tomorrow" or "3pm next thursday")? Note: I do write Ruby (which is how I know about Chronic) but this project must use .NET. | We developed exactly what you are looking for on an internal project. We are thinking of making this public if there is sufficient need for it. Take a look at this blog for more details: http://precisionsoftwaredesign.com/blog.php . Feel free to contact me if you are interested: [email protected] This library is now a SourceForge project. The page is at: http://www.SourceForge.net/p/naturaldate The assembly is in the downloads section, and the source is available with Mercurial. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/23689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/521/"
]
} |
23,755 | When implementing a needle search of a haystack in an object-oriented way, you essentially have three alternatives: 1. needle.find(haystack)2. haystack.find(needle)3. searcher.find(needle, haystack) Which do you prefer, and why? I know some people prefer the second alternative because it avoids introducing a third object. However, I can't help feeling that the third approach is more conceptually "correct", at least if your goal is to model "the real world". In which cases do you think it is justified to introduce helper objects, such as the searcher in this example, and when should they be avoided? | Usually actions should be applied to what you are doing the action on... in this case the haystack, so I think option 2 is the most appropriate. You also have a fourth alternative that I think would be better than alternative 3: haystack.find(needle, searcher) In this case, it allows you to provide the manner in which you want to search as part of the action, and so you can keep the action with the object that is being operated on. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/23755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1709/"
]
} |
23,770 | What are some strategies that people have had success with for maintaining a change history for data in a fairly complex database. One of the applications that I frequently use and develop for could really benefit from a more comprehensive way of tracking how records have changed over time. For instance, right now records can have a number of timestamp and modified user fields, but we currently don't have a scheme for logging multiple change, for instance if an operation is rolled back. In a perfect world, it would be possible to reconstruct the record as it was after each save, etc. Some info on the DB: Needs to have the capacity to grow by thousands of records per week 50-60 Tables Main revisioned tables may have several million records each Reasonable amount of foreign keys and indexes set Using PostgreSQL 8.x | In the past I have used triggers to construct db update/insert/delete logging. You could insert a record each time one of the above actions is done on a specific table into a logging table that keeps track of the action, what db user did it, timestamp, table it was performed on, and previous value. There is probably a better answer though as this would require you to cache the value before the actual delete or update was performed I think. But you could use this to do rollbacks. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/23770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2567/"
]
} |
23,787 | What is the best way to find something in a list? I know LINQ has some nice tricks, but let's also get suggestions for C# 2.0. Lets get the best refactorings for this common code pattern. Currently I use code like this: // mObjList is a List<MyObject>MyObject match = null;foreach (MyObject mo in mObjList){ if (Criteria(mo)) { match = mo; break; }} or // mObjList is a List<MyObject>bool foundIt = false;foreach (MyObject mo in mObjList){ if (Criteria(mo)) { foundIt = true; break; }} | @ Konrad: So how do you use it? Let's say I want to match mo.ID to magicNumber. In C# 2.0 you'd write: result = mObjList.Find(delegate(int x) { return x.ID == magicNumber; }); 3.0 knows lambdas: result = mObjList.Find(x => x.ID == magicNumber); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/23787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1490/"
]
} |
23,836 | Heavy emphasis on simple. I've never made an installer and I'd rather not have to learn much. A system that I could hand a pile of files to and it would make some smart guesses about where to put them would be ideal. Go ahead and answer the general question. However In my cases I'm stuck with some extra constraints. The program to be installed is written in VB6 (or is it 5?) and a few previous versions of VB, so it's not going to be updated any time soon. I have a running install and will have a Clean VM to play with So I'll be doing a loop of: run the install, find where it's broken, fix it, add that to the installer, revert the VM, try again. If anyone has a better approach I'm open to suggestions. I MUST get it working on XP and I'd really like to also have something that will work on newer versions of Windows as well. | InnoSetup or NSIS , whichever seems easier to you. ISTool is a nice GUI tool for InnoSetup which makes creating setup scripts even easier. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/23836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
]
} |
23,853 | I am using Struts + Velocity in a Java application, but after I submit a form, the confirmation page (Velocity template) shows the variable names instead an empty label, like the Age in following example: Name : Fernando Age : {person.age} Sex : Male I would like to know how to hide it! | You can mark variables as " silent " like this: $!variable If $variable is null, nothing will be rendered. If it is not null, its value will render as it normally would. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/23853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2274/"
]
} |
23,867 | The Close method on an ICommunicationObject can throw two types of exceptions as MSDN outlines here . I understand why the Close method can throw those exceptions, but what I don't understand is why the Dispose method on a service proxy calls the Close method without a try around it. Isn't your Dispose method the one place where you want make sure you don't throw any exceptions? | You can mark variables as " silent " like this: $!variable If $variable is null, nothing will be rendered. If it is not null, its value will render as it normally would. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/23867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
]
} |
23,899 | I've got to do some significant development in a large, old, spaghetti-ridden ASP system. I've been away from ASP for a long time, focusing my energies on Rails development. One basic step I've taken is to refactor pages into subs and functions with meaningful names, so that at least it's easy to understand @ the top of the file what's generally going on. Is there a worthwhile MVC framework for ASP? Or a best practice at how to at least get business logic out of the views? (I remember doing a lot of includes back in the day -- is that still the way to do it?) I'd love to get some unit testing going for business logic too, but maybe I'm asking too much? Update: There are over 200 ASP scripts in the project, some thousands of lines long ;) UGH! We may opt for the "big rewrite" but until then, when I'm in changing a page, I want to spend a little extra time cleaning up the spaghetti. | Assumptions The documentation for the Classic ASP system is rather light. Management is not looking for a rewrite. Since you have been doing ruby on rails, your (VB/C#) ASP.NET is passable at best. My experience I too inherited a classic ASP system that was slapped together willy-nilly by ex excel-vba types. There was a lot of this stuff <font size=3>crap</font> (and sometimes missing closing tags; Argggh!). Over the course of 2.5 years I added a security system, a common library, CSS+XHTML and was able to coerce the thing to validate xhtml1.1 (sans proper mime type, unfortunately) and built a fairly robust and ajaxy reporting system that's being used daily by 80 users. I used jEdit, with cTags (as mentioned by jamting above), and a bunch of other plugins. My Advice Try to create a master include file from which to import all the stuff that's commonly used. Stuff like login/logout, database access, web services, javascript libs, etc. Do use classes. They are ultra-primitive (no inheritance) but as jamting said, they can be convenient. Indent the scripts properly. Comment Write an external architecture document. I personally use LyX, because it's brain-dead to produce a nicely formatted pdf, but you can use whatever you like. If you use a wiki, get the graphviz add-in installed and use it. It's super easy to make quick diagrams that can be easily modified. Since I have no idea how substantial the enhancements need to be, I suggest having a good high-level to mid-level architecture document will be quite useful in planning the enhancements. On the business logic unit tests, the only thing I found that works is setting up an xml-rpc listener in asp that imports the main library and exposes the functions (not subroutines though) in any of the main library's sub-includes, and then build, separately, a unit test system in a language with better support for the stuff that calls the ASP functions through xml-rpc. I use python, but I think Ruby should do the trick. (Does that make sense?). The cool thing is that the person writing the unit-test part of the software does not need to even look at the ASP code, as long as they have decent descriptions of the functions to call, so they can be someone beside you. There is a project called aspunit at sourceforge but the last release was in 2004 and it's marked as inactive. Never used it but it's pure vbscript. A cursory look at the code tells me it looks like the authors knew what they were doing. Finally, if you need help, I have some availability to do contract telecommuting work (maybe 8 hours/week max). Follow the link trail for contact info. Good luck! HTH. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/23899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2477/"
]
} |
23,907 | Basically I want to get the number of lines-of-code in the repository after each commit. The only (really crappy) ways I have found is to use git filter-branch to run wc -l * , and a script that runs git reset --hard on each commit, then runs wc -l To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on. This is what I want the tool to output (as an example): me@something:~/$ gitsloc --branch master104815345017341542 I've played around with the ruby 'git' library, but the closest I found was using the .lines() method on a diff, which seems like it should give the added lines (but does not: it returns 0 when you delete lines for example) require 'rubygems'require 'git'total = 0g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api') last = nilg.log.each do |cur| diff = g.diff(last, cur) total = total + diff.lines puts total last = curend | You might also consider gitstats , which generates this graph as an html file. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/23907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
]
} |
23,930 | I want to see all the different ways you can come up with, for a factorial subroutine, or program. The hope is that anyone can come here and see if they might want to learn a new language. Ideas: Procedural Functional Object Oriented One liners Obfuscated Oddball Bad Code Polyglot Basically I want to see an example, of different ways of writing an algorithm, and what they would look like in different languages. Please limit it to one example per entry.I will allow you to have more than one example per answer, if you are trying to highlight a specific style, language, or just a well thought out idea that lends itself to being in one post. The only real requirement is it must find the factorial of a given argument, in all languages represented. Be Creative! Recommended Guideline: # Language Name: Optional Style type - Optional bullet points Code Goes HereOther informational text goes here I will ocasionally go along and edit any answer that does not have decent formatting. | Polyglot: 5 languages, all using bignums So, I wrote a polyglot which works in the three languages I often write in, as well as one from my other answer to this question and one I just learned today. It's a standalone program, which reads a single line containing a nonnegative integer and prints a single line containing its factorial. Bignums are used in all languages, so the maximum computable factorial depends only on your computer's resources. Perl : uses built-in bignum package. Run with perl FILENAME . Haskell : uses built-in bignums. Run with runhugs FILENAME or your favorite compiler's equivalent. C++ : requires GMP for bignum support. To compile with g++, use g++ -lgmpxx -lgmp -x c++ FILENAME to link against the right libraries. After compiling, run ./a.out . Or use your favorite compiler's equivalent. brainf*ck : I wrote some bignum support in this post . Using Muller's classic distribution , compile with bf < FILENAME > EXECUTABLE . Make the output executable and run it. Or use your favorite distribution. Whitespace : uses built-in bignum support. Run with wspace FILENAME . Edit: added Whitespace as a fifth language. Incidentally, do not wrap the code with <code> tags; it breaks the Whitespace. Also, the code looks much nicer in fixed-width. char //# b=0+0{- |0*/; #>>>>,----------[>>>>,--------#definea/*#--]>>>>++<<<<<<<<[>++++++[<------>-]<-<<<#Perl><><><> <> <> <<]>>>>[[>>+<<-]>>[<<+>+>-]<->#C++--><><><><><><> < > <+<[>>>>+<<<-<[-]]>[-]#Haskell >>]>[-<<<<<[<<<<]>>>>[[>>+<<-]>>[<<+>+>-]>>]#Whitespace>>>>[-[>+<-]+>>>>]<<<<[<<<<]<<<<[<<<<#brainf*ck > < ]>>>>>[>>>[>>>>]>>>>[>>>>]<<<<[[>>>>*/exp; ;//;#+<<<<-]<<<<]>>>>+<<<<<<<[<<<<][.POLYGLOT^5.#include <gmpxx.h>//]>>>>-[>>>[>>>>]>>>>[>>>>]<<<<[>>#defineeval intmain()//>+<<<-]>>>[<<<+>>+>->#include <iostream>//<]<-[>>+<<[-]]<<[<<<<]>>>>[>[>>>#defineprint std::cout<< // ><+<-]>[<<+>+>-]<<[>>>#definez std::cin>>//<< +<<<-]>>>[<<<+>>+>-]<->+++++#define c/*++++[-<[-[>>>>+<<<<-]]>>>>[<<<<+>>>>-]<<*/#defineabs int $n //><<]<[>>+<<<<[-]>>[<<+>>-]]>>]<#defineuc mpz_class fact(int$n){/*<<<[<<<<]<<<[<<use bignum;sub#<<]>>>>-]>>>>]>>>[>[-]>>>]<<<<[>>+<<-]z{$_[0+0]=readline(*STDIN);}sub fact{my($n)=shift;#>>#[<<+>+>-]<->+<[>-<[-]]>[-<<-<<<<[>>+<<-]>>[<<+>+>+*/uc;if($n==0){return 1;}return $n*fact($n-1);}//;#eval{abs;z($n);print fact($n);print("\n")/*2;};#-]<->'+<[>-<[-]]>]<<[<<<<]<<<<-[>>+<<-]>>[<<+>+>-]+<[>-+++-}--<[-]]>[-<<++++++++++<<<<-[>>+<<-]>>[<<+>+>-++fact 0= 1 -- ><><><><> <><><]+<[>-<[-]]>]<<[<<+ +factn=n*fact(n-1){-<<]>>>>[[>>+<<-]>>[<<+>+++>+-}main=do{n<-readLn;print(fact n)}-- +>-]<->+<[>>>>+<<+{-x<-<[-]]>[-]>>]>]>>>[>>>>]<<<<[>+++++++[<+++++++>-]<--.<<<<]+written+by+++A+Rex+++2009+.';#+++x-}--x*/;} | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/23930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1337/"
]
} |
23,931 | Given two different image files (in whatever format I choose), I need to write a program to predict the chance if one being the illegal copy of another. The author of the copy may do stuff like rotating, making negative, or adding trivial details (as well as changing the dimension of the image). Do you know any algorithm to do this kind of job? | These are simply ideas I've had thinking about the problem, never tried it but I like thinking about problems like this! Before you begin Consider normalising the pictures, if one is a higher resolution than the other, consider the option that one of them is a compressed version of the other, therefore scaling the resolution down might provide more accurate results. Consider scanning various prospective areas of the image that could represent zoomed portions of the image and various positions and rotations. It starts getting tricky if one of the images are a skewed version of another, these are the sort of limitations you should identify and compromise on. Matlab is an excellent tool for testing and evaluating images. Testing the algorithms You should test (at the minimum) a large human analysed set of test data where matches are known beforehand. If for example in your test data you have 1,000 images where 5% of them match, you now have a reasonably reliable benchmark. An algorithm that finds 10% positives is not as good as one that finds 4% of positives in our test data. However, one algorithm may find all the matches, but also have a large 20% false positive rate, so there are several ways to rate your algorithms. The test data should attempt to be designed to cover as many types of dynamics as possible that you would expect to find in the real world. It is important to note that each algorithm to be useful must perform better than random guessing, otherwise it is useless to us! You can then apply your software into the real world in a controlled way and start to analyse the results it produces. This is the sort of software project which can go on for infinitum, there are always tweaks and improvements you can make, it is important to bear that in mind when designing it as it is easy to fall into the trap of the never ending project. Colour Buckets With two pictures, scan each pixel and count the colours. For example you might have the 'buckets': whiteredbluegreenblack (Obviously you would have a higher resolution of counters). Every time you find a 'red' pixel, you increment the red counter. Each bucket can be representative of spectrum of colours, the higher resolution the more accurate but you should experiment with an acceptable difference rate. Once you have your totals, compare it to the totals for a second image. You might find that each image has a fairly unique footprint, enough to identify matches. Edge detection How about using Edge Detection . (source: wikimedia.org ) With two similar pictures edge detection should provide you with a usable and fairly reliable unique footprint. Take both pictures, and apply edge detection. Maybe measure the average thickness of the edges and then calculate the probability the image could be scaled, and rescale if necessary. Below is an example of an applied Gabor Filter (a type of edge detection) in various rotations. Compare the pictures pixel for pixel, count the matches and the non matches. If they are within a certain threshold of error, you have a match. Otherwise, you could try reducing the resolution up to a certain point and see if the probability of a match improves. Regions of Interest Some images may have distinctive segments/regions of interest. These regions probably contrast highly with the rest of the image, and are a good item to search for in your other images to find matches. Take this image for example: (source: meetthegimp.org ) The construction worker in blue is a region of interest and can be used as a search object. There are probably several ways you could extract properties/data from this region of interest and use them to search your data set. If you have more than 2 regions of interest, you can measure the distances between them. Take this simplified example: (source: per2000.eu ) We have 3 clear regions of interest. The distance between region 1 and 2 may be 200 pixels, between 1 and 3 400 pixels, and 2 and 3 200 pixels. Search other images for similar regions of interest, normalise the distance values and see if you have potential matches. This technique could work well for rotated and scaled images. The more regions of interest you have, the probability of a match increases as each distance measurement matches. It is important to think about the context of your data set. If for example your data set is modern art, then regions of interest would work quite well, as regions of interest were probably designed to be a fundamental part of the final image. If however you are dealing with images of construction sites, regions of interest may be interpreted by the illegal copier as ugly and may be cropped/edited out liberally. Keep in mind common features of your dataset, and attempt to exploit that knowledge. Morphing Morphing two images is the process of turning one image into the other through a set of steps: Note, this is different to fading one image into another! There are many software packages that can morph images. It's traditionaly used as a transitional effect, two images don't morph into something halfway usually, one extreme morphs into the other extreme as the final result. Why could this be useful? Dependant on the morphing algorithm you use, there may be a relationship between similarity of images, and some parameters of the morphing algorithm. In a grossly over simplified example, one algorithm might execute faster when there are less changes to be made. We then know there is a higher probability that these two images share properties with each other. This technique could work well for rotated, distorted, skewed, zoomed, all types of copied images. Again this is just an idea I have had, it's not based on any researched academia as far as I am aware (I haven't look hard though), so it may be a lot of work for you with limited/no results. Zipping Ow's answer in this question is excellent, I remember reading about these sort of techniques studying AI. It is quite effective at comparing corpus lexicons. One interesting optimisation when comparing corpuses is that you can remove words considered to be too common, for example 'The', 'A', 'And' etc. These words dilute our result, we want to work out how different the two corpus are so these can be removed before processing. Perhaps there are similar common signals in images that could be stripped before compression? It might be worth looking into. Compression ratio is a very quick and reasonably effective way of determining how similar two sets of data are. Reading up about how compression works will give you a good idea why this could be so effective. For a fast to release algorithm this would probably be a good starting point. Transparency Again I am unsure how transparency data is stored for certain image types, gif png etc, but this will be extractable and would serve as an effective simplified cut out to compare with your data sets transparency. Inverting Signals An image is just a signal. If you play a noise from a speaker, and you play the opposite noise in another speaker in perfect sync at the exact same volume, they cancel each other out. (source: themotorreport.com.au ) Invert on of the images, and add it onto your other image. Scale it/loop positions repetitively until you find a resulting image where enough of the pixels are white (or black? I'll refer to it as a neutral canvas) to provide you with a positive match, or partial match. However, consider two images that are equal, except one of them has a brighten effect applied to it: (source: mcburrz.com ) Inverting one of them, then adding it to the other will not result in a neutral canvas which is what we are aiming for. However, when comparing the pixels from both original images, we can definatly see a clear relationship between the two. I haven't studied colour for some years now, and am unsure if the colour spectrum is on a linear scale, but if you determined the average factor of colour difference between both pictures, you can use this value to normalise the data before processing with this technique. Tree Data structures At first these don't seem to fit for the problem, but I think they could work. You could think about extracting certain properties of an image (for example colour bins) and generate a huffman tree or similar data structure. You might be able to compare two trees for similarity. This wouldn't work well for photographic data for example with a large spectrum of colour, but cartoons or other reduced colour set images this might work. This probably wouldn't work, but it's an idea. The trie datastructure is great at storing lexicons, for example a dictionarty. It's a prefix tree. Perhaps it's possible to build an image equivalent of a lexicon, (again I can only think of colours) to construct a trie. If you reduced say a 300x300 image into 5x5 squares, then decompose each 5x5 square into a sequence of colours you could construct a trie from the resulting data. If a 2x2 square contains: FFFFFF|000000|FDFD44|FFFFFF We have a fairly unique trie code that extends 24 levels, increasing/decreasing the levels (IE reducing/increasing the size of our sub square) may yield more accurate results. Comparing trie trees should be reasonably easy, and could possible provide effective results. More ideas I stumbled accross an interesting paper breif about classification of satellite imagery , it outlines: Texture measures considered are: cooccurrence matrices, gray-level differences, texture-tone analysis, features derived from the Fourier spectrum, and Gabor filters. Some Fourier features and some Gabor filters were found to be good choices, in particular when a single frequency band was used for classification. It may be worth investigating those measurements in more detail, although some of them may not be relevant to your data set. Other things to consider There are probably a lot of papers on this sort of thing, so reading some of them should help although they can be very technical. It is an extremely difficult area in computing, with many fruitless hours of work spent by many people attempting to do similar things. Keeping it simple and building upon those ideas would be the best way to go. It should be a reasonably difficult challenge to create an algorithm with a better than random match rate, and to start improving on that really does start to get quite hard to achieve. Each method would probably need to be tested and tweaked thoroughly, if you have any information about the type of picture you will be checking as well, this would be useful. For example advertisements, many of them would have text in them, so doing text recognition would be an easy and probably very reliable way of finding matches especially when combined with other solutions. As mentioned earlier, attempt to exploit common properties of your data set. Combining alternative measurements and techniques each that can have a weighted vote (dependant on their effectiveness) would be one way you could create a system that generates more accurate results. If employing multiple algorithms, as mentioned at the begining of this answer, one may find all the positives but have a false positive rate of 20%, it would be of interest to study the properties/strengths/weaknesses of other algorithms as another algorithm may be effective in eliminating false positives returned from another. Be careful to not fall into attempting to complete the never ending project, good luck! | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/23931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
23,962 | For example,Look at the code that calculates the n-th Fibonacci number: fib(int n){ if(n==0 || n==1) return 1; return fib(n-1) + fib(n-2);} The problem with this code is that it will generate stack overflow error for any number greater than 15 (in most computers). Assume that we are calculating fib(10). In this process, say fib(5) is calculated a lot of times. Is there some way to store this in memory for fast retrieval and thereby increase the speed of recursion? I am looking for a generic technique that can be used in almost all problems. | Yes your insight is correct.This is called dynamic programming . It is usually a common memory runtime trade-off. In the case of fibo, you don't even need to cache everything : [edit]The author of the question seems to be looking for a general method to cache rather than a method to compute Fibonacci. Search wikipedia or look at the code of the other poster to get this answer. Those answers are linear in time and memory. **Here is a linear-time algorithm O(n), constant in memory ** in OCaml:let rec fibo n = let rec aux = fun | 0 -> (1,1) | n -> let (cur, prec) = aux (n-1) in (cur+prec, cur) let (cur,prec) = aux n in prec;;in C++:int fibo(int n) { if (n == 0 ) return 1; if (n == 1 ) return 1; int p = fibo(0); int c = fibo(1); int buff = 0; for (int i=1; i < n; ++i) { buff = c; c = p+c; p = buff; }; return c;}; This perform in linear time. But log is actually possible !!!Roo's program is linear too, but way slower, and use memory. Here is the log algorithm O(log(n)) Now for the log-time algorithm (way way way faster), here is a method :If you know u(n), u(n-1), computing u(n+1), u(n) can be done by applying a matrix: | u(n+1) | = | 1 1 | | u(n) || u(n) | | 1 0 | | u(n-1) | So that you have : | u(n) | = | 1 1 |^(n-1) | u(1) | = | 1 1 |^(n-1) | 1 || u(n-1) | | 1 0 | | u(0) | | 1 0 | | 1 | Computing the exponential of the matrix has a logarithmic complexity. Just implement recursively the idea : M^(0) = IdM^(2p+1) = (M^2p) * MM^(2p) = (M^p) * (M^p) // of course don't compute M^p twice here. You can also just diagonalize it (not to difficult), you will find the gold number and its conjugate in its eigenvalue, and the result will give you an EXACT mathematical formula for u(n). It contains powers of those eigenvalues, so that the complexity will still be logarithmic. Fibo is often taken as an example to illustrate Dynamic Programming, but as you see, it is not really pertinent. @John:I don't think it has anything to do with do with hash. @John2:A map is a bit general don't you think? For Fibonacci case, all the keys are contiguous so that a vector is appropriate, once again there are much faster ways to compute fibo sequence, see my code sample over there. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/23962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
]
} |
23,963 | What is the minimum set of HTTP verbs that a server should allow for a web service to be classed as RESTful? What if my hoster doesn't permit PUT and DELETE ? Is this actually important, can I live happily ever after with just GET and POST ? Update: Thanks for the answers folks, Roger's answer was probably best because of the link to the Bill Venners and Elliotte Rusty Harold interview. I now get it. | Yes, you can live without PUT and DELETE. This article tells you why: http://www.artima.com/lejava/articles/why_put_and_delete.html While to true RESTafrians this may be heresy, in the real world you do what you can, with what you have. Be as rational as you can and as consistent with your own convention as you can, but you can definitely build a good RESTful system without P and D. rp | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/23963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419/"
]
} |
23,970 | Joe Van Dyk asked the Ruby mailing list : Hi, In Ruby, I guess you can't marshal a lambda/proc object, right? Is that possible in lisp or other languages? What I was trying to do: l = lamda { ... }Bj.submit "/path/to/ruby/program", :stdin => Marshal.dump(l) So, I'm sending BackgroundJob a lambda object, which contains the context/code for what to do. But, guess that wasn't possible. I ended up marshaling a normal ruby object that contained instructions for what to do after the program ran. Joe | You cannot marshal a Lambda or Proc. This is because both of them are considered closures, which means they close around the memory on which they were defined and can reference it. (In order to marshal them you'd have to Marshal all of the memory they could access at the time they were created.) As Gaius pointed out though, you can use ruby2ruby to get a hold of the string of the program. That is, you can marshal the string that represents the ruby code and then reevaluate it later. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/23970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
]
} |
24,041 | I'm using markdown to edit this question right now. In some wikis I used wiki markup. Are they the same thing? Are they related? Please explain. If I want to implement one or the other in a web project (like stackoverflow) what do I need to use? | Markup is a generic term for a language that describes a document's formatting Markdown is a specific markup library: http://daringfireball.net/projects/markdown/ These days the term is more commonly used to refer to markup languages that mimic the style of the library. See: https://en.wikipedia.org/wiki/Markdown | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/24041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1363/"
]
} |
24,045 | I currently use AnkhSVN to integrate subversion into Visual Studio. Is there any reason I should switch to VisualSVN? AnkhSVN is free (in more than one sense of the word) while VisualSVN costs $50. So right there unless I'm missing some great feature of VisualSVN I don't see any reason to switch. | I used VisualSVN until Ankh hit 2.0, and ever since, I've abandoned VisualSVN. Ankh has surpassed VisualSVN in functionality, in my mind, and all the 1.x perf and integration issues are gone. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/24045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163/"
]
} |
24,109 | I want to expand my programming horizons to Linux. A good, dependable basic toolset is important, and what is more basic than an IDE? I could find these SO topics: Lightweight IDE for linux and What tools do you use to developC++ applications on Linux? I'm not looking for a lightweight IDE. If an IDE is worth the money, then I will pay for it, so it need not be free. My question, then: What good, C++ programming IDE is available for Linux? The minimums are fairly standard: syntax highlighting, code completion (like intellisense or its Eclipse counterpart) and integrated debugging (e.g., basicbreakpoints). I have searched for it myself, but there are so many that it is almost impossible to separate the good from the bads by hand, especially for someone like me who has little C++ coding experience in Linux. I know that Eclipse supports C++ , and I really like that IDE for Java, but is it any good for C++ and is there something better? The second post actually has some good suggestions, but what I am missing is what exactly makes the sugested IDE so good for the user, what are its (dis)advantages? Maybe my question should therefore be: What IDE do you propose (given your experiences), and why? | Initially: confusion When originally writing this answer, I had recently made the switch from Visual Studio (with years of experience) to Linux and the first thing I did was try to find a reasonable IDE. At the time this was impossible: no good IDE existed. Epiphany: UNIX is an IDE. All of it. 1 And then I realised that the IDE in Linux is the command line with its tools: First you set up your shell Bash, in my case, but many people prefer fish or (Oh My) Zsh ; and your editor; pick your poison — both are state of the art: Neovim 2 or Emacs . Depending on your needs, you will then have to install and configure several plugins to make the editor work nicely (that’s the one annoying part). For example, most programmers on Vim will benefit from the YouCompleteMe plugin for smart autocompletion. Once that’s done, the shell is your command interface to interact with the various tools — Debuggers (gdb), Profilers (gprof, valgrind), etc. You set up your project/build environment using Make , CMake , SnakeMake or any of the various alternatives. And you manage your code with a version control system (most people use Git ). You also use tmux (previously also screen) to multiplex (= think multiple windows/tabs/panels) and persist your terminal session. The point is that, thanks to the shell and a few tool writing conventions, these all integrate with each other . And that way the Linux shell is a truly integrated development environment , completely on par with other modern IDEs. (This doesn’t mean that individual IDEs don’t have features that the command line may be lacking, but the inverse is also true.) To each their own I cannot overstate how well the above workflow functions once you’ve gotten into the habit. But some people simply prefer graphical editors, and in the years since this answer was originally written, Linux has gained a suite of excellent graphical IDEs for several different programming languages (but not, as far as I’m aware, for C++). Do give them a try even if — like me — you end up not using them. Here’s just a small and biased selection: For Python development, there’s PyCharm For R, there’s RStudio For JavaScript and TypeScript, there’s Visual Studio Code (which is also a good all-round editor) And finally, many people love the Sublime Text editor for general code editing. Keep in mind that this list is far from complete. 1 I stole that title from dsm’s comment. 2 I used to refer to Vim here. And while plain Vim is still more than capable, Neovim is a promising restart, and it’s modernised a few old warts. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/24109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/46/"
]
} |
24,179 | I'm interested in finding out how the recently-released ( http://mirror.facebook.com/facebook/hive/hadoop-0.17/ ) Hive compares to HBase in terms of performance. The SQL-like interface used by Hive is very much preferable to the HBase API we have implemented. | It's hard to find much about Hive, but I found this snippet on the Hive site that leans heavily in favor of HBase (bold added): Hive is based on Hadoop which is a batch processing system. Accordingly, this system does not and cannot promise low latencies on queries . The paradigm here is strictly of submitting jobs and being notified when the jobs are completed as opposed to real time queries. As a result it should not be compared with systems like Oracle where analysis is done on a significantly smaller amount of data but the analysis proceeds much more iteratively with the response times between iterations being less than a few minutes. For Hive queries response times for even the smallest jobs can be of the order of 5-10 minutes and for larger jobs this may even run into hours. Since HBase and HyperTable are all about performance (being modeled on Google's BigTable), they sound like they would certainly be much faster than Hive, at the cost of functionality and a higher learning curve (e.g., they don't have joins or the SQL-like syntax). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/24179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2588/"
]
} |
24,200 | I am hitting some performance bottlenecks with my C# client inserting bulk data into a SQL Server 2005 database and I'm looking for ways in which to speed up the process. I am already using the SqlClient.SqlBulkCopy (which is based on TDS) to speed up the data transfer across the wire which helped a lot, but I'm still looking for more. I have a simple table that looks like this: CREATE TABLE [BulkData]( [ContainerId] [int] NOT NULL, [BinId] [smallint] NOT NULL, [Sequence] [smallint] NOT NULL, [ItemId] [int] NOT NULL, [Left] [smallint] NOT NULL, [Top] [smallint] NOT NULL, [Right] [smallint] NOT NULL, [Bottom] [smallint] NOT NULL, CONSTRAINT [PKBulkData] PRIMARY KEY CLUSTERED ( [ContainerIdId] ASC, [BinId] ASC, [Sequence] ASC)) I'm inserting data in chunks that average about 300 rows where ContainerId and BinId are constant in each chunk and the Sequence value is 0-n and the values are pre-sorted based on the primary key. The %Disk time performance counter spends a lot of time at 100% so it is clear that disk IO is the main issue but the speeds I'm getting are several orders of magnitude below a raw file copy. Does it help any if I: Drop the Primary key while I am doing the inserting and recreate it later Do inserts into a temporary table with the same schema and periodically transfer them into the main table to keep the size of the table where insertions are happening small Anything else? --Based on the responses I have gotten, let me clarify a little bit: Portman: I'm using a clustered index because when the data is all imported I will need to access data sequentially in that order. I don't particularly need the index to be there while importing the data. Is there any advantage to having a nonclustered PK index while doing the inserts as opposed to dropping the constraint entirely for import? Chopeen: The data is being generated remotely on many other machines (my SQL server can only handle about 10 currently, but I would love to be able to add more). It's not practical to run the entire process on the local machine because it would then have to process 50 times as much input data to generate the output. Jason: I am not doing any concurrent queries against the table during the import process, I will try dropping the primary key and see if that helps. | Here's how you can disable/enable indexes in SQL Server: --Disable Index ALTER INDEX [IX_Users_UserID] SalesDB.Users DISABLEGO--Enable Index ALTER INDEX [IX_Users_UserID] SalesDB.Users REBUILD Here are some resources to help you find a solution: Some bulk loading speed comparisons Use SqlBulkCopy to Quickly Load Data from your Client to SQL Server Optimizing Bulk Copy Performance Definitely look into NOCHECK and TABLOCK options: Table Hints (Transact-SQL) INSERT (Transact-SQL) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/24200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1948/"
]
} |
24,221 | What is the purpose of annotations in Java? I have this fuzzy idea of them as somewhere in between a comment and actual code. Do they affect the program at run time? What are their typical usages? Are they unique to Java? Is there a C++ equivalent? | Annotations are primarily used by code that is inspecting other code. They are often used for modifying (i.e. decorating or wrapping) existing classes at run-time to change their behavior. Frameworks such as JUnit and Hibernate use annotations to minimize the amount of code you need to write yourself to use the frameworks. Oracle has a good explanation of the concept and its meaning in Java on their site. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/24221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/142/"
]
} |
24,270 | As far as I can tell, in spite of the countless millions or billions spent on OOP education, languages, and tools, OOP has not improved developer productivity or software reliability, nor has it reduced development costs. Few people use OOP in any rigorous sense (few people adhere to or understand principles such as LSP); there seems to be little uniformity or consistency to the approaches that people take to modelling problem domains. All too often, the class is used simply for its syntactic sugar; it puts the functions for a record type into their own little namespace. I've written a large amount of code for a wide variety of applications. Although there have been places where true substitutable subtyping played a valuable role in the application, these have been pretty exceptional. In general, though much lip service is given to talk of "re-use" the reality is that unless a piece of code does exactly what you want it to do, there's very little cost-effective "re-use". It's extremely hard to design classes to be extensible in the right way , and so the cost of extension is normally so great that "re-use" simply isn't worthwhile. In many regards, this doesn't surprise me. The real world isn't "OO", and the idea implicit in OO--that we can model things with some class taxonomy--seems to me very fundamentally flawed (I can sit on a table, a tree stump, a car bonnet, someone's lap--but not one of those is-a chair). Even if we move to more abstract domains, OO modelling is often difficult, counterintuitive, and ultimately unhelpful (consider the classic examples of circles/ellipses or squares/rectangles). So what am I missing here? Where's the value of OOP, and why has all the time and money failed to make software any better? | The real world isn't "OO", and the idea implicit in OO--that we can model things with some class taxonomy--seems to me very fundamentally flawed While this is true and has been observed by other people (take Stepanov, inventor of the STL), the rest is nonsense. OOP may be flawed and it certainly is no silver bullet but it makes large-scale applications much simpler because it's a great way to reduce dependencies. Of course, this is only true for “good” OOP design. Sloppy design won't give any advantage. But good, decoupled design can be modelled very well using OOP and not well using other techniques. There are much better, more universal models ( Haskell's type model comes to mind) but these are also often more complicated and/or difficult to implement efficiently. OOP is a good trade-off between extremes. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/24270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2131/"
]
} |
24,279 | In my second year of University we were "taught" Haskell, I know almost nothing about it and even less about functional programming. What is functional programming, why and/xor where would I want to use it instead of non-functional programming and am I correct in thinking that C is a non-functional programming language? | One key feature in a functional language is the concept of first-class functions. The idea is that you can pass functions as parameters to other functions and return them as values. Functional programming involves writing code that does not change state. The primary reason for doing so is so that successive calls to a function will yield the same result. You can write functional code in any language that supports first-class functions, but there are some languages, like Haskell, which do not allow you to change state. In fact, you're not supposed to make any side effects (like printing out text) at all - which sounds like it could be completely useless. Haskell instead employs a different approach to IO: monads. These are objects that contain the desired IO operation to be executed by your interpreter's toplevel. At any other level they are simply objects in the system. What advantages does functional programming provide? Functional programming allows coding with fewer potentials for bugs because each component is completely isolated. Also, using recursion and first-class functions allows for simple proofs of correctness which typically mirror the structure of the code. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/24279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
24,298 | I'm looking for a pre-built solution I can use in my RoR application. I'm ideally looking for something similar to the ASP.NET Forms authentication that provides email validation, sign-up controls, and allows users to reset their passwords. Oh yeah, and easily allows me to pull the user that is currently logged into the application. I've started to look into the already written pieces, but I've found it to be really confusing. I've looked at LoginGenerator, RestfulAuthentication, SaltedLoginGenerator, but there doesn't seem to be one place that has great tutorials or provide a comparison of them. If there's a site I just haven't discovered yet, or if there is a de-facto standard that most people use, I'd appreciate the helping hand. | AuthLogic appears to be the new kid on the block and seems to be the next evolution of restful_authentication, easier to use, etc http://github.com/binarylogic/authlogic/tree/master Edit: now that Rails 3 is out, Devise seems to be the new, new kid on the block https://github.com/plataformatec/devise or I have been rolling my own authentication now with the has_secure_password built in to Rails http://railscasts.com/episodes/250-authentication-from-scratch-revised Side note: Ruby Toolbox is a great site for finding the current best solution in various categories (based on the number of GitHub watchers): http://ruby-toolbox.com/categories/rails_authentication.html | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/24298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/168/"
]
} |
24,310 | I started using IRC at a young age, and I have always been fascinated with it. As a language exercise, I was thinking about programming a simple IRC client in Ruby with Shoes as a graphical front-end. My question to you, kind-sirs, what do I need to become familiar with to start on this great adventure (besides shoes and Ruby of course)? I imagine there is some-sort of specification on IRC Protocol. Any pointers? | An earlier post mentioned RFC1459. While it is a very good introduction to IRC, it has actually been superseded by RFCs 2810-2813. Here is a more complete list of documentation you need to program anything IRC-related: RFC1459 (original RFC; superseded, but still useful) RFC2810 (IRC architecture) RFC2811 (IRC channel management) RFC2812 (IRC client protocol) RFC2813 (IRC server protocol) CTCP specification DCC specification Updated CTCP specification (not all clients support this) ISupport (response code 005) draft (almost all servers support this nowadays) Client capabilities (CAP command) draft (supported by some servers/clients) IRCv3 standards and proposals (the future features of IRC, some of which are already widely supported) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/24310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25/"
]
} |
24,451 | I've long been under the impression that goto should never be used if possible. However, while perusing libavcodec (which is written in C) the other day, I was surprised to notice multiple uses of it. Is it ever advantageous to use goto in a language that supports loops and functions? If so, why? Please provide a concrete example that clearly justifies the use of a goto . | Everybody who is anti- goto cites, directly or indirectly, Edsger Dijkstra's GoTo Considered Harmful article to substantiate their position. Too bad Dijkstra's article has virtually nothing to do with the way goto statements are used these days and thus what the article says has little to no applicability to the modern programming scene. The goto -less meme verges now on a religion, right down to its scriptures dictated from on high, its high priests and the shunning (or worse) of perceived heretics. Let's put Dijkstra's paper into context to shed a little light on the subject. When Dijkstra wrote his paper the popular languages of the time were unstructured procedural ones like BASIC, FORTRAN (the earlier dialects) and various assembly languages. It was quite common for people using the higher-level languages to jump all over their code base in twisted, contorted threads of execution that gave rise to the term "spaghetti code". You can see this by hopping on over to the classic Trek game written by Mike Mayfield and trying to figure out how things work. Take a few moments to look that over. THIS is "the unbridled use of the go to statement" that Dijkstra was railing against in his paper in 1968. THIS is the environment he lived in that led him to write that paper. The ability to jump anywhere you like in your code at any point you liked was what he was criticising and demanding be stopped. Comparing that to the anaemic powers of goto in C or other such more modern languages is simply risible. I can already hear the raised chants of the cultists as they face the heretic. "But," they will chant, "you can make code very difficult to read with goto in C." Oh yeah? You can make code very difficult to read without goto as well. Like this one: #define _ -F<00||--F-OO--;int F=00,OO=00;main(){F_OO();printf("%1.3f\n",4.*-F/OO/OO);}F_OO(){ _-_-_-_ _-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-__-_-_-_-_-_-_-_-_-_-_-_-_-_-_-__-_-_-_-_-_-_-_-_-_-_-_-_-_-_-__-_-_-_-_-_-_-_-_-_-_-_-_-_-_-__-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_-_-_-_-_ _-_-_-_-_-_-_-_ _-_-_-_} Not a goto in sight, so it must be easy to read, right? Or how about this one: a[900]; b;c;d=1 ;e=1;f; g;h;O; main(k,l)char* *l;{g= atoi(* ++l); for(k=0;k*k< g;b=k ++>>1) ;for(h= 0;h*h<=g;++h); --h;c=( (h+=g>h *(h+1)) -1)>>1;while(d <=g){ ++O;for (f=0;f< O&&d<=g;++f)a[ b<<5|c] =d++,b+= e;for( f=0;f<O&&d<=g; ++f)a[b <<5|c]= d++,c+= e;e= -e;}for(c =0;c<h; ++c){ for(b=0 ;b<k;++b){if(b <k/2)a[ b<<5|c] ^=a[(k -(b+1))<<5|c]^= a[b<<5 |c]^=a[ (k-(b+1 ))<<5|c];printf( a[b<<5|c ]?"%-4d" :" " ,a[b<<5|c]);} putchar( '\n');}} /*Mike Laman*/ No goto there either. It must therefore be readable. What's my point with these examples? It's not language features that make unreadable, unmaintainable code. It's not syntax that does it. It's bad programmers that cause this. And bad programmers, as you can see in that above item, can make any language feature unreadable and unusable. Like the for loops up there. (You can see them, right?) Now to be fair, some language constructs are easier to abuse than others. If you're a C programmer, however, I'd peer far more closely at about 50% of the uses of #define long before I'd go on a crusade against goto ! So, for those who've bothered to read this far, there are several key points to note. Dijkstra's paper on goto statements was written for a programming environment where goto was a lot more potentially damaging than it is in most modern languages that aren't an assembler. Automatically throwing away all uses of goto because of this is about as rational as saying "I triedto have fun once but didn't like it so now I'm against it". There are legitimate uses of the modern (anaemic) goto statements in code that cannot be adequatelyreplaced by other constructs. There are, of course, illegitimate uses of the same statements. There are, too, illegitimate uses of the modern control statements like the " godo " abomination where an always-false do loop is broken out of using break in place of a goto . These are often worse than judicious use of goto . | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/24451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597/"
]
} |
24,470 | Trying to find some simple SQL Server PIVOT examples. Most of the examples that I have found involve counting or summing up numbers. I just want to pivot some string data. For example, I have a query returning the following. Action1 VIEW Action1 EDIT Action2 VIEW Action3 VIEW Action3 EDIT I would like to use PIVOT (if even possible) to make the results like so: Action1 VIEW EDIT Action2 VIEW NULL Action3 VIEW EDIT Is this even possible with the PIVOT functionality? | Remember that the MAX aggregate function will work on text as well as numbers. This query will only require the table to be scanned once. SELECT Action, MAX( CASE data WHEN 'View' THEN data ELSE '' END ) ViewCol, MAX( CASE data WHEN 'Edit' THEN data ELSE '' END ) EditCol FROM t GROUP BY Action | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/24470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2626/"
]
} |
24,481 | What is the " best " way to store international addresses in a database? Answer in the form of a schema and an explanation of the reasons why you chose to normalize (or not) the way you did. Also explain why you chose the type and length of each field. Note: You decide what fields you think are necessary. | Plain freeform text. Validating all the world's post/zip codes is too hard; a fixed list of countries is too politically sensitive; mandatory state/region/other administrative subdivision is just plain inappropriate (all too often I'm asked which county I live in--when I don't, because Greater London is not a county at all). More to the point, it's simply unnecessary. Your application is highly unlikely to be modelling addresses in any serious way. If you want a postal address, ask for the postal address. Most people aren't so stupid as to put in something other than a postal address, and if they do, they can kiss their newly purchased item bye-bye. The exception to this is if you're doing something that's naturally constrained to one country anyway. In this situation, you should ask for, say, the { postcode, house number } pair, which is enough to identify a postal address. I imagine you could achieve similar things with the extended zip code in the US. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/24481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2627/"
]
} |
24,496 | While going through university and from following the development of SO, I've heard a lot about the Model-View-Controller architectural design pattern. I inadvertently used the MVC pattern even before I knew what it was, and still use it in my everyday job. From what I've seen, it's probably the most popular pattern used today. What I haven't heard much about though, are the alternative patterns you can use instead of MVC. What options are there, and for what reasons would you decide to use them over MVC? I'm also interested in knowing the types of systems they are typical of being used for. Finally, what are the pros and cons that come along with using them? | Passive View - http://martinfowler.com/eaaDev/PassiveScreen.html Supervising Controller - http://martinfowler.com/eaaDev/SupervisingPresenter.html Model-View-Presenter - http://martinfowler.com/eaaDev/ModelViewPresenter.html My personal favorite is the Passive View . More testable than others I've seen including MVC. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/24496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628/"
]
} |
24,515 | Not very technical, but... I have to implement a bad words filter in a new site we are developing. So I need a "good" bad words list to feed my db with... any hint / direction? Looking around with google I found this one, and it's a start, but nothing more. Yes, I know that this kind of filters are easily escaped... but the client will is the client will !!! :-) The site will have to filter out both english and italian words, but for italian I can ask my colleagues to help me with a community-built list of "parolacce" :-) - an email will do. Thanks for any help. | Beware of clbuttic mistakes . "Apple made the clbuttic mistake of forcing out their visionary - I mean, look at what NeXT has been up to!" Hmm. "clbuttic". Google "clbuttic" - thousands of hits! There's someone who call his car 'clbuttic'. There are "Clbuttic Steam Engine" message boards. Webster's dictionary - no help. Hmm. What can this be? HINT: People who make buttumptions about their regex scripts, will be embarbutted when they repeat this mbuttive mistake. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/24515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1178/"
]
} |
24,528 | I'm curious to hear the experiences of those who are currently running their SVN server on Windows. Jeff Atwood has a post on how to setup SVN as a Windows service . It's a great first step, but it doesn't touch on other topics, such as: What to use for a web-based repository browser? WebSVN can work on Windows, but it ain't pretty. How to manage the passwd file? Is it possible to integrate with Active Directory without running Apache? Strategies for backing up the repository. Useful global ignore patterns for Visual Studio development (suggestions here , here , and here for example). Our company switched from SourceGear Vault to Subversion about one month ago. We've got the basics down pat, but would love to discover people's tips and tricks for running SVN in a MSFT world. | Use VisualSVN Server . It integrates with Windows authentication and it handles all the apache setup. It's as painless as SVN can be on Windows. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/24528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1690/"
]
} |
24,542 | Is there any reason not to use the bitwise operators &, |, and ^ for "bool" values in C++? I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression. I also sometimes want all parts of a condition to be evaluated whether the result is true or not (rather than short-circuiting), so I use & and |. I also need to accumulate Boolean values sometimes, and &= and |= can be quite useful. I've gotten a few raised eyebrows when doing this, but the code is still meaningful and cleaner than it would be otherwise. Is there any reason NOT to use these for bools? Are there any modern compilers that give bad results for this? | || and && are boolean operators and the built-in ones are guaranteed to return either true or false . Nothing else. | , & and ^ are bitwise operators. When the domain of numbers you operate on is just 1 and 0, then they are exactly the same, but in cases where your booleans are not strictly 1 and 0 – as is the case with the C language – you may end up with some behavior you didn't want. For instance: BOOL two = 2;BOOL one = 1;BOOL and = two & one; //and = 0BOOL cand = two && one; //cand = 1 In C++, however, the bool type is guaranteed to be only either a true or a false (which convert implicitly to respectively 1 and 0 ), so it's less of a worry from this stance, but the fact that people aren't used to seeing such things in code makes a good argument for not doing it. Just say b = b && x and be done with it. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/24542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1891/"
]
} |
24,546 | I'm trying to fetch Wikipedia pages using LWP::Simple , but they're not coming back. This code: #!/usr/bin/perluse strict;use LWP::Simple;print get("http://en.wikipedia.org/wiki/Stack_overflow"); doesn't print anything. But if I use some other webpage, say http://www.google.com , it works fine. Is there some other name that I should be using to refer to Wikipedia pages? What could be going on here? | Apparently Wikipedia blocks LWP::Simple requests: http://www.perlmonks.org/?node_id=695886 The following works instead: #!/usr/bin/perluse strict;use LWP::UserAgent;my $url = "http://en.wikipedia.org/wiki/Stack_overflow";my $ua = LWP::UserAgent->new();my $res = $ua->get($url);print $res->content; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/24546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/112/"
]
} |
24,551 | I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields. Should I do it at declaration?: public class Dice{ private int topFace = 1; private Random myRand = new Random(); public void Roll() { // ...... }} or in a constructor?: public class Dice{ private int topFace; private Random myRand; public Dice() { topFace = 1; myRand = new Random(); } public void Roll() { // ..... }} I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach. | My rules: Don't initialize with the default values in declaration ( null , false , 0 , 0.0 …). Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field. If the value of the field changes because of a constructor parameter put the initialization in the constructors. Be consistent in your practice (the most important rule). | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/24551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2635/"
]
} |
24,556 | In LINQ to SQL, is it possible to check to see if an entity is already part of the data context before trying to attach it? A little context if it helps... I have this code in my global.asax as a helper method. Normally, between requests, this isn't a problem. But right after signing in, this is getting called more than once, and the second time I end up trying to attach the Member object in the same unit of work where it was created. private void CheckCurrentUser(){ if (!HttpContext.Current.User.Identity.IsAuthenticated) { AppHelper.CurrentMember = null; return; } IUserService userService = new UserService(); if (AppHelper.CurrentMember != null) userService.AttachExisting(AppHelper.CurrentMember); else AppHelper.CurrentMember = userService.GetMember( HttpContext.Current.User.Identity.Name, AppHelper.CurrentLocation);} | My rules: Don't initialize with the default values in declaration ( null , false , 0 , 0.0 …). Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field. If the value of the field changes because of a constructor parameter put the initialization in the constructors. Be consistent in your practice (the most important rule). | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/24556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2595/"
]
} |
24,579 | Is there a good ruby gem for a WYSIWYG editor that will easily work with a rails app? | Though it's certainly not a direct answer, in the past I've found I prefer to use RedCloth (or a Markdown parser if you don't enjoy Textile) and use a simple textarea with an AJAXy preview. Generally speaking, WYSIWYG editors have a long history of creating redundant tags and similar, leading to potentially broken pieces of HTML. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/24579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.