source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
39,977
I know how to use tags in subversion. I create a tag every time I get to a release milestone. What I don't quite understand is how they work. Is a tag just a copy, made from what ever revision I specify? Or is a tag more like a reference, where internally subversion just says GO TO /trunk/project/ Revision 5 or whatever. The command to create a tag ( svn copy ) seems to imply that it's a copy, but I've seen other people write that subversion doesn't really copy anything. Say I dump just the HEAD revision of a repository. I don't care about any history except the tags. Are those tags dumped along with the rest of the Head revision? Finally, is all this just programming magic that I don't really want to know.
Yes, a svn copy (whether you are thinking of it as a tag, a branch, or copying a file in trunk) is all the same. SVN will internally create a pointer to the source location at that revision. If you then make changes to the copy (which you are likely to do if it is a branch or a copied file in trunk, but shouldn't do for tags), SVN will only store what was changed, rather than creating a whole new copy.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/39977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30/" ] }
40,022
I'm using LINQ to SQL classes in a project where the database design is still in a bit of flux. Is there an easy way of synchronising the classes with the schema, or do I need to manually update the classes if a table design changes?
You can use SQLMetal.exe to generate your dbml and or cs/vb file. Use a pre-build script to start it and target the directory where your datacontext project belongs. C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\x64\sqlmetal.exe /server:<SERVER> /database:<database> /code:"path\Solution\DataContextProject\dbContext.cs" /language:csharp /namespace:<your namespace>
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/40022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048/" ] }
40,043
How can I create a new database from my C# application? I'm assuming once I create it, I can simply generate a connection string on the fly and connect to it, and the issue all the CREATE TABLE statements.
KB307283 explains how to create a database using ADO.NET. From the article: String str;SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");str = "CREATE DATABASE MyDatabase ON PRIMARY " + "(NAME = MyDatabase_Data, " + "FILENAME = 'C:\\MyDatabaseData.mdf', " + "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " + "LOG ON (NAME = MyDatabase_Log, " + "FILENAME = 'C:\\MyDatabaseLog.ldf', " + "SIZE = 1MB, " + "MAXSIZE = 5MB, " + "FILEGROWTH = 10%)";SqlCommand myCommand = new SqlCommand(str, myConn);try { myConn.Open(); myCommand.ExecuteNonQuery(); MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);}catch (System.Exception ex){ MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);}finally{ if (myConn.State == ConnectionState.Open) { myConn.Close(); }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ] }
40,075
I am writing a few extensions to mimic the map and reduce functions in Lisp. public delegate R ReduceFunction<T,R>(T t, R previous);public delegate void TransformFunction<T>(T t, params object[] args);public static R Reduce<T,R>(this List<T> list, ReduceFunction<T,R> r, R initial){ var aggregate = initial; foreach(var t in list) aggregate = r(t,aggregate); return aggregate;}public static void Transform<T>(this List<T> list, TransformFunction<T> f, params object [] args){ foreach(var t in list) f(t,args);} The transform function will cut down on cruft like: foreach(var t in list) if(conditions && moreconditions) //do work etc Does this make sense? Could it be better?
These look very similar to extensions in Linq already: //takes a function that matches the Func<T,R> delegatelistInstance.Aggregate( startingValue, (x, y) => /* aggregate two subsequent values */ );//takes a function that matches the Action<T> delegatelistInstance.ForEach( x => /* do something with x */); Why is the 2nd example called Transform? Do you intend to change the values in the list somehow? If that's the case you may be better off using ConvertAll<T> or Select<T> .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/40075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1455/" ] }
40,116
How do I get it to work with my project? http://ajax.asp.net/ http://www.codeplex.com/AjaxControlToolkit/
Install the ASP.NET AJAX Control Toolkit Download the ZIP fileAjaxControlToolkit-Framework3.5SP1-DllOnly.zipfrom the ASP.NET AJAX ControlToolkit Releases page of theCodePlex web site. Copy the contents of this zip filedirectly into the bin directory ofyour web site. Update web.config Put this in your web.config under the <controls> section: <?xml version="1.0"?><configuration> ... <system.web> ... <pages> ... <controls> ... <add tagPrefix="ajaxtoolkit" namespace="AjaxControlToolkit" assembly="AjaxControlToolKit"/> </controls> </pages> ... </system.web> ...</configuration> Setup Visual Studio Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit" Inside that tab, right-click on the Toolbox and select "Choose Items..." When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog. You can now use the controls in your web sites!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ] }
40,119
How do you find a memory leak in Java (using, for example, JHat)? I have tried to load the heap dump up in JHat to take a basic look. However, I do not understand how I am supposed to be able to find the root reference ( ref ) or whatever it is called. Basically, I can tell that there are several hundred megabytes of hash table entries ([java.util.HashMap$Entry or something like that), but maps are used all over the place... Is there some way to search for large maps, or perhaps find general roots of large object trees? [Edit]Ok, I've read the answers so far but let's just say I am a cheap bastard (meaning I am more interested in learning how to use JHat than to pay for JProfiler). Also, JHat is always available since it is part of the JDK. Unless of course there is no way with JHat but brute force, but I can't believe that can be the case. Also, I do not think I will be able to actually modify (adding logging of all map sizes) and run it for long enough for me to notice the leak.
I use following approach to finding memory leaks in Java. I've used jProfiler with great success, but I believe that any specialized tool with graphing capabilities (diffs are easier to analyze in graphical form) will work. Start the application and wait until it get to "stable" state, when all the initialization is complete and the application is idle. Run the operation suspected of producing a memory leak several times to allow any cache, DB-related initialization to take place. Run GC and take memory snapshot. Run the operation again. Depending on the complexity of operation and sizes of data that is processed operation may need to be run several to many times. Run GC and take memory snapshot. Run a diff for 2 snapshots and analyze it. Basically analysis should start from greatest positive diff by, say, object types and find what causes those extra objects to stick in memory. For web applications that process requests in several threads analysis gets more complicated, but nevertheless general approach still applies. I did quite a number of projects specifically aimed at reducing memory footprint of the applications and this general approach with some application specific tweaks and trick always worked well.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/40119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4208/" ] }
40,154
How can you beta test an iPhone app? I can get it on my own device, and anyone that gives me a device, I can run it on theirs, but is there a way to do a limited release via the app store for beta testing? Related: Also, see this question on getting your app onto phones without using the App Store.
Creating ad-hoc distribution profiles The instructions that Apple provides are here , but here is how I created a general provisioning profile that will work with multiple apps, and added a beta tester. My setup: Xcode 3.2.1 iPhone SDK 3.1.3 Before you get started, make sure that.. You can run the app on your own iPhone through Xcode. Step A: Add devices to the Provisioning Portal Send an email to each beta tester with the following message: To get my app on onto your iPhone I need some information about your phone. Guess what, there is an app for that! Click on the below link and install and then run the app. http://itunes.apple.com/app/ad-hoc-helper/id285691333?mt=8 This app will create an email. Please send it to me. Collect all the UDIDs from your testers. Go to the Provisioning Portal . Go to the section Devices . Click on the button Add Devices and add the devices previously collected. Step B: Create a new provisioning profile Start the Mac OS utility program Keychain Access . In its main menu, select Keychain Access / Certificate Assistant / Request a Certificate From a Certificate Authority... The dialog that pops up should aready have your email and name it it. Select the radio button Saved to disk and Continue. Save the file to disk. Go back to the Provisioning Portal . Go to the section Certificates . Go to the tab Distribution . Click the button Request Certificate . Upload the file you created with Keychain Access: CertificateSigningRequest.certSigningRequest . Click the button Aprove . Refresh your browser until the status reads Issued . Click the Download button and save the file distribution_identify.cer . Doubleclick the file to add it to the Keychain. Backup the certificate by selecting its private key and the File / Export Items... . Go back to the Provisioning Portal again. Go to the section Provisioning . Go to the tab Distribution . Click the button New Profile . Select the radio button Ad hoc . Enter a profile name, I named mine Evertsson Common Ad Hoc . Select the app id. I have a common app id to use for multiple apps: Evertsson Common . Select the devices, in my case my own and my tester's. Submit. Refresh the browser until the status field reads Active . Click the button Download and save the file to disk. Doubleclick the file to add it to Xcode. Step C: Build the app for distribution Open your project in Xcode. Open the Project Info pane: In Groups & Files select the topmost item and press Cmd+I . Go to the tab Configuration . Select the configuration Release . Click the button Duplicate and name it Distribution . Close the Project Info pane. Open the Target Info pane: In Groups & Files expand Targets , select your target and press Cmd+I . Go to the tab Build . Select the Configuration named Distribution . Find the section Code Signing . Set the value of Code Signing Identity / Any iPhone OS Device to iPhone Distribution . Close the Target Info pane. In the main window select the Active Configuration to Distribution . Create a new file from the file template Code Signing / Entitlements . Name it Entitlements.plist . In this file, uncheck the checkbox get-task-allow . Bring up the Target Info pane, and find the section Code Signing again. After Code Signing Entitlements enter the file name Entitlements.plist . Save, clean, and build the project. In Groups & Files find the folder MyApp / Products and expand it. Right click the app and select Reveal in Finder . Zip the .app file and the .mobileprovision file and send the archive to your tester. Here is my app. To install it onto your phone: Unzip the archive file. Open iTunes. Drag both files into iTunes and drop them on the Library group. Sync your phone to install the app. Done! Phew. This worked for me. So far I've only added one tester.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/40154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245/" ] }
40,161
Does C# have built-in support for parsing strings of page numbers? By page numbers, I mean the format you might enter into a print dialog that's a mixture of comma and dash-delimited. Something like this: 1,3,5-10,12 What would be really nice is a solution that gave me back some kind of list of all page numbers represented by the string. In the above example, getting a list back like this would be nice: 1,3,5,6,7,8,9,10,12 I just want to avoid rolling my own if there's an easy way to do it.
Should be simple: foreach( string s in "1,3,5-10,12".Split(',') ) { // try and get the number int num; if( int.TryParse( s, out num ) ) { yield return num; continue; // skip the rest } // otherwise we might have a range // split on the range delimiter string[] subs = s.Split('-'); int start, end; // now see if we can parse a start and end if( subs.Length > 1 && int.TryParse(subs[0], out start) && int.TryParse(subs[1], out end) && end >= start ) { // create a range between the two values int rangeLength = end - start + 1; foreach(int i in Enumerable.Range(start, rangeLength)) { yield return i; } }} Edit: thanks for the fix ;-)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/40161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ] }
40,193
I've got to get a directory listing that contains about 2 million files, but when I do an ls command on it nothing comes back. I've waited 3 hours. I've tried ls | tee directory.txt , but that seems to hang forever. I assume the server is doing a lot of inode sorting. Is there any way to speed up the ls command to just get a directory listing of filenames? I don't care about size, dates, permission or the like at this time.
ls -U will do the ls without sorting. Another source of slowness is --color . On some linux machines, there is a convenience alias which adds --color=auto' to the ls call, making it look up file attributes for each file found (slow), to color the display. This can be avoided by ls -U --color=never or \ls -U .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/40193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1536194/" ] }
40,211
I have a flag enum below. [Flags]public enum FlagTest{ None = 0x0, Flag1 = 0x1, Flag2 = 0x2, Flag3 = 0x4} I cannot make the if statement evaluate to true. FlagTest testItem = FlagTest.Flag1 | FlagTest.Flag2;if (testItem == FlagTest.Flag1){ // Do something, // however This is never true.} How can I make this true?
In .NET 4 there is a new method Enum.HasFlag . This allows you to write: if ( testItem.HasFlag( FlagTest.Flag1 ) ){ // Do Stuff} which is much more readable, IMO. The .NET source indicates that this performs the same logic as the accepted answer: public Boolean HasFlag(Enum flag) { if (!this.GetType().IsEquivalentTo(flag.GetType())) { throw new ArgumentException( Environment.GetResourceString( "Argument_EnumTypeDoesNotMatch", flag.GetType(), this.GetType())); } ulong uFlag = ToUInt64(flag.GetValue()); ulong uThis = ToUInt64(GetValue()); // test predicate return ((uThis & uFlag) == uFlag); }
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/40211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2469/" ] }
40,242
I joined a new company about a month ago. The company is rather small in size and has pretty strong "start-up" feel to it. I'm working as a Java developer on a team of 3 others. The company primarily sells a service to for businesses/business-type people to use in communicating with each other. One of the main things I have been, and will be working on, is the main website for the company - from which the service is sold, existing users login to check their service and pay their bills, new users can sign up for a trial, etc. Currently this is a JSP application deployed on Tomcat, with access to a database done thru a persistence layer written by the company itself. A repeated and growing frustration I am having here (and I'm pretty happy with the job overall, so this isn't an "oh no I don't like my job"-type post) is the lack of any larger design or architecture for this web application. The app is made up of several dozen JSP pages, with almost no logic existing in Servlets or Beans or any other sort of framework. Many of the JSP pages are thousands of lines of code, they jsp:include other JSP pages, business logic is mixed in with the HTML, frequently used snippets of code (such as obtaining a web service connection) is cut and paste rather than reused, etc. In other words, the application is a mess. There have been some rumblings within the company of trying to re-architect this site so that it fits MVC better; I think that the developers and higher-ups are beginning to realize that this current pattern of spaghetti code isn't sustainable or very easily scalable to add more features for the users. The higher-ups and developers are wary of completely re-writing the thing (with good reason, since this would mean several weeks or months of work re-writing existing functionality), but we've had some discussions of (slowly) re-writing certain areas of the site into a new framework. What are some of the best strategies to enable moving the application and codebase into this direction? How can I as a developer really help move this along, and quickly, without seeming like the jerk-y new guy who comes into a job and tells everyone that what they've written is crap? Are there any proven strategies or experiences that you've used in your own job experience when you've encountered this sort of thing?
Your best bet is probably to refactor it slowly as you go along. Few us of have the resources that would be required to completely start from scratch with something that has so many business rules buried in it. Management really hates it when you spend months on developing an app that has more bugs than the one you replaced. If you have the opportunity to build any separate apps from scratch, use all of the best practices there and use it to demonstrate how effective they are. When you can, incorporate those ideas gradually into the old application.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ] }
40,244
Assume that I have programs P0 , P1 , ... P(n-1) for some n > 0 . How can I easily redirect the output of program Pi to program P(i+1 mod n) for all i ( 0 <= i < n )? For example, let's say I have a program square , which repeatedly reads a number and than prints the square of that number, and a program calc , which sometimes prints a number after which it expects to be able to read the square of it. How do I connect these programs such that whenever calc prints a number, square squares it returns it to calc ? Edit: I should probably clarify what I mean with "easily". The named pipe/fifo solution is one that indeed works (and I have used in the past), but it actually requires quite a bit of work to do properly if you compare it with using a bash pipe. (You need to get a not yet existing filename, make a pipe with that name, run the "pipe loop", clean up the named pipe.) Imagine you could no longer write prog1 | prog2 and would always have to use named pipes to connect programs. I'm looking for something that is almost as easy as writing a "normal" pipe. For instance something like { prog1 | prog2 } >&0 would be great.
After spending quite some time yesterday trying to redirect stdout to stdin , I ended up with the following method. It isn't really nice, but I think I prefer it over the named pipe/fifo solution. read | { P0 | ... | P(n-1); } >/dev/fd/0 The { ... } >/dev/fd/0 is to redirect stdout to stdin for the pipe sequence as a whole (i.e. it redirects the output of P(n-1) to the input of P0). Using >&0 or something similar does not work; this is probably because bash assumes 0 is read-only while it doesn't mind writing to /dev/fd/0 . The initial read -pipe is necessary because without it both the input and output file descriptor are the same pts device (at least on my system) and the redirect has no effect. (The pts device doesn't work as a pipe; writing to it puts things on your screen.) By making the input of the { ... } a normal pipe, the redirect has the desired effect. To illustrate with my calc / square example: function calc() { # calculate sum of squares of numbers 0,..,10 sum=0 for ((i=0; i<10; i++)); do echo $i # "request" the square of i read ii # read the square of i echo "got $ii" >&2 # debug message let sum=$sum+$ii done echo "sum $sum" >&2 # output result to stderr}function square() { # square numbers read j # receive first "request" while [ "$j" != "" ]; do let jj=$j*$j echo "square($j) = $jj" >&2 # debug message echo $jj # send square read j # receive next "request" done}read | { calc | square; } >/dev/fd/0 Running the above code gives the following output: square(0) = 0got 0square(1) = 1got 1square(2) = 4got 4square(3) = 9got 9square(4) = 16got 16square(5) = 25got 25square(6) = 36got 36square(7) = 49got 49square(8) = 64got 64square(9) = 81got 81sum 285 Of course, this method is quite a bit of a hack. Especially the read part has an undesired side-effect: termination of the "real" pipe loop does not lead to termination of the whole. I couldn't think of anything better than read as it seems that you can only determine that the pipe loop has terminated by try to writing write something to it.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4285/" ] }
40,264
Let's say you have a class called Customer, which contains the following fields: UserName Email First Name Last Name Let's also say that according to your business logic, all Customer objects must have these four properties defined. Now, we can do this pretty easily by forcing the constructor to specify each of these properties. But it's pretty easy to see how this can spiral out of control when you are forced to add more required fields to the Customer object. I've seen classes that take in 20+ arguments into their constructor and it's just a pain to use them. But, alternatively, if you don't require these fields you run into the risk of having undefined information, or worse, object referencing errors if you rely on the calling code to specify these properties. Are there any alternatives to this or do you you just have to decide whether X amount of constructor arguments is too many for you to live with?
Two design approaches to consider The essence pattern The fluent interface pattern These are both similar in intent, in that we slowly build up an intermediate object, and then create our target object in a single step. An example of the fluent interface in action would be: public class CustomerBuilder { String surname; String firstName; String ssn; public static CustomerBuilder customer() { return new CustomerBuilder(); } public CustomerBuilder withSurname(String surname) { this.surname = surname; return this; } public CustomerBuilder withFirstName(String firstName) { this.firstName = firstName; return this; } public CustomerBuilder withSsn(String ssn) { this.ssn = ssn; return this; } // client doesn't get to instantiate Customer directly public Customer build() { return new Customer(this); }}public class Customer { private final String firstName; private final String surname; private final String ssn; Customer(CustomerBuilder builder) { if (builder.firstName == null) throw new NullPointerException("firstName"); if (builder.surname == null) throw new NullPointerException("surname"); if (builder.ssn == null) throw new NullPointerException("ssn"); this.firstName = builder.firstName; this.surname = builder.surname; this.ssn = builder.ssn; } public String getFirstName() { return firstName; } public String getSurname() { return surname; } public String getSsn() { return ssn; } } import static com.acme.CustomerBuilder.customer;public class Client { public void doSomething() { Customer customer = customer() .withSurname("Smith") .withFirstName("Fred") .withSsn("123XS1") .build(); }}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/40264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ] }
40,273
A client of mine has asked me to integrate a 3rd party API into their Rails app. The only problem is that the API uses SOAP. Ruby has basically dropped SOAP in favor of REST. They provide a Java adapter that apparently works with the Java-Ruby bridge, but we'd like to keep it all in Ruby, if possible. I looked into soap4r, but it seems to have a slightly bad reputation. So what's the best way to integrate SOAP calls into a Rails app?
I built Savon to make interacting with SOAP webservices via Ruby as easy as possible. I'd recommend you check it out.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/40273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2884/" ] }
40,317
I have an NFS-mounted directory on a Linux machine that has hung. I've tried to force an unmount, but it doesn't seem to work: $ umount -f /mnt/data$ umount2: Device or resource busy$ umount: /mnt/data: device is busy If I type " mount ", it appears that the directory is no longer mounted, but it hangs if I do " ls /mnt/data ", and if I try to remove the mountpoint, I get: $ rmdir /mnt/datarmdir: /mnt/data: Device or resource busy Is there anything I can do other than reboot the machine?
You might try a lazy unmount: umount -l
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/40317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ] }
40,322
I am a member of all the roles (Browser, Content Manager, My Reports, Publisher, Report Builder). If I login with a Local Administrator account, I can see and use it fine. Any ideas?
The first thing I would check is to make sure that your normal login is mapped to a role with the correct system-level permissions. The item-level role definitions don't make a difference for the "Report Builder" button. From the browser-based report manager interface: Click "site settings" In the Security section, click "Configure system-level role definitions" Click the Role that you want to have this ability (e.g. "System Administrator" and "System User" are the default roles, but I believe that you can create your own if you want to). Make sure that the "Execute Report Definitions" task is checked/selected. This is the permission that controls whether or not the "Report Builder" button is displayed. Click "OK" and then return to the "Site Settings" page. In the Security section, click "Configure site-wide security" Click "New Role Assignment" and then map your login (or an AD group to which your login belongs might be even better) to the system-level role you edited in the previous steps. The forms are pretty straightforward, and I'd guess that your login just isn't mapped to the proper system-level role since you can see the button with the local administrator login. If that doesn't work, you might check your IIS security settings for the report service to make sure that they're configured to use windows authentication (assuming that's what you're using in the first place).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1287/" ] }
40,346
So, we have coding books , coding RSS feeds , and music to code by . Are there any coding magazines that anyone would recommend?
The venerable Dr. Dobbs Journal is still pretty good. It covers multiple platforms, and mixes some fairly hard-core technical articles with lighter fare (interviews with notables, a "Developer Diaries" column that profiles regular-Joe (and Jane) developers from a range of fields). If you are employed and have authority to spend some non-trivial amount of money on tools (or are willing to claim that you do), you can probably get them to send it to you for free. For the Microsoft world, MSDN Magazine is very useful. Some of their columns are excellent, particularly Jeff Richter's Concurrent Affairs .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2470/" ] }
40,352
And why would I use one over the other in my code?
Caution: This answer appears to be out of date. It was posted before .NET 4 became available, which apparently introduced some optimizations regarding Type and thus rendered the information in this answer obsolete. See this more recent answer for details. According to this blog post (from 2006) by Vance Morrison , RuntimeTypeHandle is a value type ( struct ) that wraps an unmanaged pointer, so Type.GetTypeHandle(obj).Equals(anotherHandle) is faster to use for strict "is exactly the same type" comparisons than obj.GetType().Equals(anotherType) — the latter creates System.Type instances which are, apparently, heavier. However, it's also less obvious, and definitely falls under the category "micro-optimization" so if you're wondering when you need one over the other, you should probably just use System.Type.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ] }
40,368
Is there a maximum number of inodes in a single directory? I have a directory of over 2 million files and can't get the ls command to work against that directory. So now I'm wondering if I've exceeded a limit on inodes in Linux. Is there a limit before a 2^64 numerical limit?
df -i should tell you the number of inodes used and free on the file system.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/40368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1536194/" ] }
40,376
Is it possible to handle POSIX signals within the Java Virtual Machine? At least SIGINT and SIGKILL should be quite platform independent.
The JVM responds to signals on its own. Some will cause the JVM to shutdown gracefully, which includes running shutdown hooks. Other signals will cause the JVM to abort without running shutdown hooks. Shutdown hooks are added using Runtime.addShutdownHook(Thread) . I don't think the JDK provides an official way to handle signals within your Java application. However, I did find this IBM article , which describes using some undocumented sun.misc.Signal class to do exactly that. The article dates from 2002 and uses JDK 1.3.1, but I've confirmed that the sun.misc.Signal class still exists in JDK 1.6.0.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4308/" ] }
40,402
I need to empty an LDF file before sending to a colleague. How do I force SQL Server to truncate the log?
In management studio: Don't do this on a live environment, but to ensure you shrink your dev db as much as you can: Right-click the database, choose Properties , then Options . Make sure "Recovery model" is set to "Simple", not "Full" Click OK Right-click the database again, choose Tasks -> Shrink -> Files Change file type to "Log" Click OK. Alternatively, the SQL to do it: ALTER DATABASE mydatabase SET RECOVERY SIMPLE DBCC SHRINKFILE (mydatabase_Log, 1) Ref: http://msdn.microsoft.com/en-us/library/ms189493.aspx
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/40402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1042/" ] }
40,471
What are the differences between a HashMap and a Hashtable in Java? Which is more efficient for non-threaded applications?
There are several differences between HashMap and Hashtable in Java: Hashtable is synchronized , whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. One of HashMap's subclasses is LinkedHashMap , so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap . This wouldn't be as easy if you were using Hashtable . Since synchronization is not an issue for you, I'd recommend HashMap . If synchronization becomes an issue, you may also look at ConcurrentHashMap .
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/40471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4316/" ] }
40,480
I always thought Java uses pass-by-reference . However, I've seen a blog post that claims that Java uses pass-by-value . I don't think I understand the distinction they're making. What is the explanation?
The terms "pass-by-value" and "pass-by-reference" have special, precisely defined meanings in computer science. These meanings differ from the intuition many people have when first hearing the terms. Much of the confusion in this discussion seems to come from this fact. The terms "pass-by-value" and "pass-by-reference" are talking about variables. Pass-by-value means that the value of a variable is passed to a function/method. Pass-by-reference means that a reference to that variable is passed to the function. The latter gives the function a way to change the contents of the variable. By those definitions, Java is always pass-by-value . Unfortunately, when we deal with variables holding objects we are really dealing with object-handles called references which are passed-by-value as well. This terminology and semantics easily confuse many beginners. It goes like this: public static void main(String[] args) { Dog aDog = new Dog("Max"); Dog oldDog = aDog; // we pass the object to foo foo(aDog); // aDog variable is still pointing to the "Max" dog when foo(...) returns aDog.getName().equals("Max"); // true aDog.getName().equals("Fifi"); // false aDog == oldDog; // true}public static void foo(Dog d) { d.getName().equals("Max"); // true // change d inside of foo() to point to a new Dog instance "Fifi" d = new Dog("Fifi"); d.getName().equals("Fifi"); // true} In the example above aDog.getName() will still return "Max" . The value aDog within main is not changed in the function foo with the Dog "Fifi" as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return "Fifi" after the call to foo . Likewise: public static void main(String[] args) { Dog aDog = new Dog("Max"); Dog oldDog = aDog; foo(aDog); // when foo(...) returns, the name of the dog has been changed to "Fifi" aDog.getName().equals("Fifi"); // true // but it is still the same dog: aDog == oldDog; // true}public static void foo(Dog d) { d.getName().equals("Max"); // true // this changes the name of d to be "Fifi" d.setName("Fifi");} In the above example, Fifi is the dog's name after call to foo(aDog) because the object's name was set inside of foo(...) . Any operations that foo performs on d are such that, for all practical purposes, they are performed on aDog , but it is not possible to change the value of the variable aDog itself. For more information on pass by reference and pass by value, consult the following answer: https://stackoverflow.com/a/430958/6005228 . This explains more thoroughly the semantics and history behind the two and also explains why Java and many other modern languages appear to do both in certain cases.
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/40480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4315/" ] }
40,485
To experiment, I've (long ago) implemented Conway's Game of Life (and I'm aware of this related question!). My implementation worked by keeping 2 arrays of booleans, representing the 'last state', and the 'state being updated' (the 2 arrays being swapped at each iteration). While this is reasonably fast, I've often wondered about how to optimize this. One idea, for example, would be to precompute at iteration N the zones that could be modified at iteration (N+1) (so that if a cell does not belong to such a zone, it won't even be considered for modification at iteration (N+1)). I'm aware that this is very vague, and I never took time to go into the details... Do you have any ideas (or experience!) of how to go about optimizing (for speed) Game of Life iterations?
I am going to quote my answer from the other question, because the chapters I mention have some very interesting and fine-tuned solutions. Some of the implementation details are in c and/or assembly, yes, but for the most part the algorithms can work in any language: Chapters 17 and 18 ofMichael Abrash's GraphicsProgrammer's Black Book are one ofthe most interesting reads I have everhad. It is a lesson in thinkingoutside the box. The whole book isgreat really, but the final optimizedsolutions to the Game of Life areincredible bits of programming.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2638/" ] }
40,495
I know I can do most of this by hacking Trac and using Git hooks, but I was wondering if someone has / knows of something ready. Commenting on (and closing) tickets from commit messages would be nice, specially if the diff appears inline with the comment/closing remark. sha1 hashes should be auto-linked to gitweb/cigt/custom git browser. I tried the GitPlugin for Trac, but the code browser was soo slow... any alternatives?
Redmine can do some of what you're asking for. Integration works in one direction, you must reference issues in commit messages , and then this data will be available in redmine. The data is then available in two views. The bug display will include a list of matched commits. The repository display will link commits to bug display pages. Redmine keeps a local (bare) repository for each project. This can be the primary repo or a remote mirror. On updates, redmine parses the commit messages and updates an internal cross reference table of change_set,issue. If the redmine repository is only used as a mirror, it will need to be updated. Updates can happen via cron or via external hook. We use a redmine github plugin and a github post-receive hook to keep redmine in sync with a primary github repository. It works, but it is still a bit clumsy.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4272/" ] }
40,568
Are square brackets in URLs allowed? I noticed that Apache commons HttpClient (3.0.1) throws an IOException, wget and Firefox however accept square brackets. URL example: http://example.com/path/to/file[3].html My HTTP client encounters such URLs but I'm not sure whether to patch the code or to throw an exception (as it actually should be).
RFC 3986 states A host identified by an Internet Protocol literal address, version 6 [RFC3513] or later, is distinguished by enclosing the IP literal within square brackets ("[" and "]"). This is the only place where square bracket characters are allowed in the URI syntax. So you should not be seeing such URI's in the wild in theory, as they should arrive encoded.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/40568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4308/" ] }
40,602
What kind of programming problems are state machines most suited for? I have read about parsers being implemented using state machines, but would like to find out about problems that scream out to be implemented as a state machine.
The easiest answer is probably that they are suited for practically any problem. Don't forget that a computer itself is also a state machine. Regardless of that, state machines are typically used for problems where there is some stream of input and the activity that needs to be done at a given moment depends the last elements seen in that stream at that point. Examples of this stream of input: some text file in the case of parsing, a string for regular expressions, events such as player entered room for game AI, etc. Examples of activities: be ready to read a number (after another number followed by a + have appear in the input in a parser for a calculator), turn around (after player approached and then sneezed), perform jumping kick (after player pressed left, left, right, up, up).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1583/" ] }
40,608
I've been using PHP for too long, but I'm new to JavaScript integration in some places. I'm trying to find the fastest way to pass database information into a page where it can be modified and displayed dynamically in JavaScript. Right now, I'm looking at loading a JSON with PHP echo statements because it's fast and effective, but I saw that I could use PHP's JSON library (PHP 5.2). Has anybody tried the new JSON library, and is it better than my earlier method?
Use the library. If you try to generate it manually, I predict with 99% certainty that the resulting text will be invalid in some way. Especially with more esoteric features like Unicode strings or exponential notation.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4247/" ] }
40,632
What are they and what are they good for? I do not have a CS degree and my background is VB6 -> ASP -> ASP.NET/C#. Can anyone explain it in a clear and concise manner?
Imagine if every single line in your program was a separate function. Each accepts, as a parameter, the next line/function to execute. Using this model, you can "pause" execution at any line and continue it later. You can also do inventive things like temporarily hop up the execution stack to retrieve a value, or save the current execution state to a database to retrieve later.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/40632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1583/" ] }
40,651
I've inherited a large VB6 app at my current workplace. I'm kinda learning VB6 on the job and there are a number of problems I'm having. The major issue at the moment is I can't figure out how to check if a key exists in a Collection object. Can anyone help?
@Mark Biek Your keyExists closely matches my standard Exists() function. To make the class more useful for COM-exposed collections and checking for numeric indexes, I'd recommend changing sKey and myCollection to not be typed. If the function is going to be used with a collection of objects, 'set' is required (on the line where val is set). EDIT : It was bugging me that I've never noticed different requirements for an object-based and value-based Exists() function. I very rarely use collections for non-objects, but this seemed such a perfect bottleneck for a bug that would be so hard to track down when I needed to check for existence. Because error handling will fail if an error handler is already active, two functions are required to get a new error scope. Only the Exists() function need ever be called: Public Function Exists(col, index) As BooleanOn Error GoTo ExistsTryNonObject Dim o As Object Set o = col(index) Exists = True Exit FunctionExistsTryNonObject: Exists = ExistsNonObject(col, index)End FunctionPrivate Function ExistsNonObject(col, index) As BooleanOn Error GoTo ExistsNonObjectErrorHandler Dim v As Variant v = col(index) ExistsNonObject = True Exit FunctionExistsNonObjectErrorHandler: ExistsNonObject = FalseEnd Function And to verify the functionality: Public Sub TestExists() Dim c As New Collection Dim b As New Class1 c.Add "a string", "a" c.Add b, "b" Debug.Print "a", Exists(c, "a") ' True ' Debug.Print "b", Exists(c, "b") ' True ' Debug.Print "c", Exists(c, "c") ' False ' Debug.Print 1, Exists(c, 1) ' True ' Debug.Print 2, Exists(c, 2) ' True ' Debug.Print 3, Exists(c, 3) ' False 'End Sub
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4315/" ] }
40,663
I'm trying to find a way to validate a large XML file against an XSD. I saw the question ...best way to validate an XML... but the answers all pointed to using the Xerces library for validation. The only problem is, when I use that library to validate a 180 MB file then I get an OutOfMemoryException. Are there any other tools,libraries, strategies for validating a larger than normal XML file? EDIT: The SAX solution worked for java validation, but the other two suggestions for the libxml tool were very helpful as well for validation outside of java.
Instead of using a DOMParser, use a SAXParser. This reads from an input stream or reader so you can keep the XML on disk instead of loading it all into memory. SAXParserFactory factory = SAXParserFactory.newInstance();factory.setValidating(true);factory.setNamespaceAware(true);SAXParser parser = factory.newSAXParser();XMLReader reader = parser.getXMLReader();reader.setErrorHandler(new SimpleErrorHandler());reader.parse(new InputSource(new FileReader ("document.xml")));
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/40663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3274/" ] }
40,665
I'm maintaining some code that uses a *= operator in a query to a Sybase database and I can't find documentation on it. Does anyone know what *= does? I assume that it is some sort of a join. select * from a, b where a.id *= b.id I can't figure out how this is different from: select * from a, b where a.id = b.id
From http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc34982_1500/html/mig_gde/mig_gde160.htm : Inner and outer tables The terms outer table and inner table describe the placement of the tables in an outer join: In a left join, the outer table and inner table are the left and right tables respectively. The outer table and inner table are also referred to as the row-preserving and null-supplying tables, respectively. In a right join, the outer table and inner table are the right and left tables respectively. For example, in the queries below, T1 is the outer table and T2 is the inner table: T1 left join T2 T2 right join T1 Or, using Transact-SQL syntax: T1 *= T2 T2 =* T1
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ] }
40,680
I need to be able to get at the full URL of the page I am on from a user control. Is it just a matter of concatenating a bunch of Request variables together? If so which ones? Or is there a more simpiler way?
I usually use Request.Url.ToString() to get the full url (including querystring), no concatenation required.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/40680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648/" ] }
40,703
It will be important for developers wanting to develop for the chrome browser to be able to review existing bugs (to avoid too much pulling-out of hair), and to add new ones (to improve the thing). Yet I can't seem to find the bug tracking for this project. It is open source, right?
Google is calling it Chromium on Google Code The Chromium Bug Reporting Page is there and has the link to submit bugs listed. (Google Account Required) Here's a direct link to the bug report form.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/40703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ] }
40,730
How do you give a C# auto-property an initial value? I either use the constructor, or revert to the old syntax. Using the Constructor: class Person { public Person() { Name = "Initial Name"; } public string Name { get; set; }} Using normal property syntax (with an initial value) private string name = "Initial Name";public string Name { get { return name; } set { name = value; }} Is there a better way?
In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor. Since C# 6.0 , you can specify initial value in-line. The syntax is: public int X { get; set; } = x; // C# 6 or higher DefaultValueAttribute is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value). At compile time DefaultValueAttribute will not impact the generated IL and it will not be read to initialize the property to that value (see DefaultValue attribute is not working with my Auto Property ). Example of attributes that impact the IL are ThreadStaticAttribute , CallerMemberNameAttribute , ...
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/40730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/946/" ] }
40,733
I am setting the .Content value of a Label to a string that contains underscores; the first underscore is being interpreted as an accelerator key. Without changing the underlying string (by replacing all _ with __ ), is there a way to disable the accelerator for Labels?
If you use a TextBlock as the Content of the Label, its Text will not absorb underscores.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/40733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2258/" ] }
40,764
Are all of these equal? Under what circumstances should I choose each over the others? var.ToString() CStr(var) CType(var, String) DirectCast(var, String) EDIT: Suggestion from NotMyself … TryCast(var, String)
Those are all slightly different, and generally have an acceptable usage. var. ToString () is going to give you the string representation of an object, regardless of what type it is. Use this if var is not a string already. CStr (var) is the VB string cast operator. I'm not a VB guy, so I would suggest avoiding it, but it's not really going to hurt anything. I think it is basically the same as CType . CType (var, String) will convert the given type into a string, using any provided conversion operators. DirectCast (var, String) is used to up-cast an object into a string. If you know that an object variable is, in fact, a string, use this. This is the same as (string)var in C#. TryCast (as mentioned by @ NotMyself ) is like DirectCast , but it will return Nothing if the variable can't be converted into a string, rather than throwing an exception. This is the same as var as string in C#. The TryCast page on MSDN has a good comparison, too.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/40764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ] }
40,769
How do I determine the (local-) path for the "Program Files" directory on a remote computer? There does not appear to any version of SHGetFolderPath (or related function) that takes the name of a remote computer as a parameter. I guess I could try to query HKLM\Software\Microsoft\Windows\CurrentVersion\ProgramFilesDir using remote-registry, but I was hoping there would be "documented" way of doing it.
Those are all slightly different, and generally have an acceptable usage. var. ToString () is going to give you the string representation of an object, regardless of what type it is. Use this if var is not a string already. CStr (var) is the VB string cast operator. I'm not a VB guy, so I would suggest avoiding it, but it's not really going to hurt anything. I think it is basically the same as CType . CType (var, String) will convert the given type into a string, using any provided conversion operators. DirectCast (var, String) is used to up-cast an object into a string. If you know that an object variable is, in fact, a string, use this. This is the same as (string)var in C#. TryCast (as mentioned by @ NotMyself ) is like DirectCast , but it will return Nothing if the variable can't be converted into a string, rather than throwing an exception. This is the same as var as string in C#. The TryCast page on MSDN has a good comparison, too.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/40769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3923/" ] }
40,787
I'd like to keep a "compile-counter" for one of my projects. I figured a quick and dirty way to do this would be to keep a text file with a plain number in it, and then simply call upon a small script to increment this each time I compile. How would I go about doing this using the regular Windows command line? I don't really feel like installing some extra shell to do this but if you have any other super simple suggestions that would accomplish just this, they're naturally appreciated as well.
You can try a plain old batchfile. @echo offfor /f " delims==" %%i in (counter.txt) do set /A temp_counter= %%i+1echo %temp_counter% > counter.txt assuming the count.bat and counter.txt are located in the same directory.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/914/" ] }
40,814
I need to execute a large set of SQL statements (creating a bunch of tables, views and stored procedures) from within a C# program. These statements need to be separated by GO statements, but SqlCommand.ExecuteNonQuery() does not like GO statements. My solution, which I suppose I'll post for reference, was to split the SQL string on GO lines, and execute each batch separately. Is there an easier/better way?
Use SQL Server Management Objects (SMO) which understands GO separators. See my blog post here: http://weblogs.asp.net/jongalloway/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts- 2D00 -the-easy-way Sample code: public static void Main() { string scriptDirectory = "c:\\temp\\sqltest\\"; string sqlConnectionString = "Integrated Security=SSPI;" + "Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)"; DirectoryInfo di = new DirectoryInfo(scriptDirectory); FileInfo[] rgFiles = di.GetFiles("*.sql"); foreach (FileInfo fi in rgFiles) { FileInfo fileInfo = new FileInfo(fi.FullName); string script = fileInfo.OpenText().ReadToEnd(); using (SqlConnection connection = new SqlConnection(sqlConnectionString)) { Server server = new Server(new ServerConnection(connection)); server.ConnectionContext.ExecuteNonQuery(script); } }} If that won't work for you, see Phil Haack's library which handles that: http://haacked.com/archive/2007/11/04/a-library-for-executing-sql-scripts-with-go-separators-and.aspx
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/40814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ] }
40,816
If I have an HTML helper like so: Name:<br /><%=Html.TextBox("txtName",20) %><br /> How do I apply a CSS class to it? Do I have to wrap it in a span? Or do I need to somehow utilize the HtmlAttributes property of the helper?
You can pass it into the TextBox call as a parameter. Name:<br/> <%= Html.TextBox("txtName", "20", new { @class = "hello" }) %> This line will create a text box with the value 20 and assign the class attribute with the value hello. I put the @ character in front of the class, because class is a reserved keyword. If you want to add other attributes, just separate the key/value pairs with commas.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/40816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ] }
40,845
Has anyone had a chance to dig into how F# Units of Measure work? Is it just type-based chicanery, or are there CLR types hiding underneath that could (potentially) be used from other .net languages? Will it work for any numerical unit, or is it limited to floating point values (which is what all the examples use)?
According to a response on the next related blog post, they are a purely static mechanism in the F# compiler. So there is no CLR representation of the units data. Its not entirely clear whether it currently works with non-float types, but from the perspective of the type system it is theoretically possible.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2495/" ] }
40,853
I have some code like this in a winforms app I was writing to query a user's mail box Storage Quota. DirectoryEntry mbstore = new DirectoryEntry( @"LDAP://" + strhome, m_serviceaccount, [m_pwd], AuthenticationTypes.Secure); No matter what approach I tried (like SecureString ), I am easily able to see the password ( m_pwd ) either using Reflector or using strings tab of Process Explorer for the executable. I know I could put this code on the server or tighten up the security using mechanisms like delegation and giving only the required privileges to the service account. Can somebody suggest a reasonably secure way to store the password in the local application without revealing the password to hackers? Hashing is not possible since I need to know the exact password (not just the hash for matching purpose).Encryption/Decryption mechanisms are not working since they are machine dependent.
The sanctified method is to use CryptoAPI and the Data Protection APIs. To encrypt, use something like this (C++): DATA_BLOB blobIn, blobOut;blobIn.pbData=(BYTE*)data;blobIn.cbData=wcslen(data)*sizeof(WCHAR);CryptProtectData(&blobIn, description, NULL, NULL, NULL, CRYPTPROTECT_LOCAL_MACHINE | CRYPTPROTECT_UI_FORBIDDEN, &blobOut);_encrypted=blobOut.pbData;_length=blobOut.cbData; Decryption is the opposite: DATA_BLOB blobIn, blobOut;blobIn.pbData=const_cast<BYTE*>(data);blobIn.cbData=length;CryptUnprotectData(&blobIn, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &blobOut);std::wstring _decrypted;_decrypted.assign((LPCWSTR)blobOut.pbData,(LPCWSTR)blobOut.pbData+blobOut.cbData/sizeof(WCHAR)); If you don't specify CRYPTPROTECT_LOCAL_MACHINE then the encrypted password can be securely stored in the registry or config file and only you can decrypt it. If you specify LOCAL_MACHINE, then anyone with access to the machine can get it.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/40853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4337/" ] }
40,863
Basically I'm going to go a bit broad here and ask a few questions to get a bit of a picture of how people are handling UI these days. Lately I've found it pretty easy to do some fancy things with UI design and with WPF specifically we're finding new ways to do layouts that are better looking and more functional for the user, but in contrast one of the business focused guys at our local .NET User Group wouldn't even think of using WPF until it had a datagrid that he could use to make Excel like input forms. So basically, have you rethought the design of your business apps as you move to Web/WPF/Silverlight designs, because for us at least - in winforms we kept things fairly functional and uniform, or are you trying to keep that "known" UI? Would a dedicated design guy (for larger teams), or a dev with more design chops rank higher when looking at hiring these days? (Check out what a designer did for Scott Hanselman's BabySmash and Microsoft's Prism demo ) Are there any design hints/tips/guidelines you use for your UI - especially for WPF? What sites would you recommend for design?
I recommend that you read Steve Krug's Don't Make Me Think first. The book has a great checklist of things that you have to take into consideration when designing your UIs. While it's focused on web usability, a lot of the lessons therein are valuable even to desktop application designers. That being said, whether you use Windows forms or WPF or Flash or whatever new and shiny thing that comes around is, it is of utmost importance to hire either a) a real designer, or b) a development guy with a lot of UI design experience, either of which who can provide you a serious URL for their design portfolio. It will help a lot not only in improving the design of your application but also unburdening your developers from thinking about UI design, and allow them to focus on the back-end code. As for "business focused" guys -- it would be really great if you would get the opinion of actual customers and stake holders, and have them do some usability testing for your application. It's their opinion that would matter most. I think it would not be difficult to get a good designer up to speed on Microsoft Expression Blend to whip up some good XAML designs that your team could use to come up with a really good product.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3717/" ] }
40,873
I have a table which is full of arbitrarily formatted phone numbers, like this 027 123 5644021 393-5593(07) 123 456042123456 I need to search for a phone number in a similarly arbitrary format ( e.g. 07123456 should find the entry (07) 123 456 The way I'd do this in a normal programming language is to strip all the non-digit characters out of the 'needle', then go through each number in the haystack, strip all non-digit characters out of it, then compare against the needle, eg (in ruby) digits_only = lambda{ |n| n.gsub /[^\d]/, '' }needle = digits_only[input_phone_number]haystack.map(&digits_only).include?(needle) The catch is, I need to do this in MySQL. It has a host of string functions, none of which really seem to do what I want. Currently I can think of 2 'solutions' Hack together a franken-query of CONCAT and SUBSTR Insert a % between every character of the needle ( so it's like this: %0%7%1%2%3%4%5%6% ) However, neither of these seem like particularly elegant solutions. Hopefully someone can help or I might be forced to use the %%%%%% solution Update: This is operating over a relatively fixed set of data, with maybe a few hundred rows. I just didn't want to do something ridiculously bad that future programmers would cry over. If the dataset grows I'll take the 'phoneStripped' approach. Thanks for all the feedback! could you use a "replace" function to strip out any instances of "(", "-" and " ", I'm not concerned about the result being numeric.The main characters I need to consider are + , - , ( , ) and space So would that solution look like this? SELECT * FROM people WHERE REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phonenumber, '('),')'),'-'),' '),'+')LIKE '123456' Wouldn't that be terribly slow?
This looks like a problem from the start. Any kind of searching you do will require a table scan and we all know that's bad. How about adding a column with a hash of the current phone numbers after stripping out all formatting characters. Then you can at least index the hash values and avoid a full blown table scan. Or is the amount of data small and not expected to grow much?Then maybe just sucking all the numbers into the client and running a search there.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ] }
40,943
What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited? I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software?
Send the following headers before outputting the file: header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");header("Content-Type: application/octet-stream");header("Content-Length: " . filesize($File));header("Connection: close"); @grom : Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/40943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277/" ] }
40,994
Does anyone have time to take a look at it? I've read a bit and it promises a lot, if it's half what they say, it'll change web Development a lot
I have compared Mozilla Firefox 3.0.1 and Google Chrome 0.2.149.27 on SunSpider JavaScript Benchmark with the following results: Firefox - total: 2900.0ms +/- 1.8% Chrome - total: 1549.2ms +/- 1.7% and on V8 Benchmark Suite with the following results (higher score is better): Firefox - score: 212 Chrome - score: 1842 and on Web Browser Javascript Benchmark with the following results: Firefox - total duration: 362 ms Chrome - total duration: 349 ms Machine: Windows XP SP2, Intel Core2 DUO T7500 @ 2.2 Ghz, 2 GB RAM All blog posts and articles that I've read so far also claim that V8 is clearly the fastest JavaScript engine out there. See for example - V8, TraceMonkey, SquirrelFish, IE8 BenchMarks "... Needless to say, Chrome’s V8 blows away all the current builds of the next-generation of JavaScript VMs. Just to be clear, WebKit and FireFox engines haven’t even hit beta, but it looks like the performance bar has just been set to an astronomical height by the V8 Team."
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/40994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ] }
41,018
Grails makes it very easy to configure datasources for different environments (development, test, production) in its DataSources.groovy file, but there seems to be no facility for configuring multiple datasources in one environment. What to I do if I need to access several databases from the same Grails application?
Connecting different databases in different domain classes is very easy in Grails 2.x.x. for example development { dataSource {//DEFAULT data source . . }dataSource_admin { //Convention is dataSource_name url = "//db url" driverClassName = "oracle.jdbc.driver.OracleDriver" username = "test" password = 'test123' }dataSource_users { }} You can use any datasources in your domain classes by class Role{ static mapping = { datasource 'users' }} class Product{ static mapping = { datasource 'admin' } } For more details look at this
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2453/" ] }
41,039
Is there a way to search the latest version of every file in TFS for a specific string or regex? This is probably the only thing I miss from Visual Source Safe... Currently I perform a Get Latest on the entire codebase and use Windows Search, but this gets quite painful with over 1GB of code in 75,000 files. EDIT : Tried the powertools mentioned, but the "Wildcard Search" option appears to only search filenames and not contents. UPDATE : We have implemented a customised search option in an existing MOSS (Search Server) installation.
Team Foundation Server 2015 (on-premises) and Visual Studio Team Services (cloud version) include built-in support for searching across all your code and work items. You can do simple string searches like foo , boolean operations like foo OR bar or more complex language-specific things like class:WebRequest You can read more about it here: https://www.visualstudio.com/en-us/docs/search/overview
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/41039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/952/" ] }
41,045
As a general rule, I prefer using value rather than pointer semantics in C++ (ie using vector<Class> instead of vector<Class*> ). Usually the slight loss in performance is more than made up for by not having to remember to delete dynamically allocated objects. Unfortunately, value collections don't work when you want to store a variety of object types that all derive from a common base. See the example below. #include <iostream>using namespace std;class Parent{ public: Parent() : parent_mem(1) {} virtual void write() { cout << "Parent: " << parent_mem << endl; } int parent_mem;};class Child : public Parent{ public: Child() : child_mem(2) { parent_mem = 2; } void write() { cout << "Child: " << parent_mem << ", " << child_mem << endl; } int child_mem;};int main(int, char**){ // I can have a polymorphic container with pointer semantics vector<Parent*> pointerVec; pointerVec.push_back(new Parent()); pointerVec.push_back(new Child()); pointerVec[0]->write(); pointerVec[1]->write(); // Output: // // Parent: 1 // Child: 2, 2 // But I can't do it with value semantics vector<Parent> valueVec; valueVec.push_back(Parent()); valueVec.push_back(Child()); // gets turned into a Parent object :( valueVec[0].write(); valueVec[1].write(); // Output: // // Parent: 1 // Parent: 2} My question is: Can I have have my cake (value semantics) and eat it too (polymorphic containers)? Or do I have to use pointers?
Since the objects of different classes will have different sizes, you would end up running into the slicing problem if you store them as values. One reasonable solution is to store container safe smart pointers. I normally use boost::shared_ptr which is safe to store in a container. Note that std::auto_ptr is not. vector<shared_ptr<Parent>> vec;vec.push_back(shared_ptr<Parent>(new Child())); shared_ptr uses reference counting so it will not delete the underlying instance until all references are removed.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/41045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2994/" ] }
41,056
I'm a long-time emacs user, and I'm now working about 1/2 time in Java. What are the best emacs libraries for Debugging Java Code Completion/Intellisense Javadoc browsing ?
I've used JDEE on several projects. It handles Code Completion. I've never used it for debugging or browsing docs, but it's a big step up from a basic text editor.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4343/" ] }
41,107
I've been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would "likely" be unique over 500K+ generation (my needs don't really require anything much more sophisticated). Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like "AEYGF7K0DM1X" .
Algorithm To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length. Implementation Here's some fairly simple and very flexible code for generating random identifiers. Read the information that follows for important application notes. public class RandomString { /** * Generate a random string. */ public String nextString() { for (int idx = 0; idx < buf.length; ++idx) buf[idx] = symbols[random.nextInt(symbols.length)]; return new String(buf); } public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static final String lower = upper.toLowerCase(Locale.ROOT); public static final String digits = "0123456789"; public static final String alphanum = upper + lower + digits; private final Random random; private final char[] symbols; private final char[] buf; public RandomString(int length, Random random, String symbols) { if (length < 1) throw new IllegalArgumentException(); if (symbols.length() < 2) throw new IllegalArgumentException(); this.random = Objects.requireNonNull(random); this.symbols = symbols.toCharArray(); this.buf = new char[length]; } /** * Create an alphanumeric string generator. */ public RandomString(int length, Random random) { this(length, random, alphanum); } /** * Create an alphanumeric strings from a secure generator. */ public RandomString(int length) { this(length, new SecureRandom()); } /** * Create session identifiers. */ public RandomString() { this(21); }} Usage examples Create an insecure generator for 8-character identifiers: RandomString gen = new RandomString(8, ThreadLocalRandom.current()); Create a secure generator for session identifiers: RandomString session = new RandomString(); Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols: String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";RandomString tickets = new RandomString(23, new SecureRandom(), easy); Use as session identifiers Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used. There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand. The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible. Use as object identifiers Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big. Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission. Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." The probability of a collision, p , is approximately n 2 /(2q x ), where n is the number of identifiers actually generated, q is the number of distinct symbols in the alphabet, and x is the length of the identifiers. This should be a very small number, like 2 ‑50 or less. Working this out shows that the chance of collision among 500k 15-character identifiers is about 2 ‑52 , which is probably less likely than undetected errors from cosmic rays, etc. Comparison with UUIDs According to their specification, UUIDs are not designed to be unpredictable, and should not be used as session identifiers. UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters. UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/41107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3803/" ] }
41,155
In the process of developing my first WCF service and when I try to use it I get "Method not Allowed" with no other explanation. I've got my interface set up with the ServiceContract and OperationContract: [OperationContract] void FileUpload(UploadedFile file); Along with the actual method: public void FileUpload(UploadedFile file) {}; To access the Service I enter http://localhost/project/myService.svc/FileUpload but I get the "Method not Allowed" error Am I missing something?
Your browser is sending an HTTP GET request: Make sure you have the WebGet attribute on the operation in the contract: [ServiceContract]public interface IUploadService{ [WebGet()] [OperationContract] string TestGetMethod(); // This method takes no arguments, returns a string. Perfect for testing quickly with a browser. [OperationContract] void UploadFile(UploadedFile file); // This probably involves an HTTP POST request. Not so easy for a quick browser test. }
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/41155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/831/" ] }
41,162
I'd like to indicate to the user of a web app that a long-running task is being performed. Once upon a time, this concept would have been communicated to the user by displaying an hourglass. Nowadays, it seems to be an animated spinning circle. (e.g., when you are loading a new tab in Firefox, or booting in Mac OS X. Coincidentally, the overflowing stack in the stackoverflow logo looks like one quarter of the circle). Is there a simple way to create this effect using Javascript (in particular, JQuery)? Ideally, I'd like to have one of these little spinners as elements in a table, to indicate to the user that the system is still active in processing a pending task (i.e., it hasn't forgotten or crashed). (Of course, I realize it's possible that the back-end has crashed and the front-end still show as an animating spinning thing, it's more for the psychological purpose of the user seeing activity). And what do you call that spinning thing, anyways?
Google Ajax activity indicator to find lots of images and image generators (the "spinning" image itself is an animated GIF). Here is one link to get you started. With the image in hand, use JQuery to toggle the visibility of the image (or perhaps its parent DIV tag). See this link for some more info. rp
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ] }
41,198
How can I get an image to stretch the height of a DIV class? Currently it looks like this: However, I would like the DIV to be stretched so the image fits properly, but I do not want to resize the `image. Here is the CSS for the DIV (the grey box): .product1 { width: 100%; padding: 5px; margin: 0px 0px 15px -5px; background: #ADA19A; color: #000000; min-height: 100px;} The CSS being applied on the image: .product{ display: inline; float: left;} So, how can I fix this?
Add overflow:auto; to .product1
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/41198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ] }
41,207
For debugging and testing I'm searching for a JavaScript shell with auto completion and if possible object introspection (like ipython). The online JavaScript Shell is really nice, but I'm looking for something local, without the need for an browser. So far I have tested the standalone JavaScript interpreter rhino, spidermonkey and google V8. But neither of them has completion. At least Rhino with jline and spidermonkey have some kind of command history via key up/down, but nothing more. Any suggestions? This question was asked again here . It might contain an answer that you are looking for.
Rhino Shell since 1.7R2 has support for completion as well. You can find more information here .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/720/" ] }
41,218
I am running MAMP locally on my laptop, and I like to test as much as I can locally. Unfortunately, since I work on e-commerce stuff (PHP), I normally force ssl in most of the checkout forms and it just fails on my laptop. Is there any easy configuration that I might be missing to allow "https" to run under MAMP? Please note, I know that I could configure Apache by hand, re-compile PHP, etc. but I'm just wondering if there's an easier way for a lazy programmer. Thanks
First, make a duplicate of /Applications/MAMP. Open /Applications/MAMP/conf/apache/httpd.conf Below the line # LoadModule foo_module modules/mod_foo.so you add LoadModule ssl_module modules/mod_ssl.so Remove all lines <IfDefine SSL> as well as </IfDefine SSL> . Open /Applications/MAMP/conf/apache/ssl.conf Remove all lines <IfDefine SSL> as well as </IfDefine SSL> . Find the line defining SSLCertificateFile and SSLCertificateKeyFile , set it to SSLCertificateFile /Applications/MAMP/conf/apache/ssl/server.crt SSLCertificateKeyFile /Applications/MAMP/conf/apache/ssl/server.key Create a new folder /Applications/MAMP/conf/apache/ssl Drop into the terminal an navigate to the new folder cd /Applications/MAMP/conf/apache/ssl Create a private key, giving a password openssl genrsa -des3 -out server.key 1024 Remove the password cp server.key server-pw.key openssl rsa -in server-pw.key -out server.key Create a certificate signing request, pressing return for default values openssl req -new -key server.key -out server.csr Create a certificate openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt Restart your server. If you encounter any problems check the system log file. The first time you visit https://localhost/ you will be asked to accept the certificate.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4247/" ] }
41,220
The .NET System.Security.Cryptography namespace has a rather bewildering collection of algorithms that I could use for encryption of credit card details. Which is the best? It clearly needs to be secure for a relatively short string. EDIT: I'm in the UK, where I understand we're OK storing encrypted credit card details so long as the three-digit CVV number is never stored. And thanks all for the great responses.
No offense, but the question is a little "misguided". There is no "silver bullet" solution. I would recommend to read up on cryptography in general and then do some threat modeling. Some questions (by no means a comprehensive list) you should ask yourself: Is the module doing the encryption the one which needs to decrypt it (in this case use symmetric crypto) or will it send data to an other module (on an other machine) which will use it (in which case you should consider public-key crypto) What do you want to protect against? Someone accessing the database but not having the sourcecode (in which case you can hardcode the encryption key directly into the source)? Someone sniffing your local network (you should consider transparent solutions like IPSec)? Someone stealing your server (it can happen even in data centers - in which case full disk encryption should be considered)? Do you really need to keep the data? Can't you directly pass it to the credit card processor and erase it after you get the confirmation? Can't you store it locally at the client in a cookie or Flash LSO? If you store it at the client, make sure that you encrypt it at the server side before putting it in a cookie. Also, if you are using cookies, make sure that you make them http only. Is it enough to compare the equality of the data (ie the data that the client has given me is the same data that I have)? If so, consider storing a hash of it. Because credit card numbers are relatively short and use a reduced set of symbols, a unique salt should be generated for each before hashing. Later edit : note that standard encryption algorithms from the same category (for example 3DES and AES - both being symmetric block cyphers) are of comparable strength. Most (commercial) systems are not broken because somebody bruteforced their encryption, but because their threat modelling was not detailed enough (or flat out they didn't have any). For example you can encrypt all the data, but if you happen to have a public facing web interface which is vulnerable to SQL injection, it won't help you much.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/41220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3546/" ] }
41,233
I'm attracted to the neatness that a single file database provides. What driver/connector library is out there to connect and use SQLite with Java. I've discovered a wrapper library, http://www.ch-werner.de/javasqlite , but are there other more prominent projects available?
The wiki lists some more wrappers: Java wrapper (around a SWIG interface): http://tk-software.home.comcast.net/ A good tutorial to use JDBC driver for SQLite. (it works at least !) http://www.ci.uchicago.edu/wiki/bin/view/VDS/VDSDevelopment/UsingSQLite Cross-platform JDBC driver which uses embedded native SQLite libraries on Windows, Linux, OS X, and falls back to pure Java implementation on other OSes: https://github.com/xerial/sqlite-jdbc (formerly zentus ) Another Java - SWIG wrapper. It only works on Win32. http://rodolfo_3.tripod.com/index.html sqlite-java-shell: 100% pure Java port of the sqlite3 commandline shell built with NestedVM. (This is not a JDBC driver). SQLite JDBC Driver for Mysaifu JVM: SQLite JDBC Driver for Mysaifu JVM and SQLite JNI Library for Windows (x86) and Linux (i386/PowerPC).
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/41233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1915/" ] }
41,244
I found an example in the VS2008 Examples for Dynamic LINQ that allows you to use a SQL-like string (e.g. OrderBy("Name, Age DESC")) for ordering. Unfortunately, the method included only works on IQueryable<T> . Is there any way to get this functionality on IEnumerable<T> ?
Just stumbled into this oldie... To do this without the dynamic LINQ library, you just need the code as below. This covers most common scenarios including nested properties. To get it working with IEnumerable<T> you could add some wrapper methods that go via AsQueryable - but the code below is the core Expression logic needed. public static IOrderedQueryable<T> OrderBy<T>( this IQueryable<T> source, string property){ return ApplyOrder<T>(source, property, "OrderBy");}public static IOrderedQueryable<T> OrderByDescending<T>( this IQueryable<T> source, string property){ return ApplyOrder<T>(source, property, "OrderByDescending");}public static IOrderedQueryable<T> ThenBy<T>( this IOrderedQueryable<T> source, string property){ return ApplyOrder<T>(source, property, "ThenBy");}public static IOrderedQueryable<T> ThenByDescending<T>( this IOrderedQueryable<T> source, string property){ return ApplyOrder<T>(source, property, "ThenByDescending");}static IOrderedQueryable<T> ApplyOrder<T>( IQueryable<T> source, string property, string methodName) { string[] props = property.Split('.'); Type type = typeof(T); ParameterExpression arg = Expression.Parameter(type, "x"); Expression expr = arg; foreach(string prop in props) { // use reflection (not ComponentModel) to mirror LINQ PropertyInfo pi = type.GetProperty(prop); expr = Expression.Property(expr, pi); type = pi.PropertyType; } Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type); LambdaExpression lambda = Expression.Lambda(delegateType, expr, arg); object result = typeof(Queryable).GetMethods().Single( method => method.Name == methodName && method.IsGenericMethodDefinition && method.GetGenericArguments().Length == 2 && method.GetParameters().Length == 2) .MakeGenericMethod(typeof(T), type) .Invoke(null, new object[] {source, lambda}); return (IOrderedQueryable<T>)result;} Edit: it gets more fun if you want to mix that with dynamic - although note that dynamic only applies to LINQ-to-Objects (expression-trees for ORMs etc can't really represent dynamic queries - MemberExpression doesn't support it). But here's a way to do it with LINQ-to-Objects. Note that the choice of Hashtable is due to favorable locking semantics: using Microsoft.CSharp.RuntimeBinder;using System;using System.Collections;using System.Collections.Generic;using System.Dynamic;using System.Linq;using System.Runtime.CompilerServices;static class Program{ private static class AccessorCache { private static readonly Hashtable accessors = new Hashtable(); private static readonly Hashtable callSites = new Hashtable(); private static CallSite<Func<CallSite, object, object>> GetCallSiteLocked( string name) { var callSite = (CallSite<Func<CallSite, object, object>>)callSites[name]; if(callSite == null) { callSites[name] = callSite = CallSite<Func<CallSite, object, object>> .Create(Binder.GetMember( CSharpBinderFlags.None, name, typeof(AccessorCache), new CSharpArgumentInfo[] { CSharpArgumentInfo.Create( CSharpArgumentInfoFlags.None, null) })); } return callSite; } internal static Func<dynamic,object> GetAccessor(string name) { Func<dynamic, object> accessor = (Func<dynamic, object>)accessors[name]; if (accessor == null) { lock (accessors ) { accessor = (Func<dynamic, object>)accessors[name]; if (accessor == null) { if(name.IndexOf('.') >= 0) { string[] props = name.Split('.'); CallSite<Func<CallSite, object, object>>[] arr = Array.ConvertAll(props, GetCallSiteLocked); accessor = target => { object val = (object)target; for (int i = 0; i < arr.Length; i++) { var cs = arr[i]; val = cs.Target(cs, val); } return val; }; } else { var callSite = GetCallSiteLocked(name); accessor = target => { return callSite.Target(callSite, (object)target); }; } accessors[name] = accessor; } } } return accessor; } } public static IOrderedEnumerable<dynamic> OrderBy( this IEnumerable<dynamic> source, string property) { return Enumerable.OrderBy<dynamic, object>( source, AccessorCache.GetAccessor(property), Comparer<object>.Default); } public static IOrderedEnumerable<dynamic> OrderByDescending( this IEnumerable<dynamic> source, string property) { return Enumerable.OrderByDescending<dynamic, object>( source, AccessorCache.GetAccessor(property), Comparer<object>.Default); } public static IOrderedEnumerable<dynamic> ThenBy( this IOrderedEnumerable<dynamic> source, string property) { return Enumerable.ThenBy<dynamic, object>( source, AccessorCache.GetAccessor(property), Comparer<object>.Default); } public static IOrderedEnumerable<dynamic> ThenByDescending( this IOrderedEnumerable<dynamic> source, string property) { return Enumerable.ThenByDescending<dynamic, object>( source, AccessorCache.GetAccessor(property), Comparer<object>.Default); } static void Main() { dynamic a = new ExpandoObject(), b = new ExpandoObject(), c = new ExpandoObject(); a.X = "abc"; b.X = "ghi"; c.X = "def"; dynamic[] data = new[] { new { Y = a }, new { Y = b }, new { Y = c } }; var ordered = data.OrderByDescending("Y.X").ToArray(); foreach (var obj in ordered) { Console.WriteLine(obj.Y.X); } }}
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/41244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786/" ] }
41,300
How do you run Emacs in Windows? What is the best flavor of Emacs to use in Windows, and where can I download it? And where is the .emacs file located?
I use EmacsW32 , it works great. EDIT: I now use regular GNU Emacs 24, see below. See its EmacsWiki page for details. To me, the biggest advantage is that: it has a version of emacsclient that starts the Emacs server if no server is running (open all your files in the same Emacs window) it includes several useful packages such as Nxml it has a Windows installer or you can build it from sources And concerning XEmacs, according to this post by Steve Yegge: To summarize, I've argued that XEmacs has a much lower market share, poorer performance, more bugs, much lower stability, and at this point probably fewer features than GNU Emacs. When you add it all up, it's the weaker candidate by a large margin. EDIT: I now use regular GNU Emacs 24. It also contains Nxml, can be installed or built from sources, and with this wrapper , the Emacs server starts if no server is running. Cheers!
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/41300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/473/" ] }
41,304
I know in ASP.NET I can get an item from a DropDownList by using DropDownList1.Items.FindByText Is there a similar method I can use in WPF for a ComboBox? Here's the scenario. I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values. In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record. Here's the scenario. I have a table called RestrictionFormat that contains a column called RestrictionType, the type is a foreign key to a table that stores these values. In my editor application I'm writing, when the user selects the RestrictionFormat from a ComboBox (this works fine), I'm pulling up the details for editing. I'm using a second ComboBox to make sure the user only selects one RestrictionType when editing. I already have the second combobox bound property from the RestrictionType table, but I need to change the selected index on it to match the value specified in the record. Does this make sense?
Can you use ItemContainerGenerator? ItemContainerGenerator contains a ContainerFromItem method that takes an object parameter. If you have a reference to the full object that your comboBox contains (or a way to reconstruct it), you can use the following: ComboBoxItem item = (ComboBoxItem)myComboBox.ItemContainerGenerator.ContainerFromItem(myObject);
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71/" ] }
41,319
What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type IEnumerable<T> and doesn't have a Count property. Right now I'm tossing up between this: if (myList.Count() == 0) { ... } and this: if (!myList.Any()) { ... } My guess is that the second option is faster, since it'll come back with a result as soon as it sees the first item, whereas the second option (for an IEnumerable) will need to visit every item to return the count. That being said, does the second option look as readable to you? Which would you prefer? Or can you think of a better way to test for an empty list? Edit @lassevk's response seems to be the most logical, coupled with a bit of runtime checking to use a cached count if possible, like this: public static bool IsEmpty<T>(this IEnumerable<T> list){ if (list is ICollection<T>) return ((ICollection<T>)list).Count == 0; return !list.Any();}
You could do this: public static Boolean IsEmpty<T>(this IEnumerable<T> source){ if (source == null) return true; // or throw an exception return !source.Any();} Edit : Note that simply using the .Count method will be fast if the underlying source actually has a fast Count property. A valid optimization above would be to detect a few base types and simply use the .Count property of those, instead of the .Any() approach, but then fall back to .Any() if no guarantee can be made.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/41319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615/" ] }
41,367
In general, what kinds of design decisions help an application scale well? (Note: Having just learned about Big O Notation , I'm looking to gather more principles of programming here. I've attempted to explain Big O Notation by answering my own question below, but I want the community to improve both this question and the answers.) Responses so far 1) Define scaling. Do you need to scale for lots of users, traffic, objects in a virtual environment? 2) Look at your algorithms. Will the amount of work they do scale linearly with the actual amount of work - i.e. number of items to loop through, number of users, etc? 3) Look at your hardware. Is your application designed such that you can run it on multiple machines if one can't keep up? Secondary thoughts 1) Don't optimize too much too soon - test first. Maybe bottlenecks will happen in unforseen places. 2) Maybe the need to scale will not outpace Moore's Law, and maybe upgrading hardware will be cheaper than refactoring.
The only thing I would say is write your application so that it can be deployed on a cluster from the very start. Anything above that is a premature optimisation. Your first job should be getting enough users to have a scaling problem. Build the code as simple as you can first, then profile the system second and optimise only when there is an obvious performance problem. Often the figures from profiling your code are counter-intuitive; the bottle-necks tend to reside in modules you didn't think would be slow. Data is king when it comes to optimisation. If you optimise the parts you think will be slow, you will often optimise the wrong things.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4376/" ] }
41,397
Right, I know I am totally going to look an idiot with this one, but my brain is just not kicking in to gear this morning. I want to have a method where I can say "if it goes bad, come back with this type of Exception", right? For example, something like ( and this doesn't work ): static ExType TestException<ExType>(string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = new Exception(message); return ex; } Now whats confusing me is that we KNOW that the generic type is going to be of an Exception type due to the where clause. However, the code fails because we cannot implicitly cast Exception to ExType . We cannot explicitly convert it either, such as: static ExType TestException<ExType>(string message) where ExType:Exception { Exception ex1 = new Exception(); ExType ex = (ExType)(new Exception(message)); return ex; } As that fails too.. So is this kind of thing possible? I have a strong feeling its going to be real simple, but I am having a tough day with the old noggin, so cut me some slack :P Update Thanks for the responses guys, looks like it wasn't me being a complete idiot! ;) OK, so Vegard and Sam got me on to the point where I could instantiate the correct type, but then obviously got stuck because the message param is read-only following instantiation. Matt hit the nail right on the head with his response, I have tested this and all works fine. Here is the example code: static ExType TestException<ExType>(string message) where ExType:Exception, new () { ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message); return ex; } Sweet! :) Thanks guys!
You can almost do it like this: static void TestException<E>(string message) where E : Exception, new(){ var e = new E(); e.Message = message; throw e;} However, that doesn't compile because Exception.Message is read only. It can only be assigned by passing it to the constructor, and there's no way to constrain a generic type with something other than a default constructor. I think you'd have to use reflection (Activator.CreateInstance) to "new up" the custom exception type with the message parameter, like this: static void TestException<E>(string message) where E : Exception{ throw Activator.CreateInstance(typeof(E), message) as E;} Edit Oops just realised you're wanting to return the exception, not throw it. The same principle applies, so I'll leave my answer as-is with the throw statements.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/41397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ] }
41,400
I am looking to do this in C/C++. I came across Variable Length Arguments , but this suggests a solution with Python and C using libffi . Now, if I want to wrap the printf function with myprintf . I do it like below: void myprintf(char* fmt, ...){ va_list args; va_start(args, fmt); printf(fmt, args); va_end(args);}int _tmain(int argc, _TCHAR* argv[]){ int a = 9; int b = 10; char v = 'C'; myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b); return 0;} But the results are not as expected! This is a number: 1244780 andthis is a character: h andanother number: 29953463 What did I miss?
The problem is that you cannot use 'printf' with va_args . You must use vprintf if you are using variable argument lists. vprint , vsprintf , vfprintf , etc. (there are also 'safe' versions in Microsoft's C runtime that will prevent buffer overruns, etc.) You sample works as follows: void myprintf(char* fmt, ...){ va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args);}int _tmain(int argc, _TCHAR* argv[]){ int a = 9; int b = 10; char v = 'C'; myprintf("This is a number: %d and \nthis is a character: %c and \n another number: %d\n", a, v, b); return 0;}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/41400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123/" ] }
41,406
I'm trying to write a page that calls PHP that's stored in a MySQL database. The page that is stored in the MySQL database contains PHP (and HTML) code which I want to run on page load. How could I go about doing this?
You can use the eval command for this. I would recommend against this though, because there's a lot of pitfalls using this approach. Debugging is hard(er), it implies some security risks (bad content in the DB gets executed, uh oh). See When is eval evil in php? for instance. Google for Eval is Evil, and you'll find a lot of examples why you should find another solution. Addition: Another good article with some references to exploits is this blogpost . Refers to past vBulletin and phpMyAdmin exploits which were caused by improper Eval usage.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/41406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3654/" ] }
41,424
Possible Duplicate: How does the Google “Did you mean?” Algorithm work? Suppose you have a search system already in your website. How can you implement the "Did you mean: <spell_checked_word> " like Google does in some search queries ?
Actually what Google does is very much non-trivial and also at first counter-intuitive. They don't do anything like check against a dictionary, but rather they make use of statistics to identify "similar" queries that returned more results than your query, the exact algorithm is of course not known. There are different sub-problems to solve here, as a fundamental basis for all Natural Language Processing statistics related there is one must have book: Foundation of Statistical Natural Language Processing . Concretely to solve the problem of word/query similarity I have had good results with using Edit Distance , a mathematical measure of string similarity that works surprisingly well. I used to use Levenshtein but the others may be worth looking into. Soundex - in my experience - is crap. Actually efficiently storing and searching a large dictionary of misspelled words and having sub second retrieval is again non-trivial, your best bet is to make use of existing full text indexing and retrieval engines (i.e. not your database's one), of which Lucene is currently one of the best and coincidentally ported to many many platforms.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/41424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ] }
41,449
The exact error is as follows Could not load file or assembly 'Microsoft.SqlServer.Replication, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. An attempt was made to load a program with an incorrect format. I've recently started working on this project again after a two month move to another project. It worked perfectly before, and I've double checked all the references.
The answer by baldy below is correct, but you may also need to enable 32-bit applications in your AppPool. Source: http://www.alexjamesbrown.com/uncategorized/could-not-load-file-or-assembly-chilkatdotnet2-or-one-of-its-dependencies-an-attempt-was-made-to-load-a-program-with-an-incorrect-format/ Whilst setting up an application to run on my local machine (running Vista 64bit) I encountered this error: Could not load file or assembly ChilkatDotNet2 or one of its dependencies. An attempt was made to load a program with an incorrect format. Obviously, the application uses ChilKat components , but it would seem that the version we are using, is only the 32bit version. To resolve this error, I set my app pool in IIS to allow 32bit applications.Open up IIS Manager, right click on the app pool, and select Advanced Settings (See below) Then set "Enable 32-bit Applications" to True. All done!
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/41449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2012/" ] }
41,453
I'd like to be able to introspect a C++ class for its name, contents (i.e. members and their types) etc. I'm talking native C++ here, not managed C++, which has reflection. I realise C++ supplies some limited information using RTTI. Which additional libraries (or other techniques) could supply this information?
What you need to do is have the preprocessor generate reflection data about the fields. This data can be stored as nested classes. First, to make it easier and cleaner to write it in the preprocessor we will use typed expression. A typed expression is just an expression that puts the type in parenthesis. So instead of writing int x you will write (int) x . Here are some handy macros to help with typed expressions: #define REM(...) __VA_ARGS__#define EAT(...)// Retrieve the type#define TYPEOF(x) DETAIL_TYPEOF(DETAIL_TYPEOF_PROBE x,)#define DETAIL_TYPEOF(...) DETAIL_TYPEOF_HEAD(__VA_ARGS__)#define DETAIL_TYPEOF_HEAD(x, ...) REM x#define DETAIL_TYPEOF_PROBE(...) (__VA_ARGS__),// Strip off the type#define STRIP(x) EAT x// Show the type without parenthesis#define PAIR(x) REM x Next, we define a REFLECTABLE macro to generate the data about each field(plus the field itself). This macro will be called like this: REFLECTABLE( (const char *) name, (int) age) So using Boost.PP we iterate over each argument and generate the data like this: // A helper metafunction for adding const to a typetemplate<class M, class T>struct make_const{ typedef T type;};template<class M, class T>struct make_const<const M, T>{ typedef typename boost::add_const<T>::type type;};#define REFLECTABLE(...) \static const int fields_n = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__); \friend struct reflector; \template<int N, class Self> \struct field_data {}; \BOOST_PP_SEQ_FOR_EACH_I(REFLECT_EACH, data, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))#define REFLECT_EACH(r, data, i, x) \PAIR(x); \template<class Self> \struct field_data<i, Self> \{ \ Self & self; \ field_data(Self & self) : self(self) {} \ \ typename make_const<Self, TYPEOF(x)>::type & get() \ { \ return self.STRIP(x); \ }\ typename boost::add_const<TYPEOF(x)>::type & get() const \ { \ return self.STRIP(x); \ }\ const char * name() const \ {\ return BOOST_PP_STRINGIZE(STRIP(x)); \ } \}; \ What this does is generate a constant fields_n that is number of reflectable fields in the class. Then it specializes the field_data for each field. It also friends the reflector class, this is so it can access the fields even when they are private: struct reflector{ //Get field_data at index N template<int N, class T> static typename T::template field_data<N, T> get_field_data(T& x) { return typename T::template field_data<N, T>(x); } // Get the number of fields template<class T> struct fields { static const int n = T::fields_n; };}; Now to iterate over the fields we use the visitor pattern. We create an MPL range from 0 to the number of fields, and access the field data at that index. Then it passes the field data on to the user-provided visitor: struct field_visitor{ template<class C, class Visitor, class I> void operator()(C& c, Visitor v, I) { v(reflector::get_field_data<I::value>(c)); }};template<class C, class Visitor>void visit_each(C & c, Visitor v){ typedef boost::mpl::range_c<int,0,reflector::fields<C>::n> range; boost::mpl::for_each<range>(boost::bind<void>(field_visitor(), boost::ref(c), v, _1));} Now for the moment of truth we put it all together. Here is how we can define a Person class that is reflectable: struct Person{ Person(const char *name, int age) : name(name), age(age) { }private: REFLECTABLE ( (const char *) name, (int) age )}; Here is a generalized print_fields function using the reflection data to iterate over the fields: struct print_visitor{ template<class FieldData> void operator()(FieldData f) { std::cout << f.name() << "=" << f.get() << std::endl; }};template<class T>void print_fields(T & x){ visit_each(x, print_visitor());} An example of using the print_fields with the reflectable Person class: int main(){ Person p("Tom", 82); print_fields(p); return 0;} Which outputs: name=Tomage=82 And voila, we have just implemented reflection in C++, in under 100 lines of code.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/41453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3233/" ] }
41,460
In simple terms, what are the reasons for, and what are the differences between the GPL v2 and GPL v3 open source licenses? Explanations and references to legal terms and further descriptions would be appreciated.
The page linked to in another answer is a good source, but a lot to read. Here is a short list of some the major differences: internationalization: they used new terminology, rather than using language tied to US legal concepts patents: they specifically address patents (including the Microsoft/Novell issue noted in another answer) “Tivo-ization”: they address the restrictions (like Tivo’s) in consumer products that take away, though hardware, the ability to modify the software DRM: they address digital rights management (which they call digital restrictions management) compatibility: they addressed compatibility with some other open source licenses termination: they addressed specifically what happens if the license is violated and the cure of violations I agree with the comment about consulting a lawyer (one who knows about software license issues, though). In doing these things (and more), they more than doubled the length of the GPL. GPL 3 is many things, and one of them is that it is a very complex, technical legal document.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/41460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3233/" ] }
41,469
I am planning on creating a small website for my personal book collection. To automate the process a little bit, I would like to create the following functionality: The website will ask me for the ISBN number of the book and will then automatically fetch the title and add it to my database. Although I am mainly interested in doing this in php, I also have some Java implementation ideas for this. I believe it could also help if the answer was as much language-agnostic as possible.
This is the LibraryThing founder. We have nothing to offer here, so I hope my comments will not seem self-serving. First, the comment about Amazon, ASINs and ISBN numbers is wrong in a number of ways. In almost every circumstance where a book has an ISBN, the ASIN and the ISBN are the same. ISBNs are not now 13 digits. Rather, ISBNs can be either 10 or 13. Ten-digit ISBNs can be expressed as 13-digit ones starting with 978, which means every ISBN currently in existence has both a 10- and a 13-digit form. There are all sorts of libraries available for converting between ISBN10 and ISBN13. Basically, you add 978 to the front and recalculate the checksum digit at the end. ISBN13 was invented because publishers were running out of ISBNs. In the near future, when 979-based ISBN13s start being used, they will not have an ISBN10 equivalent. To my knowledge, there are no published books with 979-based ISBNs, but they are coming soon. Anyway, the long and short of it is that Amazon uses the ISBN10 form for all 978 ISBN10s. In any case, whether or not Amazon uses ten or thirteen-digit ASINs, you can search Amazon by either just fine. Personally, I wouldn't put ISBN DB at the top of your list. ISBN DB mines from a number of sources, but it's not as comprehensive as Amazon or Google. Rather, I'd look into Amazon—including the various international Amazons—and then the new Google Book Data API and, after that, the OpenLibrary API. For non-English books, there are other options, like Ozone for Russian books. If you care about the highest-quality data, or if you have any books published before about 1970, you will want to look into data from libraries, available by Z39.50 protocol and usually in MARC format, or, with a few libraries in Dublin Core, using the SRU/SRW protocol. MARC format is, to a modern programmer, pretty strange stuff. But, once you get it, it's also better data and includes useful fields like the LCCN, DDC, LCC, and LCSH. LibraryThing runs off a homemade Python library that queries some 680 libraries and converts the many flavors of MARC into Amazon-compatible XML, with extras. We are currently reluctant to release the code, but maybe releasing a service soon.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/41469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ] }
41,479
After discussion with colleagues regarding the use of the 'var' keyword in C# 3 I wondered what people's opinions were on the appropriate uses of type inference via var? For example I rather lazily used var in questionable circumstances, e.g.:- foreach(var item in someList) { // ... } // Type of 'item' not clear.var something = someObject.SomeProperty; // Type of 'something' not clear.var something = someMethod(); // Type of 'something' not clear. More legitimate uses of var are as follows:- var l = new List<string>(); // Obvious what l will be.var s = new SomeClass(); // Obvious what s will be. Interestingly LINQ seems to be a bit of a grey area, e.g.:- var results = from r in dataContext.SomeTable select r; // Not *entirely clear* what results will be here. It's clear what results will be in that it will be a type which implements IEnumerable, however it isn't entirely obvious in the same way a var declaring a new object is. It's even worse when it comes to LINQ to objects, e.g.:- var results = from item in someList where item != 3 select item; This is no better than the equivilent foreach(var item in someList) { // ... } equivilent. There is a real concern about type safety here - for example if we were to place the results of that query into an overloaded method that accepted IEnumerable<int> and IEnumerable<double> the caller might inadvertently pass in the wrong type. var does maintain strong typing but the question is really whether it's dangerous for the type to not be immediately apparent on definition, something which is magnified when overloads mean compiler errors might not be issued when you unintentionally pass the wrong type to a method.
I still think var can make code more readable in some cases. If I have a Customer class with an Orders property, and I want to assign that to a variable, I will just do this: var orders = cust.Orders; I don't care if Customer.Orders is IEnumerable<Order> , ObservableCollection<Order> or BindingList<Order> - all I want is to keep that list in memory to iterate over it or get its count or something later on. Contrast the above declaration with: ObservableCollection<Order> orders = cust.Orders; To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from ObservableCollection<Order> to IList<Order> ) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/41479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3394/" ] }
41,504
Is there any library (or even better, web service) available which can convert from a latitude/longitude into a time zone?
I looked fairly deeply into this question for a project I am working on. GeoNames.org and EarthTools.com are both good options for many situations but with the following serious flaws: GeoNames.org finds the time zone by searching for the nearest point in their database that contains a time zone field. This often leads to the wrong result near borders. It is also painfully slow, leading to query times on the order of a couple seconds per request. It also doesn't return a valid time zone if there is no item in their database near the query point. GeoNames also restricts the number of queries that can be made per day, making bulk operations difficult. EarthTools.org uses a map and is able to return queries quickly, but it doesn't take into account daylight savings time for most locations, and it returns a raw offset rather than a time zone ID (i.e., they return "GMT-7" instead of "America/Chicago"). Also, I just looked at their page while preparing this post and Google Chrome warned about malware on their site. That is new to me and it may change, but is obviously a cause for concern. These flaws meant that these existing tools were not suitable for my needs so I rolled my own solution and have published it for general use. You can find it here: http://www.askgeo.com/ AskGeo is based on a time zone map of the world, so it returns a valid time zone for every valid latitude and longitude. It returns the standard time zone ID (e.g., "America/Los_Angeles") used on Linux and most other operating systems and programming frameworks. It also returns the current offset, taking full account of daylight savings time. It is extremely easy to use and usage is documented on the main page of the site. The API supports batch queries, so if you need to do a lot of look-ups, please use the batch interface rather than bog down our servers with serial requests. The bulk queries are also much faster, so everybody wins. When we first launched this, we built it on Google App Engine (GAE) and made it free to all users. This was possible because GAE's prices were so low at that time. Since then, our server load has increased substantially and GAE's prices went way up. Both factors combined led us to switch to Amazon Web Services for hosting and to start charging for commercial use, while keeping the service free for non-profit, non-commercial open source projects, and researchers. For commercial users, we provide 1000 free queries to let potential customers evaluate the API to make sure it meets their needs. See the web site for pricing and terms. The underlying library was written in Java and due to popular demand, we also released the library under a commercial license. Full documentation of the library and pricing details are on the web site. I hope this is useful. It certainly was useful for the project I was working on.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/41504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ] }
41,547
I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests. In my template setup, I have base.html, and the other pages extend this. I want to show logged in or register button in the base.html, but how can I ensure that the necessary variables are always a part of the context? It seems that each view just sets up the context as they like, and there is no global context population. Is there a way of doing this without including the user in each context creation? Or will I have to make my own custom shortcuts to setup the context properly?
There is no need to write a context processor for the user object if you already have the "django.core.context_processors.auth" in TEMPLATE_CONTEXT_PROCESSORS and if you're using RequestContext in your views. if you are using django 1.4 or latest the module has been moved to django.contrib.auth.context_processors.auth
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/41547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ] }
41,561
I'm trying to understand how namespaces work in XML. When I have an element like foo:bar, the attributes will often not have namespaces on them. But sometimes they will. Are the attribute in the namespace of the element, even when the default namespace has been declared? Looking over the xsd for xhtml it seems the attributes are part of the schema and should be in the namespace for xhtml, but they are never presented that way...
Most of the time, attributes will not be in any namespace. The namespace spec says ( emphasis mine): A default namespace declaration applies to all unprefixed element names within its scope. Default namespace declarations do not apply directly to attribute names; the interpretation of unprefixed attributes is determined by the element on which they appear. There's a reason that most XML vocabularies use non-namespaced attributes: When your elements have a namespace and those elements have attributes, then there can be no confusion: the attributes belong to your element, which belongs to your namespace. Adding a namespace prefix to the attributes would just make everything more verbose. So why do namespaced attributes exist? Because some vocabularies do useful work with mostly attributes, and can do this when mixed in with other vocabularies. The best known example is XLink . Lastly, W3C XML Schema has an all too easy way ( <schema attributeFormDefault="qualified"> ) of declaring your attributes as being in a namespace, forcing you to prefix them in your documents, even when you use a default namespace.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/41561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4315/" ] }
41,568
this kind of follows on from another question of mine. Basically, once I have the code to access the file (will review the answers there in a minute) what would be the best way to test it? I am thinking of creating a method which just spawns lots of BackgroundWorker 's or something and tells them all load/save the file, and test with varying file/object sizes. Then, get a response back from the threads to see if it failed/succeeded/made the world implode etc. Can you guys offer any suggestions on the best way to approach this? As I said before, this is all kinda new to me :) Edit Following ajmastrean's post: I am using a console app to test with Debug.Asserts :) Update I originally rolled with using BackgroundWorker to deal with the threading (since I am used to that from Windows dev) I soon realised that when I was performing tests where multiple ops (threads) needed to complete before continuing, I realised it was going to be a bit of a hack to get it to do this. I then followed up on ajmastrean 's post and realised I should really be using the Thread class for working with concurrent operations. I will now refactor using this method (albeit a different approach).
In .NET, ThreadPool threads won't return without setting up ManualResetEvent s or AutoResetEvent s. I find these overkill for a quick test method (not to mention kind of complicated to create, set, and manage). Background worker is a also a bit complex with the callbacks and such. Something I have found that works is Create an array of threads. Setup the ThreadStart method of each thread. Start each thread. Join on all threads (blocks the current thread until all other threads complete or abort) public static void MultiThreadedTest(){ Thread[] threads = new Thread[count]; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(DoSomeWork()); } foreach(Thread thread in threads) { thread.Start(); } foreach(Thread thread in threads) { thread.Join(); }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ] }
41,590
I come from a Java background, where packages are used, not namespaces. I'm used to putting classes that work together to form a complete object into packages, and then reusing them later from that package. But now I'm working in C++. How do you use namespaces in C++? Do you create a single namespace for the entire application, or do you create namespaces for the major components? If so, how do you create objects from classes in other namespaces?
Namespaces are packages essentially. They can be used like this: namespace MyNamespace{ class MyClass { };} Then in code: MyNamespace::MyClass* pClass = new MyNamespace::MyClass(); Or, if you want to always use a specific namespace, you can do this: using namespace MyNamespace;MyClass* pClass = new MyClass(); Edit: Following what bernhardrusch has said, I tend not to use the "using namespace x" syntax at all, I usually explicitly specify the namespace when instantiating my objects (i.e. the first example I showed). And as you asked below , you can use as many namespaces as you like.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/41590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585/" ] }
41,601
We are working on a large project with a measure of new/modified GUI functionality. We've found in the past that we often introduced new problems in related code when adding new functionality. We have non-technical users perform testing, but they often miss parts and allow bugs to slip through. Are there any best practices for organizing the UI testing of a WinForms project? Is there any way to automate it?
There are GUI testing tools that will click buttons and stuff for you but they're pretty fragile in my experience. The best thing to do is to keep your UI layer as thin as possible. Your event handler classes should optimally be only one or two lines that call out to other more testable classes. That way you can test your business logic in unit tests without having to actually do a button click.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4392/" ] }
41,647
When using the php include function the include is succesfully executed, but it is also outputting a char before the output of the include is outputted, the char is of hex value 3F and I have no idea where it is coming from, although it seems to happen with every include. At first I thbought it was file encoding, but this doesn't seem to be a problem. I have created a test case to demonstrate it: ( link no longer working ) http://driveefficiently.com/testinclude.php this file consists of only: <? include("include.inc"); ?> and include.inc consists of only: <? echo ("hello, world"); ?> and yet, the output is: "?hello, world" where the ? is a char with a random value. It is this value that I do not know the origins of and it is sometimes screwing up my sites a bit. Any ideas of where this could be coming from? At first I thought it might be something to do with file encoding, but I don't think its a problem.
What you are seeing is a UTF-8 Byte Order Mark: The UTF-8 representation of the BOM is the byte sequence EF BB BF, which appears as the ISO-8859-1 characters  in most text editors and web browsers not prepared to handle UTF-8. Byte Order Mark on Wikipedia PHP does not understand that these characters should be "hidden" and sends these to the browser as if they were normal characters. To get rid of them you will need to open the file using a "proper" text editor that will allow you to save the file as UTF-8 without the leading BOM. You can read more about this problem here
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1111/" ] }
41,652
We have got a custom MembershipProvider in ASP.NET . Now there are 2 possible scenario the user can be validated: User login via login.aspx page by entering his username/password. I have used Login control and linked it with the MyMembershipProvider . This is working perfectly fine. An authentication token is passed via some URL in query string form a different web sites. For this I have one overload in MembershipProvider.Validate(string authenticationToken) , which is actually validating the user. In this case we cannot use the Login control . Now how can I use the same MembershipProvider to validate the user without actually using the Login control ? I tried to call Validate manually, but this is not signing the user in. Here is the code snippet I am using if (!string.IsNullOrEmpty(Request.QueryString["authenticationToken"])) { string ticket = Request.QueryString["authenticationToken"]; MyMembershipProvider provider = Membership.Provider as MyMembershipProvider; if (provider != null) { if (provider.ValidateUser(ticket)) // Login Success else // Login Fail }}
After validation is successful, you need to sign in the user, by calling FormsAuthentication.Authenticate: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx EDIT: It is FormsAuthentication.SetAuthCookie: http://msdn.microsoft.com/en-us/library/twk5762b.aspx Also, to redirect the user back where he wanted to go, call: FormsAuthentication.RedirectFromLoginPage: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.redirectfromloginpage.aspx link text
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ] }
41,665
Is there any way to convert a bmp image to jpg/png without losing the quality in C#? Using Image class we can convert bmp to jpg but the quality of output image is very poor. Can we gain the quality level as good as an image converted to jpg using photoshop with highest quality?
var qualityEncoder = Encoder.Quality;var quality = (long)<desired quality>;var ratio = new EncoderParameter(qualityEncoder, quality );var codecParams = new EncoderParameters(1);codecParams.Param[0] = ratio;var jpegCodecInfo = <one of the codec infos from ImageCodecInfo.GetImageEncoders() with mime type = "image/jpeg">;bmp.Save(fileName, jpegCodecInfo, codecParams); // Save to JPG
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/41665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ] }
41,701
I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username) For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code like this:(jobId, label, username) = job I've realised, however, that this is a maintenance nightmare, because now I can never add new fields to the result set without breaking all of my existing code. How should I have written this? Here are my two best guesses:(jobId, label, username) = (job[0], job[1], job[2])...but that doesn't scale nicely when you have 15...20 fields or to convert the results from the SQL query to a dictionary straight away and pass that around (I don't have control over the fact that it starts life as a tuple, that's fixed for me)
I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the tuple to a dictionary and the code that actually makes use of the new values. For example: job={}job['jobid'], job['label'], job['username']=<querycode>
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4397/" ] }
41,712
As someone with some winforms and client applications experience - is it worth going back and learning the way traditional ASP .NET pages work, or is it okay with moving straight into ASP .NET MVC? I'm kind of looking for pitfalls or traps in my knowledge of general C#, that I won't know from the screencast series and things on the ASP .NET site.
Here is the great thing about MVC. It works closer to the base of the framework than normal ASP.NET Web Forms. So by using MVC and understanding it, you will have a better understanding of how WebForms work. The problem with WebForms is there is a lot of magic and about 6 years of trying to make the Web work like Windows Forms, so you have the control tree hierarchy and everything translated to the Web. With MVC you get the core with out the WinForm influence. So start with MVC, and you will easily be able to move in to WebForms if needed.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/41712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3717/" ] }
41,724
I'm hearing more and more about domain specific languages being thrown about and how they change the way you treat business logic, and I've seen Ayende's blog posts and things, but I've never really gotten exactly why I would take my business logic away from the methods and situations I'm using in my provider. If you've got some background using these things, any chance you could put it in real laymans terms: What exactly building DSLs means? What languages are you using? Where using a DSL makes sense? What is the benefit of using DSLs?
DSL's are good in situations where you need to give some aspect of the system's control over to someone else. I've used them in Rules Engines, where you create a simple language that is easier for less-technical folks to use to express themselves- particularly in workflows. In other words, instead of making them learn java: DocumentDAO myDocumentDAO = ServiceLocator.getDocumentDAO();for (int id : documentIDS) {Document myDoc = MyDocumentDAO.loadDoc(id);if (myDoc.getDocumentStatus().equals(DocumentStatus.UNREAD)) { ReminderService.sendUnreadReminder(myDoc)} I can write a DSL that lets me say: for (document : documents) {if (document is unread) { document.sendReminder} There are other situations, but basically, anywhere you might want to use a macro language, script a workflow, or allow after-market customization- these are all candidates for DSL's.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3717/" ] }
41,733
Say I have an array of records which I want to sort based on one of the fields in the record. What's the best way to achieve this? TExample = record SortOrder : integer; SomethingElse : string;end;var SomeVar : array of TExample;
You can add pointers to the elements of the array to a TList , then call TList.Sort with a comparison function, and finally create a new array and copy the values out of the TList in the desired order. However, if you're using the next version, D2009, there is a new collections library which can sort arrays. It takes an optional IComparer<TExample> implementation for custom sorting orders. Here it is in action for your specific case: TArray.Sort<TExample>(SomeVar , TDelegatedComparer<TExample>.Construct( function(const Left, Right: TExample): Integer begin Result := TComparer<Integer>.Default.Compare(Left.SortOrder, Right.SortOrder); end));
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/41733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1008/" ] }
41,766
I just saw a really cool WPF twitter client that I think is developed by the Herding Code podcast guys HerdingCode called Witty . (or at least, I see a lot of those guys using this client). This project is currently posted up on Google Code. Many of the projects on Google Code use Subversion as the version control system (including Witty). Having never used Subversion, I'm not sure what to do to download the code. On the source page for this project ( google code witty source ) it gives the following instruction: Non-members may check out a read-only working copy anonymously over HTTP. svn checkout http://wittytwitter.googlecode.com/svn/trunk/ wittytwitter-read-only I'm confused as to where I am supposed to enter the above command so that I can download the code. I have installed SVN and Tortoise (which I know almost nothing about). Thanks for any help or simply pointing me in the right direction. ...Ed (@emcpadden)
After you install Tortoise (separate SVN client not required), create a new empty folder for the project somewhere and right click it in Windows. There should be an option for SVN Checkout . Choosing that option will open a dialog box. Paste the URL you posted above in the first textbox of that dialog box and click "OK".
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/41766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2858/" ] }
41,781
I've worked with T-SQL for years but I've just moved to an organisation that is going to require writing some Oracle stuff, probably just simple CRUD operations at least until I find my feet. I'm not going to be migrating databases from one to the other simply interacting with existing Oracle databases from an Application Development perspective. Is there are tool or utility available to easily translate T-SQL into Oracle SQL, a keyword mapper is the sort of thing I'm looking for. P.S. I'm too lazy to RTFM, besides it's not going to be a big part of my role so I just want something to get me up to speed a little faster.
The language difference listed so far are trivial compared to the logical differences. Anyone can lookup NVL. What's hard to lookup is DDL In SQL server you manipulate your schema, anywhere, anytime, with little or no fuss. In Oracle, we don't like DDL in stored procedures so you have jump through hoops. You need to use EXECUTE IMMEDIATE to perform a DDL function. Temp Tables IN SQL Server when the logic becomes a bit tough, the common thing is to shortcut the sql and have it resolved to a temp table and then the next step is done using that temp table.MSSS makes it very easy to do this. In Oracle we don't like that. By forcing an intermediate result you completely prevent the Optimizer from finding a shortcut for you. BUT If you must stop halfway and persist the intermediate results Oracle wants you to make the temp table in advance, not on the fly. Locks In MSSS you worry about locking, you have nolock hints to apply to DML, you have lock escalation to reduce the count of locks. In Oracle we don't worry about these in that way. Read Commited Until recently MSSS didn't fully handle Read Committed isolation so you worried about dirty reads. Oracle has been that way for decades. etc MSSS has no concept of Bitmap indexes, IOT, Table Clusters, Single Table hash clusters, non unique indexes enforcing unique constraints....
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403/" ] }
41,837
I have a table with more than a millon rows. This table is used to index tiff images. Each image has fields like date , number , etc. I have users that index these images in batches of 500. I need to know if it is better to first insert 500 rows and then perform 500 updates or, when the user finishes indexing, to do the 500 inserts with all the data. A very important thing is that if I do the 500 inserts at first, this time is free for me because I can do it the night before. So the question is: is it better to do inserts or inserts and updates, and why? I have defined a id value for each image, and I also have other indices on the fields.
Updates in Sql server result in ghosted rows - i.e. Sql crosses one row out and puts a new one in. The crossed out row is deleted later. Both inserts and updates can cause page-splits in this way, they both effectively 'add' data, it's just that updates flag the old stuff out first. On top of this updates need to look up the row first, which for lots of data can take longer than the update. Inserts will just about always be quicker, especially if they are either in order or if the underlying table doesn't have a clustered index. When inserting larger amounts of data into a table look at the current indexes - they can take a while to change and build. Adding values in the middle of an index is always slower. You can think of it like appending to an address book: Mr Z can just be added to the last page, while you'll have to find space in the middle for Mr M.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/41837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1154/" ] }
41,842
When should I include PDB files for a production release? Should I use the Optimize code flag and how would that affect the information I get from an exception? If there is a noticeable performance benefit I would want to use the optimizations but if not I'd rather have accurate debugging info. What is typically done for a production app?
When you want to see source filenames and line numbers in your stacktraces, generate PDBs using the pdb-only option. Optimization is separate from PDB generation, i.e. you can optimize and generate PDBs without a performance hit. From the C# Language Reference If you use /debug:full, be aware that there is some impact on the speed and size of JIT optimized code and a small impact on code quality with /debug:full. We recommend /debug:pdbonly or no PDB for generating release code.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3615/" ] }
41,869
If I run the following query in SQL Server 2000 Query Analyzer: BULK INSERT OurTable FROM 'c:\OurTable.txt' WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t', ROWS_PER_BATCH = 10000, TABLOCK) On a text file that conforms to OurTable's schema for 40 lines, but then changes format for the last 20 lines (lets say the last 20 lines have fewer fields), I receive an error. However, the first 40 lines are committed to the table. Is there something about the way I'm calling Bulk Insert that makes it not be transactional, or do I need to do something explicit to force it to rollback on failure?
BULK INSERT acts as a series of individual INSERT statements and thus, if the job fails, it doesn't roll back all of the committed inserts. It can, however, be placed within a transaction so you could do something like this: BEGIN TRANSACTIONBEGIN TRYBULK INSERT OurTable FROM 'c:\OurTable.txt' WITH (CODEPAGE = 'RAW', DATAFILETYPE = 'char', FIELDTERMINATOR = '\t', ROWS_PER_BATCH = 10000, TABLOCK)COMMIT TRANSACTIONEND TRYBEGIN CATCHROLLBACK TRANSACTIONEND CATCH
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/41869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2831/" ] }
41,894
Is there a way to find the name of the program that is running in Java? The class of the main method would be good enough.
Try this: StackTraceElement[] stack = Thread.currentThread ().getStackTrace (); StackTraceElement main = stack[stack.length - 1]; String mainClass = main.getClassName (); Of course, this only works if you're running from the main thread. Unfortunately I don't think there's a system property you can query to find this out. Edit: Pulling in @John Meagher's comment, which is a great idea: To expand on @jodonnell you can also get all stack traces in the system using Thread.getAllStackTraces(). From this you can search all the stack traces for the "main" Thread to determine what the main class is. This will work even if your class is not running in the main thread.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/41894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/823/" ] }
41,898
I'm a software engineer, not a lawyer, and my university doesn't offer any courses geared toward licensing software. In fact, their law-related courses are lacking (but slowly growing in number). Where can I go to learn about open-source licenses and how to choose them?
There are lots described here: http://www.gnu.org/licenses/license-list.html#SoftwareLicenses The decision of which one to use can be political, but should ultimately be determined by your plans/desires for the software. If you want to ensure it is always free then choose GPL or another "Copyleft" license. If you don't mind some commercial use, choose another one that's compatible with that.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ] }
41,925
What is a good data structure for storing phone numbers in database fields? I'm looking for something that is flexible enough to handle international numbers, and also something that allows the various parts of the number to be queried efficiently. Edit: Just to clarify the use case here: I currently store numbers in a single varchar field, and I leave them just as the customer entered them. Then, when the number is needed by code, I normalize it. The problem is that if I want to query a few million rows to find matching phone numbers, it involves a function, like where dbo.f_normalizenum(num1) = dbo.f_normalizenum(num2) which is terribly inefficient. Also queries that are looking for things like the area code become extremely tricky when it's just a single varchar field. [Edit] People have made lots of good suggestions here, thanks! As an update, here is what I'm doing now: I still store numbers exactly as they were entered, in a varchar field, but instead of normalizing things at query time, I have a trigger that does all that work as records are inserted or updated. So I have ints or bigints for any parts that I need to query, and those fields are indexed to make queries run faster.
First, beyond the country code, there is no real standard. About the best you can do is recognize, by the country code, which nation a particular phone number belongs to and deal with the rest of the number according to that nation's format. Generally, however, phone equipment and such is standardized so you can almost always break a given phone number into the following components C Country code 1-10 digits (right now 4 or less, but that may change) A Area code (Province/state/region) code 0-10 digits (may actually want a region field and an area field separately, rather than one area code) E Exchange (prefix, or switch) code 0-10 digits L Line number 1-10 digits With this method you can potentially separate numbers such that you can find, for instance, people that might be close to each other because they have the same country, area, and exchange codes. With cell phones that is no longer something you can count on though. Further, inside each country there are differing standards. You can always depend on a (AAA) EEE-LLLL in the US, but in another country you may have exchanges in the cities (AAA) EE-LLL, and simply line numbers in the rural areas (AAA) LLLL. You will have to start at the top in a tree of some form, and format them as you have information. For example, country code 0 has a known format for the rest of the number, but for country code 5432 you might need to examine the area code before you understand the rest of the number. You may also want to handle vanity numbers such as (800) Lucky-Guy , which requires recognizing that, if it's a US number, there's one too many digits (and you may need to full representation for advertising or other purposes) and that in the US the letters map to the numbers differently than in Germany. You may also want to store the entire number separately as a text field (with internationalization) so you can go back later and re-parse numbers as things change, or as a backup in case someone submits a bad method to parse a particular country's format and loses information.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/41925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ] }
41,934
When I do a file search on eclipse it includes the .svn directories by default. I tried excluding them from the build path but they still appear on file search results.
Spaceman is right. With Helios, choose Project -> Properties -> Resource -> Resource Filters and then add an exclude filter for type "Folder" with name .svn .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/41934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/823/" ] }
41,937
I need to convert latitude/longitude coordinates into Easting/Northing coordinates in the Alberta 10 TM Projection. The 10 TM projection is similar to UTM, but it is a custom projection for the province of Alberta, Canada. I think (with some effort) I could code it myself but would rather not reinvent the wheel if it's been done already.
Grab PROJ Cartographic Projections library - open source library. Suggested parameters for 10TM: +proj=tmerc +lon_0=-115 +k_0=0.9992 +x_0=500000 +datum=NAD27 According to this post you may need to: change the ellps to GRS80 if your 10TMdata is referenced to the NAD83 datum(instead of NAD27/clrk66). You mayalso need to change the false northing(y_0) to be -5000000 if your 10TMcoordinates for Alberta are less than5,000,000 (an AltaLIS "standard"). I should mention that proj.4 is the library to get for any kind of geographic coordinate system transformation. There's pretty much no transformation it can't do. I also recommend reading Map Projections-A Working Manual (Paperback) by John Snyder if you are into these kinds of things.. it's a classic. :) (fixed the link)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1958/" ] }
41,948
I'm creating an application which lets you define events with a time frame. I want to automatically fill in the end date when the user selects or changes the start date. I can't quite figure out, however, how to get the difference between the two times, and then how to create a new end Date using that difference.
In JavaScript, dates can be transformed to the number of milliseconds since the epoc by calling the getTime() method or just using the date in a numeric expression. So to get the difference, just subtract the two dates. To create a new date based on the difference, just pass the number of milliseconds in the constructor. var oldBegin = ...var oldEnd = ...var newBegin = ...var newEnd = new Date(newBegin + oldEnd - oldBegin); This should just work EDIT : Fixed bug pointed by @bdukes EDIT : For an explanation of the behavior, oldBegin , oldEnd , and newBegin are Date instances. Calling operators + and - will trigger Javascript auto casting and will automatically call the valueOf() prototype method of those objects. It happens that the valueOf() method is implemented in the Date object as a call to getTime() . So basically: date.getTime() === date.valueOf() === (0 + date) === (+date)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/41948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2688/" ] }
41,963
Well the subject is the question basically. Are there any version control systems out there for 3d models. An open source approach would be preferred of course. I am looking for functionality along the lines of subversion however more basic systems would be of interest as well. Basic operations like branching / merging / commit should be available in one form or another. UPDATE: With open source approach I don't mean free but the option of heavily expanding and customizing the system when needed UPDATE2: I don't know how to describe this in the best way but the format of the 3d model is not that important. We will be using IFC models and mostly CAD programs. The approach Adam Davis describes is probably what I am looking for.
This is going to be difficult since most 3D CAD programs do not take into account the possibility of revision, so when you load something and then save it again it may completely re-order the points (there are reasons for this, usually done for performance). Further, large models represented in a text format are huge files, and will take forever to copy/merge/etc. There is no current system that will manage this, but there's a really big need in the industry for it. I would expect such a system would have a model normalizer that converts to and from the desired CAD format and the revision format. It could then handle merges and track changes more easily. It would also need to output diffs in a form that you could open a "diffed" model in a cad program and the changes are shown in a different color or otherwise highlighted. No one is going to be able to look at a text diff and understand what they're looking at. This diffing program would ultimately need to support understanding that two models are the same even though the 0,0,0 location and rotation are not the same (difficult matching problem) and give the user some interface to allow them to help it when it gets stuck. You'd probably have to deal with the parts of the model separately (bones, mesh, textures, etc) and have a third file that synchronizes them when converting them to an inclusive model file for use and modification. It's not a trivial problem... But if you started on something that just handled meshes and open sourced it, you'd probably get a lot of people interested.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2970/" ] }
41,969
I want to open a folder window, in the appropriate file manager, from within a cross-platform (windows/mac/linux) Python application. On OSX, I can open a window in the finder with os.system('open "%s"' % foldername) and on Windows with os.startfile(foldername) What about unix/linux? Is there a standard way to do this or do I have to special case gnome/kde/etc and manually run the appropriate application (nautilus/konqueror/etc)? This looks like something that could be specified by the freedesktop.org folks (a python module, similar to webbrowser , would also be nice!).
os.system('xdg-open "%s"' % foldername) xdg-open can be used for files/urls also
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3002/" ] }
41,994
What is the fastest method of parsing an XML file in C#? I'm using .Net 2.0
If you're using .Net 2 then the XmlReader and XmlDocument are about it. If you can use .Net 3.5 then the new Linq to Xml methods are a big improvement.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/41994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3294/" ] }