instruction
stringlengths
0
30k
If you're using ASP.Net there are a number of validation controls you can use. These controls are written in a very generic way, such that most of them automatically duplicate your validation logic between the client and server, even though you only set options for the control in one place. You are also free to inherit from them to create additional domain specific validators, and there are third-party control packs on the web you can get that add to the base controls. Even if you're not using ASP.Net it's worth taking a look at how this is done. It will give you ideas for how to do something similar in your own platform.
I've taken to hand-coding all of my DDL (creates/alter/delete) statements, adding them to my .sln as text files, and using normal versioning (using subversion, but any revision control should work). This way, I not only get the benefit of versioning, but updating live from dev/stage is the same process for code and database - tags, branches and so on work all the same. Otherwise, I agree redgate isn't expensive if you don't have a company buying it for you. If you can get a company to buy it for you though, it really is worth it!
I've taken to hand-coding all of my DDL (creates/alter/delete) statements, adding them to my .sln as text files, and using normal versioning (using subversion, but any revision control should work). This way, I not only get the benefit of versioning, but updating live from dev/stage is the same process for code and database - tags, branches and so on work all the same. Otherwise, I agree redgate is expensive if you don't have a company buying it for you. If you can get a company to buy it for you though, it really is worth it!
There are three ways to iterate over a result set. The best way in terms of both readability and performance is usually to use the built-in cursor iterator. <pre> curs.execute('select * from people') for row in curs: print row </pre> You can fetch all the rows into a list, but this can have some bad side effects if the result set is large. - You have to wait for the entire result set to be returned to your client process. - You may eat up a lot of memory in your client to hold the built-up list. - It may take a while for Python to construct and deconstruct the list which you are going to immediately discard anyways. <pre> for row in curs.fetchall(): print row </pre> Finally, you can loop over the result set fetching one row at a time. In general, there's no particular advantage in doing this over using the iterator. If there is something in your programming logic that seems to indicate there is an advantage in doing this, perhaps you should reconsider your programming logic. <pre>row = curs.fetchone() while row: print row row = curs.fetchone()<pre>
I agree that scripting everything is the best way to go and is what I advocate at work. You should script everything from DB and object creation to populating your lookup tables. Anything you do in UI only won't translate (especially for changes... not so much for first deployments) and will end up requiring a tools like what Redgate offers.
Confirm that you have the correct email address before sending out emails. If someone gives the wrong email address on sign-up, beat them over the head about it ASAP. Always include clear "how to unsubscribe" information in EVERY email. Do not require the user to login to unsubscribe, it should be a unique url for 1-click unsubscribe. This will prevent people from marking your mails as spam because "unsubscribing" is too hard.
The typical solution is to dump the database as necessary and backup those files. Depending on your development platform, there may be opensource plugins available. Rolling your own code to do it is usually fairly trivial. Note: You may want to backup the database dump instead of putting it into version control. The files can get huge fast in version control, and cause your entire source control system to become slow (I'm recalling a CVS horror story at the moment).
The best way to do this without any compromises would be to implement your own ControllerFactory by inheriting off of IControllerFactory. The CreateController method that you will implement handles creating the controller instance to handle the request by the RouteHandler and the ControllerActionInvoker. The convention is to use the name of the controller, when creating it, therefore you will need to override this functionality. This will be where you put your custom logic for creating the controller based on the route since you will have multiple controllers with the same name, but in different folders. Then you will need to register your custom controller factory in the application startup, just like your routes. Another area you will need to take into consideration is finding your views when creating the controller. If you plan on using the same view for all of them, then you shouldn't have to do anything different than the convention being used. If you plan on organizing your views also, then you will need to create your own ViewLocator also and assign it to the controller when creating it in your controller factory. To get an idea of code, there are a few questions I have answered on SO that relate to this question, but this one is different to some degree, because the controller names will be the same. I included links for reference. - [Views in separate assemblies in ASP.NET MVC][1] - [asp.net mvc - subfolders][2] Another route, but may require some compromises will be to use the new AcceptVerbs attribute. Check this [question][3] out for more details. I haven't played with this new functionality yet, but it could be another route. [1]: http://stackoverflow.com/questions/19746/views-in-seperate-assemblies-in-aspnet-mvc [2]: http://stackoverflow.com/questions/26715/aspnet-mvc-subfolders [3]: http://stackoverflow.com/questions/36197/aspnet-mvc-structuring-controllers
The code you posted is missing one important ingredient: the function stateChanged. If you don't quite understand the code you posted yourself, then what happens is when the call to getchats.php is complete, a function "stateChanged" is called and that function will be responsible for handling the response. Since the script you're calling and the function itself is prefixed with "gets" then I'm pretty sure the response is something you're going to be interested in. That aside, there are a number of ways to improve on the code you posted. I'd guess it works by declaring a single "xmlHttp" object and then making that available to every function (because if it doesn't, the stateChanged function has no way of getting the response). This is fine until you run an AJAX request before the last one (or last few) haven't replied yet, which in that case the object reference is overwritten to the latest request each time. Also, any AJAX code worth its salt provides functionality for sucess and failure (server errors, page not found, etc.) cases so that the appriopiate message can be delivered to the user. If you just want to use AJAX functionality on your website then I'd point you in the direction of [jQuery][1] or a [similar][2] [framework][3]. BUT if you actually want to understand the technology and what is happening behind the scenes, I'd continue doing what you're doing and asking specific questions as you try to build a small lightweight AJAX class on your own. This is how I done it, and although I use the jQuery framework today.. I'm still glad I know how it works behind the scenes. [1]: http://www.jquery.com [2]: http://www.prototypejs.org [3]: http://www.mootools.net
To everyone just starting using version control: **Please do not use git (or hg or bzr) because of the hype** Use git (or hg or bzr) because they are **better tools** for managing source code than SVN. I used SVN for a few years at work, and switched over to git 6 months ago. Without learning SVN first I would be totaly lost when it comes to a DVCS. For people just starting out with version control: - Start by downloading SVN - Learn _why_ you need version control - Learn how to commit, checkout, branch - Learn why merging in SVN is such a pain Then switch over to a DVCS and learn: - How to clone/branch/commit - How easy it is to merge your branches back (go branch crazy!) - How easy it is to rewrite commit history and keep your branches<br/>up to date with the main line ([git rebase -i][1]) - How to publish your changes so others can benefit [1]:http://www.kernel.org/pub/software/scm/git/docs/git-rebase.html
To everyone just starting using version control: **Please do not use git (or hg or bzr) because of the hype** Use git (or hg or bzr) because they are **better tools** for managing source code than SVN. I used SVN for a few years at work, and switched over to git 6 months ago. Without learning SVN first I would be totaly lost when it comes to using a DVCS. For people just starting out with version control: - Start by downloading SVN - Learn _why_ you need version control - Learn how to commit, checkout, branch - Learn why merging in SVN is such a pain Then switch over to a DVCS and learn: - How to clone/branch/commit - How easy it is to merge your branches back (go branch crazy!) - How easy it is to rewrite commit history and keep your branches<br/>up to date with the main line ([git rebase -i][1], ) - How to publish your changes so others can benefit ---------- tldr; crowd: Start with SVN and learn the basics, then graduate to a DVCS. [1]:http://www.kernel.org/pub/software/scm/git/docs/git-rebase.html
Is this a good way to determine OS Architecture?
|c#|windows|registry|
Since the WMI class Win32_OperatingSystem only includes OSArchitecture, I quickly wrote up a method using the registry to try and determine whether or not the current system is a 32 or 64bit system. private Boolean is64BitOperatingSystem() { RegistryKey localEnvironment = Registry.LocalMachine.OpenSubKey ("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"); String processorArchitecture = (String) localEnvironment.GetValue("PROCESSOR_ARCHITECTURE"); if (processorArchitecture.Equals("x86")) { return false; } else { return true; } } It's worked out pretty well for us so far, but I'm not sure how much I like looking through the registry. Is this a pretty standard practice or is there a better method? **Edit**: Wow, that code looks a lot prettier in the preview. I'll consider linking to a pastebin or something, next time.
Since the WMI class Win32_OperatingSystem only includes OSArchitecture in Windows Vista, I quickly wrote up a method using the registry to try and determine whether or not the current system is a 32 or 64bit system. private Boolean is64BitOperatingSystem() { RegistryKey localEnvironment = Registry.LocalMachine.OpenSubKey ("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"); String processorArchitecture = (String) localEnvironment.GetValue("PROCESSOR_ARCHITECTURE"); if (processorArchitecture.Equals("x86")) { return false; } else { return true; } } It's worked out pretty well for us so far, but I'm not sure how much I like looking through the registry. Is this a pretty standard practice or is there a better method? **Edit**: Wow, that code looks a lot prettier in the preview. I'll consider linking to a pastebin or something, next time.
How about an object oriented approach? You could deserialise the XML to an object, set the location value on the object, then serialise back to XML. [XStream](http://xstream.codehaus.org/tutorial.html) makes this really easy. For example, you would define the main object, which in your case is CustomData (I'm using public fields to keep the example simple): public class CustomData { public String tag1; public String tag2; public String location; public String tag3; } Then you initialize XStream: XStream xstream = new XStream(); // if you need to output the main tag in lowercase, use the following line xstream.alias("customdata", CustomData.class); Now you can construct an object from XML, set the location field on the object and regenerate the XML: CustomData d = (CustomData)xstream.fromXML(xml); d.location = "http://stackoverflow.com"; xml = xstream.toXML(d); How does that sound?
- The memory windows, very useful if you're doing low level stuff. - Control + K , Control + F - Format selection - great for quickly making code neat - Regions, some love them, some hate them, most don't even know they exist - Changing variables in debug windows during execution - Tracepoints - Conditional break points - Hold down Alt and drag for 'rectangular' selection. - Control+B for a breakpoint, to break at function - Control+I for incremental search, F3 to iterate
Split the big system to smaller pieces. And don't think that it's so complex, because it usually isn't. By thinking too complex it just ruins your thoughts and eventually the design. Some point you just realize that you could do the same thing easier, and then you redesign it. Atleast this has been my major mistake in designing. Keep it simple!
Here's some code I wrote in C# using .NET 1.1 a few years ago. Not sure if this would be exactly what you need (and may not be my best code :)). using System; using System.Data; using System.Data.OleDb; namespace ExportExcelToAccess { /// <summary> /// Summary description for ExcelHelper. /// </summary> public sealed class ExcelHelper { private const string CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<FILENAME>;Extended Properties=\"Excel 8.0;HDR=Yes;\";"; public static DataTable GetDataTableFromExcelFile(string fullFileName, ref string sheetName) { OleDbConnection objConnection = new OleDbConnection(); objConnection = new OleDbConnection(CONNECTION_STRING.Replace("<FILENAME>", fullFileName)); DataSet dsImport = new DataSet(); try { objConnection.Open(); DataTable dtSchema = objConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); if( (null == dtSchema) || ( dtSchema.Rows.Count <= 0 ) ) { //raise exception if needed } if( (null != sheetName) && (0 != sheetName.Length)) { if( !CheckIfSheetNameExists(sheetName, dtSchema) ) { //raise exception if needed } } else { //Reading the first sheet name from the Excel file. sheetName = dtSchema.Rows[0]["TABLE_NAME"].ToString(); } new OleDbDataAdapter("SELECT * FROM [" + sheetName + "]", objConnection ).Fill(dsImport); } catch (Exception) { //raise exception if needed } finally { // Clean up. if(objConnection != null) { objConnection.Close(); objConnection.Dispose(); } } return dsImport.Tables[0]; #region Commented code for importing data from CSV file. // string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source=" + System.IO.Path.GetDirectoryName(fullFileName) +";" +"Extended Properties=\"Text;HDR=YES;FMT=Delimited\""; // // System.Data.OleDb.OleDbConnection conText = new System.Data.OleDb.OleDbConnection(strConnectionString); // new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(fullFileName).Replace(".", "#"), conText).Fill(dsImport); // return dsImport.Tables[0]; #endregion } /// <summary> /// This method checks if the user entered sheetName exists in the Schema Table /// </summary> /// <param name="sheetName">Sheet name to be verified</param> /// <param name="dtSchema">schema table </param> private static bool CheckIfSheetNameExists(string sheetName, DataTable dtSchema) { foreach(DataRow dataRow in dtSchema.Rows) { if( sheetName == dataRow["TABLE_NAME"].ToString() ) { return true; } } return false; } } }
You didn't state what web server you were using, but Apache has a nice little module called [Mime Magic](http://httpd.apache.org/docs/1.3/mod/mod_mime_magic.html) which it uses to determine the type of a file when told to do so. It reads some of the file's content and tries to figure out what type it is based on the characters found. And as [Dave Webb Mentioned](http://stackoverflow.com/questions/43580/how-to-find-the-mime-type-of-a-file-in-python#43588) the [MimeTypes Module](http://docs.python.org/lib/module-mimetypes.html) under python will work, provided an extension is handy.
You didn't state what web server you were using, but Apache has a nice little module called [Mime Magic](http://httpd.apache.org/docs/1.3/mod/mod_mime_magic.html) which it uses to determine the type of a file when told to do so. It reads some of the file's content and tries to figure out what type it is based on the characters found. And as [Dave Webb Mentioned](http://stackoverflow.com/questions/43580/how-to-find-the-mime-type-of-a-file-in-python#43588) the [MimeTypes Module](http://docs.python.org/lib/module-mimetypes.html) under python will work, provided an extension is handy. Alternatively, if you are sitting on a UNIX box you can use <code>sys.popen('file -i ' + fileName, 'r')</code> to grab the MIME type. Windows should have an equivalent command, but I'm unsure as to what it is.
You didn't state what web server you were using, but Apache has a nice little module called [Mime Magic](http://httpd.apache.org/docs/1.3/mod/mod_mime_magic.html) which it uses to determine the type of a file when told to do so. It reads some of the file's content and tries to figure out what type it is based on the characters found. And as [Dave Webb Mentioned](http://stackoverflow.com/questions/43580/how-to-find-the-mime-type-of-a-file-in-python#43588) the [MimeTypes Module](http://docs.python.org/lib/module-mimetypes.html) under python will work, provided an extension is handy. Alternatively, if you are sitting on a UNIX box you can use <code>sys.popen('file -i ' + fileName, mode='r')</code> to grab the MIME type. Windows should have an equivalent command, but I'm unsure as to what it is.
I cant think of a way to have just the Timeout property changed automatically via the webconfig. Manually configure the value or use DI to read the value in for you. It maybe possible also to change the value globally on the machine config.
By the way @[ZombieSheep](#43618) solution date ('Y-m-d', mktime(0,0,0,$MM + 1,-1,$YYYY)); does not work it should be date ('Y-m-d', mktime(0,0,0,$MM + 1,0,$YYYY)); // Day zero instead of -1 Of course @Michał Słaby's accepted solution is the simplest.
Perl lets you make part of your regular expression case-insensitive by using the (?i:) pattern modifier. Modern regex flavors allow you to apply modifiers to only part of the regular expression. If you insert the modifier (?ism) in the middle of the regex, the modifier only applies to the part of the regex to the right of the modifier. You can turn off modes by preceding them with a minus sign. All modes after the minus sign will be turned off. E.g. (?i-sm) turns on case insensitivity, and turns off both single-line mode and multi-line mode. Not all regex flavors support this. JavaScript and Python apply all mode modifiers to the entire regular expression. They don't support the (?-ismx) syntax, since turning off an option is pointless when mode modifiers apply to the whole regular expressions. All options are off by default. You can quickly test how the regex flavor you're using handles mode modifiers. The regex (?i)te(?-i)st should match test and TEst, but not teST or TEST. [Source][1] [1]: http://www.regular-expressions.info/modifiers.html
You can take the C code almost without changes: uint sdbm( string str ) { uint hash = 0; foreach( char ch in str ) { hash = ch + (hash << 6) + (hash << 16) - hash; } return hash; } Or did you think of something more sophisticated?
I don't have a C compiler set up so I can't test to see if it performs the same, but I *think* the following is correct: private static ulong SBDM(string str) { ulong hash = 0; foreach (char c in str) { hash = c + (hash << 6) + (hash << 16) - hash; } return hash; } If you just need to get a hash of the string and it doesn't matter too much what the implementation is you can always do theString.GetHashCode();
WildcardQuery error in Solr
|search|lucene|solr|
I use solr to search for documents and when trying to search for documents using this query "<code>id:*</code>", I get this query parser exception telling that it cannot parse the query with * or ? as the first character. HTTP Status 400 - org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery type Status report message org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery description The request sent by the client was syntactically incorrect (org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery). Is there any patch for getting this to work with just * ? Or is it very costly to do such a query?
@[Sadie](http://stackoverflow.com/questions/15851/refactoring-away-labeled-loops#15946): > They all look less readable than the original, in that they involve spending more code on the mechanism of the code rather than on the algorithm itself Externalizing the second loop outside the algorithm is not necessarily less readable. If the method name is well chosen, it can improve readability. > Some of them are broken, or were before they were edited. Most damning is the fact that people are having to think quite hard about how to write the code without labels and not break anything. I have a different point of view: some of them are broken because it is hard to figure out the behavior of the original algorithm. > Some come with a performance penalty of running the same test twice, which may not always be trivial. The alternative to that is storing and passing round booleans, which gets ugly. The performance penalty is minor. However I agree that running a test twice is not a nice solution. > Refactoring the relevant part of the code into a method is effectively a no-op: it rearranges how the code is laid out in the file, but has no effect on how it's executed. I don't see the point. Yep, it doesn't change the behavior, like... refactoring? > Certainly there are cases where labels are used incorrectly and should be refactored away. I just don't think it should be treated as some unbreakable rule. I totally agree. But as you have pointed out, some of us have difficulties while refactoring this example. Even if the initial example is readable, it is hard to maintain.
I got into this once, even tried using PSP Dashboard. It's just too hard to keep up with. Who wants to use a stop watch for all their activities? Follow Joel's advice on Painless Scheduling and Evidence Based Scheduling. +1 this question, -1 to PSP.
In the occasions when this has been relevant to me (which, truth be told, is not often) we have tended to do a combination of hosting a dev copy of the solution in-house and mocking what we can't host. I personally think that the more you can host on individual dev boxes the better-- if your dev's PCs are powerful enough to have the entire thing running plus whatever else they need to develop then they should be doing this. It allows them to have tonnes of flexability to develop without worrying about other people.
Cast int to Enum in C#
|c#|enums|casting|
What's a quick and easy way to cast an int to an enum in c#?
You could spend literally thousands of dollars on the dev kit or you could be a bad person and go look at the [homebrew stuff][1]. It is technically hacking though, so I only hypothetically recommend it. [1]: http://hbc.hackmii.com/
From a string: YourEnum foo = (YourEnum) Enum.Parse(typeof(yourEnum), yourString); From an int: YourEnum foo = (YourEnum)yourInt;
int one = 1; MyEnum e = (MyEnum)one;
Just cast it: MyEnum e = (MyEnum)3; You can check if it's in range using [Enum.IsDefined][1]: if (Enum.IsDefined(typeof(MyEnum), 3)) { ... } [1]: http://msdn.microsoft.com/en-us/library/system.enum.isdefined.aspx
Ok, here's a funky helper method to give you a flexible way to activate a type given an array of parameters: static object GetInstanceFromParameters(string typeName, params object[] pars) { var t = Assembly.GetExecutingAssembly().GetType(typeName); var c = t.GetConstructor(pars.Select(p => p.GetType()).ToArray()); if (c == null) return null; return c.Invoke(pars); } And you call it like this: Foo f = GetInstanceFromParameters("SmartDeviceProject1.Foo", "hello", 17) as Foo; So you pass the name of the type as the first parameter, and then all the constructor's parameters in order.
Ok, here's a funky helper method to give you a flexible way to activate a type given an array of parameters: static object GetInstanceFromParameters(Assembly a, string typeName, params object[] pars) { var t = a.GetType(typeName); var c = t.GetConstructor(pars.Select(p => p.GetType()).ToArray()); if (c == null) return null; return c.Invoke(pars); } And you call it like this: Foo f = GetInstanceFromParameters(a, "SmartDeviceProject1.Foo", "hello", 17) as Foo; So you pass the assembly and the name of the type as the first two parameters, and then all the constructor's parameters in order.
Yes the SDKs (and dev hardware) are expensive, and you must be an actual company with an actual office to get one.
Robust Random Number Generation in C++/C#
|c#|c++|random|
I'm looking for a performant, reasonably robust RNG using no special hardware. It can use mathematical methods (Mersenne Twister, etc), it can "collect entropy" from the machine, whatever. On Linux/etc we have a drand48() which generates 48 random bits. I'd like a similar function/class for C++ or C# which can generate more than 32 bits of randomness and which low-order bits are equally as random as high-order bits. It doesn't have to be cryptographically secure but it must not use or be based on the C-language rand() or .NET System.Random. Any source code, links to source, etc. would be appreciated! Failing that, what TYPE of RNG should I be looking for? Thanks!
For C++, [Boost.Random](http://www.boost.org/libs/random/) is probably what you're looking for. It has support for MT (among many other algorithms), and can collect entropy via the `nondet_random` class. Check it out! :-)
Hmm, ok. I'd suggest code like this, then: typedef struct { int type; int result; } DialogData; static gboolean display_dialog(gpointer user_data) { DialogData *dialog_data = user_data; GtkWidget *dialog; if (dialog_data->type & MB_YESNO) dialog = gtk_message_dialog_new(...); else dialog = gtk_message_dialog_new(...); // Set title, etc. dialog_data->result = gtk_dialog_run(...); gtk_main_quit(); // Quits the main loop run in MessageBox() return FALSE; } int MessageBox(...) { DialogData dialog_data; dialog_data.type = type; gtk_idle_add(display_dialog, &dialog_data); gtk_main(); // Do stuff based on dialog_data.result } The struct is because you need to pass around a couple pieces of data. The `gtk_idle_add()` call adds a method to be run when the main loop is running and idle, and the `FALSE` return value from the `display_dialog()` call means that it's only run once. After we get the result from the dialog, we quit the main loop. That'll cause the `gtk_main()` in your main `MessageBox()` method to return, and you'll be able to access the result from there. Hope this helps!
The Gnu Scientific Library (GSL) <http://www.gnu.org/software/gsl> has a pretty extensive set of RN generators, test harness, etc. If you're on linux, it's probably already available on your system.
[The Gnu Scientific Library][1] (GSL) has a pretty extensive set of RN generators, test harness, etc. If you're on linux, it's probably already available on your system. [1]: http://www.gnu.org/software/gsl
Interesting question! I would do this by picking combinations, something like the following in python. The hardest part is probably first pass verification, i.e. if f(1,2,3) returns true, is that a correct result? Once you have verified that, then this is a good basis for regression testing. Probably it's a good idea to make a set of test cases that you know will be all true (e.g. 3,4,5 for this triangle case), and a set of test cases that you know will be all false (e.g. 0,1,inf). Then you can more easily verify the tests are correct. <pre> # xpermutations from http://code.activestate.com/recipes/190465 from xpermutations import * lengths=[-1,0,1,5,10,0,1000,'inf'] for c in xselections(lengths,3): # or xuniqueselections print 'tstfunc(%s,%s,%s);'%tuple(c) </pre> <pre> tstfunc(-1,-1,-1); tstfunc(-1,-1,0); tstfunc(-1,-1,1); tstfunc(-1,-1,5); tstfunc(-1,-1,10); tstfunc(-1,-1,0); tstfunc(-1,-1,1000); tstfunc(-1,-1,inf); tstfunc(-1,0,-1); tstfunc(-1,0,0); ... </pre>
Since the WMI class Win32_OperatingSystem only includes OSArchitecture in Windows Vista, I quickly wrote up a method using the registry to try and determine whether or not the current system is a 32 or 64bit system. private Boolean is64BitOperatingSystem() { RegistryKey localEnvironment = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"); String processorArchitecture = (String) localEnvironment.GetValue("PROCESSOR_ARCHITECTURE"); if (processorArchitecture.Equals("x86")) { return false; } else { return true; } } It's worked out pretty well for us so far, but I'm not sure how much I like looking through the registry. Is this a pretty standard practice or is there a better method? **Edit**: Wow, that code looks a lot prettier in the preview. I'll consider linking to a pastebin or something, next time.
Since the WMI class Win32_OperatingSystem only includes OSArchitecture in Windows Vista, I quickly wrote up a method using the registry to try and determine whether or not the current system is a 32 or 64bit system. private Boolean is64BitOperatingSystem() { RegistryKey localEnvironment = Registry.LocalMachine.OpenSubKey ("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"); String processorArchitecture = (String) localEnvironment.GetValue("PROCESSOR_ARCHITECTURE"); if (processorArchitecture.Equals("x86")) { return false; } else { return true; } } It's worked out pretty well for us so far, but I'm not sure how much I like looking through the registry. Is this a pretty standard practice or is there a better method? **Edit**: Wow, that code looks a lot prettier in the preview. I'll consider linking to a pastebin or something, next time.
Since the WMI class Win32_OperatingSystem only includes OSArchitecture in Windows Vista, I quickly wrote up a method using the registry to try and determine whether or not the current system is a 32 or 64bit system. private Boolean is64BitOperatingSystem() { RegistryKey localEnvironment = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"); String processorArchitecture = (String) localEnvironment.GetValue("PROCESSOR_ARCHITECTURE"); if (processorArchitecture.Equals("x86")) { return false; } else { return true; } } It's worked out pretty well for us so far, but I'm not sure how much I like looking through the registry. Is this a pretty standard practice or is there a better method? **Edit**: Wow, that code looks a lot prettier in the preview. I'll consider linking to a pastebin or something, next time.
It's kind of pointless to talk about "database performance", "query performance" is a better term here. And the answer is: it depends on the query, data that it operates on, indexes, hardware, etc. You can get an idea of how many rows are going to be scanned and what indexes are going to be used with EXPLAIN syntax. 2GB does not really count as a "large" database - it's more of a medium size.
[OmniAudit][1] might be a good solution for you need. I've never used it before because I'm quite happy writing my own audit routines, but it sounds good. [1]: http://www.krell-software.com/omniaudit/
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.
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.
You could use (?:F|f)(?:O|o)(?:O|o) The ?: in the brackets in .Net means it's non-capturing, and just used to group the terms of the | (or) statement.
Can I update/select from a table in one query?
|mysql|
I need to select data when a page is viewed and update the 'views' column is there a way to do this in one query, or do I have to use to distinct queries?
"I switched to a local version of prototypejs and added some debugging in the offending method (createWraper) but the debugging never appears before the error..." Actually the offending function being called when the error occurs is "wrapper" which is created inside createWrapper (but not called there). Basically what is happening is that you've attached a function as the event handler for an element, and the function doesn't actually exist. If you're trying to put any debug information in to try and pinpoint which function "doesn't exist" then add your alert messages or firebug console output inside the wrapper function between lines 3871 and 3878.
You would have to do this in two statements in one transaction Begin Tran Update Pages Set Views = Views + 1 Where ID = @ID Select Columns From Pages Where ID = @ID Commit Tran
What language are you using? A standard way to do this would be something like /([Ff][Oo]{2}|BAR)/ with case sensitivity on, but in Java, for example, there is a case sensitivity modifier (?i) which makes all characters to the right of it case insensitive and (?-i) which forces sensitivity. An example of that Java regex modifier can be found [here](http://exampledepot.com/egs/java.util.regex/Case.html).
Unfortunately syntax for case-insensitive matching is not common. In .NET you can use RegexOptions.IgnoreCase flag or **?i** modifier
OK, first is dead easy. date ('Y-m-d', mktime(0,0,0,MM,01,YYYY)); Last is a little trickier, but not much. date ('Y-m-d', mktime(0,0,0,MM + 1,-1,YYYY)); If I remember my PHP date stuff correctly... **edit - Gah! Beaten to it about a million times...
Yeah, if you were being efficient you'd throw everything into the same vertex buffer, but I don't think drawing 100 cubes will push any GPU produced in the past 5 years, so you should be fine following the suggestions above. Write a basic pass through vertex shader, shade however you desire in the pixel shader. Either pass in a world matrix and do the translation in the vertex shader, or just compute the world space vertex positions on the CPU side (do this if your cubes are going to stay fixed). You could get fancy and do [geometry instancing][1] etc, but just get the basics going first. [1]: http://en.wikipedia.org/wiki/Geometry_instancing
Better yet, a site domain dictionary, containing a definition (over time) for every programming term on Stackoverflow, with the definition itself modded according to the Wiki-like aspects Atwood and others have been discussing. There are coding dictionaries out there but they're all either a) crap or b) not extensible or editable in a collaborative way. Right now if I come across an unfamiliar programming term or acronym my first stop is Google, followed by Wiki, followed by one of the many dedicated dictionaries. No reason why Stackoverflow shouldn't be on that list.
Perhaps the most common usees of #define in C# is to differentiate between debug/release and different platforms (for example Windows and X-Box 360 in the XNA framework).
I've had a look at the Video from Molley Rocket and Looked through Jari Komppa's cached tutorials. An IM-GUI seems the best way to go, I think it will be a lot more streamlined, and lot quicker to build than the system I originally had in mind. Now a new issue, I can only except one Answer. :( Thanks again to Monjardin and dooz, cheers. thing2k
It has been my experience that Java applications (.NET also) that consider the database last are highly likely to perform poorly when placed into a corporate environment. You need to really think about your audience. You didn't say if it was a web app or not. Either way the infrastructure that you are implementing on is important when considering how you handle your data. No matter what methodology you consider, how you get and save your data and it's impact on performance should be right up there as one of your #1 priorities.
ASP.NET LocationProvider
|asp.net|security|sitemap|provider|
We need to replace the menu system in our main ASP.NET application. So naturally we're looking at the ASP.NET SiteMapProvider and Menu controls. However we also need enough security to prevent users from directly entering URLs that they shouldn't have access to. We can do this by putting <location> entries in web.config and securing them individually but that's going to be a PITA to manage across multiple web servers. Is there a Provider that can be used to, well, provide the equivalent of the <location> entries? I haven't been able to find one, and it's slightly frustrating given the existence of the [ConfigurationLocation][1] class. Alternatively is there a configuration option we're missing in SiteMapProvider that will restrict users from getting to URLs they shouldn't? Phil [1]: http://msdn.microsoft.com/en-us/library/system.configuration.configurationlocation.aspx
The first general purpose use for the CLR in SQL 2005 I created was a SQL 2005 assembly that has a variety of functions that perform string operations and pattern matches using regular expressions. The native string functions in SQL 2005 can be augmented so that you can validate common formats like phone numbers or credit card numbers or perform ad-hoc regular expressions within stored procedures. For deterministic user defined functions, I have found the SQL CLR support to be very performant.
Keeping validation logic in sync between server and client sides
|database|architecture|
In my [previous question][1] most commenters agreed that having validation logic both at client & server sides is a good thing. However there is a problem - you need to keep your validation rules in sync between database and client code. So the question is how can we deal with it ? One approach is to use ORM techniques, modern ORM tools can produce code that can take care of data validation prior sending it to the server. I'm interested in hearing your opinions. Do you have some kind of standard process to deal with this problem? Or maybe you think that this is not a problem at all? :) [1]: http://stackoverflow.com/questions/39371/database-exception-handling-best-practices
|database|architecture|
In my [previous question][1] most commenters agreed that having validation logic both at client & server sides is a good thing. However there is a problem - you need to keep your validation rules in sync between database and client code. So the question is how can we deal with it ? One approach is to use ORM techniques, modern ORM tools can produce code that can take care of data validation prior sending it to the server. I'm interested in hearing your opinions. Do you have some kind of standard process to deal with this problem? Or maybe you think that this is not a problem at all? :) **EDIT**: Guys, first of all thank you for your answers. Tomorrow I will sum up you answers and update question's text like in [this case][1] [1]: http://stackoverflow.com/questions/39371/database-exception-handling-best-practices
I doubt you can find a regex that matches all (and only) the function calls in some source code. But maybe you could use a tool like [Understand](http://www.scitools.com/products/understand/), or your IDE, to browse your code.
Probably the single most important thing is to use a framework, such as [jQuery][1], or [prototype][2], to iron out the differences between browsers, and also make things easier in general. [1]: http://jquery.com/ [2]: http://www.prototypejs.org/
If you're using C#, take a look at [StyleCop](http://code.msdn.microsoft.com/sourceanalysis).
Visual Studio uses the settings in Tools > Options > Text Editor > [your language] > Formatting to set how it auto-formats code. You can set it up how you like and then use Tools > Import and Export settings to create a .settings file for your team to import and use. It won't enforce rules, but it will make the default VS behavior the same for everyone.
We use and like [Mercurial][1]. It follows a distributed model - it eliminates some of the sense of having to "check in" work. Mozilla has [moved to Mercurial][2], which is a good sign that it's not going to go away any time soon. One con, in my opinion, is that there isn't a very good GUI for it. If you're comfortable with the command line, though, it's pretty handy. [Mercurial Documentation][3] [Unofficial Manual][4] [1]: http://www.selenic.com/mercurial/wiki/ [2]: http://developer.mozilla.org/en/docs/Mercurial [3]: http://www.selenic.com/mercurial/wiki/ [4]: http://hgbook.red-bean.com/hgbook.html
The easiest way to test for 64-bit under .NET is to check the value of IntPtr.Size. EDIT: Doh! This will tell you whether or not the current process is 64-bit, not the OS as a whole. Sorry!
Try creating a div document.createElement( 'div' ); And then set the tag soup HTML to the innerHTML of the div. The browser should process that into XML, which then you can parse.
Try creating a div document.createElement( 'div' ); And then set the tag soup HTML to the innerHTML of the div. The browser should process that into XML, which then you can parse. > The innerHTML property takes a string > that specifies a valid combination of > text and elements. When the innerHTML > property is set, the given string > completely replaces the existing > content of the object. If the string > contains HTML tags, the string is > parsed and formatted as it is placed > into the document.
Looking into the registry is perfectly valid, so long as you can be sure that the user of the application will always have access to what you need. That said, add 4 spaces before each code line to get this: private Boolean is64BitOperatingSystem() { RegistryKey localEnvironment = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"); String processorArchitecture = (String)localEnvironment.GetValue("PROCESSOR_ARCHITECTURE"); if (processorArchitecture.Equals("x86")) { return false; } else { return true; } }
Looking into the registry is perfectly valid, so long as you can be sure that the user of the application will always have access to what you need.
> The easiest way to test for 64-bit under .NET is to check the value of IntPtr.Size. I believe the value of IntPtr.Size is 4 for a 32bit app that's running under WOW, isn't it? **Edit**: @Edit: Yeah. :)
Take a look at Raymond Chens solution: [http://blogs.msdn.com/oldnewthing/archive/2005/02/01/364563.aspx][1] and here's the PINVOKE for .NET: [http://www.pinvoke.net/default.aspx/kernel32/IsWow64Process.html?diff=y][2] [1]: http://blogs.msdn.com/oldnewthing/archive/2005/02/01/364563.aspx [2]: http://www.pinvoke.net/default.aspx/kernel32/IsWow64Process.html?diff=y
Take a look at Raymond Chens solution: [http://blogs.msdn.com/oldnewthing/archive/2005/02/01/364563.aspx][1] and here's the PINVOKE for .NET: [http://www.pinvoke.net/default.aspx/kernel32/IsWow64Process.html?diff=y][2] **Update:** I'd take issue with checking for 'x86'. Who's to say what intel's or AMD's next 32 bit processor may be designated as. The probability is low but it is a risk. You should ask the OS to determine this via the correct API's, not by querying what could be a OS version/platform specific value that may be considered opaque to the outside world. Just my 2c. [1]: http://blogs.msdn.com/oldnewthing/archive/2005/02/01/364563.aspx [2]: http://www.pinvoke.net/default.aspx/kernel32/IsWow64Process.html?diff=y
|apache-flex|data-binding|actionscript|mxml|
|apache-flex|actionscript-3|data-binding|mxml|
Your question is a little ambiguous - are you looking to keep track of the first instances of every letter? If so, an array of length 26 might be the best option. Whenever you insert text into a string at a position lower than the index you have, just compute the offset based on the length of the inserted string.
I don't really understand the question - you throw an exception as you normally would. If `MyThing` implements `IDisposable`, then: using ( MyThing thing = new MyThing() ) { ... throw new ApplicationException("oops"); } And `thing.Dispose` will be called as you leave the block, as the exception's thrown. If you want to combine a try/catch/finally and a using, you can either nest them: try { ... using ( MyThing thing = new MyThing() ) { ... } ... } catch ( Exception e ) { .... } finally { .... } (Or put the try/catch/finally in the using): using ( MyThing thing = new MyThing() ) { ... try { ... } catch ( Exception e ) { .... } finally { .... } ... } // thing.Dispose is called now Or you can unroll the `using` and explicitly call `Dispose` in the `finally` block as @[Quarrelsome](#36094) demonstrated.
I don't really understand the question - you throw an exception as you normally would. If `MyThing` implements `IDisposable`, then: using ( MyThing thing = new MyThing() ) { ... throw new ApplicationException("oops"); } And `thing.Dispose` will be called as you leave the block, as the exception's thrown. If you want to combine a try/catch/finally and a using, you can either nest them: try { ... using ( MyThing thing = new MyThing() ) { ... } ... } catch ( Exception e ) { .... } finally { .... } (Or put the try/catch/finally in the using): using ( MyThing thing = new MyThing() ) { ... try { ... } catch ( Exception e ) { .... } finally { .... } ... } // thing.Dispose is called now Or you can unroll the `using` and explicitly call `Dispose` in the `finally` block as @[Quarrelsome](#36094) demonstrated, adding any extra exception-handling or -recovery code that you need in the `finally` (or in the `catch`).
I don't really understand the question - you throw an exception as you normally would. If `MyThing` implements `IDisposable`, then: using ( MyThing thing = new MyThing() ) { ... throw new ApplicationException("oops"); } And `thing.Dispose` will be called as you leave the block, as the exception's thrown. If you want to combine a try/catch/finally and a using, you can either nest them: try { ... using ( MyThing thing = new MyThing() ) { ... } ... } catch ( Exception e ) { .... } finally { .... } (Or put the try/catch/finally in the using): using ( MyThing thing = new MyThing() ) { ... try { ... } catch ( Exception e ) { .... } finally { .... } ... } // thing.Dispose is called now Or you can unroll the `using` and explicitly call `Dispose` in the `finally` block as @[Quarrelsome](#36094) demonstrated, adding any extra exception-handling or -recovery code that you need in the `finally` (or in the `catch`). EDIT: In response to @[Toran Billups](#36100), if you need to process exceptions aside from ensuring that your `Dispose` method is called, you'll either have to use a `using` and `try/catch/finally` or unroll the `using` - I don't thinks there's any other way to accomplish what you want.