source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
4,430 | Is there available any tool for PHP which can be used to generate code for consuming a web service based on its WSDL ? Something comparable to clicking "Add Web Reference" in Visual Studio or the Eclipse plugin which does the same thing for Java. | In PHP 5 you can use SoapClient on the WSDL to call the web service functions. For example : $client = new SoapClient("some.wsdl"); and $client is now an object which has class methods as defined in some.wsdl. So if there was a method called getTime in the WSDL then you would just call: $result = $client->getTime(); And the result of that would (obviously) be in the $result variable. You can use the __getFunctions method to return a list of all the available methods. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/4430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/349/"
]
} |
4,432 | Typical way of creating a CSV string (pseudocode): Create a CSV container object (like a StringBuilder in C#). Loop through the strings you want to add appending a comma after each one. After the loop, remove that last superfluous comma. Code sample: public string ReturnAsCSV(ContactList contactList){ StringBuilder sb = new StringBuilder(); foreach (Contact c in contactList) { sb.Append(c.Name + ","); } sb.Remove(sb.Length - 1, 1); //sb.Replace(",", "", sb.Length - 1, 1) return sb.ToString();} I like the idea of adding the comma by checking if the container is empty, but doesn't that mean more processing as it needs to check the length of the string on each occurrence? I feel that there should be an easier/cleaner/more efficient way of removing that last comma. Any ideas? | You could use LINQ to Objects : string [] strings = contactList.Select(c => c.Name).ToArray();string csv = string.Join(",", strings); Obviously that could all be done in one line, but it's a bit clearer on two. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/4432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/202/"
]
} |
4,434 | Let's say that there is a solution that contains two projects (Project1 and Project2). Project1 is set as a StartUp Project (its name is displayed in a bold font). I double-click some file in Project2 to open it. The file opens, but something else happens too - Project2 gets set as a StartUp Project. I tried to find an option in configuration to change it, but I found none. Can this feature (though it's more like a bug to me) be disabled? | The way to select a startup project is described in Sara Ford's blog "Visual Studio Tip of the Day " (highly recommended). She has a post there about setting up StartUp projects . Essentially there are 2 ways, the easiest one being right-clicking on the desired project, and choosing "Set As StartUp Project". That prevents other projects from becoming the StartUp project, even if you click on one their files. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/4434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/95/"
]
} |
4,529 | Has anyone tried installing SQL Server 2008 Developer on a machine that already has 2005 Developer installed? I am unsure if I should do this, and I need to keep 2005 on this machine for the foreseeable future in order to test our application easily. Since I sometimes need to take backup files of databases and make available for other people in the company I cannot just replace 2005 with 2008 as I suspect (but do not know) that the databases aren't 100% backwards compatible. What kind of issues would arise? Do I need to install the new version with an instance name, will that work? Can I use a different port number to distinguish them? I found this entry on technet: http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=3496209&SiteID=17 It doesn't say more than just yes you can do this and I kinda suspected that this was doable anyway, but I need to know if there are anything I need to know before I start installing. Anyone? | Yes this is possible. You will have to create a named instance not used by another version of SQL Server as per the previous answer and version 3.5 of .Net installed. Works great!! Here the list of prerequisites: .NET Framework 3.5 SP1 Windows Installer 4.5 Windows PowerShell 1.0 | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/4529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
]
} |
4,533 | How do I generate an ETag HTTP header for a resource file? | An etag is an arbitrary string that the server sends to the client that the client will send back to the server the next time the file is requested. The etag should be computable on the server based on the file. Sort of like a checksum, but you might not want to checksum every file sending it out. server client <------------- request file foo file foo etag: "xyz" --------> <------------- request file foo etag: "xyz" (what the server just sent) (the etag is the same, so the server can send a 304) I built up a string in the format "datestamp-file size-file inode number". So, if a file is changed on the server after it has been served out to the client, the newly regenerated etag won't match if the client re-requests it. char *mketag(char *s, struct stat *sb){ sprintf(s, "%d-%d-%d", sb->st_mtime, sb->st_size, sb->st_ino); return s;} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/4533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
]
} |
4,545 | Does anyone remember the XMP tag? What was it used for and why was it deprecated? | A quick Google search on W3C reveals that XMP was introduced for displaying preformatted text in HTML 3.2 and earlier. When W3C deprecated the XMP tag, it suggested using the PRE tag as a preferred alternative. Update: http://www.w3.org/TR/REC-html32#xmp , http://www.w3.org/MarkUp/html-spec/html-spec_5.html#SEC5.5.2.1 | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/4545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
]
} |
4,610 | How is it possible to make prototype methods in C#.Net? In JavaScript, I can do the following to create a trim method for the string object: String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,"");} How can I go about doing this in C#.Net? | You can't dynamically add methods to existing objects or classes in .NET, except by changing the source for that class. You can, however, in C# 3.0, use extension methods, which look like new methods, but are compile-time magic. To do this for your code: public static class StringExtensions{ public static String trim(this String s) { return s.Trim(); }} To use it: String s = " Test ";s = s.trim(); This looks like a new method, but will compile the exact same way as this code: String s = " Test ";s = StringExtensions.trim(s); What exactly are you trying to accomplish? Perhaps there are better ways of doing what you want? | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/4610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
]
} |
4,622 | What is the complete and correct syntax for the SQL Case expression? | The complete syntax depends on the database engine you're working with: For SQL Server: CASE case-expression WHEN when-expression-1 THEN value-1 [ WHEN when-expression-n THEN value-n ... ] [ ELSE else-value ]END or: CASE WHEN boolean-when-expression-1 THEN value-1 [ WHEN boolean-when-expression-n THEN value-n ... ] [ ELSE else-value ]END expressions, etc: case-expression - something that produces a valuewhen-expression-x - something that is compared against the case-expressionvalue-1 - the result of the CASE statement if: the when-expression == case-expression OR the boolean-when-expression == TRUEboolean-when-exp.. - something that produces a TRUE/FALSE answer Link: CASE (Transact-SQL) Also note that the ordering of the WHEN statements is important. You can easily write multiple WHEN clauses that overlap, and the first one that matches is used . Note : If no ELSE clause is specified, and no matching WHEN-condition is found, the value of the CASE expression will be NULL . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/4622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
]
} |
4,629 | I can do an eval("something()"); to execute the code dynamically in JavaScript. Is there a way for me to do the same thing in C#? An example of what I am trying to do is: I have an integer variable (say i ) and I have multiple properties by the names: "Property1", "Property2", "Property3", etc.Now, I want to perform some operations on the " Property i " property depending on the value of i . This is really simple with Javascript. Is there any way to do this with C#? | DISCLAIMER: This answer was written back in 2008. The landscape has changed drastically since then. Look at the other answers on this page, especially the one detailing Microsoft.CodeAnalysis.CSharp.Scripting . Rest of answer will be left as it was originally posted but is no longer accurate. Unfortunately, C# isn't a dynamic language like that. What you can do, however, is to create a C# source code file, full with class and everything, and run it through the CodeDom provider for C# and compile it into an assembly, and then execute it. This forum post on MSDN contains an answer with some example code down the page somewhat: create a anonymous method from a string? I would hardly say this is a very good solution, but it is possible anyway. What kind of code are you going to expect in that string? If it is a minor subset of valid code, for instance just math expressions, it might be that other alternatives exists. Edit : Well, that teaches me to read the questions thoroughly first. Yes, reflection would be able to give you some help here. If you split the string by the ; first, to get individual properties, you can use the following code to get a PropertyInfo object for a particular property for a class, and then use that object to manipulate a particular object. String propName = "Text";PropertyInfo pi = someObject.GetType().GetProperty(propName);pi.SetValue(someObject, "New Value", new Object[0]); Link: PropertyInfo.SetValue Method | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/4629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384/"
]
} |
4,661 | I have more than one OpenID as I have tried out numerous. As people take up OpenID different suppliers are going to emerge I may want to switch provinders. As all IDs are me, and all are authenticated against the same email address, shouldn't I be able to log into stack overflow with any of them and be able to hit the same account? | I think each site that implements OpenID would have to build their software to allow multiple entries for your OpenID credentials. However, just because a site doesn't allow you to create multiple entries doesn't mean you can't swap out OpenID suppliers. How to turn your blog into an OpenID STEP 1: Get an OpenID. There a lots of servers and services out there you can use. I use http://www.myopenid.com STEP 2: Add these two lines to your blog's main template in-between the <HEAD></HEAD> tags at the top of your template. Most all blog engines support editing your template so this should be an easy and very possible thing to do. Example: <link rel="openid.server" href="http://www.myopenid.com/server" /> <link rel="openid.delegate" href=http://YOURUSERNAME.myopenid.com/ /> This will let you use your domain/blog as your OpenID. Credits to Scott Hanselman and Simon Willison for these simple instructions. Switch Your Supplier Now that your OpenID points to your blog, you can update your link rel href's to point to a new supplier and all the places that you've tied your blog's OpenID will use the new supplier. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/4661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/274/"
]
} |
4,664 | Should the folders in a solution match the namespace? In one of my teams projects, we have a class library that has many sub-folders in the project. Project Name and Namespace: MyCompany.Project.Section . Within this project, there are several folders that match the namespace section: Folder Vehicles has classes in the MyCompany.Project.Section.Vehicles namespace Folder Clothing has classes in the MyCompany.Project.Section.Clothing namespace etc. Inside this same project, is another rogue folder Folder BusinessObjects has classes in the MyCompany.Project.Section namespace There are a few cases like this where folders are made for "organizational convenience". My question is: What's the standard? In class libraries do the folders usually match the namespace structure or is it a mixed bag? | Also, note that if you use the built-in templates to add classes to a folder, it will by default be put in a namespace that reflects the folder hierarchy. The classes will be easier to find and that alone should be reasons good enough. The rules we follow are: Project/assembly name is the same as the root namespace, except for the .dll ending Only exception to the above rule is a project with a .Core ending, the .Core is stripped off Folders equals namespaces One type per file (class, struct, enum, delegate, etc.) makes it easy to find the right file | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/4664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
4,684 | I'm currently experimenting with build script, and since I have an ASP.net Web Part under source control, my build script should do that at the end: Grab the "naked" Windows 2003 IIS VMWare or Virtual PC Image from the Network Boot it up Copy the Files from the Build Folder to the Server Install it Do whatever else is needed I have never tried automating a Virtual Machine, but I saw that both VMWare and Virtual Server offer automation facilities. While I cannot use Virtual Server (Windows XP Home :-(), Virtual PC works. Does anyone here have experience with either VMWare Server or Virtual PC 2007 SP1 in terms of automation? Which one is better suited (I run windows, so the Platform-independence of VMWare does not count) and easier to automate? | With VMWare, there is the Virtual Machine Automation APIs (VIX API) . You can find the reference guide here . It works with VMWare Server and WorkStation, but AFAIK it's not available for ESX Server. From the main page for VIX: The VIX API allows you to write scripts and programs that automate virtual machine operations. The API is high-level, easy to use, and practical for both script writers and application programmers. It runs on VMware Server and Workstation products, both Windows and Linux. Bindings are provided for C, Perl, and COM (Visual Basic, VBscript, C#). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/4684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
]
} |
4,689 | What fonts do you use for programming, and for what language/IDE? I use Consolas for all my Visual Studio work, any other recommendations? | Either Consolas (download) or Andale Mono (download) . I mostly use Andale Mono. I wrote an article about programming fonts a long time ago , I think Consolas wasn't even out yet. http://www.deadprogrammer.com/photos/fonts.gif I find that typing Illegal1 = O0 is a good test of suitability. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/4689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/637/"
]
} |
4,724 | I really feel that I should learn Lisp and there are plenty of good resources out there to help me do it. I'm not put off by the complicated syntax, but where in "traditional commercial programming" would I find places it would make sense to use it instead of a procedural language. Is there a commercial killer-app out there that's been written in Lisp ? | One of the main uses for Lisp is in Artificial Intelligence. A friend of mine at college took a graduate AI course and for his main project he wrote a " Lights Out " solver in Lisp. Multiple versions of his program utilized slightly different AI routines and testing on 40 or so computers yielded some pretty neat results (I wish it was online somewhere for me to link to, but I don't think it is). Two semesters ago I used Scheme (a language based on Lisp) to write an interactive program that simulated Abbott and Costello's "Who's on First" routine. Input from the user was matched against some pretty complicated data structures (resembling maps in other languages, but much more flexible) to choose what an appropriate response would be. I also wrote a routine to solve a 3x3 slide puzzle (an algorithm which could easily be extended to larger slide puzzles). In summary, learning Lisp (or Scheme) may not yield many practical applications beyond AI but it is an extremely valuable learning experience, as many others have stated. Programming in a functional language like Lisp will also help you think recursively (if you've had trouble with recursion in other languages, this could be a great help). | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/4724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
]
} |
4,738 | I'm developing a data access component that will be used in a website that contains a mix of classic ASP and ASP.NET pages, and need a good way to manage its configuration settings. I'd like to use a custom ConfigurationSection , and for the ASP.NET pages this works great. But when the component is called via COM interop from a classic ASP page, the component isn't running in the context of an ASP.NET request and therefore has no knowledge of web.config. Is there a way to tell the ConfigurationManager to just load the configuration from an arbitrary path (e.g. ..\web.config if my assembly is in the /bin folder)? If there is then I'm thinking my component can fall back to that if the default ConfigurationManager.GetSection returns null for my custom section. Any other approaches to this would be welcome! | Try this: System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(strConfigPath); //Path to your config fileSystem.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap); | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/4738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205/"
]
} |
4,794 | I've written (most of) an application in Flex and I am concerned with protecting the source code. I fired up a demo of Trillix swf decompiler and opened up the swf file that was installed to my Program Files directory. I saw that all of the actionscript packages I wrote were there. I'm not too concerned with the packages, even though there is a substantial amount of code, because it still seems pretty unusable without the mxml files. I think they are converted to actionscript, or atleast I hope. However, I would still like to explore obfuscation. Does anyone have any experience with Flash / Actionscript 3 / Flex obfuscators? Can you recommend a good product? | Here's what I would do. Compile your application to a SWF file. Then encrypt the SWF using AES. Make a "wrapper" application that loads the encrypted SWF into a ByteArray using URLLoader Use the as3crypto library to decrypt the swf at runtime. Once decrypted, use Loader.loadBytes to load the decrypted swf into the wrapper application. This will make it a lot harder to get your code. Not impossible, but harder. For AIR applications you could leave the SWF encrypted when delivering the application to the end-user. Then you could provide a registration key that contains the key used to decrypt the SWF. Also, here is a link to an AS3 obfuscator. I am not sure how well it works though. http://www.ambiera.com/irrfuscator/index.html | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/4794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26/"
]
} |
4,816 | How do you resolve a domain name to an IP address with .NET/C#? | using System.Net;foreach (IPAddress address in Dns.GetHostAddresses("www.google.com")){ Console.WriteLine(address.ToString());} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/4816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/390/"
]
} |
4,824 | Is there a C library function that will return the index of a character in a string? So far, all I've found are functions like strstr that will return the found char *, not it's location in the original string. | strstr returns a pointer to the found character, so you could use pointer arithmetic: (Note: this code not tested for its ability to compile, it's one step away from pseudocode.) char * source = "test string"; /* assume source address is */ /* 0x10 for example */char * found = strstr( source, "in" ); /* should return 0x18 */if (found != NULL) /* strstr returns NULL if item not found */{ int index = found - source; /* index is 8 */ /* source[8] gets you "i" */} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/4824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/75/"
]
} |
4,850 | I am new to C# and am doing some work in an existing application. I have a DirectX viewport that has components in it that I want to be able to position using arrow keys. Currently I am overriding ProcessCmdKey and catching arrow input and send an OnKeyPress event. This works, but I want to be able to use modifiers( ALT + CTRL + SHIFT ). As soon as I am holding a modifier and press an arrow no events are triggered that I am listening to. Does anyone have any ideas or suggestions on where I should go with this? | Within your overridden ProcessCmdKey how are you determining which key has been pressed? The value of keyData (the second parameter) will change dependant on the key pressed and any modifier keys, so, for example, pressing the left arrow will return code 37, shift-left will return 65573, ctrl-left 131109 and alt-left 262181. You can extract the modifiers and the key pressed by ANDing with appropriate enum values: protected override bool ProcessCmdKey(ref Message msg, Keys keyData){ bool shiftPressed = (keyData & Keys.Shift) != 0; Keys unmodifiedKey = (keyData & Keys.KeyCode); // rest of code goes here} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/4850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41/"
]
} |
4,860 | We have a question with regards to XML-sig and need detail about the optional elements as well as some of the canonicalization and transform stuff. We're writing a spec for a very small XML-syntax payload that will go into the metadata of media files and it needs to by cryptographically signed. Rather than re-invent the wheel, We thought we should use the XML-sig spec but I think most of it is overkill for what we need, and so we like to have more information/dialogue with people who know the details. Specifically, do we need to care about either transforms or canonicalization if the XML is very basic with no tabs for formatting and is specific to our needs? | Within your overridden ProcessCmdKey how are you determining which key has been pressed? The value of keyData (the second parameter) will change dependant on the key pressed and any modifier keys, so, for example, pressing the left arrow will return code 37, shift-left will return 65573, ctrl-left 131109 and alt-left 262181. You can extract the modifiers and the key pressed by ANDing with appropriate enum values: protected override bool ProcessCmdKey(ref Message msg, Keys keyData){ bool shiftPressed = (keyData & Keys.Shift) != 0; Keys unmodifiedKey = (keyData & Keys.KeyCode); // rest of code goes here} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/4860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/661/"
]
} |
4,911 | So in my simple learning website, I use the built in ASP.NET authentication system. I am adding now a user table to save stuff like his zip, DOB etc. My question is: In the new table, should the key be the user name (the string) or the user ID which is that GUID looking number they use in the asp_ tables . If the best practice is to use that ugly guid, does anyone know how to get it? it seems to not be accessible as easily as the name ( System.Web.HttpContext.Current.User.Identity.Name ) If you suggest I use neither (not the guid nor the userName fields provided by ASP.NET authentication) then how do I do it with ASP.NET authentication? One option I like is to use the email address of the user as login, but how to I make ASP.NET authentication system use an email address instead of a user name? (or there is nothing to do there, it is just me deciding I "know" userName is actually an email address? Please note: I am not asking on how get a GUID in .NET, I am just referring to the userID column in the asp_ tables as guid. The user name is unique in ASP.NET authentication. | You should use some unique ID, either the GUID you mention or some other auto generated key. However, this number should never be visible to the user. A huge benefit of this is that all your code can work on the user ID, but the user's name is not really tied to it. Then, the user can change their name (which I've found useful on sites). This is especially useful if you use email address as the user's login... which is very convenient for users (then they don't have to remember 20 IDs in case their common user ID is a popular one). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/4911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/350/"
]
} |
4,913 | Using VS2008, C#, .Net 2 and Winforms how can I make a regular Button look "pressed"?Imagine this button is an on/off switch. ToolStripButton has the Checked property, but the regular Button does not. | One method you can used to obtain this option is by placing a "CheckBox" object and changing its "Appearance" from "Normal" to "Button" this will give you the same functionality that I believe you are looking for. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/4913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/626/"
]
} |
4,922 | I saw this in an answer to another question , in reference to shortcomings of the Java spec: There are more shortcomings and this is a subtle topic. Check this out: public class methodOverloading{ public static void hello(Integer x){ System.out.println("Integer"); } public static void hello(long x){ System.out.println("long"); } public static void main(String[] args){ int i = 5; hello(i); }} Here "long" would be printed (haven't checked it myself), because the compiler chooses widening over auto-boxing. Be careful when using auto-boxing or don't use it at all! Are we sure that this is actually an example of widening instead of autoboxing, or is it something else entirely? On my initial scanning, I would agree with the statement that the output would be "long" on the basis of i being declared as a primitive and not an object. However, if you changed hello(long x) to hello(Long x) the output would print "Integer" What's really going on here? I know nothing about the compilers/bytecode interpreters for java... | In the first case, you have a widening conversion happening. This can be see when runinng the "javap" utility program (included w/ the JDK), on the compiled class: public static void main(java.lang.String[]); Code: 0: iconst_ 5 1: istore_ 1 2: iload_ 1 3: i2l 4: invokestatic #6; //Method hello:(J)V 7: return} Clearly, you see the I2L, which is the mnemonic for the widening Integer-To-Long bytecode instruction. See reference here . And in the other case, replacing the "long x" with the object "Long x" signature, you'll have this code in the main method: public static void main(java.lang.String[]); Code: 0: iconst_ 5 1: istore_ 1 2: iload_ 1 3: invokestatic #6; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 6: invokestatic #7; //Method hello:(Ljava/lang/Integer;)V 9: return} So you see the compiler has created the instruction Integer.valueOf(int), to box the primitive inside the wrapper. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/4922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/670/"
]
} |
4,923 | I'm using ColdFusion to populate a template that includes HTML unordered lists ( <ul> s). Most of these aren't that long, but a few have ridiculously long lengths and could really stand to be in 2-3 columns. Is there an HTML, ColdFusion or perhaps JavaScript (I'm accepting jQuery solutions) way to do this easily? It's not worth some over-complicated heavyweight solution to save some scrolling. | So I dug up this article from A List Apart CSS Swag: Multi-Column Lists . I ended up using the first solution, it's not the best but the others require either using complex HTML that can't be generated dynamically, or creating a lot of custom classes, which could be done but would require loads of in-line styling and possibly a huge page. Other solutions are still welcome though. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/4923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/666/"
]
} |
4,942 | When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it? | This is one of those cases that really boil down to personal preference or situational details. If you're more comfortable and experienced with Python, then say so. Are they asking you to justify it because they're more comfortable with one of the other environments? After you're done, will the system be passed off to someone else for long-term maintenance? If they ask you to use a technology or language that you're not as familiar with, then make sure they know up-front that it's going to take you longer. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/4942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
4,949 | We have a PHP project that we would like to version control. Right now there are three of us working on a development version of the project which resides in an external folder to which all of our Eclipse IDEs are linked, and thus no version control. What is the right way and the best way to version control this? We have an SVN set up, but we just need to find a good way to check in and out that allows us to test on the development server. Any ideas? | We were in a similar situation, and here's what we ended up doing: Set up two branches -- the release and development branch. For the development branch, include a post-commit hook that deploys the repository to the dev server, so you can test. Once you're ready, you merge your changes into the release branch. I'd also suggest putting in a post-commit hook for deployment there. You can also set up individual development servers for each of the team members, on their workstations. I find that it speeds things up a bit, although you do have some more setup time. We had to use a single development server, because we were using a proprietary CMS and ran into licensing issues. So our post-commit hook was a simple FTP bot. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/4949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/673/"
]
} |
4,973 | I am trying to lay out a table-like page with two columns. I want the rightmost column to dock to the right of the page, and this column should have a distinct background color. The content in the right side is almost always going to be smaller than that on the left. I would like the div on the right to always be tall enough to reach the separator for the row below it. How can I make my background color fill that space? .rightfloat { color: red; background-color: #BBBBBB; float: right; width: 200px;}.left { font-size: 20pt;}.separator { clear: both; width: 100%; border-top: 1px solid black;} <div class="separator"> <div class="rightfloat"> Some really short content. </div> <div class="left"> Some really really really really really really really really really really big content </div></div><div class="separator"> <div class="rightfloat"> Some more short content. </div> <div class="left"> Some really really really really really really really really really really big content </div></div> Edit: I agree that this example is very table-like and an actual table would be a fine choice. But my "real" page will eventually be less table-like, and I'd just like to first master this task! Also, for some reason, when I create/edit my posts in IE7, the code shows up correctly in the preview view, but when I actually post the message, the formatting gets removed. Editing my post in Firefox 2 seems to have worked, FWIW. Another edit: Yeah, I unaccepted GateKiller's answer. It does indeed work nicely on my simple page, but not in my actual heavier page. I'll investigate some of the links y'all have pointed me to. | Ahem... The short answer to your question is that you must set the height of 100% to the body and html tag, then set the height to 100% on each div element you want to make 100% the height of the page. Actually, 100% height will not work in most design situations - this may be short but it is not a good answer. Google "any column longest" layouts. The best way is to put the left and right cols inside a wrapper div , float the left and right cols and then float the wrapper - this makes it stretch to the height of the inner containers - then set background image on the outer wrapper. But watch for any horizontal margins on the floated elements in case you get the IE "double margin float bug". | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/4973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/404/"
]
} |
5,024 | Does anyone know where online copies of the old The Perl Journal articles can be found? I know they are now owned by Dr. Dobb's, just the main page for it says they are part of whatever section the subject matter is relevant too, rather than being indexed together. That said, I have never been able to find any of them online on that site. I know Mark Jason Dominus has a few of his articles on his site , any one know of any other good places? Or even what search terms to use at Dr. Dobb's? | Volumes 1-5 (1996 -> 2000) can be found at http://www.foo.be/docs/tpj/ Hmm, looks like that was the entire run? I though it was longer than that for some reason. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/5024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
]
} |
5,071 | I've played with CVS a little bit and am not the most familiar with all of its capabilities, but a huge annoyance for me is trying to add new directories that contain more directories in them. Running " cvs add " only adds the contents of the current directory, and using " cvs import " didn't look like the right thing either since it's still all code I'm producing (this howto claimed import is for 3rd party sources ) Do you guys know any way to recursively add everything in a given directory to the current CVS project (or if SVN or git makes this notably easier)? | I found this worked pretty effectively: First, add all the directories, but not any named "CVS": find . -type d \! -name CVS -exec cvs add '{}' \; Then add all the files, excluding anything in a CVS directory: find . \( -type d -name CVS -prune \) -o \( -type f -exec cvs add '{}' \; \) Now, if anyone has a cure for the embarrassment of using CVS in this day and age... | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/5071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
]
} |
5,087 | My company is in the process of starting down the Grails path. The reason for that is that the current developers are heavy on Java but felt the need for a MVC-style language for some future web development projects. Personally, I'm coming from the design/usability world, but as I take more "front-end" responsibilities I'm starting to feel the need for learning a language more intensively so I can code some logic but especially the front-end code for my UIs and stuff. I've been trying to get into Python/Django personally, but just never invested too much time on it. Now that my company is "jumping" into Grails I bought the " Agile Web Development with Rails (3rd Ed - Beta) " and I'm starting to get into RoR . I'd still like to learn Python in the future or on the side, but my biggest question is: Should I be learning RoR, and have a more versatile language in my "portfolio", knowing that my RoR knowledge will be useful for my Grails needs as well?? -OR- Should I just skip RoR and focus on learning Grails that I'll be needing for work soon, and work on learning RoR/Django (Ruby/Python) later? Basically the question revolves around the usefulness of Grails in a non-corporate setting and the similarities between Rails and Grails. (and this, while trying to avoid the centennial discussion of Python vs Ruby (on Rails) :)) | Mmh, I don't know how to say this. Some people might bash me over this. Language (Groovy and Ruby) As a language I reckon Ruby is more funky compared to Groovy. Groovy only exists to ease Java programmer as you don't need to learn too much new syntax. But overall I reckon is not as funky as Ruby. Groovy wouldn't be the JVM language that is worth to learn based on attender's vote in this year's JavaOne but instead Scala is the one to go. Besides that, the original creator of Groovy himself does not have faith in the language he created himself in the first place. Community and Job openings As for the community, Grails community is not as big as Rails, though since the acquirement by Spring more and more people are using it in serious application. Rails has more job openings in the market compared to Grails (that is if you want to invest in looking a new job). The framework (Grails and Rails) But, as a framework, if you really care about maintainability and need access to Java framework and legacy Java system, Grails is the way to go as it provides cleaner access to Java. Grails itself is built upon several popular Java framework (Spring & Hibernate). Rails itself IMHO is funky like Ruby itself, but it's funkyness costs you maintainability. Matz himself prefers Merb over Rails 2 because Rails create a DSL on top of Ruby which is really against the Ruby philosophy. And I reckon because Rails itself is opiniated, which in turn if you don't have the same opinion as the creator, it might not fit your needs. Conclusion So in your case, learn Grails as that is the company's consensus (you need to respect the consensus) and if you still want to secure your job. But, invest some time learning Rails and Ruby too if you want to open a chance getting a new job in the future. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/5087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/682/"
]
} |
5,118 | I'm working on a website that will switch to a new style on a set date. The site's built-in semantic HTML and CSS, so the change should just require a CSS reference change. I'm working with a designer who will need to be able to see how it's looking, as well as a client who will need to be able to review content updates in the current look as well as design progress on the new look. I'm planning to use a magic querystring value and/or a javascript link in the footer which writes out a cookie to select the new CSS page. We're working in ASP.NET 3.5. Any recommendations? I should mention that we're using IE Conditional Comments for IE8, 7, and 6 support. I may create a function that does a replacement: <link href="Style/<% GetCssRoot() %>.css" rel="stylesheet" type="text/css" /><!--[if lte IE 8]> <link type="text/css" href="Style/<% GetCssRoot() %>-ie8.css" rel="stylesheet" /><![endif]--><!--[if lte IE 7]> <link type="text/css" href="Style/<% GetCssRoot() %>-ie7.css" rel="stylesheet" /><![endif]--><!--[if lte IE 6]> <link type="text/css" href="Style/<% GetCssRoot() %>-ie6.css" rel="stylesheet" /><![endif]--> | In Asp.net 3.5, you should be able to set up the Link tag in the header as a server tag. Then in the codebehind you can set the href property for the link element, based on a cookie value, querystring, date, etc. In your aspx file: <head> <link id="linkStyles" rel="stylesheet" type="text/css" runat="server" /></head> And in the Code behind: protected void Page_Load(object sender, EventArgs e) { string stylesheetAddress = // logic to determine stylesheet linkStyles.Href = stylesheetAddress;} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/5118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5/"
]
} |
5,170 | I was wondering if there are any alternatives to Microsoft's SQL Server Management Studio? Not there's anything wrong with SSMS, but sometimes it just seem too big an application where all I want todo is browse/edit tables and run queries. | I've started using LinqPad . In addition to being more lightweight than SSMS, you can also practice writing LINQ queries- way more fun than boring old TSQL! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/5170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
]
} |
5,179 | ASP.NET server-side controls postback to their own page. This makes cases where you want to redirect a user to an external page, but need to post to that page for some reason (for authentication, for instance) a pain. An HttpWebRequest works great if you don't want to redirect, and JavaScript is fine in some cases, but can get tricky if you really do need the server-side code to get the data together for the post. So how do you both post to an external URL and redirect the user to the result from your ASP.NET codebehind code? | Here's how I solved this problem today. I started from this article on C# Corner, but found the example - while technically sound - a little incomplete. Everything he said was right, but I needed to hit a few external sites to piece this together to work exactly as I wanted. It didn't help that the user was not technically submitting a form at all; they were clicking a link to go to our support center, but to log them in an http post had to be made to the support center's site. This solution involves using HttpContext.Current.Response.Write() to write the data for the form, then using a bit of Javascript on the <body onload=""> method to submit the form to the proper URL. When the user clicks on the Support Center link, the following method is called to write the response and redirect the user: public static void PassthroughAuthentication(){ System.Web.HttpContext.Current.Response.Write("<body onload=document.forms[0].submit();window.location=\"Home.aspx\";>"); System.Web.HttpContext.Current.Response.Write("<form name=\"Form\" target=_blank method=post action=\"https://external-url.com/security.asp\">"); System.Web.HttpContext.Current.Response.Write(string.Format("<input type=hidden name=\"cFName\" value=\"{0}\">", "Username")); System.Web.HttpContext.Current.Response.Write("</form>"); System.Web.HttpContext.Current.Response.Write("</body>");} The key to this method is in that onload bit of Javascript, which , when the body of the page loads, submits the form and then redirects the user back to my own Home page. The reason for that bit of hoodoo is that I'm launching the external site in a new window, but don't want the user to resubmit the hidden form if they refresh the page. Plus that hidden form pushed the page down a few pixels which got on my nerves. I'd be very interested in any cleaner ideas anyone has on this one. Eric Sipple | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/5179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/111/"
]
} |
5,222 | What is the Java equivalent of PHP's $_POST ? After searching the web for an hour, I'm still nowhere closer. | Your HttpServletRequest object has a getParameter(String paramName) method that can be used to get parameter values. http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/5222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/429/"
]
} |
5,223 | I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object? const myObject = new Object();myObject["firstname"] = "Gareth";myObject["lastname"] = "Simpson";myObject["age"] = 21; | Updated answer Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys() so the above code just becomes: var size = Object.keys(myObj).length; This doesn't have to modify any existing prototype since Object.keys() is now built-in. Edit : Objects can have symbolic properties that can not be returned via Object.key method. So the answer would be incomplete without mentioning them. Symbol type was added to the language to create unique identifiers for object properties. The main benefit of the Symbol type is the prevention of overwrites. Object.keys or Object.getOwnPropertyNames does not work for symbolic properties. To return them you need to use Object.getOwnPropertySymbols . var person = { [Symbol('name')]: 'John Doe', [Symbol('age')]: 33, "occupation": "Programmer"};const propOwn = Object.getOwnPropertyNames(person);console.log(propOwn.length); // 1let propSymb = Object.getOwnPropertySymbols(person);console.log(propSymb.length); // 2 Older answer The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be: Object.size = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size;};// Get the size of an objectconst myObj = {}var size = Object.size(myObj); There's a sort of convention in JavaScript that you don't add things to Object.prototype , because it can break enumerations in various libraries. Adding methods to Object is usually safe, though. | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/5223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147/"
]
} |
5,269 | In C#, (and feel free to answer for other languages), what order does the runtime evaluate a logic statement? Example: DataTable myDt = new DataTable();if (myDt != null && myDt.Rows.Count > 0){ //do some stuff with myDt} Which statement does the runtime evaluate first - myDt != null or: myDt.Rows.Count > 0 ? Is there a time when the compiler would ever evaluate the statement backwards? Perhaps when an "OR" operator is involved? & is known as a logical bitwise operator and will always evaluate all the sub-expressions What is a good example of when to use the bitwise operator instead of the "short-circuited boolean"? | C# : Left to right, and processing stops if a non-match (evaluates to false) is found. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/5269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
]
} |
5,323 | It seems like every time I try to create a pure CSS layout it takes me much longer than if I'd use a table or two. Getting three columns to be equal lengths with different amounts of data seems to require particular fancy hacks, especially when dealing with cross-browser issues. My Question: Who are these few tables going to hurt? Tables seem to work particularly well on tabular data — why are they so reviled in this day and age? Google.com has a table in its source code, so do many other sites ( stackoverflow.com does not by the way ). | Since this is stack overflow , I'll give you my programmer's answer semantics 101 First take a look at this code and think about what's wrong here... class car { int wheels = 4; string engine;}car mybike = new car();mybike.wheels = 2;mybike.engine = null; The problem, of course, is that a bike is not a car. The car class is an inappropriate class for the bike instance. The code is error-free, but is semantically incorrect. It reflects poorly on the programmer. semantics 102 Now apply this to document markup. If your document needs to present tabular data, then the appropriate tag would be <table> . If you place navigation into a table however, then you're misusing the intended purpose of the <table> element. In the second case, you're not presenting tabular data -- you're (mis)using the <table> element to achieve a presentational goal. conclusion Whom does this hurt? No one. Who benefits if you use semantic markup? You -- and your professional reputation. Now go and do the right thing. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/5323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556/"
]
} |
5,328 | So, in Java, the first line of your constructor HAS to be a call to super... be it implicitly calling super(), or explicitly calling another constructor. What I want to know is, why can't I put a try block around that? My specific case is that I have a mock class for a test. There is no default constructor, but I want one to make the tests simpler to read. I also want to wrap the exceptions thrown from the constructor into a RuntimeException. So, what I want to do is effectively this: public class MyClassMock extends MyClass { public MyClassMock() { try { super(0); } catch (Exception e) { throw new RuntimeException(e); } } // Mocked methods} But Java complains that super isn't the first statement. My workaround: public class MyClassMock extends MyClass { public static MyClassMock construct() { try { return new MyClassMock(); } catch (Exception e) { throw new RuntimeException(e); } } public MyClassMock() throws Exception { super(0); } // Mocked methods} Is this the best workaround? Why doesn't Java let me do the former? My best guess as to the "why" is that Java doesn't want to let me have a constructed object in a potentially inconsistent state... however, in doing a mock, I don't care about that. It seems I should be able to do the above... or at least I know that the above is safe for my case... or seems as though it should be anyways. I am overriding any methods I use from the tested class, so there is no risk that I am using uninitialized variables. | Unfortunately, compilers can't work on theoretical principles, and even though you may know that it is safe in your case, if they allowed it, it would have to be safe for all cases. In other words, the compiler isn't stopping just you, it's stopping everyone, including all those that don't know that it is unsafe and needs special handling. There are probably other reasons for this as well, as all languages usually have ways to do unsafe things if one knows how to deal with them. In C# .NET there are similar provisions, and the only way to declare a constructor that calls a base constructor is this: public ClassName(...) : base(...) in doing so, the base constructor will be called before the body of the constructor, and you cannot change this order. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/5328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
]
} |
5,329 | I'm currently evaluating the MSF for CMMI process template under TFS for use on my development team, and I'm having trouble understanding the need for separate bug and change request work item types. I understand that it is beneficial to be able to differentiate between bugs (errors) and change requests (changing requirements) when generating reports. In our current system, however, we only have a single type of change request and just use a field to indicate whether it is a bug, requirement change, etc (this field can be used to build report queries). What are the benefits of having a separate workflow for bugs? I'm also confused by the fact that developers can submit work against a bug or a change request, I thought the intended workflow was for bugs to generate change requests which are what the developer references when making changes. | @Luke I don't disagree with you, but this difference is typically the explanation given for why there is two different processes available for handling the two types of issues. I'd say that if the color of the home page was originally designed to be red, and for some reason it is blue, that's easily a quick fix and doesn't need to involve many people or man-hours to do the change. Just check out the file, change the color, check it back in and update the bug. However, if the color of the home page was designed to be red, and is red, but someone thinks it needs to be blue, that is, to me anyway, a different type of change. For instance, have someone thought about the impact this might have on other parts of the page, like images and logos overlaying the blue background? Could there be borders of things that looks bad? Link underlining is blue, will that show up? As an example, I am red/green color blind, changing the color of something is, for me, not something I take lightly. There are enough webpages on the web that gives me problems. Just to make a point that even the most trivial change can be nontrivial if you consider everything. The actual end implementation change is probably much of the same, but to me a change request is a different beast, precisely because it needs to be thought about more to make sure it will work as expected. A bug, however, is that someone said this is how we're going to do it and then someone did it differently. A change request is more like but we need to consider this other thing as well... hmm... . There are exceptions of course, but let me take your examples apart. If the server was designed to handle more than 300,000,000,000 pageviews, then yes, it is a bug that it doesn't. But designing a server to handle that many pageviews is more than just saying our server should handle 300,000,000,000 pageviews , it should contain a very detailed specification for how it can do that, right down to processing time guarantees and disk access average times. If the code is then implemented exactly as designed, and unable to perform as expected, then the question becomes: did we design it incorrectly or did we implement it incorrectly? . I agree that in this case, wether it is to be considered a design flaw or a implementation flaw depends on the actual reason for why it fails to live up to expectations. For instance, if someone assumed disks were 100x times as fast as they actually are, and this is deemed to be the reason for why the server fails to perform as expected, I'd say this is a design bug, and someone needs to redesign. If the original requirement of that many pageviews is still to be held, a major redesign with more in-memory data and similar might have to be undertaken. However, if someone has just failed to take into account how raid disks operate and how to correctly benefit from striped media, that's a bug and might not need that big of a change to fix. Again, there will of course be exceptions. In any case, the original difference I stated is the one I have found to be true in most cases. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/5329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
]
} |
5,374 | I would have thought this would be an easy one to Google, but I've been unsucessful. I want to assign a variable the value out of an attribute (easy so far) then use that variable to select another node based on the value of that attribute. Example: <xsl:variable name="myId" select="@id" /><xsl value-of select="//Root/Some/Other/Path/Where[@id='{@myId}']/@Name /> That does not work. If I replace the {@myId} with the value that is in the variable then it does find the right node, but doign it this way produces nothing. I'm sure I'm missing something, or perhaps there is a different way to do it. The context is that there is related data under different top-level nodes that share the same id value so I need to get the related nodes in my template. | Ok, I finally figured it out. Silly problem really, I simply needed to leave out the quotes and the braces. One of those times when I thought that I'd already tried that. :D Oh, and I mistyped @myId in the first example, the code was actually $myId. <xsl:variable name="myId" select="@id" /><xsl value-of select="//Root/Some/Other/Path/Where[@id=$myId]/@Name" /> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/5374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/312/"
]
} |
5,415 | I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number? | >>> import struct>>> struct.pack('f', 3.141592654)b'\xdb\x0fI@'>>> struct.unpack('f', b'\xdb\x0fI@')(3.1415927410125732,)>>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0)'\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@' | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/5415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
]
} |
5,419 | When I try to print a Unicode string in a Windows console, I get an error . UnicodeEncodeError: 'charmap' codec can't encode character .... I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this?Is there any way I can make Python automatically print a ? instead of failing in this situation? Edit: I'm using Python 2.5. Note: @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!! @JFSebastian answer is more relevant as of today (6 Jan 2016). | Note: This answer is sort of outdated (from 2008). Please use the solution below with care!! Here is a page that details the problem and a solution (search the page for the text Wrapping sys.stdout into an instance ): PrintFails - Python Wiki Here's a code excerpt from that page: $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' UTF-8 <type 'unicode'> 2 Б Б $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' | cat None <type 'unicode'> 2 Б Б There's some more information on that page, well worth a read. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/5419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207/"
]
} |
5,425 | I have a page that is generated which inserts an HTML comment near the top of the page. Inside the comment is a *nix-style command. <!-- command --option value --option2 value2 --option3 --> This comment breaks the page completely. What is wrong with the comment to cause this to happen, and why is this the case? | Comments in the XML Spec from the w3.org : For compatibility, the string "--" (double-hyphen) MUST NOT occur within comments. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/5425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/219/"
]
} |
5,428 | Is it worth learning the convention or is it a bane to readability and maintainability? | Considering that most people that use Hungarian Notation is following the misunderstood version of it, I'd say it's pretty pointless. If you want to use the original definition of it, it might make more sense, but other than that it is mostly syntactic sugar. If you read the Wikipedia article on the subject, you'll find two conflicting notations, Systems Hungarian Notation and Apps Hungarian Notation . The original, good, definition is the Apps Hungarian Notation , but most people use the Systems Hungarian Notation . As an example of the two, consider prefixing variables with l for length, a for area and v for volume. With such notation, the following expression makes sense: int vBox = aBottom * lVerticalSide; but this doesn't: int aBottom = lSide1; If you're mixing the prefixes, they're to be considered part of the equation, and volume = area * length is fine for a box, but copying a length value into an area variable should raise some red flags. Unfortunately, the other notation is less useful, where people prefix the variable names with the type of the value, like this: int iLength;int iVolume;int iArea; some people use n for number, or i for integer, f for float, s for string etc. The original prefix was meant to be used to spot problems in equations, but has somehow devolved into making the code slightly easier to read since you don't have to go look for the variable declaration. With todays smart editors where you can simply hover over any variable to find the full type, and not just an abbreviation for it, this type of hungarian notation has lost a lot of its meaning. But, you should make up your own mind. All I can say is that I don't use either. Edit Just to add a short notice, while I don't use Hungarian Notation , I do use a prefix, and it's the underscore. I prefix all private fields of classes with a _ and otherwise spell their names as I would a property, titlecase with the first letter uppercase. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/5428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/659/"
]
} |
5,473 | Is it possible to undo the changes caused by the following command? If so, how? git reset --hard HEAD~1 | Pat Notz is correct. You can get the commit back so long as it's been within a few days. git only garbage collects after about a month or so unless you explicitly tell it to remove newer blobs. $ git initInitialized empty Git repository in .git/$ echo "testing reset" > file1$ git add file1$ git commit -m 'added file1'Created initial commit 1a75c1d: added file1 1 files changed, 1 insertions(+), 0 deletions(-) create mode 100644 file1$ echo "added new file" > file2$ git add file2$ git commit -m 'added file2'Created commit f6e5064: added file2 1 files changed, 1 insertions(+), 0 deletions(-) create mode 100644 file2$ git reset --hard HEAD^HEAD is now at 1a75c1d... added file1$ cat file2cat: file2: No such file or directory$ git reflog1a75c1d... HEAD@{0}: reset --hard HEAD^: updating HEADf6e5064... HEAD@{1}: commit: added file2$ git reset --hard f6e5064HEAD is now at f6e5064... added file2$ cat file2added new file You can see in the example that the file2 was removed as a result of the hard reset, but was put back in place when I reset via the reflog. | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/5473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
]
} |
5,482 | The ASP.NET AJAX ModalPopupExtender has OnCancelScript and OnOkScript properties, but it doesn't seem to have an OnShowScript property. I'd like to specify a javascript function to run each time the popup is shown. In past situations, I set the TargetControlID to a dummy control and provide my own control that first does some JS code and then uses the JS methods to show the popup. But in this case, I am showing the popup from both client and server side code. Anyone know of a way to do this? BTW, I needed this because I have a textbox in the modal that I want to make a TinyMCE editor. But the TinyMCE init script doesn't work on invisible textboxes, so I had to find a way to run it at the time the modal was shown | hmmm... I'm pretty sure that there's a shown event for the MPE... this is off the top of my head, but I think you can add an event handler to the shown event on page_load function pageLoad(){ var popup = $find('ModalPopupClientID'); popup.add_shown(SetFocus);}function SetFocus(){ $get('TriggerClientId').focus();} i'm not sure tho if this will help you with calling it from the server side tho | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/5482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/698/"
]
} |
5,507 | Does it make sense, having all of the C#-managed-bliss, to go back to Petzold's Programming Windows and try to produce code w/ pure WinAPI? What can be learn from it? Isn't it just too outdated to be useful? | This question is bordering on religious :) But I'll give my thoughts anyway. I do see value in learing the Win32 API. Most, if not all, GUI libraries (managed or unmanaged) result in calls to the Win32 API. Even the most thorough libraries don't cover 100% of the API, and hence there are always gaps which need to be plugged by direct API calls or P/invoking. Some of the names of the wrappers around the API calls have similar names to the underlying API calls, but those names aren't exactly self-documenting. So understanding the underlying API, and the terminology used therein, will aid in understanding the wrapper APIs and what they actually do. Plus, if you understand the nature of the underlying APIs that are used by frameworks, then you will make better choices with regards to which library functionality you should use in a given scenario. Cheers! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/5507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/861/"
]
} |
5,511 | How are you handling the entry of numeric values in WPF applications? Without a NumericUpDown control, I've been using a TextBox and handling its PreviewKeyDown event with the code below, but it's pretty ugly. Has anyone found a more graceful way to get numeric data from the user without relying on a third-party control? private void NumericEditPreviewKeyDown(object sender, KeyEventArgs e){ bool isNumPadNumeric = (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal; bool isNumeric = (e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod; if ((isNumeric || isNumPadNumeric) && Keyboard.Modifiers != ModifierKeys.None) { e.Handled = true; return; } bool isControl = ((Keyboard.Modifiers != ModifierKeys.None && Keyboard.Modifiers != ModifierKeys.Shift) || e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Insert || e.Key == Key.Down || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Tab || e.Key == Key.PageDown || e.Key == Key.PageUp || e.Key == Key.Enter || e.Key == Key.Return || e.Key == Key.Escape || e.Key == Key.Home || e.Key == Key.End); e.Handled = !isControl && !isNumeric && !isNumPadNumeric;} | How about: protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e){ e.Handled = !AreAllValidNumericChars(e.Text); base.OnPreviewTextInput(e);}private bool AreAllValidNumericChars(string str){ foreach(char c in str) { if(!Char.IsNumber(c)) return false; } return true;} | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/5511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615/"
]
} |
5,527 | I just saw a comment of suggesting J# , and it made me wonder... is there a real, beneficial use of J# over Java? So, my feeling is that the only reason you would even consider using J# is that management has decreed that the company should jump on the Java bandwagon... and the .NET bandwagon. If you use J#, you are effectively losing the biggest benefit of picking Java... rich cross platform support. Sure there is Mono, but it's not as richly supported or as full featured right? I remember hearing Forms are not fully (perhaps at all) supported. I'm not trying to bash .NET here, I'm just saying, if you are going to go the Microsoft route, why not just use C#? If you are going to go the Java route, why would J# enter the picture? I'm hoping to find some real world cases here, so please especially respond if you've ACTUALLY used J# in a REAL project, and why. | J# is no longer included in VS2008. Unless you already have J# code, you should probably stay away. From j# product page: Since customers have told us that the existing J# feature set largely meets their needs and usage of J# is declining, Microsoft is retiring the Visual J# product and Java Language Conversion Assistant tool to better allocate resources for other customer requirements. The J# language and JLCA tool will not be available in future versions of Visual Studio. To preserve existing customer investments in J#, Microsoft will continue to support the J# and JLCA technology that shipped with Visual Studio 2005 through to 2015 as per our product life-cycle strategy. For more information, see Expanded Microsoft Support Lifecycle Policy for Business & Development Products. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/5527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
]
} |
5,598 | My gut feel is that document based web services are preferred in practice - is this other peoples experience? Are they easier to support? (I noted that SharePoint uses Any for the "document type" in its WSDL interface, I guess that makes it Document based). Also - are people offering both WSDL and Rest type services now for the same functionality? WSDL is popular for code generation, but for front ends like PHP and Rails they seem to prefer rest. | Document versus RPC is only a question if you are using SOAP Web Services which require a service description ( WSDL ). RESTful web services do not not use WSDL because the service can't be described by it, and the feeling is that REST is simpler and easier to understand. Some people have proposed WADL as a way to describe REST services. Languages like Python, Ruby and PHP make it easier to work with REST. the WSDL is used to generate C# code (a web service proxy) that can be easily called from a static language. This happens when you add a Service Reference or Web Reference in Visual Studio. Whether you provide SOAP or REST services depends on your user population. Whether the services are to be used over the internet or just inside your organization affects your choice. SOAP may have some features (WS-* standards) that work well for B2B or internal use, but suck for an internet service. Document/literal versus RPC for SOAP services are described on this IBM DevelopWorks article . Document/literal is generally considered the best to use in terms of interoperability (Java to .NET etc). As to whether it is easier to support, that depends on your circumstances. My personal view is that people tend to make this stuff more complicated than it needs to be, and REST's simpler approach is superior. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/5598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699/"
]
} |
5,600 | I have several tables whose only unique data is a uniqueidentifier (a Guid) column. Because guids are non-sequential (and they're client-side generated so I can't use newsequentialid()), I have made a non-primary, non-clustered index on this ID field rather than giving the tables a clustered primary key. I'm wondering what the performance implications are for this approach. I've seen some people suggest that tables should have an auto-incrementing ("identity") int as a clustered primary key even if it doesn't have any meaning, as it means that the database engine itself can use that value to quickly look up a row instead of having to use a bookmark. My database is merge-replicated across a bunch of servers, so I've shied away from identity int columns as they're a bit hairy to get right in replication. What are your thoughts? Should tables have primary keys? Or is it ok to not have any clustered indexes if there are no sensible columns to index that way? | When dealing with indexes, you have to determine what your table is going to be used for. If you are primarily inserting 1000 rows a second and not doing any querying, then a clustered index is a hit to performance. If you are doing 1000 queries a second, then not having an index will lead to very bad performance. The best thing to do when trying to tune queries/indexes is to use the Query Plan Analyzer and SQL Profiler in SQL Server. This will show you where you are running into costly table scans or other performance blockers. As for the GUID vs ID argument, you can find people online that swear by both. I have always been taught to use GUIDs unless I have a really good reason not to. Jeff has a good post that talks about the reasons for using GUIDs: https://blog.codinghorror.com/primary-keys-ids-versus-guids/ . As with most anything development related, if you are looking to improve performance there is not one, single right answer. It really depends on what you are trying to accomplish and how you are implementing the solution. The only true answer is to test, test, and test again against performance metrics to ensure that you are meeting your goals. [Edit]@Matt, after doing some more research on the GUID/ID debate I came across this post. Like I mentioned before, there is not a true right or wrong answer. It depends on your specific implementation needs. But these are some pretty valid reasons to use GUIDs as the primary key: For example, there is an issue known as a "hotspot", where certain pages of data in a table are under relatively high currency contention. Basically, what happens is most of the traffic on a table (and hence page-level locks) occurs on a small area of the table, towards the end. New records will always go to this hotspot, because IDENTITY is a sequential number generator. These inserts are troublesome because they require Exlusive page lock on the page they are added to (the hotspot). This effectively serializes all inserts to a table thanks to the page locking mechanism. NewID() on the other hand does not suffer from hotspots. Values generated using the NewID() function are only sequential for short bursts of inserts (where the function is being called very quickly, such as during a multi-row insert), which causes the inserted rows to spread randomly throughout the table's data pages instead of all at the end - thus eliminating a hotspot from inserts. Also, because the inserts are randomly distributed, the chance of page splits is greatly reduced. While a page split here and there isnt too bad, the effects do add up quickly. With IDENTITY, page Fill Factor is pretty useless as a tuning mechanism and might as well be set to 100% - rows will never be inserted in any page but the last one. With NewID(), you can actually make use of Fill Factor as a performance-enabling tool. You can set Fill Factor to a level that approximates estimated volume growth between index rebuilds, and then schedule the rebuilds during off-peak hours using dbcc reindex. This effectively delays the performance hits of page splits until off-peak times. If you even think you might need to enable replication for the table in question - then you might as well make the PK a uniqueidentifier and flag the guid field as ROWGUIDCOL. Replication will require a uniquely valued guid field with this attribute, and it will add one if none exists. If a suitable field exists, then it will just use the one thats there. Yet another huge benefit for using GUIDs for PKs is the fact that the value is indeed guaranteed unique - not just among all values generated by this server, but all values generated by all computers - whether it be your db server, web server, app server, or client machine. Pretty much every modern language has the capability of generating a valid guid now - in .NET you can use System.Guid.NewGuid. This is VERY handy when dealing with cached master-detail datasets in particular. You dont have to employ crazy temporary keying schemes just to relate your records together before they are committed. You just fetch a perfectly valid new Guid from the operating system for each new record's permanent key value at the time the record is created. http://forums.asp.net/t/264350.aspx | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/5600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/615/"
]
} |
5,611 | I know that just using rand() is predictable, if you know what you're doing, and have access to the server. I have a project that is highly dependent upon choosing a random number that is as unpredictable as possible. So I'm looking for suggestions, either other built-in functions or user functions, that can generate a better random number. I used this to do a little test: $i = 0;while($i < 10000){ $rand = rand(0, 100); if(!isset($array[$rand])){ $array[$rand] = 1; } else { $array[$rand]++; } sort($array); $i++;} I found the results to be evenly distributed, and there is an odd pattern to the number of times each number is generated. | Adding, multiplying, or truncating a poor random source will give you a poor random result. See Introduction to Randomness and Random Numbers for an explanation. You're right about PHP rand() function. See the second figure on Statistical Analysis for a striking illustration. (The first figure is striking, but it's been drawn by Scott Adams, not plotted with rand()). One solution is to use a true random generator such as random.org . Another, if you're on Linux/BSD/etc. is to use /dev/random . If the randomness is mission critical, you will have to use a hardware random generator . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/5611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
]
} |
5,629 | It is supposed to be backwards compatible with HTML4 and XHTML. John Resig posted about some of the benefits . As long as we don't use any of the new and not supported yet features, would there be any downside to start building sites with this doctype? | Well consider this: When serving as text/html, all you need a doctype for is to trigger standards mode. Beyond that, the doctype does nothing as far as browsers are concerned. When serving as text/html, whether you use XHTML markup or HTML markup, it's treated by browsers as HTML. So, really it comes down to using the shortest doctype that triggers standards mode (<!DOCTYPE html>) and using HTML markup that produces the correct result in browsers. The rest is about conforming, validation and markup prerference. With that said, using <!DOCTYPE html> now and trying to make your markup conform to HTML5 is not a bad idea as long as you stick to stable features that work in browsers now. You wouldn't use anything in HTML4 or XHTML 1.x that doesn't work in browsers, would you? In other words, you use <!DOCTYPE html> with HTML4-like markup while honoring things that have been clarified in HTML5. HTML5 is about browser compatibility after all. The downside to using HTML5 now is that the spec can change quite often. This makes it important for you to keep up with the spec as it actively changes. Also http://validator.nu/ might not always be up-to-date, but http://validator.w3.org/ isn't always up-to-date either, so don't let that stop you. Of course, if you want to use XHTML 1.0 markup and conform to XHTML 1.0, then you shouldn't use <!DOCTYPE html>. Personally, I always use <!DOCTYPE html> for HTML. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/5629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/653/"
]
} |
5,649 | Does anyone know of any good tools (I'm looking for IDEs) to write assembly on the Mac. Xcode is a little cumbersome to me. Also, on the Intel Macs, can I use generic x86 asm? Or is there a modified instruction set? Any information about post Intel. Also: I know that on windows, asm can run in an emulated environment created by the OS to let the code think it's running on its own dedicated machine. Does OS X provide the same thing? | After installing any version of Xcode targeting Intel-based Macs, you should be able to write assembly code. Xcode is a suite of tools, only one of which is the IDE, so you don't have to use it if you don't want to. (That said, if there are specific things you find clunky, please file a bug at Apple's bug reporter - every bug goes to engineering.) Furthermore, installing Xcode will install both the Netwide Assembler (NASM) and the GNU Assembler (GAS); that will let you use whatever assembly syntax you're most comfortable with. You'll also want to take a look at the Compiler & Debugging Guides , because those document the calling conventions used for the various architectures that Mac OS X runs on, as well as how the binary format and the loader work. The IA-32 (x86-32) calling conventions in particular may be slightly different from what you're used to. Another thing to keep in mind is that the system call interface on Mac OS X is different from what you might be used to on DOS/Windows, Linux, or the other BSD flavors. System calls aren't considered a stable API on Mac OS X; instead, you always go through libSystem. That will ensure you're writing code that's portable from one release of the OS to the next. Finally, keep in mind that Mac OS X runs across a pretty wide array of hardware - everything from the 32-bit Core Single through the high-end quad-core Xeon. By coding in assembly you might not be optimizing as much as you think; what's optimal on one machine may be pessimal on another. Apple regularly measures its compilers and tunes their output with the "-Os" optimization flag to be decent across its line, and there are extensive vector/matrix-processing libraries that you can use to get high performance with hand-tuned CPU-specific implementations. Going to assembly for fun is great. Going to assembly for speed is not for the faint of heart these days. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/5649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/703/"
]
} |
5,694 | I got this error today when trying to open a Visual Studio 2008 project in Visual Studio 2005: The imported project "C:\Microsoft.CSharp.targets" was not found. | Open your csproj file in notepad (or notepad++)Find the line: <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> and change it to <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/5694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
]
} |
5,706 | I recently encountered a problem where a value was null if accessed with Request.Form but fine if retrieved with Request.Params. What are the differences between these methods that could cause this? | Request.Form only includes variables posted through a form, while Request.Params includes both posted form variables and get variables specified as URL parameters. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/5706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
]
} |
5,724 | Is there a better windows command line shell other than cmd which has better copy paste between Windows' windows and console windows? | Enable QuickEdit mode , under the Options tab of your shortcut to the command shell. Mark with the mouse, right-click to copy, right-click again to paste. While you're there, enable a hotkey (like CTRL + ALT + C ) for lightning fast access to the shell. And no, you can't have CTRL + C for COPY , because CTRL + C means BREAK . On a related note, the Microsoftee who changed the default setting of QuickEdit mode between Windows Server 2000 and 2003 is an idiot and I heap curses upon him each workday. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/5724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/108465/"
]
} |
5,727 | Why are pointers such a leading factor of confusion for many new, and even old, college level students in C or C++? Are there any tools or thought processes that helped you understand how pointers work at the variable, function, and beyond level? What are some good practice things that can be done to bring somebody to the level of, "Ah-hah, I got it," without getting them bogged down in the overall concept? Basically, drill like scenarios. | Pointers is a concept that for many can be confusing at first, in particular when it comes to copying pointer values around and still referencing the same memory block. I've found that the best analogy is to consider the pointer as a piece of paper with a house address on it, and the memory block it references as the actual house. All sorts of operations can thus be easily explained. I've added some Delphi code down below, and some comments where appropriate. I chose Delphi since my other main programming language, C#, does not exhibit things like memory leaks in the same way. If you only wish to learn the high-level concept of pointers, then you should ignore the parts labelled "Memory layout" in the explanation below. They are intended to give examples of what memory could look like after operations, but they are more low-level in nature. However, in order to accurately explain how buffer overruns really work, it was important that I added these diagrams. Disclaimer: For all intents and purposes, this explanation and the example memorylayouts are vastly simplified. There's more overhead and a lot more details you wouldneed to know if you need to deal with memory on a low-level basis. However, for theintents of explaining memory and pointers, it is accurate enough. Let's assume the THouse class used below looks like this: type THouse = class private FName : array[0..9] of Char; public constructor Create(name: PChar); end; When you initialize the house object, the name given to the constructor is copied into the private field FName. There is a reason it is defined as a fixed-size array. In memory, there will be some overhead associated with the house allocation, I'll illustrate this below like this: ---[ttttNNNNNNNNNN]--- ^ ^ | | | +- the FName array | +- overhead The "tttt" area is overhead, there will typically be more of this for various types of runtimes and languages, like 8 or 12 bytes. It is imperative that whatever values are stored in this area never gets changed by anything other than the memory allocator or the core system routines, or you risk crashing the program. Allocate memory Get an entrepreneur to build your house, and give you the address to the house. In contrast to the real world, memory allocation cannot be told where to allocate, but will find a suitable spot with enough room, and report back the address to the allocated memory. In other words, the entrepreneur will choose the spot. THouse.Create('My house'); Memory layout: ---[ttttNNNNNNNNNN]--- 1234My house Keep a variable with the address Write the address to your new house down on a piece of paper. This paper will serve as your reference to your house. Without this piece of paper, you're lost, and cannot find the house, unless you're already in it. var h: THouse;begin h := THouse.Create('My house'); ... Memory layout: h v---[ttttNNNNNNNNNN]--- 1234My house Copy pointer value Just write the address on a new piece of paper. You now have two pieces of paper that will get you to the same house, not two separate houses. Any attempts to follow the address from one paper and rearrange the furniture at that house will make it seem that the other house has been modified in the same manner, unless you can explicitly detect that it's actually just one house. Note This is usually the concept that I have the most problem explaining to people, two pointers does not mean two objects or memory blocks. var h1, h2: THouse;begin h1 := THouse.Create('My house'); h2 := h1; // copies the address, not the house ... h1 v---[ttttNNNNNNNNNN]--- 1234My house ^ h2 Freeing the memory Demolish the house. You can then later on reuse the paper for a new address if you so wish, or clear it to forget the address to the house that no longer exists. var h: THouse;begin h := THouse.Create('My house'); ... h.Free; h := nil; Here I first construct the house, and get hold of its address. Then I do something to the house (use it, the ... code, left as an exercise for the reader), and then I free it. Lastly I clear the address from my variable. Memory layout: h <--+ v +- before free---[ttttNNNNNNNNNN]--- | 1234My house <--+ h (now points nowhere) <--+ +- after free---------------------- | (note, memory might still xx34My house <--+ contain some data) Dangling pointers You tell your entrepreneur to destroy the house, but you forget to erase the address from your piece of paper. When later on you look at the piece of paper, you've forgotten that the house is no longer there, and goes to visit it, with failed results (see also the part about an invalid reference below). var h: THouse;begin h := THouse.Create('My house'); ... h.Free; ... // forgot to clear h here h.OpenFrontDoor; // will most likely fail Using h after the call to .Free might work, but that is just pure luck. Most likely it will fail, at a customers place, in the middle of a critical operation. h <--+ v +- before free---[ttttNNNNNNNNNN]--- | 1234My house <--+ h <--+ v +- after free---------------------- | xx34My house <--+ As you can see, h still points to the remnants of the data in memory, butsince it might not be complete, using it as before might fail. Memory leak You lose the piece of paper and cannot find the house. The house is still standing somewhere though, and when you later on want to construct a new house, you cannot reuse that spot. var h: THouse;begin h := THouse.Create('My house'); h := THouse.Create('My house'); // uh-oh, what happened to our first house? ... h.Free; h := nil; Here we overwrote the contents of the h variable with the address of a new house, but the old one is still standing... somewhere. After this code, there is no way to reach that house, and it will be left standing. In other words, the allocated memory will stay allocated until the application closes, at which point the operating system will tear it down. Memory layout after first allocation: h v---[ttttNNNNNNNNNN]--- 1234My house Memory layout after second allocation: h v---[ttttNNNNNNNNNN]---[ttttNNNNNNNNNN] 1234My house 5678My house A more common way to get this method is just to forget to free something, instead of overwriting it as above. In Delphi terms, this will occur with the following method: procedure OpenTheFrontDoorOfANewHouse;var h: THouse;begin h := THouse.Create('My house'); h.OpenFrontDoor; // uh-oh, no .Free here, where does the address go?end; After this method has executed, there's no place in our variables that the address to the house exists, but the house is still out there. Memory layout: h <--+ v +- before losing pointer---[ttttNNNNNNNNNN]--- | 1234My house <--+ h (now points nowhere) <--+ +- after losing pointer---[ttttNNNNNNNNNN]--- | 1234My house <--+ As you can see, the old data is left intact in memory, and will notbe reused by the memory allocator. The allocator keeps track of whichareas of memory has been used, and will not reuse them unless youfree it. Freeing the memory but keeping a (now invalid) reference Demolish the house, erase one of the pieces of paper but you also have another piece of paper with the old address on it, when you go to the address, you won't find a house, but you might find something that resembles the ruins of one. Perhaps you will even find a house, but it is not the house you were originally given the address to, and thus any attempts to use it as though it belongs to you might fail horribly. Sometimes you might even find that a neighbouring address has a rather big house set up on it that occupies three address (Main Street 1-3), and your address goes to the middle of the house. Any attempts to treat that part of the large 3-address house as a single small house might also fail horribly. var h1, h2: THouse;begin h1 := THouse.Create('My house'); h2 := h1; // copies the address, not the house ... h1.Free; h1 := nil; h2.OpenFrontDoor; // uh-oh, what happened to our house? Here the house was torn down, through the reference in h1 , and while h1 was cleared as well, h2 still has the old, out-of-date, address. Access to the house that is no longer standing might or might not work. This is a variation of the dangling pointer above. See its memory layout. Buffer overrun You move more stuff into the house than you can possibly fit, spilling into the neighbours house or yard. When the owner of that neighbouring house later on comes home, he'll find all sorts of things he'll consider his own. This is the reason I chose a fixed-size array. To set the stage, assume thatthe second house we allocate will, for some reason, be placed before thefirst one in memory. In other words, the second house will have a loweraddress than the first one. Also, they're allocated right next to each other. Thus, this code: var h1, h2: THouse;begin h1 := THouse.Create('My house'); h2 := THouse.Create('My other house somewhere'); ^-----------------------^ longer than 10 characters 0123456789 <-- 10 characters Memory layout after first allocation: h1 v-----------------------[ttttNNNNNNNNNN] 5678My house Memory layout after second allocation: h2 h1 v v---[ttttNNNNNNNNNN]----[ttttNNNNNNNNNN] 1234My other house somewhereouse ^---+--^ | +- overwritten The part that will most often cause crash is when you overwrite important partsof the data you stored that really should not be randomly changed. For instanceit might not be a problem that parts of the name of the h1-house was changed,in terms of crashing the program, but overwriting the overhead of theobject will most likely crash when you try to use the broken object,as will overwriting links that is stored toother objects in the object. Linked lists When you follow an address on a piece of paper, you get to a house, and at that house there is another piece of paper with a new address on it, for the next house in the chain, and so on. var h1, h2: THouse;begin h1 := THouse.Create('Home'); h2 := THouse.Create('Cabin'); h1.NextHouse := h2; Here we create a link from our home house to our cabin. We can follow the chain until a house has no NextHouse reference, which means it's the last one. To visit all our houses, we could use the following code: var h1, h2: THouse; h: THouse;begin h1 := THouse.Create('Home'); h2 := THouse.Create('Cabin'); h1.NextHouse := h2; ... h := h1; while h <> nil do begin h.LockAllDoors; h.CloseAllWindows; h := h.NextHouse; end; Memory layout (added NextHouse as a link in the object, noted withthe four LLLL's in the below diagram): h1 h2 v v---[ttttNNNNNNNNNNLLLL]----[ttttNNNNNNNNNNLLLL] 1234Home + 5678Cabin + | ^ | +--------+ * (no link) In basic terms, what is a memory address? A memory address is in basic terms just a number. If you think of memoryas a big array of bytes, the very first byte has the address 0, the next onethe address 1 and so on upwards. This is simplified, but good enough. So this memory layout: h1 h2 v v---[ttttNNNNNNNNNN]---[ttttNNNNNNNNNN] 1234My house 5678My house Might have these two address (the leftmost - is address 0): h1 = 4 h2 = 23 Which means that our linked list above might actuall look like this: h1 (=4) h2 (=28) v v---[ttttNNNNNNNNNNLLLL]----[ttttNNNNNNNNNNLLLL] 1234Home 0028 5678Cabin 0000 | ^ | +--------+ * (no link) It is typical to store an address that "points nowhere" as a zero-address. In basic terms, what is a pointer? A pointer is just a variable holding a memory address. You can typically ask the programminglanguage to give you its number, but most programming languages and runtimes tries tohide the fact that there is a number beneath, just because the number itself does notreally hold any meaning to you. It is best to think of a pointer as a black box, ie.you don't really know or care about how it is actually implemented, just as long as itworks. | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/5727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568/"
]
} |
5,759 | I just moved over to the Visual Basic team here at work. What is the equivalent keyword to break in Visual Basic, that is, to exit a loop early but not the method? | In both Visual Basic 6.0 and VB.NET you would use: Exit For to break from For loop Wend to break from While loop Exit Do to break from Do loop depending on the loop type. See Exit Statements for more details. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/5759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/713/"
]
} |
5,787 | I'm just in the process of parsing some text and can't remember what the escape character is for a tab in C#? | Easy one! "\t" Edit: In fact, here's something official: Escape Sequences | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/5787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
]
} |
5,791 | Does anyone here use VB.NET and have a strong preference for or against using IsNothing as opposed to Is Nothing (for example, If IsNothing(anObject) or If anObject Is Nothing... )? If so, why? EDIT: If you think they're both equally acceptable, do you think it's best to pick one and stick with it, or is it OK to mix them? | If you take a look at the MSIL as it's being executed you'll see that it doesn't compile down to the exact same code. When you use IsNothing() it actually makes a call to that method as opposed to just evaluating the expression. The reason I would tend to lean towards using "Is Nothing" is when I'm negating it becomes "IsNot Nothing' rather than "Not IsNothing(object)" which I personally feel looks more readable. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/5791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/133/"
]
} |
5,821 | How do I escape the underscore character? I am writing something like the following where clause and want to be able to find actual entries with _d at the end. Where Username Like '%_d' | T-SQL Reference for LIKE : You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets. The following table shows several examples of using the LIKE keyword and the [ ] wildcard characters. For your case: ... LIKE '%[_]d' | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/5821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
]
} |
5,842 | Two users wanted to share the same database, originally written in MS Access, without conflicting with one another over a single MDB file. I moved the tables from a simple MS Access database to MySQL using its Migration Toolkit (which works well, by the way) and set up Access to link to those tables via ODBC. So far, I've run into the following: You can't insert/update/delete rows in a table without a primary key (no surprise there). AutoNumber fields in MS Access must be the primary key or they'll just end up as integer columns in MySQL (natch, why wouldn't it be the PK?) The tables were migrated to MySQL's InnoDB table type, but the Access relationships didn't become MySQL foreign key constraints. Once the database is in use, can I expect any other issues? Particularly when both users are working in the same table? | I had an application that worked likewise: an MS Access frontend to a MySQL backend. It was such a huge pain that I ended up writing a Win32 frontend instead. From the top of my head, I encountered the following problems: Development of the ODBC link seems to have ceased long ago. There are various different versions floating around --- very confusing. The ODBC link doesn't support Unicode/UTF8, and I remember there were other issues with it as well (though some could be overcome by careful configuration). You probably want to manually tweak your db schema to make it compatible with MS Access. I see you already found out about the needed surrogate keys (i.e., int primary keys) :-) You should keep in mind that you may need to use pass-through queries to do more sophisticated SQL manipulations of the MySQL database. Be careful with using lots of VBA, as that tends to corrupt your frontend file. Regularly compressing the database (using main menu, Tools | Database utilities | Compress and restore, or something like that --- I'm using the Dutch version) and making lots of backups is necessary. Access tends to cause lots of network traffic. Like, really huge lots. I haven't been able to find a solution for that. Using a network monitor is recommended if you want to keep an eye on that! Access insists on storing booleans as 0/-1. IMHO, 0/+1 makes more sense, and I believe it is the default way of doing things in MySQL as well. Not a huge problem, but if your checkboxes don't work, you should definitely check this. One possible alternative would be to put the backend (with the data) on a shared drive. I remember this is well-documented, also in the help. You may want to have a look at some general advice on splitting into a frontend and a backend and code that automatically reconnects to the backend on startup ; I can also send you some more sample code, or post it here. Otherwise, you might also want to consider MS SQL. I don't have experience with that, but I presume it works together with MS Access much more nicely! | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/5842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726/"
]
} |
5,846 | How do I turn the following 2 queries into 1 query $sql = "SELECT level FROM skills WHERE id = $id LIMIT 1;";$result = $db->sql_query($sql);$level = (int) $db->sql_fetchfield('level');$db->sql_freeresult($result);++$level;$sql = "UPDATE skills SET level = $level WHERE id = $id;";$result = $db->sql_query($sql);$db->sql_freeresult($result); I'm using it in a phpBB mod but the gist is that I grab the level, add one to it then update, it seems that it'd be much easier and faster if I could do it as one query. Edit: $id has already been forced to be an integer, thus no escaping is needed this time. | I get downmodded for this? $sql = "UPDATE skills SET level = level+1 WHERE id = $id";$result = $db->sql_query($sql);$db->sql_freeresult($result); In Teifion's specific case, the phpBB DDL lists that particular field as NOT NULL, so there's no danger of incrementing NULL. In the general case, you should not use NULL to represent zero. Incrementing NULL should give an answer of NULL. If you're the kind of misguided developer who thinks NULL=0, step away from keyboard and find another pastime, you're just making life hard for the rest of us. Of course, this is the computer industry and who are we to say you're wrong? If you're not wrong, use $sql = "UPDATE skills SET level = COALESCE(level,0)+1 WHERE id = $id"; ...but let's face it: you're wrong. If everyone starts at level 0, then your DDL should include level INT DEFAULT '0' NOT NULL in case the programmers forget to set it when they create a record. If not everyone starts on level 0, then skip the DEFAULT and force the programmer to supply a value on creation. If some people are beyond levels, for whom having a level is a meaningless thing, then adding one to their level equally has no meaning. In that case, drop the NOT NULL from the DDL. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/5846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
5,857 | I have a page upon which a user can choose up to many different paragraphs. When the link is clicked (or button), an email will open up and put all those paragraphs into the body of the email, address it, and fill in the subject. However, the text can be too long for a mailto link. Any way around this? We were thinking about having an SP from the SQL Server do it but the user needs a nice way of 'seeing' the email before they blast 50 executive level employees with items that shouldn't be sent...and of course there's the whole thing about doing IT for IT rather than doing software programming. 80( When you build stuff for IT, it doesn't (some say shouldn't) have to be pretty just functional. In other words, this isn't the dogfood we wake it's just the dog food we have to eat. We started talking about it and decided that the 'mail form' would give us exactly what we are looking for. A very different look to let the user know that the gun is loadedand aimed. The ability to change/add text to the email. Send a copy to themselves or not. Can be coded quickly. | By putting the data into a form, I was able to make the body around 1800 characters long before the form stopped working. The code looked like this: <form action="mailto:youremail@domain.com"> <input type="hidden" name="Subject" value="Email subject"> <input type="hidden" name="Body" value="Email body"> <input type="submit"></form> Edit : The best way to send emails from a web application is of course to do just that, send it directly from the web application, instead of relying on the users mailprogram. As you've discovered, the protocol for sending information to that program is limited, but with a server-based solution you would of course not have those limitations. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/5857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
]
} |
5,909 | I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server? import urllibimport reurl = "http://www.someurl.com"# Download the page locallyf = urllib.urlopen(url)html = f.read()f.close()f = open ("temp.htm", "w")f.write (html)f.close()# List only the .TXT / .ZIP filesfnames = re.findall('^.*<a href="(\w+(?:\.txt|.zip)?)".*$', html, re.MULTILINE)for fname in fnames: print fname, "..." f = urllib.urlopen(url + "/" + fname) #### Here I want to check the filesize to download or not #### file = f.read() f.close() f = open (fname, "w") f.write (file) f.close() @Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. Examples: Local Size Server Size 2.223.533 2.115.516 664.603 662.121 It has anything to do with the CR/LF conversion? | I have reproduced what you are seeing: import urllib, oslink = "http://python.org"print "opening url:", linksite = urllib.urlopen(link)meta = site.info()print "Content-Length:", meta.getheaders("Content-Length")[0]f = open("out.txt", "r")print "File on disk:",len(f.read())f.close()f = open("out.txt", "w")f.write(site.read())site.close()f.close()f = open("out.txt", "r")print "File on disk after download:",len(f.read())f.close()print "os.stat().st_size returns:", os.stat("out.txt").st_size Outputs this: opening url: http://python.orgContent-Length: 16535File on disk: 16535File on disk after download: 16535os.stat().st_size returns: 16861 What am I doing wrong here? Is os.stat().st_size not returning the correct size? Edit:OK, I figured out what the problem was: import urllib, oslink = "http://python.org"print "opening url:", linksite = urllib.urlopen(link)meta = site.info()print "Content-Length:", meta.getheaders("Content-Length")[0]f = open("out.txt", "rb")print "File on disk:",len(f.read())f.close()f = open("out.txt", "wb")f.write(site.read())site.close()f.close()f = open("out.txt", "rb")print "File on disk after download:",len(f.read())f.close()print "os.stat().st_size returns:", os.stat("out.txt").st_size this outputs: $ python test.pyopening url: http://python.orgContent-Length: 16535File on disk: 16535File on disk after download: 16535os.stat().st_size returns: 16535 Make sure you are opening both files for binary read/write. // open for binary writeopen(filename, "wb")// open for binary readopen(filename, "rb") | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/5909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/394/"
]
} |
5,913 | This gets the value of whatever is selected in my dropdown menu. document.getElementById('newSkill').value I cannot however find out what property to go after for the text that's currently displayed by the drop down menu. I tried "text" then looked at W3Schools but that didn't have the answer, does anybody here know? For those not sure, here's the HTML for a drop down box. <select name="newSkill" id="newSkill"> <option value="1">A skill</option> <option value="2">Another skill</option> <option value="3">Yet another skill</option></select> | Based on your example HTML code, here's one way to get the displayed text of the currently selected option: var skillsSelect = document.getElementById("newSkill");var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text; | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/5913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
5,916 | For those of you in the Visual Studio environment, how do you feel about wrapping any of your code in #regions? (or if any other IDE has something similar...) | 9 out of 10 times, code folding means that you have failed to use the SoC principle for what its worth. I more or less feel the same thing about partial classes. If you have a piece of code you think is too big you need to chop it up in manageable (and reusable) parts, not hide or split it up. It will bite you the next time someone needs to change it, and cannot see the logic hidden in a 250 line monster of a method. Whenever you can, pull some code out of the main class, and into a helper or factory class. foreach (var item in Items){ //.. 100 lines of validation and data logic..} is not as readable as foreach (var item in Items){ if (ValidatorClass.Validate(item)) RepositoryClass.Update(item);} My $0.02 anyways. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/5916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396/"
]
} |
5,949 | I've always preferred to use long integers as primary keys in databases, for simplicity and (assumed) speed. But when using a REST or Rails-like URL scheme for object instances, I'd then end up with URLs like this: http://example.com/user/783 And then the assumption is that there are also users with IDs of 782, 781, ..., 2, and 1. Assuming that the web app in question is secure enough to prevent people entering other numbers to view other users without authorization, a simple sequentially-assigned surrogate key also "leaks" the total number of instances (older than this one), in this case users, which might be privileged information. (For instance, I am user #726 in stackoverflow.) Would a UUID /GUID be a better solution? Then I could set up URLs like this: http://example.com/user/035a46e0-6550-11dd-ad8b-0800200c9a66 Not exactly succinct, but there's less implied information about users on display. Sure, it smacks of "security through obscurity" which is no substitute for proper security, but it seems at least a little more secure. Is that benefit worth the cost and complexity of implementing UUIDs for web-addressable object instances? I think that I'd still want to use integer columns as database PKs just to speed up joins. There's also the question of in-database representation of UUIDs. I know MySQL stores them as 36-character strings. Postgres seems to have a more efficient internal representation (128 bits?) but I haven't tried it myself. Anyone have any experience with this? Update: for those who asked about just using the user name in the URL (e.g., http://example.com/user/yukondude ), that works fine for object instances with names that are unique, but what about the zillions of web app objects that can really only be identified by number? Orders, transactions, invoices, duplicate image names, stackoverflow questions, ... | I can't say about the web side of your question. But uuids are great for n-tier applications. PK generation can be decentralized: each client generates it's own pk without risk of collision. And the speed difference is generally small. Make sure your database supports an efficient storage datatype (16 bytes, 128 bits).At the very least you can encode the uuid string in base64 and use char(22). I've used them extensively with Firebird and do recommend. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/5949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726/"
]
} |
6,007 | How do I make Log4net only log Info level logs? Is that even possible? Can you only set a threshold? This is what I have, and it logs Info and above as I would expect. Is there anything i can do to make it only log info? <logger name="BrokerCollection.Model.XmlDocumentCreationTask"> <appender-ref ref="SubmissionAppender"/> <level value="Info" /></logger> | Within the definition of the appender, I believe you can do something like this: <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender"> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="INFO"/> <param name="LevelMax" value="INFO"/> </filter> ...</appender> | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/6007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
]
} |
6,009 | Let's say you have a typical web app and with a file configuration.whatever. Every developer working on the project will have one version for their dev boxes, there will be a dev, prod and stage versions. How do you deal with this in source control? Not check in this file at all, check it with different names or do something fancy altogether? | What I've done in the past is to have a default config file which is checked in to source control. Then, each developer has their own override config file which is excluded from source control. The app first loads the default, and then if the override file is present, loads that and uses any settings from the override in preference to the default file. In general, the smaller the override file the better, but it can always contain more settings for a developer with a very non-standard environment. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/6009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556/"
]
} |
6,080 | We are in the early design stages of a major rewrite of our product. Right now our customers are mostly businesses. We manage accounts. User names for an account are each on their own namespace but it means that we can't move assets between servers. We want to move to a single namespace. But that brings the problem of unique user names. So what's the best idea? Email address (w/verification) ? Unique alpha-numeric string ("johnsmith9234")? Should we look at OpenID? | EMAIL ADDRESS Rational Users don't change emails very often Removes the step of asking for username and email address, which you'll need anyway Users don't often forget their email address (see number one) Email will be unique unless the user already registered for the site, in which case forward them to a forgot your password screen Almost everyone is using email as the primary login for access to a website, this means the rate of adoption shouldn't be affected by the fact that you're asking for an email address Update After registration, be sure to ask the user to create some kind of username, don't litter a public site with their email address! Also, another benefit of using an email address as a login: you won't need any other information (like password / password confirm), just send them a temp password through the mail, or forgo passwords altogether and send them a one-use URL to their email address every time they'd like to login (see: mugshot.org ) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/6080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/758/"
]
} |
6,085 | Our automated build machine needs to archive the version numbers of the OS plus various tools used during each build. (In case we ever need to replicate exactly the same build later on, perhaps when the machine is long dead.) I see the command "msinfo32.exe" can be used to dump a whole load of system version information, which we might as well archive. Does anyone know of a way to easily archive the version numbers of the Visual Studio tools? What mechanisms do other developers use to gather this kind of information for archive purposes? Extra information for Fabio Gomes. I agree with you that in 5 years time it'll probably be impossible to recreate the exact OS and tool configuration (down to the nearest security update). Unfortunately this really comes from a contractual requirement. As part of our deliverable to a customer we must provide a copy of all source code and clear instructions on exactly how to replicate the build. It's probably impossible for us to meet this requirement perfectly. So - I'll just mark your answer as correct (I agree with you that it's practically impossible), and get on with playing with the rest of stack overflow. :) PS. It would be really great if stack overflow supported replies to answers instead of having to edit the original question.. But I see it has already been denied . | EMAIL ADDRESS Rational Users don't change emails very often Removes the step of asking for username and email address, which you'll need anyway Users don't often forget their email address (see number one) Email will be unique unless the user already registered for the site, in which case forward them to a forgot your password screen Almost everyone is using email as the primary login for access to a website, this means the rate of adoption shouldn't be affected by the fact that you're asking for an email address Update After registration, be sure to ask the user to create some kind of username, don't litter a public site with their email address! Also, another benefit of using an email address as a login: you won't need any other information (like password / password confirm), just send them a temp password through the mail, or forgo passwords altogether and send them a one-use URL to their email address every time they'd like to login (see: mugshot.org ) | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/6085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755/"
]
} |
6,126 | It's something that's bugged me in every language I've used, I have an if statement but the conditional part has so many checks that I have to split it over multiple lines, use a nested if statement or just accept that it's ugly and move on with my life. Are there any other methods that you've found that might be of use to me and anybody else that's hit the same problem? Example, all on one line: if (var1 = true && var2 = true && var2 = true && var3 = true && var4 = true && var5 = true && var6 = true){ Example, multi-line: if (var1 = true && var2 = true && var2 = true && var3 = true && var4 = true && var5 = true && var6 = true){ Example-nested: if (var1 = true && var2 = true && var2 = true && var3 = true){ if (var4 = true && var5 = true && var6 = true) { | Separate the condition in several booleans and then use a master boolean as the condition. bool isOpaque = object.Alpha == 1.0f;bool isDrawable = object.CanDraw && object.Layer == currentLayer;bool isHidden = hideList.Find(object);bool isVisible = isOpaque && isDrawable && ! isHidden;if(isVisible){ // ...} Better yet: public bool IsVisible { get { bool isOpaque = object.Alpha == 1.0f; bool isDrawable = object.CanDraw && object.Layer == currentLayer; bool isHidden = hideList.Find(object); return isOpaque && isDrawable && ! isHidden; }}void Draw(){ if(IsVisible) { // ... }} Make sure you give your variables name that actualy indicate intention rather than function. This will greatly help the developer maintaining your code... it could be YOU! | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/6126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
]
} |
6,130 | I'm using subclipse in Flex Builder 3, and recently received this error when trying to commit: svn: Checksum mismatch for '/Users/redacted/Documents/Flex Builder 3/path/to/my/file.mxml'; expected: 'f8cb275de72776657406154dd3c10348', actual: 'null' I worked around it by: Committing all the other changed files, omitting the troublesome one. Copying the contents of the trouble file to a TextMate window Deleting my project in FlexBuilder/Eclipse Checking my project out fresh from SVN Copying the text of the trouble file back in from the TextMate Window Committing the changes. It worked, but I can't help but think there's a better way. What's actaully happening to cause the svn:checksum error, and what's the best fix. Maybe more important -- is this a symptom of a greater problem? | The file in the .svn directory that keeps track of what you have checked out, when, what revision, and from where, has gotten corrupted somehow, for that particular file. This is no more dangerous or critical than the normal odd file problem, and can be because of various problems, like a subversion program dying mid-change, power-disruption, etc. Unless it happens more I wouldn't make much out of it. It can be fixed by doing what you did, make a copy of your work-files, check out a fresh copy, and add the modified files back in. Note that this might cause problems if you have a busy project where you would normally have to merge in changes. For instance, you and a collegue both check out a fresh copy, and start working on the same file. At some point, your collegue checks in his modifications. When you attempt to do the same, you get the checksum problem you have. If you now make copies of your changed files, do a fresh checkout, then subversion will lose track of how your changes should be merged back in. If you didn't get the problem in this case, when you got around to checkin in your modifications, you would need to update your working copy first, and possibly handle a conflict with your file. However, if you do a fresh checkout, complete with your collegues changes, it now looks like you removed his changes and substituted with your own. No conflicts, and no indications from subversion that something is amiss. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/6130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/763/"
]
} |
6,134 | I have a problem with some zombie-like processes on a certain server that need to be killed every now and then. How can I best identify the ones that have run for longer than an hour or so? | If they just need to be killed: if [[ "$(uname)" = "Linux" ]];then killall --older-than 1h someprocessname;fi If you want to see what it's matching if [[ "$(uname)" = "Linux" ]];then killall -i --older-than 1h someprocessname;fi The -i flag will prompt you with yes/no for each process match. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/6134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726/"
]
} |
6,155 | What kinds of hook scripts are people using for Subversion? Just general ideas but code would be great too! | I am using the pre-revprop-change hook that allows me to actually go back and edit comments and such information after the commit has been performed. This is very useful if there is missing/erroneous information in the commit comments. Here I post a pre-revprop-change.bat batch file for Windows NT or later. Youcan certainly enhance it with more modifications. You can also derive a post-revprop-change.cmd from it to back up the old snv:log somewhere or just to append it to the new log. The only tricky part was to be able to actually parse the stdin fromthe batch file. This is done here with the FIND.EXE command. The other thing is that I have had reports from other users of issues with the use of the /b with the exit command. You may just need to remove that /b in your specific application if error cases do not behave well. @ECHO OFFset repos=%1set rev=%2set user=%3set propname=%4set action=%5:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Only allow changes to svn:log. The author, date and other revision:: properties cannot be changed::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::if /I not '%propname%'=='svn:log' goto ERROR_PROPNAME:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Only allow modifications to svn:log (no addition/overwrite or deletion)::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::if /I not '%action%'=='M' goto ERROR_ACTION:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Make sure that the new svn:log message contains some text.::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::set bIsEmpty=truefor /f "tokens=*" %%g in ('find /V ""') do ( set bIsEmpty=false)if '%bIsEmpty%'=='true' goto ERROR_EMPTYgoto :eof:ERROR_EMPTYecho Empty svn:log properties are not allowed. >&2goto ERROR_EXIT:ERROR_PROPNAMEecho Only changes to svn:log revision properties are allowed. >&2goto ERROR_EXIT:ERROR_ACTIONecho Only modifications to svn:log revision properties are allowed. >&2goto ERROR_EXIT:ERROR_EXITexit /b 1 | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/6155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/204/"
]
} |
6,173 | I'm looking for a .NET regular expression extract all the URLs from a webpage but haven't found one to be comprehensive enough to cover all the different ways you can specify a link. And a side question: Is there one regex to rule them all ? Or am I better off using a series of less complicated regular expressions and just using mutliple passes against the raw HTML? (Speed vs. Maintainability) | ((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+) I took this from regexlib.com [editor's note: the {1} has no real function in this regex; see this post ] | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322/"
]
} |
6,184 | When you subscribe to an event on an object from within a form, you are essentially handing over control of your callback method to the event source. You have no idea whether that event source will choose to trigger the event on a different thread. The problem is that when the callback is invoked, you cannot assume that you can make update controls on your form because sometimes those controls will throw an exception if the event callback was called on a thread different than the thread the form was run on. | To simplify Simon's code a bit, you could use the built in generic Action delegate. It saves peppering your code with a bunch of delegate types you don't really need. Also, in .NET 3.5 they added a params parameter to the Invoke method so you don't have to define a temporary array. void SomethingHappened(object sender, EventArgs ea){ if (InvokeRequired) { Invoke(new Action<object, EventArgs>(SomethingHappened), sender, ea); return; } textBox1.Text = "Something happened";} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/6184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/756/"
]
} |
6,207 | Has anyone had any experience in building a 'real world' application with the Smart Client Software Factory , from Microsofts Patterns and Practices group? I'm looking for advice on how difficult it was to master, whether it decreased your time to market and any other general pitfalls. | We used SCSF for a real world app with about 10 developers. It was a steep learning curve to set up and develop a pattern of usage, but once it was set up, introducing new developers to the project was VERY easy. Using CAB and SCSF was very beneficial to our project especially getting each developer up to speed and productive. A downfall of SCSF is that it provides ALOT of functionality that may not be used (we probably only used 60% of the functionality). I am also using SCSF for a new project and am considering refactoring to PRISM. PRISM allows you to cull the functionality that is not used. If you use WPF, I suggest looking into PRISM. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/770/"
]
} |
6,301 | Why is Array.Length an int, and not a uint . This bothers me (just a bit) because a length value can never be negative. This also forced me to use an int for a length-property on my own class, because when you specify an int-value, this needs to be cast explicitly... So the ultimate question is: is there any use for an unsigned int ( uint )? Even Microsoft seems not to use them. | Unsigned int isn't CLS compliant and would therefore restrict usage of the property to those languages that do implement a UInt . See here: Framework 1.1 Introduction to the .NET Framework Class Library Framework 2.0 .NET Framework Class Library Overview | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/6301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56/"
]
} |
6,325 | Why are unsigned integers not CLS compliant? I am starting to think the type specification is just for performance and not for correctness. | Not all languages have the concept of unsigned ints. For example VB 6 had no concept of unsigned ints which I suspect drove the decision of the designers of VB7/7.1 not to implement as well (it's implemented now in VB8). To quote: http://msdn.microsoft.com/en-us/library/12a7a7h3.aspx The CLS was designed to be large enough to include the languageconstructs that are commonly needed by developers, yet small enoughthat most languages are able to support it. In addition, any languageconstruct that makes it impossible to rapidly verify the type safetyof code was excluded from the CLS so that all CLS-compliant languagescan produce verifiable code if they choose to do so. Update: I did wonder about this some years back, and whilst I can't see why a UInt wouldn't be type safety verifiable, I guess the CLS guys had to have a cut off point somewhere as to what would be the baseline minimum number of value types supported. Also when you think about the longer term where more and more languages are being ported to the CLR why force them to implement unsigned ints to gain CLS compliance if there is absolutely no concept, ever? | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/6325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56/"
]
} |
6,326 | I have the following html.erb code that I'm looking to move to Haml: <span class="<%= item.dashboardstatus.cssclass %>" ><%= item.dashboardstatus.status %></span> What it does is associate the CSS class of the currently assigned status to the span. How is this done in Haml? I'm sure I'm missing something really simple. | Not sure. Maybe: %span{:class => item.dashboardstatus.cssclass }= item.dashboardstatus.status | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/722/"
]
} |
6,340 | I've got a table that is supposed to track days and costs for shipping product from one vendor to another. We (brilliantly :p) stored both the shipping vendors (FedEx, UPS) with the product handling vendors (Think... Dunder Mifflin) in a "VENDOR" table. So, I have three columns in my SHIPPING_DETAILS table that all reference VENDOR.no. For some reason MySQL isn't letting me define all three as foreign keys. Any ideas? CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', INDEX (shipping_vendor_no), INDEX (start_vendor_no), INDEX (end_vendor_no), FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) ) TYPE = INNODB; Edited to remove double primary key definition... Yeah, unfortunately that didn't fix it though. Now I'm getting: Can't create table './ REMOVED MY DB NAME /SHIPPING_GRID.frm' (errno: 150) Doing a phpinfo() tells me this for mysql: Client API version 5.0.45 Yes, the VENDOR.no is type int(6). | You defined the primary key twice. Try: CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', INDEX (shipping_vendor_no), INDEX (start_vendor_no), INDEX (end_vendor_no), FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) ) TYPE = INNODB; The VENDOR primary key must be INT(6), and both tables must be of type InnoDB. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58/"
]
} |
6,371 | I've had a hard time trying to find good examples of how to manage database schemas and data between development, test, and production servers. Here's our setup. Each developer has a virtual machine running our app and the MySQL database. It is their personal sandbox to do whatever they want. Currently, developers will make a change to the SQL schema and do a dump of the database to a text file that they commit into SVN. We're wanting to deploy a continuous integration development server that will always be running the latest committed code. If we do that now, it will reload the database from SVN for each build. We have a test (virtual) server that runs "release candidates." Deploying to the test server is currently a very manual process, and usually involves me loading the latest SQL from SVN and tweaking it. Also, the data on the test server is inconsistent. You end up with whatever test data the last developer to commit had on his sandbox server. Where everything breaks down is the deployment to production. Since we can't overwrite the live data with test data, this involves manually re-creating all the schema changes. If there were a large number of schema changes or conversion scripts to manipulate the data, this can get really hairy. If the problem was just the schema, It'd be an easier problem, but there is "base" data in the database that is updated during development as well, such as meta-data in security and permissions tables. This is the biggest barrier I see in moving toward continuous integration and one-step-builds. How do you solve it? A follow-up question: how do you track database versions so you know which scripts to run to upgrade a given database instance? Is a version table like Lance mentions below the standard procedure? Thanks for the reference to Tarantino. I'm not in a .NET environment, but I found their DataBaseChangeMangement wiki page to be very helpful. Especially this Powerpoint Presentation (.ppt) I'm going to write a Python script that checks the names of *.sql scripts in a given directory against a table in the database and runs the ones that aren't there in order based on a integer that forms the first part of the filename. If it is a pretty simple solution, as I suspect it will be, then I'll post it here. I've got a working script for this. It handles initializing the DB if it doesn't exist and running upgrade scripts as necessary. There are also switches for wiping an existing database and importing test data from a file. It's about 200 lines, so I won't post it (though I might put it on pastebin if there's interest). | There are a couple of good options. I wouldn't use the "restore a backup" strategy. Script all your schema changes, and have your CI server run those scripts on the database. Have a version table to keep track of the current database version, and only execute the scripts if they are for a newer version. Use a migration solution. These solutions vary by language, but for .NET I use Migrator.NET. This allows you to version your database and move up and down between versions. Your schema is specified in C# code. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/6371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/763/"
]
} |
6,373 | There are two popular closure styles in javascript. The first I call anonymous constructor : new function() { var code...} and the inline executed function : (function() { var code...})(); are there differences in behaviour between those two? Is one "better" over the other? | Both cases will execute the function, the only real difference is what the return value of the expression may be, and what the value of "this" will be inside the function. Basically behaviour of new expression Is effectively equivalent to var tempObject = {};var result = expression.call(tempObject);if (result is not an object) result = tempObject; Although of course tempObject and result are transient values you can never see (they're implementation details in the interpreter), and there is no JS mechanism to do the "is not an object" check. Broadly speaking the "new function() { .. }" method will be slower due to the need to create the this object for the constructor. That said this should be not be a real difference as object allocation is not slow, and you shouldn't be using such code in hot code (due to the cost of creating the function object and associated closure). Edit: one thing i realised that i missed from this is that the tempObject will get expression s prototype, eg. (before the expression.call ) tempObject.__proto__ = expression.prototype | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56/"
]
} |
6,392 | I am running a Tomcat application, and I need to display some time values. Unfortunately, the time is coming up an hour off. I looked into it and discovered that my default TimeZone is being set to: sun.util.calendar.ZoneInfo[id="GMT-08:00", offset=-28800000, dstSavings=0, useDaylight=false, transitions=0, lastRule=null] Rather than the Pacific time zone. This is further indicated when I try to print the default time zone's display name , and it comes up "GMT-08:00", which seems to indicate to me that it is not correctly set to the US Pacific time zone. I am running on Ubuntu Hardy Heron, upgraded from Gutsy Gibbon. Is there a configuration file I can update to tell the JRE to use Pacific with all the associated daylight savings time information? The time on my machine shows correctly, so it doesn't seem to be an OS-wide misconfiguration. Ok, here's an update. A coworker suggested I update JAVA_OPTS in my /etc/profile to include "-Duser.timezone=US/Pacific", which worked (I also saw CATALINA_OPTS, which I updated as well). Actually, I just exported the change into the variables rather than use the new /etc/profile (a reboot later will pick up the changes and I will be golden). However, I still think there is a better solution... there should be a configuration for Java somewhere that says what timezone it is using, or how it is grabbing the timezone. If someone knows such a setting, that would be awesome, but for now this is a decent workaround. I am using 1.5, and it is most definitely a DST problem. As you can see, the time zone is set to not use daylight savings. My belief is it is generically set to -8 offset rather than the specific Pacific timezone. Since the generic -8 offset has no daylight savings info, it's of course not using it, but the question is, where do I tell Java to use Pacific time zone when it starts up? I'm NOT looking for a programmatic solution, it should be a configuration solution. | It's a "quirk" in the way the JVM looks up the zoneinfo file. See Bug ID 6456628 . The easiest workaround is to make /etc/localtime a symlink to the correct zoneinfo file. For Pacific time, the following commands should work: # sudo cp /etc/localtime /etc/localtime.dist# sudo ln -fs /usr/share/zoneinfo/America/Los_Angeles /etc/localtime I haven't had any problems with the symlink approach. Edit: Added "sudo" to the commands. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/6392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
]
} |
6,406 | Is it possible to access an element on a Master page from the page loaded within the ContentPlaceHolder for the master? I have a ListView that lists people's names in a navigation area on the Master page. I would like to update the ListView after a person has been added to the table that the ListView is data bound to. The ListView currently does not update it's values until the cache is reloaded. We have found that just re-running the ListView.DataBind() will update a listview's contents. We have not been able to run the ListView.DataBind() on a page that uses the Master page. Below is a sample of what I wanted to do but a compiler error says "PeopleListView does not exist in the current context" GIS.master - Where ListView resides ...<asp:ListView ID="PeopleListView"... GISInput_People.aspx - Uses GIS.master as it's master page GISInput_People.aspx.cs AddNewPerson(){ // Add person to table .... // Update Person List PeopleListView.DataBind(); ...} What would be the best way to resolve an issue like this in C# .Net? | I believe you could do this by using this.Master.FindControl or something similar, but you probably shouldn't - it requires the content page to know too much about the structure of the master page. I would suggest another method, such as firing an event in the content area that the master could listen for and re-bind when fired. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/576/"
]
} |
6,414 | In a C# (feel free to answer for other languages) loop, what's the difference between break and continue as a means to leave the structure of the loop, and go to the next iteration? Example: foreach (DataRow row in myTable.Rows){ if (someConditionEvalsToTrue) { break; //what's the difference between this and continue ? //continue; }} | break will exit the loop completely, continue will just skip the current iteration. For example: for (int i = 0; i < 10; i++) { if (i == 0) { break; } DoSomeThingWith(i);} The break will cause the loop to exit on the first iteration - DoSomeThingWith will never be executed. This here: for (int i = 0; i < 10; i++) { if(i == 0) { continue; } DoSomeThingWith(i);} Will not execute DoSomeThingWith for i = 0 , but the loop will continue and DoSomeThingWith will be executed for i = 1 to i = 9 . | {
"score": 12,
"source": [
"https://Stackoverflow.com/questions/6414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
]
} |
6,440 | I've been using a lot of new .NET 3.5 features in the work that I've been doing, lately. The application that I'm building is intended for distribution among consumers who will probably not have the latest version (or perhaps any version ) of the .NET framework on their machines. I went to go download the .NET 3.5 redistributable package only to find out that it's almost 200 MB! This is unacceptable for my application, because it's supposed to be a quick and painless consumer application that installs quickly and keeps a low profile on the user's machine. For users that have .NET 3.5 already installed, our binary downloads have been instantaneous, so far. This 200 MB gorilla will more than quadruple the size of the download. Is there any other option than this redistributable package that I can use to make sure the framework is on the machine that won't take the user out of our "quick and painless" workflow? Our target time from beginning of download to finalizing the install is less than two minutes. Is it just not possible for someone who doesn't already have .NET installed? | That's one of the sad reasons i'm still targeting .net 2.0 whenever possible :/ But people don't neccessarily need the full 200 MB Package. There is a 3 MB Bootstrapper which will only download the required components: .net 3.5 SP1 Bootstrapper However, the worst case scenario is still a pretty hefty download. Also, see this article for a more detailed explanation on the size and an alternative workaround to the size problem. Addition: Since answering this question, Scott Hanselman created SmallestDotNet.com , which will determine the smallest required download. Doesn't change the worst case scenario, but is still useful to know. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/560/"
]
} |
6,467 | I need to do date arithmetic in Unix shell scripts that I use to control the execution of third party programs. I'm using a function to increment a day and another to decrement: IncrementaDia(){echo $1 | awk 'BEGIN { diasDelMes[1] = 31 diasDelMes[2] = 28 diasDelMes[3] = 31 diasDelMes[4] = 30 diasDelMes[5] = 31 diasDelMes[6] = 30 diasDelMes[7] = 31 diasDelMes[8] = 31 diasDelMes[9] = 30 diasDelMes[10] = 31 diasDelMes[11] = 30 diasDelMes[12] = 31}{ anio=substr($1,1,4) mes=substr($1,5,2) dia=substr($1,7,2) if((anio % 4 == 0 && anio % 100 != 0) || anio % 400 == 0) { diasDelMes[2] = 29; } if( dia == diasDelMes[int(mes)] ) { if( int(mes) == 12 ) { anio = anio + 1 mes = 1 dia = 1 } else { mes = mes + 1 dia = 1 } } else { dia = dia + 1 }}END { printf("%04d%02d%02d", anio, mes, dia)}'}if [ $# -eq 1 ]; then tomorrow=$1else today=$(date +"%Y%m%d") tomorrow=$(IncrementaDia $hoy)fi but now I need to do more complex arithmetic. What it's the best and more compatible way to do this? | Assuming you have GNU date , like so: date --date='1 days ago' '+%a' And similar phrases . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/6467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/527/"
]
} |
6,484 | Mocking sealed classes can be quite a pain. I currently favor an Adapter pattern to handle this, but something about just keeps feels weird. So, What is the best way you mock sealed classes? Java answers are more than welcome . In fact, I would anticipate that the Java community has been dealing with this longer and has a great deal to offer. But here are some of the .NET opinions: Why Duck Typing Matters for C#Develoepers Creating wrappersfor sealed and other types formocking Unit tests for WCF (and Moq) | My general rule of thumb is that objects that I need to mock should have a common interface too. I think this is right design-wise and makes tests a lot easier (and is usually what you get if you do TDD). More about this can be read in the Google Testing Blog latest post (See point 9). Also, I've been working mainly in Java in the past 4 years and I can say that I can count on one hand the number of times I've created a final (sealed) class. Another rule here is I should always have a good reason to seal a class, as opposed to sealing it by default. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/307/"
]
} |
6,499 | There are a few ways to get class-like behavior in javascript, the most common seem to be prototype based like this: function Vector(x, y, x) { this.x = x; this.y = y; this.z = z; return this;}Vector.prototype.length = function () { return Math.sqrt(this.x * this.x ... ); } and closure based approaches similar to function Vector(x, y, z) { this.length = function() { return Math.sqrt(x * x + ...); }} For various reasons the latter is faster, but I've seen (and I frequently do write) the prototype version and was curious as to what other people do. | Assigning functions to the prototype is better (for public methods) because all instances of the class will share the same copy of the method. If you assign the function inside the constructor as in the second example, every time you create a new instance, the constructor creates a new copy of the length function and assigns it to just that one instance. However this latter technique is useful if you want each copy to have it's own copy, the main use of that being to do private/privileges methods which have access to private variables declared inside the constructor and inherited via the closure mechanism. Douglas Crockford has a good summary . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/784/"
]
} |
6,512 | I'm working on a Scheme interpreter written in C. Currently it uses the C runtime stack as its own stack, which is presenting a minor problem with implementing continuations. My current solution is manual copying of the C stack to the heap then copying it back when needed. Aside from not being standard C, this solution is hardly ideal. What is the simplest way to implement continuations for Scheme in C? | I remember reading an article that may be of help to you: Cheney on the M.T.A. :-) Some implementations of Scheme I know of, such as SISC , allocate their call frames on the heap. @ollie: You don't need to do the hoisting if all your call frames are on the heap. There's a tradeoff in performance, of course: the time to hoist, versus the overhead required to allocate all frames on the heap. Maybe it should be a tunable runtime parameter in the interpreter. :-P | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
]
} |
6,547 | One of those classic programming interview questions... You are given two marbles, and told that they will break when dropped from some certain height (and presumably suffer no damage if dropped from below that height). You’re then taken to a 100 story building (presumably higher than the certain height), and asked to find the highest floor your can drop a marble from without breaking it as efficiently as possible. Extra info You must find the correct floor (not a possible range) The marbles are both guaranteed to break at the same floor Assume it takes zero time for you to change floors - only the number of marble drops counts Assume the correct floor is randomly distributed in the building | The interesting thing here is how you can do it in the least amount of drops possible. Going to the 50th floor and dropping the first would be disastrous if the breaking floor is the 49th, resulting in us having to do 50 drops. We should drop the first marble at floor n, where n is the max amount of drops required. If the marble breaks at floor n, we may have to make n-1 drops after that. If the marble doesn't break we go up to floor 2n-1 and if it breaks here we have to drop the second marble n-2 times in the worst case. We continue like this up to the 100th floor and try to break it at 3n-2, 4n-3.... and n+(n-1)+(n-2)+...1 <=100 n=14 Is the maximum drops required | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/6547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
]
} |
6,557 | It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way. List<string> sl = new List<string>();List<object> ol;ol = sl; results in Cannot implicitly convert type System.Collections.Generic.List<string> to System.Collections.Generic.List<object> And then... List<string> sl = new List<string>();List<object> ol;ol = (List<object>)sl; results in Cannot convert type System.Collections.Generic.List<string> to System.Collections.Generic.List<object> Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution. | Think of it this way, if you were to do such a cast, and then add an object of type Foo to the list, the list of strings is no longer consistent. If you were to iterate the first reference, you would get a class cast exception because once you hit the Foo instance, the Foo could not be converted to string! As a side note, I think it would be more significant whether or not you can do the reverse cast: List<object> ol = new List<object>();List<string> sl;sl = (List<string>)ol; I haven't used C# in a while, so I don't know if that is legal, but that sort of cast is actually (potentially) useful. In this case, you are going from a more general class (object) to a more specific class (string) that extends from the general one. In this way, if you add to the list of strings, you are not violating the list of objects. Does anybody know or can test if such a cast is legal in C#? | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/6557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
]
} |
6,578 | I'm just beginning to have a look at Objective-C and Cocoa with a view to playing with the iPhone SDK. I'm reasonably comfortable with C's malloc and free concept, but Cocoa's references counting scheme has me rather confused. I'm told it's very elegant once you understand it, but I'm just not over the hump yet. How do release , retain and autorelease work and what are the conventions about their use? (Or failing that, what did you read which helped you get it?) | Let's start with retain and release ; autorelease is really just a special case once you understand the basic concepts. In Cocoa, each object keeps track of how many times it is being referenced (specifically, the NSObject base class implements this). By calling retain on an object, you are telling it that you want to up its reference count by one. By calling release , you tell the object you are letting go of it, and its reference count is decremented. If, after calling release , the reference count is now zero, then that object's memory is freed by the system. The basic way this differs from malloc and free is that any given object doesn't need to worry about other parts of the system crashing because you've freed memory they were using. Assuming everyone is playing along and retaining/releasing according to the rules, when one piece of code retains and then releases the object, any other piece of code also referencing the object will be unaffected. What can sometimes be confusing is knowing the circumstances under which you should call retain and release . My general rule of thumb is that if I want to hang on to an object for some length of time (if it's a member variable in a class, for instance), then I need to make sure the object's reference count knows about me. As described above, an object's reference count is incremented by calling retain . By convention, it is also incremented (set to 1, really) when the object is created with an "init" method. In either of these cases, it is my responsibility to call release on the object when I'm done with it. If I don't, there will be a memory leak. Example of object creation: NSString* s = [[NSString alloc] init]; // Ref count is 1[s retain]; // Ref count is 2 - silly // to do this after init[s release]; // Ref count is back to 1[s release]; // Ref count is 0, object is freed Now for autorelease . Autorelease is used as a convenient (and sometimes necessary) way to tell the system to free this object up after a little while. From a plumbing perspective, when autorelease is called, the current thread's NSAutoreleasePool is alerted of the call. The NSAutoreleasePool now knows that once it gets an opportunity (after the current iteration of the event loop), it can call release on the object. From our perspective as programmers, it takes care of calling release for us, so we don't have to (and in fact, we shouldn't). What's important to note is that (again, by convention) all object creation class methods return an autoreleased object. For example, in the following example, the variable "s" has a reference count of 1, but after the event loop completes, it will be destroyed. NSString* s = [NSString stringWithString:@"Hello World"]; If you want to hang onto that string, you'd need to call retain explicitly, and then explicitly release it when you're done. Consider the following (very contrived) bit of code, and you'll see a situation where autorelease is required: - (NSString*)createHelloWorldString{ NSString* s = [[NSString alloc] initWithString:@"Hello World"]; // Now what? We want to return s, but we've upped its reference count. // The caller shouldn't be responsible for releasing it, since we're the // ones that created it. If we call release, however, the reference // count will hit zero and bad memory will be returned to the caller. // The answer is to call autorelease before returning the string. By // explicitly calling autorelease, we pass the responsibility for // releasing the string on to the thread's NSAutoreleasePool, which will // happen at some later time. The consequence is that the returned string // will still be valid for the caller of this function. return [s autorelease];} I realize all of this is a bit confusing - at some point, though, it will click. Here are a few references to get you going: Apple's introduction to memory management. Cocoa Programming for Mac OS X (4th Edition) , by Aaron Hillegas - a very well written book with lots of great examples. It reads like a tutorial. If you're truly diving in, you could head to Big Nerd Ranch . This is a training facility run by Aaron Hillegas - the author of the book mentioned above. I attended the Intro to Cocoa course there several years ago, and it was a great way to learn. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/6578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
]
} |
6,607 | I'm a new Windows programmer and I'm not sure where I should store user configurable application settings. I understand the need to provide a user friendly means for the user to change application settings, like an Edit | Settings form or similar. But where should I store the values after the user hits the Apply button on that form? What are the pros and cons of storing settings in the Windows registry vs. storing them in a local INI file or config file or similar? | Pros of config file: Easy to do. Don't need to know any Windows API calls. You just need to know the file I/O interface of your programming language. Portable. If you port your application to another OS, you don't need to change your settings format. User-editable. The user can edit the config file outside of the program executing. Pros of registry: Secure. The user can't accidentally delete the config file or corrupt the data unless he/she knows about regedit. And then the user is just asking for trouble. I'm no expert Windows programmer, but I'm sure that using the registry makes it easier to do other Windows-specific things (user-specific settings, network administration stuff like group policy, or whatever else). If you just need a simple way to store config information, I would recommend a config file, using INI or XML as the format. I suggest using the registry only if there is something specific you want to get out of using the registry. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/6607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27687/"
]
} |
6,612 | On a recent Java project, we needed a free Java based real-time data plotting utility. After much searching, we found this tool called the Scientific Graphics Toolkit or SGT from NOAA. It seemed pretty robust, but we found out that it wasn't terribly configurable. Or at least not configurable enough to meet our needs. We ended up digging very deeply into the Java code and reverse engineering the code and changing it all around to make the plot tool look and act the way we wanted it to look and act. Of course, this killed any chance for future upgrades from NOAA. So what free or cheap Java based data plotting tools or libraries do you use? Followup: Thanks for the JFreeChart suggestions. I checked out their website and it looks like a very nice data charting and plotting utility. I should have made it clear in my original question that I was looking specifically to plot real-time data. I corrected my question above to make that point clear. It appears that JFreeChart support for live data is marginal at best, though . Any other suggestions out there? | I've had success using JFreeChart on multiple projects. It is very configurable. JFreeChart is open source, but they charge for the developer guide . If you're doing something simple, the sample code is probably good enough. Otherwise, $50 for the developer guide is a pretty good bargain. With respect to "real-time" data, I've also used JFreeChart for these sorts of applications. Unfortunately, I had to create some custom data models with appropriate synchronization mechanisms to avoid race conditions. However, it wasn't terribly difficult and JFreeChart would still be my first choice. However, as the FAQ suggests, JFreeChart might not give you the best performance if that is a big concern. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27687/"
]
} |
6,623 | After changing the output directory of a visual studio project it started to fail to build with an error very much like: C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin\sgen.exe /assembly:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryCaseManagement\obj\Release\EASDiscoveryCaseManagement.dll /proxytypes /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Common\target\win_x32\release\results\EASDiscovery.Common.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EasDiscovery.Export\target\win_x32\release\results\EASDiscovery.Export.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\ItemCache\target\win_x32\release\results\EasDiscovery.ItemCache.dll /reference:c:\p4root\Zantaz\trunk\EASDiscovery\RetrievalEngine\target\win_x32\release\results\EasDiscovery.RetrievalEngine.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\EASDiscoveryJobs\target\win_x32\release\results\EASDiscoveryJobs.dll /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Shared.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.Misc.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinChart.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDataSource.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinDock.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinEditors.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinGrid.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinListView.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinMaskedEdit.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinStatusBar.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTabControl.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinToolbars.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.UltraWinTree.v8.1.dll" /reference:"C:\Program Files\Infragistics\NetAdvantage for .NET 2008 Vol. 1 CLR 2.0\Windows Forms\Bin\Infragistics2.Win.v8.1.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.Common.dll" /reference:"C:\Program Files\Microsoft Visual Studio 8\ReportViewer\Microsoft.ReportViewer.WinForms.dll" /reference:C:\p4root\Zantaz\trunk\EASDiscovery\PreviewControl\target\win_x32\release\results\PreviewControl.dll /reference:C:\p4root\Zantaz\trunk\EASDiscovery\Quartz\src\Quartz\target\win_x32\release\results\Scheduler.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.configuration.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Design.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.DirectoryServices.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.Services.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /compiler:/delaysign- Error: The specified module could not be found. (Exception from HRESULT: 0x8007007E) C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Microsoft.Common.targets(1902,9): error MSB6006: "sgen.exe" exited with code 1. I changed the output directory to target/win_x32/release/results but the path in sgen doesn't seem to have been updated. There seems to be no reference in the project to what path is passed into sgen so I'm unsure how to fix it. As a workaround I have disabled the serialization generation but it would be nice to fix the underlying problem. Has anybody else seen this? | If you are having this problem while building your VS.NET project in Release mode here is the solution: Go to the project properties and click on the Build tab and set the value of the "Generate Serialization Assembly" dropdown to "Off". Sgen.exe is "The XML Serializer Generator creates an XML serialization assembly for types in a specified assembly in order to improve the startup performance of a XmlSerializer when it serializes or deserializes objects of the specified types." ( MSDN ) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/6623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.