source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
104,339
I'm doing some Objective-C programming that involves parsing an NSXmlDocument and populating an objects properties from the result. First version looked like this: if([elementName compare:@"companyName"] == 0) [character setCorporationName:currentElementText]; else if([elementName compare:@"corporationID"] == 0) [character setCorporationID:currentElementText]; else if([elementName compare:@"name"] == 0) ... But I don't like the if-else-if-else pattern this produces. Looking at the switch statement I see that i can only handle ints , chars etc and not objects... so is there a better implementation pattern I'm not aware of? BTW I did actually come up with a better solution for setting the object's properties, but I want to know specifically about the if - else vs switch pattern in Objective-C
I hope you'll all forgive me for going out on a limb here, but I would like to address the more general question of parsing XML documents in Cocoa without the need of if-else statements. The question as originally stated assigns the current element text to an instance variable of the character object. As jmah pointed out, this can be solved using key-value coding. However, in a more complex XML document this might not be possible. Consider for example the following. <xmlroot> <corporationID> <stockSymbol>EXAM</stockSymbol> <uuid>31337</uuid> </corporationID> <companyName>Example Inc.</companyName></xmlroot> There are multiple approaches to dealing with this. Off of the top of my head, I can think of two using NSXMLDocument. The first uses NSXMLElement. It is fairly straightforward and does not involve the if-else issue at all. You simply get the root element and go through its named elements one by one. NSXMLElement* root = [xmlDocument rootElement];// Assuming that we only have one of each element.[character setCorperationName:[[[root elementsForName:@"companyName"] objectAtIndex:0] stringValue]];NSXMLElement* corperationId = [root elementsForName:@"corporationID"];[character setCorperationStockSymbol:[[[corperationId elementsForName:@"stockSymbol"] objectAtIndex:0] stringValue]];[character setCorperationUUID:[[[corperationId elementsForName:@"uuid"] objectAtIndex:0] stringValue]]; The next one uses the more general NSXMLNode, walks through the tree, and directly uses the if-else structure. // The first line is the same as the last example, because NSXMLElement inherits from NSXMLNodeNSXMLNode* aNode = [xmlDocument rootElement];while(aNode = [aNode nextNode]){ if([[aNode name] isEqualToString:@"companyName"]){ [character setCorperationName:[aNode stringValue]]; }else if([[aNode name] isEqualToString:@"corporationID"]){ NSXMLNode* correctParent = aNode; while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){ if([[aNode name] isEqualToString:@"stockSymbol"]){ [character setCorperationStockSymbol:[aNode stringValue]]; }else if([[aNode name] isEqualToString:@"uuid"]){ [character setCorperationUUID:[aNode stringValue]]; } } }} This is a good candidate for eliminating the if-else structure, but like the original problem, we can't simply use switch-case here. However, we can still eliminate if-else by using performSelector. The first step is to define the a method for each element. - (NSNode*)parse_companyName:(NSNode*)aNode{ [character setCorperationName:[aNode stringValue]]; return aNode;}- (NSNode*)parse_corporationID:(NSNode*)aNode{ NSXMLNode* correctParent = aNode; while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){ [self invokeMethodForNode:aNode prefix:@"parse_corporationID_"]; } return [aNode previousNode];}- (NSNode*)parse_corporationID_stockSymbol:(NSNode*)aNode{ [character setCorperationStockSymbol:[aNode stringValue]]; return aNode;}- (NSNode*)parse_corporationID_uuid:(NSNode*)aNode{ [character setCorperationUUID:[aNode stringValue]]; return aNode;} The magic happens in the invokeMethodForNode:prefix: method. We generate the selector based on the name of the element, and perform that selector with aNode as the only parameter. Presto bango, we've eliminated the need for an if-else statement. Here's the code for that method. - (NSNode*)invokeMethodForNode:(NSNode*)aNode prefix:(NSString*)aPrefix{ NSNode* ret = nil; NSString* methodName = [NSString stringWithFormat:@"%@%@:", prefix, [aNode name]]; SEL selector = NSSelectorFromString(methodName); if([self respondsToSelector:selector]) ret = [self performSelector:selector withObject:aNode]; return ret;} Now, instead of our larger if-else statement (the one that differentiated between companyName and corporationID), we can simply write one line of code NSXMLNode* aNode = [xmlDocument rootElement];while(aNode = [aNode nextNode]){ aNode = [self invokeMethodForNode:aNode prefix:@"parse_"];} Now I apologize if I got any of this wrong, it's been a while since I've written anything with NSXMLDocument, it's late at night and I didn't actually test this code. So if you see anything wrong, please leave a comment or edit this answer. However, I believe I have just shown how properly-named selectors can be used in Cocoa to completely eliminate if-else statements in cases like this. There are a few gotchas and corner cases. The performSelector: family of methods only takes 0, 1, or 2 argument methods whose arguments and return types are objects, so if the types of the arguments and return type are not objects, or if there are more than two arguments, then you would have to use an NSInvocation to invoke it. You have to make sure that the method names you generate aren't going to call other methods, especially if the target of the call is another object, and this particular method naming scheme won't work on elements with non-alphanumeric characters. You could get around that by escaping the XML element names in your method names somehow, or by building an NSDictionary using the method names as the keys and the selectors as the values. This can get pretty memory intensive and end up taking a longer time. performSelector dispatch like I described is pretty fast. For very large if-else statements, this method may even be faster than an if-else statement.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/104339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18590/" ] }
104,383
In Visual Basic 6, when I attempt to access Project > References , it throws an error: Error accessing system registry I am: Logged in as the local computer administrator running Windows XP Professional and I can execute regedt32.exe and access all the registry keys just fine. VB6 was installed as the local administrator. Any idea why this happens? I'm running crystal reports 8.5 and it supposed to already have fixed that issue but apparently I still have the issue with 8.5 installed. I have also made the attempt of reinstalling crystal reports with no luck on the issue.
Depending on the Windows OS you have (I have Windows 7 Enterprise), you might want to try giving administrator rights to the REGTLIB.EXE (located in C:\Windws). Right click on the REGTLIB.EXE file. Select Properties from the pop-up menu. Then select the Compatiblity tab. On the Compatiblity tab, check/select the Run this program as Administrator checkbox. Click OK to save your changes. It might take take care of the problem for you. It worked for me. Good luck.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/104383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18853/" ] }
104,420
How do I generate all the permutations of a list? For example: permutations([])[]permutations([1])[1]permutations([1, 2])[1, 2][2, 1]permutations([1, 2, 3])[1, 2, 3][1, 3, 2][2, 1, 3][2, 3, 1][3, 1, 2][3, 2, 1]
Use itertools.permutations from the standard library : import itertoolslist(itertools.permutations([1, 2, 3])) Adapted from here is a demonstration of how itertools.permutations might be implemented: def permutations(elements): if len(elements) <= 1: yield elements return for perm in permutations(elements[1:]): for i in range(len(elements)): # nb elements[0:1] works in both string and list contexts yield perm[:i] + elements[0:1] + perm[i:] A couple of alternative approaches are listed in the documentation of itertools.permutations . Here's one: def permutations(iterable, r=None): # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC # permutations(range(3)) --> 012 021 102 120 201 210 pool = tuple(iterable) n = len(pool) r = n if r is None else r if r > n: return indices = range(n) cycles = range(n, n-r, -1) yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return And another, based on itertools.product : def permutations(iterable, r=None): pool = tuple(iterable) n = len(pool) r = n if r is None else r for indices in product(range(n), repeat=r): if len(set(indices)) == r: yield tuple(pool[i] for i in indices)
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/104420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3399/" ] }
104,439
The Eclipse projects are all stored in the Eclipse Foundation CVS servers. Using the source is a great way to debug your code and to figure out how to do new things. Unfortunately in a large software project like BIRT, it can be difficult to know which projects and versions are required for a particular build. So what is the best way to get the source for a particular build?
Use itertools.permutations from the standard library : import itertoolslist(itertools.permutations([1, 2, 3])) Adapted from here is a demonstration of how itertools.permutations might be implemented: def permutations(elements): if len(elements) <= 1: yield elements return for perm in permutations(elements[1:]): for i in range(len(elements)): # nb elements[0:1] works in both string and list contexts yield perm[:i] + elements[0:1] + perm[i:] A couple of alternative approaches are listed in the documentation of itertools.permutations . Here's one: def permutations(iterable, r=None): # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC # permutations(range(3)) --> 012 021 102 120 201 210 pool = tuple(iterable) n = len(pool) r = n if r is None else r if r > n: return indices = range(n) cycles = range(n, n-r, -1) yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return And another, based on itertools.product : def permutations(iterable, r=None): pool = tuple(iterable) n = len(pool) r = n if r is None else r for indices in product(range(n), repeat=r): if len(set(indices)) == r: yield tuple(pool[i] for i in indices)
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/104439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5412/" ] }
104,458
How can styles be applied to CheckBoxList ListItems. Unlike other controls, such as the Repeater where you can specify <ItemStyle> , you can't seem to specify a style for each individual control. Is there some sort of work around?
You can add Attributes to ListItems programmatically as follows. Say you've got a CheckBoxList and you are adding ListItems. You can add Attributes along the way. ListItem li = new ListItem("Richard Byrd", "11");li.Selected = false;li.Attributes.Add("Style", "color: red;");CheckBoxList1.Items.Add(li); This will make the color of the listitem text red. Experiment and have fun.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/104458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12096/" ] }
104,485
I'm trying to skin HTML output which I don't have control over. One of the elements is a div with a style="overflow: auto" attribute. Is there a way in CSS to force that div to use overflow: hidden; ?
You can add !important to the end of your style, like this: element { overflow: hidden !important;} This is something you should not rely on normally, but in your case that's the best option. Changing the value in Javascript strays from the best practice of separating markup, presentation, and behavior (html/css/javascript).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/104485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4898/" ] }
104,516
In PHP, the HEREDOC string declarations are really useful for outputting a block of html. You can have it parse in variables just by prefixing them with $, but for more complicated syntax (like $var[2][3]), you have to put your expression inside {} braces. In PHP 5, it is possible to actually make function calls within {} braces inside a HEREDOC string, but you have to go through a bit of work. The function name itself has to be stored in a variable, and you have to call it like it is a dynamically-named function. For example: $fn = 'testfunction';function testfunction() { return 'ok'; }$string = <<< heredocplain text and now a function: {$fn()}heredoc; As you can see, this is a bit more messy than just: $string = <<< heredocplain text and now a function: {testfunction()}heredoc; There are other ways besides the first code example, such as breaking out of the HEREDOC to call the function, or reversing the issue and doing something like: ?><!-- directly output html and only breaking into php for the function -->plain text and now a function: <?PHP print testfunction(); ?> The latter has the disadvantage that the output is directly put into the output stream (unless I'm using output buffering), which might not be what I want. So, the essence of my question is: is there a more elegant way to approach this? Edit based on responses: It certainly does seem like some kind of template engine would make my life much easier, but it would require me basically invert my usual PHP style. Not that that's a bad thing, but it explains my inertia.. I'm up for figuring out ways to make life easier though, so I'm looking into templates now.
I would not use HEREDOC at all for this, personally. It just doesn't make for a good "template building" system. All your HTML is locked down in a string which has several disadvantages No option for WYSIWYG No code completion for HTML from IDEs Output (HTML) locked to logic files You end up having to use hacks like what you're trying to do now to achieve more complex templating, such as looping Get a basic template engine, or just use PHP with includes - it's why the language has the <?php and ?> delimiters. template_file.php <html><head> <title><?php echo $page_title; ?></title></head><body> <?php echo getPageContent(); ?></body> index.php <?php$page_title = "This is a simple demo";function getPageContent() { return '<p>Hello World!</p>';}include('template_file.php');
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/104516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9330/" ] }
104,520
I have been seriously disappointed with WPF validation system. Anyway! How can I validate the complete form by clicking the "button"? For some reason everything in WPF is soo complicated! I can do the validation in 1 line of code in ASP.NET which requires like 10-20 lines of code in WPF!! I can do this using my own ValidationEngine framework: Customer customer = new Customer();customer.FirstName = "John";customer.LastName = String.Empty;ValidationEngine.Validate(customer);if (customer.BrokenRules.Count > 0){ // do something display the broken rules! }
A WPF application should disable the button to submit a form iff the entered data is not valid. You can achieve this by implementing the IDataErrorInfo interface on your business object, using Bindings with ValidatesOnDataErrors =true . For customizing the look of individual controls in the case of errors, set a Validation.ErrorTemplate . XAML: <Window x:Class="Example.CustomerWindow" ...> <Window.CommandBindings> <CommandBinding Command="ApplicationCommands.Save" CanExecute="SaveCanExecute" Executed="SaveExecuted" /> </Window.CommandBindings> <StackPanel> <TextBox Text="{Binding FirstName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" /> <TextBox Text="{Binding LastName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" /> <Button Command="ApplicationCommands.Save" IsDefault="True">Save</Button> <TextBlock Text="{Binding Error}"/> </StackPanel></Window> This creates a Window with two TextBox es where you can edit the first and last name of a customer. The "Save" button is only enabled if no validation errors have occurred. The TextBlock beneath the button shows the current errors, so the user knows what's up. The default ErrorTemplate is a thin red border around the erroneous Control. If that doesn't fit into you visual concept, look at Validation in Windows Presentation Foundation article on CodeProject for an in-depth look into what can be done about that. To get the window to actually work, there has to be a bit infrastructure in the Window and the Customer. Code Behind // The CustomerWindow class receives the Customer to display// and manages the Save commandpublic class CustomerWindow : Window{ private Customer CurrentCustomer; public CustomerWindow(Customer c) { // store the customer for the bindings DataContext = CurrentCustomer = c; InitializeComponent(); } private void SaveCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = ValidationEngine.Validate(CurrentCustomer); } private void SaveExecuted(object sender, ExecutedRoutedEventArgs e) { CurrentCustomer.Save(); }}public class Customer : IDataErrorInfo, INotifyPropertyChanged{ // holds the actual value of FirstName private string FirstNameBackingStore; // the accessor for FirstName. Only accepts valid values. public string FirstName { get { return FirstNameBackingStore; } set { FirstNameBackingStore = value; ValidationEngine.Validate(this); OnPropertyChanged("FirstName"); } } // similar for LastName string IDataErrorInfo.Error { get { return String.Join("\n", BrokenRules.Values); } } string IDataErrorInfo.this[string columnName] { get { return BrokenRules[columnName]; } }} An obvious improvement would be to move the IDataErrorInfo implementation up the class hierarchy, since it only depends on the ValidationEngine , but not the business object. While this is indeed more code than the simple example you provided, it also has quite a bit more of functionality than only checking for validity. This gives you fine grained, and automatically updated indications to the user about validation problems and automatically disables the "Save" button as long as the user tries to enter invalid data.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/104520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3797/" ] }
104,550
Are .css files always needed? Or may I have a .css "basic" file and define other style items inside the HTML page? Does padding , borders and so on always have to be defined in a .css file that is stored separately, or may I embed then into an HTML page?
It is technically possible to use inline CSS formatting exclusively and have no external stylesheet. You can also embed the stylesheet within the HTML document. The best practice in web design is to separate out the CSS into a separate stylesheet. The reason for this is that the CSS stylesheet exists for the purpose of defining the presentation style of the document. The HTML file exists to define the structure and content of the document. And perhaps you may have JavaScript files which exist to add additional behavior to the document. Keeping the presentation, markup, and behavior separate creates a cleaner design. From a practical perspective, if you have a single external CSS stylesheet the browser can cache it. If multiple pages on your site have the same look and feel, they can use the same external stylesheet which only needs to be downloaded once by the web browser. This will make your network bandwidth bills lower as well as creating a faster end user experience.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/104550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19159/" ] }
104,592
From Wired magazine: ...the Palin hack didn't require any real skill. Instead, the hacker simply reset Palin's password using her birthdate, ZIP code and information about where she met her spouse -- the security question on her Yahoo account, which was answered (Wasilla High) by a simple Google search. We cannot trust such security questions to reset forgotten passwords. How do you design a better system?
Out-of-band communication is the way to go. For instance, sending a temporary password in SMS may be acceptable (depending on the system). I've seen this implemented often by telecoms, where SMS is cheap/free/part of business, and the user's cellphone number is pre-registered... Banks often require a phone call to/from a specific number, but I personally am not too crazy about that.... And of course, depending on the system, forcing the user to come in to the branch office to personally identify themselves can also work (just royally annoy the user). Bottom line, DON'T create a weaker channel to bypass the strong password requirements.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/104592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ] }
104,599
I need to write a Java Comparator class that compares Strings, however with one twist. If the two strings it is comparing are the same at the beginning and end of the string are the same, and the middle part that differs is an integer, then compare based on the numeric values of those integers. For example, I want the following strings to end up in order they're shown: aaa bbb 3 ccc bbb 12 ccc ccc 11 ddd eee 3 ddd jpeg2000 eee eee 12 ddd jpeg2000 eee As you can see, there might be other integers in the string, so I can't just use regular expressions to break out any integer. I'm thinking of just walking the strings from the beginning until I find a bit that doesn't match, then walking in from the end until I find a bit that doesn't match, and then comparing the bit in the middle to the regular expression "[0-9]+", and if it compares, then doing a numeric comparison, otherwise doing a lexical comparison. Is there a better way? Update I don't think I can guarantee that the other numbers in the string, the ones that may match, don't have spaces around them, or that the ones that differ do have spaces.
The Alphanum Algorithm From the website "People sort strings with numbers differently than software. Most sorting algorithms compare ASCII values, which produces an ordering that is inconsistent with human logic. Here's how to fix it." Edit: Here's a link to the Java Comparator Implementation from that site.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/104599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3333/" ] }
104,601
I want to do a Response.Redirect("MyPage.aspx") but have it open in a new browser window. I've done this before without using the JavaScript register script method. I just can't remember how?
I just found the answer and it works :) You need to add the following to your server side link/button: OnClientClick="aspnetForm.target ='_blank';" My entire button code looks something like: <asp:LinkButton ID="myButton" runat="server" Text="Click Me!" OnClick="myButton_Click" OnClientClick="aspnetForm.target ='_blank';"/> In the server side OnClick I do a Response.Redirect("MyPage.aspx"); and the page is opened in a new window. The other part you need to add is to fix the form's target otherwise every link will open in a new window. To do so add the following in the header of your POPUP window. <script type="text/javascript"> function fixform() { if (opener.document.getElementById("aspnetForm").target != "_blank") return; opener.document.getElementById("aspnetForm").target = ""; opener.document.getElementById("aspnetForm").action = opener.location.href; }</script> and <body onload="fixform()">
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/104601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
104,603
Is there a way to iterate (through foreach preferably) over a collection using reflection? I'm iterating over the properties in an object using reflection, and when the program gets to a type that is a collection, I'd like it to iterate over the contents of the collection and be able to access the objects in the collection. At the moment I have an attribute set on all of my properties, with an IsCollection flag set to true on the properties that are collections. My code checks for this flag and if it's true, it gets the Type using reflection. Is there a way to invoke GetEnumerator or Items somehow on a collection to be able to iterate over the items?
I had this issue, but instead of using reflection, i ended up just checking if it was IEnumerable. All collections implement that. if (item is IEnumerable){ foreach (object o in (item as IEnumerable)) { }} else { // reflect over item}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/104603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12999/" ] }
104,612
I want to copy a live production database into my local development database. Is there a way to do this without locking the production database? I'm currently using: mysqldump -u root --password=xxx -h xxx my_db1 | mysql -u root --password=xxx -h localhost my_db1 But it's locking each table as it runs.
Does the --lock-tables=false option work? According to the man page , if you are dumping InnoDB tables you can use the --single-transaction option: --lock-tables, -lLock all tables before dumping them. The tables are locked with READLOCAL to allow concurrent inserts in the case of MyISAM tables. Fortransactional tables such as InnoDB and BDB, --single-transaction isa much better option, because it does not need to lock the tables atall. For innodb DB : mysqldump --single-transaction=TRUE -u username -p DB
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/104612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ] }
104,618
I've been trying to get into F# on and off for a while but I keep getting put off. Why? Because no matter which 'beginners' resource I try to look at I see very simple examples that start using the operator -> . However, nowhere have I found as yet that provides a clear simple explanation of what this operator means. It's as though it must be so obvious that it doesn't need explanation even to complete newbies. I must therefore be really dense or perhaps it's nearly 3 decades of previous experience holding me back. Can someone please, explain it or point to a truly accessible resource that explains it?
'->' is not an operator. It appears in the F# syntax in a number of places, and its meaning depends on how it is used as part of a larger construct. Inside a type, '->' describes function types as people have described above. For example let f : int -> int = ... says that 'f' is a function that takes an int and returns an int. Inside a lambda ("thing that starts with 'fun' keyword"), '->' is syntax that separates the arguments from the body. For example fun x y -> x + y + 1 is an expression that defines a two argument function with the given implementation. Inside a "match" construct, '->' is syntax that separates patterns from the code that should run if the pattern is matched. For example, in match someList with| [] -> 0| h::t -> 1 the stuff to the left of each '->' are patterns, and the stuff on the right is what happens if the pattern on the left was matched. The difficulty in understanding may be rooted in the faulty assumption that '->' is "an operator" with a single meaning. An analogy might be "." in C#, if you have never seen any code before, and try to analyze the "." operator based on looking at "obj.Method" and "3.14" and "System.Collections", you may get very confused, because the symbol has different meanings in different contexts. Once you know enough of the language to recognize these contexts, however, things become clear.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/104618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17516/" ] }
104,640
By default when using a webapp server in Eclipse Web Tools, the server startup will fail after a timeout of 45 seconds. I can increase this timeout in the server instance properties, but I don't see a way to disable the timeout entirely (useful when debugging application startup). Is there a way to do this?
In Eclipse Indigo, you can edit the default timeout by double-clicking on the server in the "servers" view and changing the timeout for start (see graphic). Save your changes, and you're good to go!
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/104640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5586/" ] }
104,674
It's known that you should declare events that take as parameters (object sender, EventArgs args) . Why?
This allows the consuming developer the ability to write a single event handler for multiple events, regardless of sender or event. Edit: Why would you need a different pattern? You can inherit EventArgs to provide any amount of data, and changing the pattern is only going to serve to confuse and frustrate any developer that is forced to consume this new pattern.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/104674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ] }
104,799
Why isn't Collection.remove(Object o) generic? Seems like Collection<E> could have boolean remove(E o); Then, when you accidentally try to remove (for example) Set<String> instead of each individual String from a Collection<String> , it would be a compile time error instead of a debugging problem later.
Josh Bloch and Bill Pugh refer to this issue in Java Puzzlers IV: The Phantom Reference Menace, Attack of the Clone, and Revenge of The Shift . Josh Bloch says (6:41) that they attempted to generify the get method of Map, remove method and some other, but "it simply didn't work". There are too many reasonable programs that could not be generified if you only allow the generic type of the collection as parameter type. The example given by him is an intersection of a List of Number s and a List of Long s.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/104799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15816/" ] }
104,850
I want to try to convert a string to a Guid, but I don't want to rely on catching exceptions ( for performance reasons - exceptions are expensive for usability reasons - the debugger pops up for design reasons - the expected is not exceptional In other words the code: public static Boolean TryStrToGuid(String s, out Guid value){ try { value = new Guid(s); return true; } catch (FormatException) { value = Guid.Empty; return false; }} is not suitable. I would try using RegEx, but since the guid can be parenthesis wrapped, brace wrapped, none wrapped, makes it hard. Additionally, I thought certain Guid values are invalid(?) Update 1 ChristianK had a good idea to catch only FormatException , rather than all. Changed the question's code sample to include suggestion. Update 2 Why worry about thrown exceptions? Am I really expecting invalid GUIDs all that often? The answer is yes . That is why I am using TryStrToGuid - I am expecting bad data. Example 1 Namespace extensions can be specified by appending a GUID to a folder name . I might be parsing folder names, checking to see if the text after the final . is a GUID. c:\Program Filesc:\Program Files.oldc:\Usersc:\Users.oldc:\UserManager.{CE7F5AA5-6832-43FE-BAE1-80D14CD8F666}c:\Windowsc:\Windows.old Example 2 I might be running a heavily used web-server wants to check the validity of some posted back data. I don't want invalid data tying up resources 2-3 orders of magnitude higher than it needs to be. Example 3 I might be parsing a search expression entered by a user. If they enter GUID's I want to process them specially (such as specifically searching for that object, or highlight and format that specific search term in the response text.) Update 3 - Performance benchmarks Test converting 10,000 good Guids, and 10,000 bad Guids. Catch FormatException: 10,000 good: 63,668 ticks 10,000 bad: 6,435,609 ticksRegex Pre-Screen with try-catch: 10,000 good: 637,633 ticks 10,000 bad: 717,894 ticksCOM Interop CLSIDFromString 10,000 good: 126,120 ticks 10,000 bad: 23,134 ticks p.s. I shouldn't have to justify a question.
Performance Benchmarks Catch exception: 10,000 good: 63,668 ticks 10,000 bad: 6,435,609 ticksRegex Pre-Screen: 10,000 good: 637,633 ticks 10,000 bad: 717,894 ticksCOM Interop CLSIDFromString 10,000 good: 126,120 ticks 10,000 bad: 23,134 ticks COM Intertop (Fastest) Answer: /// <summary>/// Attempts to convert a string to a guid./// </summary>/// <param name="s">The string to try to convert</param>/// <param name="value">Upon return will contain the Guid</param>/// <returns>Returns true if successful, otherwise false</returns>public static Boolean TryStrToGuid(String s, out Guid value){ //ClsidFromString returns the empty guid for null strings if ((s == null) || (s == "")) { value = Guid.Empty; return false; } int hresult = PInvoke.ObjBase.CLSIDFromString(s, out value); if (hresult >= 0) { return true; } else { value = Guid.Empty; return false; }}namespace PInvoke{ class ObjBase { /// <summary> /// This function converts a string generated by the StringFromCLSID function back into the original class identifier. /// </summary> /// <param name="sz">String that represents the class identifier</param> /// <param name="clsid">On return will contain the class identifier</param> /// <returns> /// Positive or zero if class identifier was obtained successfully /// Negative if the call failed /// </returns> [DllImport("ole32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true)] public static extern int CLSIDFromString(string sz, out Guid clsid); }} Bottom line: If you need to check if a string is a guid, and you care about performance, use COM Interop. If you need to convert a guid in String representation to a Guid, use new Guid(someString);
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/104850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ] }
104,854
When I start Tomcat (6.0.18) from Eclipse (3.4), I receive this message (first in the log): WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server: (project name)' did not find a matching property. Seems this message does not have any severe impact, however, does anyone know how to get rid of it?
The solution to this problem is very simple. Double click on your tomcat server. It will open the server configuration. Under server options check ‘Publish module contents to separate XML files’ checkbox. Restart your server. This time your page will come without any issues.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/104854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17585/" ] }
104,866
Looking for C# class which wraps calls to do the following: read and write a key valueread & write a key entry enumerate the entries in a key. This is important. For example, need to list all entries in:HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources (I scanned through some codeproject.com registry classes and they didn't enumerate)
Microsoft.Win32.Registry
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/104866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5232/" ] }
104,918
My question is related to the command pattern, where we have the following abstraction (C# code) : public interface ICommand{ void Execute();} Let's take a simple concrete command, which aims to delete an entity from our application. A Person instance, for example. I'll have a DeletePersonCommand , which implements ICommand . This command needs the Person to delete as a parameter, in order to delete it when Execute method is called. What is the best way to manage parametrized commands ? How to pass parameters to commands, before executing them ?
You'll need to associate the parameters with the command object, either by constructor or setter injection (or equivalent). Perhaps something like this: public class DeletePersonCommand: ICommand{ private Person personToDelete; public DeletePersonCommand(Person personToDelete) { this.personToDelete = personToDelete; } public void Execute() { doSomethingWith(personToDelete); }}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/104918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4687/" ] }
104,953
I'm trying to create a horizontal 100% stacked bar graph using HTML and CSS. I'd like to create the bars using DIVs with background colors and percentage widths depending on the values I want to graph. I also want to have a grid lines to mark an arbitrary position along the graph. In my experimentation, I've already gotten the bars to stack horizontally by assigning the CSS property float: left . However, I'd like to avoid that, as it really seems to mess with the layout in confusing ways. Also, the grid lines don't seem to work very well when the bars are floated. I think that CSS positioning should be able to handle this, but I don't yet know how to do it. I want to be able to specify the position of several elements relative to the top-left corner of their container. I run into this sort of issue regularly (even outside of this particular graph project), so I'd like a method that's: Cross-browser (ideally without too many browser hacks) Runs in Quirks mode As clear/clean as possible, to facilitate customizations Done without JavaScript if possible.
You are right that CSS positioning is the way to go. Here's a quick run down: position: relative will layout an element relative to itself. In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It's important to note that because it's removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour). However, you're most likely interested in position: absolute which will position an element relative to a container. By default, the container is the browser window, but if a parent element either has position: relative or position: absolute set on it, then it will act as the parent for positioning coordinates for its children. To demonstrate: #container { position: relative; border: 1px solid red; height: 100px;}#box { position: absolute; top: 50px; left: 20px;} <div id="container"> <div id="box">absolute</div></div> In that example, the top left corner of #box would be 100px down and 50px left of the top left corner of #container . If #container did not have position: relative set, the coordinates of #box would be relative to the top left corner of the browser view port.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/104953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ] }
104,959
If I have a std::vector or std::map variable, and I want to see the contents, it's a big pain to see the nth element while debugging. Is there a plugin, or some trick to making it easier to watch STL container variables while debugging (VS2003/2005/2008) ?
For vectors, this thread on the msdn forums has a code snippet for setting a watch on a vector index that might help.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/104959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10705/" ] }
104,960
What is the best way to interact with a database using Haskell? I'm accustomed to using some sort of ORM (Django's ORM, hibernate, etc.) and something similar would be nice when creating apps with HAppS . Edit: I'd like to be free to choose from Postgresql MySql and SQLite as far as the actual databases go.
The library I have in mind is not an ORM, but it may still do what you want. If you want something that makes your database accesses safe while integrating things into your program nicely then try out HaskellDB . It basically looks at your schema, generates some data structures, and then gives you type safe ways to query. It's been around for quite a while and the community opinion is that it's good and stable. To use it, you'll need some underlying Haskell DB library like HSQL. Good luck!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/104960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3446/" ] }
104,983
In Python specifically, how do variables get shared between threads? Although I have used threading.Thread before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing? I have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem. Thanks in advance!
In Python, everything is shared, except for function-local variables (because each function call gets its own set of locals, and threads are always separate function calls.) And even then, only the variables themselves (the names that refer to objects) are local to the function; objects themselves are always global, and anything can refer to them.The Thread object for a particular thread is not a special object in this regard. If you store the Thread object somewhere all threads can access (like a global variable) then all threads can access that one Thread object. If you want to atomically modify anything that another thread has access to, you have to protect it with a lock. And all threads must of course share this very same lock, or it wouldn't be very effective. If you want actual thread-local storage, that's where threading.local comes in. Attributes of threading.local are not shared between threads; each thread sees only the attributes it itself placed in there. If you're curious about its implementation, the source is in _threading_local.py in the standard library.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/104983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19215/" ] }
105,007
I have read this post about how to test private methods. I usually do not test them, because I always thought it's faster to test only public methods that will be called from outside the object. Do you test private methods? Should I always test them?
I do not unit test private methods. A private method is an implementation detail that should be hidden to the users of the class. Testing private methods breaks encapsulation. If I find that the private method is huge or complex or important enough to require its own tests, I just put it in another class and make it public there ( Method Object ). Then I can easily test the previously-private-but-now-public method that now lives on its own class.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/105007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ] }
105,014
A while ago I came across some code that marked a member variable of a class with the mutable keyword. As far as I can see it simply allows you to modify a variable in a const method: class Foo { private: mutable bool done_; public: void doSomething() const { ...; done_ = true; } }; Is this the only use of this keyword or is there more to it than meets the eye? I have since used this technique in a class, marking a boost::mutex as mutable allowing const functions to lock it for thread-safety reasons, but, to be honest, it feels like a bit of a hack.
It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result. Since c++11 mutable can be used on a lambda to denote that things captured by value are modifiable (they aren't by default): int x = 0;auto f1 = [=]() mutable {x = 42;}; // OKauto f2 = [=]() {x = 42;}; // Error: a by-value capture cannot be modified in a non-mutable lambda
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/105014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ] }
105,031
Using C#, I want to get the total amount of RAM that my computer has.With the PerformanceCounter I can get the amount of Available ram, by setting: counter.CategoryName = "Memory";counter.Countername = "Available MBytes"; But I can't seem to find a way to get the total amount of memory. How would I go about doing this? Update: MagicKat: I saw that when I was searching, but it doesn't work - "Are you missing an assembly or reference?". I've looked to add that to the References, but I don't see it there.
Add a reference to Microsoft.VisualBasic and a using Microsoft.VisualBasic.Devices; . The ComputerInfo class has all the information that you need.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/105031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13713/" ] }
105,034
How do I create GUIDs (globally-unique identifiers) in JavaScript? The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around. I'm not sure what routines are available on all browsers, how "random" and seeded the built-in random number generator is, etc.
UUIDs (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDentifier), according to RFC 4122 , are identifiers designed to provide certain uniqueness guarantees. While it is possible to implement RFC-compliant UUIDs in a few lines of JavaScript code (e.g., see @broofa's answer , below) there are several common pitfalls: Invalid id format (UUIDs must be of the form " xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx ", where x is one of [0-9, a-f] M is one of [1-5], and N is [8, 9, a, or b] Use of a low-quality source of randomness (such as Math.random ) Thus, developers writing code for production environments are encouraged to use a rigorous, well-maintained implementation such as the uuid module.
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/105034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4926/" ] }
105,075
I'd like to run a long rsync command in Cygwin by double clicking on a .sh file in Windows. It must start in the file's containing directory (e.g. /cygdrive/c/scripts/) so that relative paths work. Anyone gotten this to work? Note: I've just found here , a Cygwin package that manages Windows context menus (Bash Prompt Here). It might have some clues.
Ok, I've found something that works. Associating a batch file as Vladimir suggested didn't work, but the bash arguments were key. Short and sweet: associate with this command: "C:\cygwin\bin\bash.exe" -li "%1" %* Long version if you don't know how: In Explorer, go to Tools/Folder Options/File Types. I already had an SH entry for Bash Script. If you don't have one, click New and enter "SH" to create one. With the SH extension selected, click Advanced. Choose the "open" action and click edit (or create the action). This is the command to use: "C:\cygwin\bin\bash.exe" -li "%1" %* . Note that without the -li , it was returing "command not found" on my scripts. You may also want to add SH to your PATHEXT environment variable: WinKey+Pause / Advanced / Environment Variables / System Variables / PATHEXT Thanks for your help, guys!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/105075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1701/" ] }
105,095
If you are relying on an implementation of Python that has a Global Interpreter Lock (i.e. CPython) and writing multithreaded code, do you really need locks at all? If the GIL doesn't allow multiple instructions to be executed in parallel, wouldn't shared data be unnecessary to protect? sorry if this is a dumb question, but it is something I have always wondered about Python on multi-processor/core machines. same thing would apply to any other language implementation that has a GIL.
You will still need locks if you share state between threads. The GIL only protects the interpreter internally. You can still have inconsistent updates in your own code. For example: #!/usr/bin/env pythonimport threadingshared_balance = 0class Deposit(threading.Thread): def run(self): for _ in xrange(1000000): global shared_balance balance = shared_balance balance += 100 shared_balance = balanceclass Withdraw(threading.Thread): def run(self): for _ in xrange(1000000): global shared_balance balance = shared_balance balance -= 100 shared_balance = balancethreads = [Deposit(), Withdraw()]for thread in threads: thread.start()for thread in threads: thread.join()print shared_balance Here, your code can be interrupted between reading the shared state ( balance = shared_balance ) and writing the changed result back ( shared_balance = balance ), causing a lost update. The result is a random value for the shared state. To make the updates consistent, run methods would need to lock the shared state around the read-modify-write sections (inside the loops) or have some way to detect when the shared state had changed since it was read .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/105095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16148/" ] }
105,113
Most of us have already used the casual patterns such as MVC , strategy , etc. But there must be some unusual solutions to unusual problems, and I'd like to hear about it.
Crash Only Software: http://www.usenix.org/events/hotos03/tech/full_papers/candea/candea_html/ Abstract Crash-only programs crash safely and recover quickly. There is only one way to stop such software -- by crashing it -- and only one way to bring it up -- by initiating recovery. Crash-only systems are built from crash-only components, and the use of transparent component-level retries hides intra-system component crashes from end users. In this paper we advocate a crash-only design for Internet systems, showing that it can lead to more reliable, predictable code and faster, more effective recovery. We present ideas on how to build such crash-only Internet services, taking successful techniques to their logical extreme.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/105113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ] }
105,130
What are the major reasons for using WinDbg vs the Visual Studio debugger? And is it commonly used as a complete replacement for the Visual Studio debugger, or more for when the need arises.
If you are wondering why you should use windbg over Visual Studio, then you need to read Advanced Windows Debugging . Any time you need to debug a truly ugly problem windbg has better technology to do it with than Visual Studio. Windbg has a more powerful scripting language and allows you to write DLLs to automate difficult problems. It will install gflags.exe, which gives you better control over the heap for debugging memory overwrites. You don't actually need to run the install, you can just copy the files over and be ready to go. Also it installs adsplus.vb, so you can take mini-dumps of running processes. It is also very easy to setup to perform remote debugging. There is nothing better than being able to debug a problem from your own desk instead of fighting the 15" monitor that flickers on a test PC. For day to day code writing I use Visual Studio, but once you need to start debugging problems from other computers or find yourself in a very ugly situation, windbg is the only way to go. Spending some time learning windbg is a great investment. Also if you look at crash dumps there are two great resources, http://www.dumpanalysis.org/blog and http://blogs.msdn.com/ntdebugging/default.aspx that do all their debugging using windbg.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/105130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19263/" ] }
105,147
Working on a new back end system for my company, and one of their requests is for a window to become locked down and for the user to be sent to the login screen if they leave it idle for to long. I figure I'd do this with JavaScript by attaching listeners to clicks, mouse moves and key-ups but I worry about messing with other scripts. Any suggestions?
If you are wondering why you should use windbg over Visual Studio, then you need to read Advanced Windows Debugging . Any time you need to debug a truly ugly problem windbg has better technology to do it with than Visual Studio. Windbg has a more powerful scripting language and allows you to write DLLs to automate difficult problems. It will install gflags.exe, which gives you better control over the heap for debugging memory overwrites. You don't actually need to run the install, you can just copy the files over and be ready to go. Also it installs adsplus.vb, so you can take mini-dumps of running processes. It is also very easy to setup to perform remote debugging. There is nothing better than being able to debug a problem from your own desk instead of fighting the 15" monitor that flickers on a test PC. For day to day code writing I use Visual Studio, but once you need to start debugging problems from other computers or find yourself in a very ugly situation, windbg is the only way to go. Spending some time learning windbg is a great investment. Also if you look at crash dumps there are two great resources, http://www.dumpanalysis.org/blog and http://blogs.msdn.com/ntdebugging/default.aspx that do all their debugging using windbg.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/105147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9176/" ] }
105,198
I'm still a little unclear and when to wrap a lock around some code. My general rule-of-thumb is to wrap an operation in a lock when it reads or writes to a static variable. But when a static variable is ONLY read (e.g. it's a readonly that is set during type initialization), accessing it doesn't need to be wrapped in a lock statement, right? I recently saw some code that looked like the following example, and it made me think there may be some gaps in my multithreading knowledge: class Foo{ private static readonly string bar = "O_o"; private bool TrySomething() { string bar; lock(Foo.objectToLockOn) { bar = Foo.bar; } // Do something with bar }} That just doesn't make sense to me--why would there by concurrency issues with READING a register? Also, this example brings up another question. Is one of these better than the other? (E.g. example two holds the lock for less time?) I suppose I could disassemble the MSIL... class Foo{ private static string joke = "yo momma"; private string GetJoke() { lock(Foo.objectToLockOn) { return Foo.joke; } }} vs. class Foo{ private static string joke = "yo momma"; private string GetJoke() { string joke; lock(Foo.objectToLockOn) { joke = Foo.joke; } return joke; }}
Since none of the code you've written modifies the static field after initialization, there is no need for any locking. Just replacing the string with a new value won't need synchronization either, unless the new value depends on the results of a read of the old value. Static fields aren't the only things that need synchronization, any shared reference which could be modified is vulnerable to synchronization issues. class Foo{ private int count = 0; public void TrySomething() { count++; }} You might suppose that two threads executing the TrySomething method would be fine. But its not. Thread A reads the value of count (0) into a register so it can be incremented. Context switch! The thread scheduler decides thread A has had enough execution time. Next in line is Thread B. Thread B reads the value of count (0) into a register. Thread B increments the register. Thread B saves the result (1) to count. Context switch back to A. Thread A reloads the register with the value of count (0) saved on its stack. Thread A increments the register. Thread A saves the result (1) to count. So, even though we called count++ twice, the value of count has just gone from 0 to 1. Lets make the code thread-safe: class Foo{ private int count = 0; private readonly object sync = new object(); public void TrySomething() { lock(sync) count++; }} Now when Thread A gets interrupted Thread B cannot mess with count because it will hit the lock statement and then block until Thread A has released sync. By the way, there is an alternative way to make incrementing Int32s and Int64s thread-safe: class Foo{ private int count = 0; public void TrySomething() { System.Threading.Interlocked.Increment(ref count); }} Regarding the second part of your question, I think I would just go with whichever is easier to read, any performance difference there will be negligible. Early optimisation is the root of all evil, etc. Why threading is hard
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/105198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ] }
105,212
Suppose I have a directory /dir inside which there are 3 symlinks to other directories /dir/dir11 , /dir/dir12 , and /dir/dir13 . I want to list all the files in dir including the ones in dir11 , dir12 and dir13 . To be more generic, I want to list all files including the ones in the directories which are symlinks. find . , ls -R , etc stop at the symlink without navigating into them to list further.
The -L option to ls will accomplish what you want. It dereferences symbolic links. So your command would be: ls -LR You can also accomplish this with find -follow The -follow option directs find to follow symbolic links to directories. On Mac OS X use find -L as -follow has been deprecated.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/105212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18072/" ] }
105,252
How do I convert between big-endian and little-endian values in C++? For clarity, I have to translate binary data (double-precision floating point values and 32-bit and 64-bit integers) from one CPU architecture to another. This doesn't involve networking, so ntoh() and similar functions won't work here. Note: The answer I accepted applies directly to compilers I'm targeting (which is why I chose it). However, there are other very good, more portable answers here.
If you're using Visual C++ do the following: You include intrin.h and call the following functions: For 16 bit numbers: unsigned short _byteswap_ushort(unsigned short value); For 32 bit numbers: unsigned long _byteswap_ulong(unsigned long value); For 64 bit numbers: unsigned __int64 _byteswap_uint64(unsigned __int64 value); 8 bit numbers (chars) don't need to be converted. Also these are only defined for unsigned values they work for signed integers as well. For floats and doubles it's more difficult as with plain integers as these may or not may be in the host machines byte-order. You can get little-endian floats on big-endian machines and vice versa. Other compilers have similar intrinsics as well. In GCC for example you can directly call some builtins as documented here : uint32_t __builtin_bswap32 (uint32_t x)uint64_t __builtin_bswap64 (uint64_t x) (no need to include something). Afaik bits.h declares the same function in a non gcc-centric way as well. 16 bit swap it's just a bit-rotate. Calling the intrinsics instead of rolling your own gives you the best performance and code density btw..
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/105252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19129/" ] }
105,264
I'm new to the WCSF and can't seem to find anything related to "building a custom template" for creating the views/presenters/code-behinds/etc with your own flavor ... Can anyone point me in the right direction?
If you're using Visual C++ do the following: You include intrin.h and call the following functions: For 16 bit numbers: unsigned short _byteswap_ushort(unsigned short value); For 32 bit numbers: unsigned long _byteswap_ulong(unsigned long value); For 64 bit numbers: unsigned __int64 _byteswap_uint64(unsigned __int64 value); 8 bit numbers (chars) don't need to be converted. Also these are only defined for unsigned values they work for signed integers as well. For floats and doubles it's more difficult as with plain integers as these may or not may be in the host machines byte-order. You can get little-endian floats on big-endian machines and vice versa. Other compilers have similar intrinsics as well. In GCC for example you can directly call some builtins as documented here : uint32_t __builtin_bswap32 (uint32_t x)uint64_t __builtin_bswap64 (uint64_t x) (no need to include something). Afaik bits.h declares the same function in a non gcc-centric way as well. 16 bit swap it's just a bit-rotate. Calling the intrinsics instead of rolling your own gives you the best performance and code density btw..
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/105264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2701/" ] }
105,311
What is a "table-driven method"? As mentioned by Bill Gates in the second Windows Vista commercial at 1:05.
Table-driven methods are schemes that allow you to look up information in a table rather than using logic statements (i.e. case, if). In simple cases, it's quicker and easier to use logic statements, but as the logic chain becomes more complex, table-driven code is simpler than complicated logic, easier to modify and more efficient. Reference: McConnell, Steve. Code Complete, Second Edition. Redmond (Washington): Microsoft, 2004. Print. Page 411, Paragraph 1.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/105311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19272/" ] }
105,372
How can you enumerate an enum in C#? E.g. the following code does not compile: public enum Suit{ Spades, Hearts, Clubs, Diamonds}public void EnumerateAllSuitsDemoMethod(){ foreach (Suit suit in Suit) { DoSomething(suit); }} And it gives the following compile-time error: 'Suit' is a 'type' but is used like a 'variable' It fails on the Suit keyword, the second one.
foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit))){} Note : The cast to (Suit[]) is not strictly necessary, but it does make the code 0.5 ns faster .
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/105372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ] }
105,400
I am maintaining a pretty sizable application and database and am noticing some poor database performance in a few of our stored procedures. I always hear that "adding an index" can be done to help performance. I am certainly no DBA, and I do not understand what indexes are, why they help, and how to create them. I basically need an indexes 101. Can anyone give me resources so that I can learn?
Think of an index similar to a card catalog in the library. An index keeps you from having to search through every isle or shelf for a book. Instead, you may be able to find the items you want from a commonly used field, such as and ID, Name, etc. When you build an index the database basically creates something separate that a query could hit to rather than scanning the entire table. You speed up the query by allowing it to search a smaller subset of data, or an optimized set of data.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/105400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ] }
105,418
I want to be able to figure out what port a particular program is using. Are there any programs available online or that come with windows that will tell me which processes are using which ports on my computer? PS - before you downmod this for not being a programming question, I'm looking for the program to test some networking code.
netstat -b -a lists the ports in use and gives you the executable that's using each one. I believe you need to be in the administrator group to do this, and I don't know what security implications there are on Vista. I usually add -n as well to make it a little faster, but adding -b can make it quite slow. Edit : If you need more functionality than netstat provides, vasac suggests that you try TCPView .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/105418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5021/" ] }
105,477
I think I've got it down to the most basic case: int main(int argc, char ** argv) { int * arr; foo(arr); printf("car[3]=%d\n",arr[3]); free (arr); return 1;}void foo(int * arr) { arr = (int*) malloc( sizeof(int)*25 ); arr[3] = 69;} The output is this: > ./a.out car[3]=-1869558540 a.out(4100) malloc: *** error for object 0x8fe01037: Non-aligned pointer being freed *** set a breakpoint in malloc_error_break to debug> If anyone can shed light on where my understanding is failing, it'd be greatly appreciated.
You pass the pointer by value, not by reference, so whatever you do with arr inside foo will not make a difference outside the foo-function. As m_pGladiator wrote one way is to declare a reference to pointer like this (only possible in C++ btw. C does not know about references): int main(int argc, char ** argv) { int * arr; foo(arr); printf("car[3]=%d\n",arr[3]); free (arr); return 1;}void foo(int * &arr ) { arr = (int*) malloc( sizeof(int)*25 ); arr[3] = 69;} Another (better imho) way is to not pass the pointer as an argument but to return a pointer: int main(int argc, char ** argv) { int * arr; arr = foo(); printf("car[3]=%d\n",arr[3]); free (arr); return 1;}int * foo(void ) { int * arr; arr = (int*) malloc( sizeof(int)*25 ); arr[3] = 69; return arr;} And you can pass a pointer to a pointer. That's the C way to pass by reference. Complicates the syntax a bit but well - that's how C is... int main(int argc, char ** argv) { int * arr; foo(&arr); printf("car[3]=%d\n",arr[3]); free (arr); return 1;}void foo(int ** arr ) { (*arr) = (int*) malloc( sizeof(int)*25 ); (*arr)[3] = 69;}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/105477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
105,546
We have got loads of options for php + MySQL + Apache combo... Which is the best pack among these ? Lets confine our ideas to WAMP vs XAMPP , is there a better option to go for? I created an online programming contest web app called CodeFire on XAMPP , later I had to switch to WAMP , where none of the php scripts worked properly... what standard should I follow?
I like XAMPP, personally. I have an install running on a thumbdrive that I carry around that's pretty much my development environment for LAMP web dev on any machine I happen to be at (I'm mostly on Windows client machines). Small, fully-functional, and stable - works really well for my needs.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/105546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8786/" ] }
105,564
The original query looks like this (MySQL): SELECT * FROM books WHERE title LIKE "%text%" OR description LIKE "%text%" ORDER BY date Would it be possible to rewrite it (without unions or procedures), so that result will look like this: list of books where title matches query ordered by date, followed by: list of books where description matches query ordered by date So basically just give a higher priority to matching titles over descriptions.
In sql server I would do the following: select * from books where title like '%text%' or description like '%text%'order by case when title like '%text%' then 1 else 2 end, date I'm not sure if you can include columns in ORDER BY in mysql that aren't in the SELECT, but that's the principle I'd use. Otherwise, just include the derived column in the SELECT as well.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/105564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20128/" ] }
105,572
Is there a SQL or PHP script that I can run that will change the default collation in all tables and fields in a database? I can write one myself, but I think that this should be something that readily available at a site like this. If I can come up with one myself before somebody posts one, I will post it myself.
Be careful! If you actually have utf stored as another encoding, you could have a real mess on your hands. Back up first. Then try some of the standard methods: for instance http://www.cesspit.net/drupal/node/898 http://www.hackszine.com/blog/archive/2007/05/mysql_database_migration_latin.html I've had to resort to converting all text fields to binary, then back to varchar/text. This has saved my ass. I had data is UTF8, stored as latin1. What I did: Drop indexes.Convert fields to binary.Convert to utf8-general ci If your on LAMP, don’t forget to add set NAMES command before interacting with the db, and make sure you set character encoding headers.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/105572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
105,613
Is it possible to use XPath to select only the nodes that have a particular child elements? For example, from this XML I only want the elements in pets that have a child of 'bar'. So the resulting dataset would contain the lizard and pig elements from this example: <pets> <cat> <foo>don't care about this</foo> </cat> <dog> <foo>not this one either</foo> </dog> <lizard> <bar>lizard should be returned, because it has a child of bar</bar> </lizard> <pig> <bar>return pig, too</bar> </pig></pets> This Xpath gives me all pets: "/pets/*" , but I only want the pets that have a child node of name 'bar' .
Here it is, in all its glory /pets/*[bar] English: Give me all children of pets that have a child bar
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/105613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10876/" ] }
105,642
Update : Looks like the query does not throw any timeout. The connection is timing out. This is a sample code for executing a query. Sometimes, while executing time consuming queries, it throws a timeout exception. I cannot use any of these techniques:1) Increase timeout.2) Run it asynchronously with a callback. This needs to run in a synchronous manner. please suggest any other techinques to keep the connection alive while executing a time consuming query? private static void CreateCommand(string queryString, string connectionString){ using (SqlConnection connection = new SqlConnection( connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); command.Connection.Open(); command.ExecuteNonQuery(); }}
Since you are using ExecuteNonQuery which does not return any rows, you can try this polling based approach. It executes the query in an asyc manner (without callback)but the application will wait (inside a while loop) until the query is complete. From MSDN . This should solve the timeout problem. Please try it out. But, I agree with others that you should think more about optimizing the query to perform under 30 seconds. IAsyncResult result = command.BeginExecuteNonQuery(); int count = 0; while (!result.IsCompleted) { Console.WriteLine("Waiting ({0})", count++); System.Threading.Thread.Sleep(1000); } Console.WriteLine("Command complete. Affected {0} rows.", command.EndExecuteNonQuery(result));
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/105642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19306/" ] }
105,659
I know there's no standard C function to do this. I was wondering what are the techniques to to this on Windows and *nix? (Windows XP is my most important OS to do this on right now.)
glibc provides backtrace() function. http://www.gnu.org/software/libc/manual/html_node/Backtraces.html
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/105659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6386/" ] }
105,702
I'm about to put a beta version of the site I'm working on up on the web. It needs to have a beta code to restrict access. The site is written in django. I don't want to change the fundamental Auth system to accommodate a beta code, and I don't care particularly that the security of the beta code is iron-clad, just that it's a significant stumbling block. How should I do this? It's a fairly large project, so adding code to every view is far from ideal. That solution works well. The Middleware Class I ended up with this this: from django.http import HttpResponseRedirectclass BetaMiddleware(object): """ Require beta code session key in order to view any page. """ def process_request(self, request): if request.path != '/beta/' and not request.session.get('in_beta'): return HttpResponseRedirect('%s?next=%s' % ('/beta/', request.path))
Start with this Django snippet , but modify it to check request.session['has_beta_access'] . If they don't have it, then have it return a redirect to a "enter beta code" page that, when posted to with the right code, sets that session variable to True . Making it a public beta then just consists of removing that middleware from your MIDDLEWARE_CLASSES setting.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/105702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6007/" ] }
105,721
I know how to generally move around in command mode, specifically, jumping to lines, etc. But what is the command to jump to the end of the line that I am currently on?
Just the $ (dollar sign) key. You can use A to move to the end of the line and switch to editing mode (Append). To jump the last non-blank character, you can press g then _ keys. The opposite of A is I (Insert mode at beginning of line), as an aside. Pressing just the ^ will place your cursor at the first non-white-space character of the line.
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/105721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/757/" ] }
105,725
I have seen a lot of C/C++ based solutions to this problem where we have to write a program that upon execution prints its own source. some solutions -- http://www.cprogramming.com/challenges/solutions/self_print.html Quine Page solution in many languages There are many more solutions on the net, each different from the other. I wonder how do we approach to such a problem, what goes inside the mind of the one who solves it. Lend me some insights into this problem... While solutions in interpreted languages like perl, php, ruby, etc might be easy... i would like to know how does one go about designing it in compiled languages...
Aside from cheating¹ there is no difference between compiled and interpreted languages. The generic approach to quines is quite easy. First, whatever the program looks like, at some point it has to print something: print ... However, what should it print? Itself. So it needs to print the "print" command: print "print ..." What should it print next? Well, in the mean time the program grew, so it needs to print the string starting with "print", too: print "print \"print ...\"" Now the program grew again, so there's again more to print: print "print \"print \\\"...\\\"\"" And so on.With every added code there's more code to print.This approach is getting nowhere,but it reveals an interesting pattern:The string "print \"" is repeated over and over again.It would be nice to put the repeating partinto a variable: a = "print \""print a However, the program just changed,so we need to adjust a: a = "a = ...\nprint a"print a When we now try to fill in the "...",we run into the same problems as before.Ultimately, we want to write something like this: a = "a = " + (quoted contents of a) + "\nprint a"print a But that is not possible,because even if we had such a function quoted() for quoting,there's still the problem that we define a in terms of itself: a = "a = " + quoted(a) + "\nprint a"print a So the only thing we can do is putting a place holder into a : a = "a = @\nprint a"print a And that's the whole trick!Anything else is now clear.Simply replace the place holderwith the quoted contents of a : a = "a = @\nprint a"print a.replace("@", quoted(a)) Since we have changed the code,we need to adjust the string: a = "a = @\nprint a.replace(\"@\", quoted(a))"print a.replace("@", quoted(a)) And that's it!All quines in all languages work that way(except the cheating ones). Well, you should ensure that you replace onlythe first occurence of the place holder.And if you use a second place holder,you can avoid needing to quote the string. But those are minor issuesand easy to solve.If fact, the realization of quoted() and replace() are the only details in which the various quines really differ. ¹ by making the program read its source file
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/105725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8786/" ] }
105,770
I want to add a comma in the thousands place for a number. Would String.Format() be the correct path to take? What format would I use?
String.Format("{0:n}", 1234); // Output: 1,234.00String.Format("{0:n0}", 9876); // No digits after the decimal point. Output: 9,876
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/105770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ] }
105,776
I was given a MySQL database file that I need to restore as a database on my Windows Server 2008 machine. I tried using MySQL Administrator, but I got the following error: The selected file was generated by mysqldump and cannot be restored by this application. How do I get this working?
It should be as simple as running this: mysql -u <user> -p < db_backup.dump If the dump is of a single database you may have to add a line at the top of the file: USE <database-name-here>; If it was a dump of many databases, the use statements are already in there. To run these commands, open up a command prompt (in Windows) and cd to the directory where the mysql.exe executable is (you may have to look around a bit for it, it'll depend on how you installed mysql, i.e. standalone or as part of a package like WAMP). Once you're in that directory, you should be able to just type the command as I have it above.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/105776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ] }
105,788
coming back to postgresql after several years of oracle ... what are the state-of-the art postgresql administrative/ddl generating/data inserting frontends on windows? it would be nice if it had integration for postgis as well. it should be standalone or alternatively a plugin for intellij idea thinking back, all the windows programs specific for postgresql i have used were crap, especially PGAdmin. had it become better?
I like Postgresql Maestro . I also use their version for MySql. I'm pretty statisfied with their product. Or you can use the free tool PgAdmin.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/105788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16542/" ] }
105,834
I saw this quote on the question: What is a good functional language on which to build a web service? Scala in particular doesn't support tail-call elimination except in self-recursive functions, which limits the kinds of composition you can do (this is a fundamental limitation of the JVM). Is this true? If so, what is it about the JVM that creates this fundamental limitation?
This post: Recursion or Iteration? might help. In short, tail call optimization is hard to do in the JVM because of the security model and the need to always have a stack trace available. These requirements could in theory be supported, but it would probably require a new bytecode (see John Rose's informal proposal ). There is also more discussion in Sun bug #4726340 , where the evaluation (from 2002) ends: I believe this could be done nonetheless, but it is not a small task. Currently, there is some work going on in the Da Vinci Machine project. The tail call subproject's status is listed as "proto 80%"; it is unlikely to make it into Java 7, but I think it has a very good chance at Java 8.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/105834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5113/" ] }
105,838
What are real-world problems where a recursive approach is the natural solution besides depth-first search (DFS)? (I don't consider Tower of Hanoi , Fibonacci number , or factorial real-world problems. They are a bit contrived in my mind.)
A real world example of recursion
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/105838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19324/" ] }
105,852
After reading " What’s your/a good limit for cyclomatic complexity? ", I realize many of my colleagues were quite annoyed with this new QA policy on our project: no more 10 cyclomatic complexity per function. Meaning: no more than 10 'if', 'else', 'try', 'catch' and other code workflow branching statement. Right. As I explained in ' Do you test private method? ', such a policy has many good side-effects. But: At the beginning of our (200 people - 7 years long) project, we were happily logging (and no, we can not easily delegate that to some kind of ' Aspect-oriented programming ' approach for logs). myLogger.info("A String");myLogger.fine("A more complicated String");... And when the first versions of our System went live, we experienced huge memory problem not because of the logging (which was at one point turned off), but because of the log parameters (the strings), which are always calculated, then passed to the 'info()' or 'fine()' functions, only to discover that the level of logging was 'OFF', and that no logging were taking place! So QA came back and urged our programmers to do conditional logging. Always. if(myLogger.isLoggable(Level.INFO) { myLogger.info("A String");if(myLogger.isLoggable(Level.FINE) { myLogger.fine("A more complicated String");... But now, with that 'can-not-be-moved' 10 cyclomatic complexity level per function limit, they argue that the various logs they put in their function is felt as a burden, because each "if(isLoggable())" is counted as +1 cyclomatic complexity! So if a function has 8 'if', 'else' and so on, in one tightly-coupled not-easily-shareable algorithm, and 3 critical log actions... they breach the limit even though the conditional logs may not be really part of said complexity of that function... How would you address this situation ? I have seen a couple of interesting coding evolution (due to that 'conflict') in my project, but I just want to get your thoughts first. Thank you for all the answers. I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing) So when a wrote above "A String", I actually meant aFunction(), with aFunction() returning a String, and being a call to a complicated method collecting and computing all kind of log data to be displayed by the logger... or not (hence the issue, and the obligation to use conditional logging, hence the actual issue of artificial increase of 'cyclomatic complexity'...) I now get the ' variadic function' point advanced by some of you (thank you John). Note: a quick test in java6 shows that my varargs function does evaluate its arguments before being called, so it can not be applied for function call, but for 'Log retriever object' (or 'function wrapper'), on which the toString() will only be called if needed. Got it. I have now posted my experience on this topic. I will leave it there until next Tuesday for voting, then I will select one of your answers. Again, thank you for all the suggestions :)
With current logging frameworks, the question is moot Current logging frameworks like slf4j or log4j 2 don't require guard statements in most cases. They use a parameterized log statement so that an event can be logged unconditionally, but message formatting only occurs if the event is enabled. Message construction is performed as needed by the logger, rather than pre-emptively by the application. If you have to use an antique logging library, you can read on to get more background and a way to retrofit the old library with parameterized messages. Are guard statements really adding complexity? Consider excluding logging guards statements from the cyclomatic complexity calculation. It could be argued that, due to their predictable form, conditional logging checks really don't contribute to the complexity of the code. Inflexible metrics can make an otherwise good programmer turn bad. Be careful! Assuming that your tools for calculating complexity can't be tailored to that degree, the following approach may offer a work-around. The need for conditional logging I assume that your guard statements were introduced because you had code like this: private static final Logger log = Logger.getLogger(MyClass.class);Connection connect(Widget w, Dongle d, Dongle alt) throws ConnectionException{ log.debug("Attempting connection of dongle " + d + " to widget " + w); Connection c; try { c = w.connect(d); } catch(ConnectionException ex) { log.warn("Connection failed; attempting alternate dongle " + d, ex); c = w.connect(alt); } log.debug("Connection succeeded: " + c); return c;} In Java, each of the log statements creates a new StringBuilder , and invokes the toString() method on each object concatenated to the string. These toString() methods, in turn, are likely to create StringBuilder instances of their own, and invoke the toString() methods of their members, and so on, across a potentially large object graph. (Before Java 5, it was even more expensive, since StringBuffer was used, and all of its operations are synchronized.) This can be relatively costly, especially if the log statement is in some heavily-executed code path. And, written as above, that expensive message formatting occurs even if the logger is bound to discard the result because the log level is too high. This leads to the introduction of guard statements of the form: if (log.isDebugEnabled()) log.debug("Attempting connection of dongle " + d + " to widget " + w); With this guard, the evaluation of arguments d and w and the string concatenation is performed only when necessary. A solution for simple, efficient logging However, if the logger (or a wrapper that you write around your chosen logging package) takes a formatter and arguments for the formatter, the message construction can be delayed until it is certain that it will be used, while eliminating the guard statements and their cyclomatic complexity. public final class FormatLogger{ private final Logger log; public FormatLogger(Logger log) { this.log = log; } public void debug(String formatter, Object... args) { log(Level.DEBUG, formatter, args); } … &c. for info, warn; also add overloads to log an exception … public void log(Level level, String formatter, Object... args) { if (log.isEnabled(level)) { /* * Only now is the message constructed, and each "arg" * evaluated by having its toString() method invoked. */ log.log(level, String.format(formatter, args)); } }}class MyClass { private static final FormatLogger log = new FormatLogger(Logger.getLogger(MyClass.class)); Connection connect(Widget w, Dongle d, Dongle alt) throws ConnectionException { log.debug("Attempting connection of dongle %s to widget %s.", d, w); Connection c; try { c = w.connect(d); } catch(ConnectionException ex) { log.warn("Connection failed; attempting alternate dongle %s.", d); c = w.connect(alt); } log.debug("Connection succeeded: %s", c); return c; }} Now, none of the cascading toString() calls with their buffer allocations will occur unless they are necessary! This effectively eliminates the performance hit that led to the guard statements. One small penalty, in Java, would be auto-boxing of any primitive type arguments you pass to the logger. The code doing the logging is arguably even cleaner than ever, since untidy string concatenation is gone. It can be even cleaner if the format strings are externalized (using a ResourceBundle ), which could also assist in maintenance or localization of the software. Further enhancements Also note that, in Java, a MessageFormat object could be used in place of a "format" String , which gives you additional capabilities such as a choice format to handle cardinal numbers more neatly. Another alternative would be to implement your own formatting capability that invokes some interface that you define for "evaluation", rather than the basic toString() method.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/105852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6309/" ] }
105,884
I have an .Net MVC application which runs fine if I use the build in Visual Studio Webserver. If I use the projects property pages to switch to IIS as the webserver and create a virtual directory for my project, any request I send to the server results in a "Directory listing denied" failure. Does anyone know a solution for this?
With current logging frameworks, the question is moot Current logging frameworks like slf4j or log4j 2 don't require guard statements in most cases. They use a parameterized log statement so that an event can be logged unconditionally, but message formatting only occurs if the event is enabled. Message construction is performed as needed by the logger, rather than pre-emptively by the application. If you have to use an antique logging library, you can read on to get more background and a way to retrofit the old library with parameterized messages. Are guard statements really adding complexity? Consider excluding logging guards statements from the cyclomatic complexity calculation. It could be argued that, due to their predictable form, conditional logging checks really don't contribute to the complexity of the code. Inflexible metrics can make an otherwise good programmer turn bad. Be careful! Assuming that your tools for calculating complexity can't be tailored to that degree, the following approach may offer a work-around. The need for conditional logging I assume that your guard statements were introduced because you had code like this: private static final Logger log = Logger.getLogger(MyClass.class);Connection connect(Widget w, Dongle d, Dongle alt) throws ConnectionException{ log.debug("Attempting connection of dongle " + d + " to widget " + w); Connection c; try { c = w.connect(d); } catch(ConnectionException ex) { log.warn("Connection failed; attempting alternate dongle " + d, ex); c = w.connect(alt); } log.debug("Connection succeeded: " + c); return c;} In Java, each of the log statements creates a new StringBuilder , and invokes the toString() method on each object concatenated to the string. These toString() methods, in turn, are likely to create StringBuilder instances of their own, and invoke the toString() methods of their members, and so on, across a potentially large object graph. (Before Java 5, it was even more expensive, since StringBuffer was used, and all of its operations are synchronized.) This can be relatively costly, especially if the log statement is in some heavily-executed code path. And, written as above, that expensive message formatting occurs even if the logger is bound to discard the result because the log level is too high. This leads to the introduction of guard statements of the form: if (log.isDebugEnabled()) log.debug("Attempting connection of dongle " + d + " to widget " + w); With this guard, the evaluation of arguments d and w and the string concatenation is performed only when necessary. A solution for simple, efficient logging However, if the logger (or a wrapper that you write around your chosen logging package) takes a formatter and arguments for the formatter, the message construction can be delayed until it is certain that it will be used, while eliminating the guard statements and their cyclomatic complexity. public final class FormatLogger{ private final Logger log; public FormatLogger(Logger log) { this.log = log; } public void debug(String formatter, Object... args) { log(Level.DEBUG, formatter, args); } … &c. for info, warn; also add overloads to log an exception … public void log(Level level, String formatter, Object... args) { if (log.isEnabled(level)) { /* * Only now is the message constructed, and each "arg" * evaluated by having its toString() method invoked. */ log.log(level, String.format(formatter, args)); } }}class MyClass { private static final FormatLogger log = new FormatLogger(Logger.getLogger(MyClass.class)); Connection connect(Widget w, Dongle d, Dongle alt) throws ConnectionException { log.debug("Attempting connection of dongle %s to widget %s.", d, w); Connection c; try { c = w.connect(d); } catch(ConnectionException ex) { log.warn("Connection failed; attempting alternate dongle %s.", d); c = w.connect(alt); } log.debug("Connection succeeded: %s", c); return c; }} Now, none of the cascading toString() calls with their buffer allocations will occur unless they are necessary! This effectively eliminates the performance hit that led to the guard statements. One small penalty, in Java, would be auto-boxing of any primitive type arguments you pass to the logger. The code doing the logging is arguably even cleaner than ever, since untidy string concatenation is gone. It can be even cleaner if the format strings are externalized (using a ResourceBundle ), which could also assist in maintenance or localization of the software. Further enhancements Also note that, in Java, a MessageFormat object could be used in place of a "format" String , which gives you additional capabilities such as a choice format to handle cardinal numbers more neatly. Another alternative would be to implement your own formatting capability that invokes some interface that you define for "evaluation", rather than the basic toString() method.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/105884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440/" ] }
105,932
It seems like a standard requirement: next time the user launches the application, open the window in the same position and state as it was before. Here's my wish list: Window position same as it was Unless the screen has resized and the old position is now off screen. Splitters should retain their position Tab containers should retain their selection Some dropdowns should retain their selection Window state (maximize, minimize, normal) is the same as it was. Maybe you should never start minimized, I haven't decided. I'll add my current solutions as an answer along with the limitations.
My other option is to write more custom code around the application settings and execute it on formLoad and formClosed. This doesn't use data binding. Drawbacks: More code to write. Very fiddly. The order you set the properties on formLoad is confusing. For example, you have to make sure you've set the window size before you set the splitter distance. Right now, this is my preferred solution, but it seems like too much work. To reduce the work, I created a WindowSettings class that serializes the window location, size, state, and any splitter positions to a single application setting. Then I can just create a setting of that type for each form in my application, save on close, and restore on load. I posted the source code , including the WindowSettings class and some forms that use it. Instructions on adding it to a project are included in the WindowSettings.cs file. The trickiest part was figuring out how to add an application setting with a custom type. You choose Browse... from the type dropdown, and then manually enter the namespace and class name. Types from your project don't show up in the list. Update: I added some static methods to simplify the boilerplate code that you add to each form. Once you've followed the instructions for adding the WindowSettings class to your project and creating an application setting, here's an example of the code that has to be added to each form whose position you want to record and restore. private void MyForm_FormClosing(object sender, FormClosingEventArgs e) { Settings.Default.CustomWindowSettings = WindowSettings.Record( Settings.Default.CustomWindowSettings, this, splitContainer1); } private void MyForm_Load(object sender, EventArgs e) { WindowSettings.Restore( Settings.Default.CustomWindowSettings, this, splitContainer1); }
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/105932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4794/" ] }
105,950
I can't seem to figure out how to set the default database in Sql Server from code. This can be either .Net code or T-Sql (T-Sql would be nice since it would be easy to use in any language). I searched Google and could only find how to do it in Sql Server Management Studio.
from: http://doc.ddart.net/mssql/sql70/sp_da-di_6.htm sp_defaultdb [@loginame =] 'login' , [@defdb =] 'database'
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/105950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/320/" ] }
106,033
Suppose I am writing an application in C++ and C#. I want to write the low level parts in C++ and write the high level logic in C#. How can I load a .NET assembly from my C++ program and start calling methods and accessing the properties of my C# classes?
[Guid("123565C4-C5FA-4512-A560-1D47F9FDFA20")]public interface IConfig{ [DispId(1)] string Destination{ get; } [DispId(2)] void Unserialize(); [DispId(3)] void Serialize();}[ComVisible(true)][Guid("12AC8095-BD27-4de8-A30B-991940666927")][ClassInterface(ClassInterfaceType.None)]public sealed class Config : IConfig{ public Config() { } public string Destination { get { return ""; } } public void Serialize() { } public void Unserialize() { }} After that, you need to regasm your assembly. Regasm will add the necessary registry entries to allow your .NET component to be see as a COM Component. After, you can call your .NET Component in C++ in the same way as any other COM component.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4828/" ] }
106,036
I have a WinForms app written in C# with .NET 3.5. It runs a lengthy batch process. I want the app to update status of what the batch process is doing. What is the best way to update the UI?
The BackgroundWorker sounds like the object you want.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ] }
106,053
I already know the obvious answer to this question: "just download <insert favorite windows grep or grep-like tool here>". However, I work in an environment with strict controls by the local IT staff as to what we're allowed to have on our computers. Suffice it to say: I have access to Perl on Windows XP. Here's a quick Perl script I came up with that does what I want, but I haven't figured up how to set up a batch file such that I can either pipe a command output into it, or pass a file (or list of files?) as an argument after the "expression to grep": perl -n -e "print $_ if (m![expression]!);" [filename] How do I write a batch script that I can do something like, for example: dir | grep.bat mypatterngrep.bat mypattern myfile.txt EDIT : Even though I marked another "answer", I wanted to give kudos to Ray Hayes answer , as it is really the "Windows Way" to do it, even if another answer is technically closer to what I wanted.
Most of the power of grep is already available on your machine in the Windows application FindStr.exe which is part of all Windows 2000, XP and Vista machines! It offers RegExpr etc. Far easier than a batch file which in turn calls Perl! c:\>FindStr /? Searches for strings in files.FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file] [/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]] strings [[drive:][path]filename[ ...]] /B Matches pattern if at the beginning of a line. /E Matches pattern if at the end of a line. /L Uses search strings literally. /R Uses search strings as regular expressions. /S Searches for matching files in the current directory and all subdirectories. /I Specifies that the search is not to be case-sensitive. /X Prints lines that match exactly. /V Prints only lines that do not contain a match. /N Prints the line number before each line that matches. /M Prints only the filename if a file contains a match. /O Prints character offset before each matching line. /P Skip files with non-printable characters. /OFF[LINE] Do not skip files with offline attribute set. /A:attr Specifies color attribute with two hex digits. See "color /?" /F:file Reads file list from the specified file(/ stands for console). /C:string Uses specified string as a literal search string. /G:file Gets search strings from the specified file(/ stands for console). /D:dir Search a semicolon delimited list of directories strings Text to be searched for. [drive:][path]filename Specifies a file or files to search.Use spaces to separate multiple search strings unless the argument is prefixedwith /C. For example, 'FINDSTR "hello there" x.y' searches for "hello" or"there" in file x.y. 'FINDSTR /C:"hello there" x.y' searches for"hello there" in file x.y.Regular expression quick reference: . Wildcard: any character * Repeat: zero or more occurances of previous character or class ^ Line position: beginning of line $ Line position: end of line [class] Character class: any one character in set [^class] Inverse class: any one character not in set [x-y] Range: any characters within the specified range \x Escape: literal use of metacharacter x \<xyz Word position: beginning of word xyz\> Word position: end of word
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13140/" ] }
106,058
Someone is trying to sell Lisp to me, as a super powerful language that can do everything ever, and then some. Is there a practical code example of Lisp's power? (Preferably alongside equivalent logic coded in a regular language.)
I like macros. Here's code to stuff away attributes for people from LDAP. I just happened to have that code lying around and fiigured it'd be useful for others. Some people are confused over a supposed runtime penalty of macros, so I've added an attempt at clarifying things at the end. In The Beginning, There Was Duplication (defun ldap-users () (let ((people (make-hash-table :test 'equal))) (ldap:dosearch (ent (ldap:search *ldap* "(&(telephonenumber=*) (cn=*))")) (let ((mail (car (ldap:attr-value ent 'mail))) (uid (car (ldap:attr-value ent 'uid))) (name (car (ldap:attr-value ent 'cn))) (phonenumber (car (ldap:attr-value ent 'telephonenumber)))) (setf (gethash uid people) (list mail name phonenumber)))) people)) You can think of a "let binding" as a local variable, that disappears outside the LET form. Notice the form of the bindings -- they are very similar, differing only in the attribute of the LDAP entity and the name ("local variable") to bind the value to. Useful, but a bit verbose and contains duplication. On the Quest for Beauty Now, wouldn't it be nice if we didn't have to have all that duplication? A common idiom is is WITH-... macros, that binds values based on an expression that you can grab the values from. Let's introduce our own macro that works like that, WITH-LDAP-ATTRS, and replace it in our original code. (defun ldap-users () (let ((people (make-hash-table :test 'equal))) ; equal so strings compare equal! (ldap:dosearch (ent (ldap:search *ldap* "(&(telephonenumber=*) (cn=*))")) (with-ldap-attrs (mail uid name phonenumber) ent (setf (gethash uid people) (list mail name phonenumber)))) people)) Did you see how a bunch of lines suddenly disappeared, and was replaced with just one single line? How to do this? Using macros, of course -- code that writes code! Macros in Lisp is a totally different animal than the ones you can find in C/C++ through the use of the pre-processor: here, you can run real Lisp code (not the #define fluff in cpp) that generates Lisp code, before the other code is compiled. Macros can use any real Lisp code, i.e., ordinary functions. Essentially no limits. Getting Rid of Ugly So, let's see how this was done. To replace one attribute, we define a function. (defun ldap-attr (entity attr) `(,attr (car (ldap:attr-value ,entity ',attr)))) The backquote syntax looks a bit hairy, but what it does is easy. When you call LDAP-ATTRS, it'll spit out a list that contains the value of attr (that's the comma), followed by car ("first element in the list" (cons pair, actually), and there is in fact a function called first you can use, too), which receives the first value in the list returned by ldap:attr-value . Because this isn't code we want to run when we compile the code (getting the attribute values is what we want to do when we run the program), we don't add a comma before the call. Anyway. Moving along, to the rest of the macro. (defmacro with-ldap-attrs (attrs ent &rest body) `(let ,(loop for attr in attrs collecting `,(ldap-attr ent attr)) ,@body)) The ,@ -syntax is to put the contents of a list somewhere, instead of the actual list. Result You can easily verify that this will give you the right thing. Macros are often written this way: you start off with code you want to make simpler (the output), what you want to write instead (the input), and then you start molding the macro until your input gives the correct output. The function macroexpand-1 will tell you if your macro is correct: (macroexpand-1 '(with-ldap-attrs (mail phonenumber) ent (format t "~a with ~a" mail phonenumber))) evaluates to (let ((mail (car (trivial-ldap:attr-value ent 'mail))) (phonenumber (car (trivial-ldap:attr-value ent 'phonenumber)))) (format t "~a with ~a" mail phonenumber)) If you compare the LET-bindings of the expanded macro with the code in the beginning, you'll find that it is in the same form! Compile-time vs Runtime: Macros vs Functions A macro is code that is run at compile-time , with the added twist that they can call any ordinary function or macro as they please! It's not much more than a fancy filter, taking some arguments, applying some transformations and then feeding the compiler the resulting s-exps. Basically, it lets you write your code in verbs that can be found in the problem domain, instead of low-level primitives from the language! As a silly example, consider the following (if when wasn't already a built-in):: (defmacro my-when (test &rest body) `(if ,test (progn ,@body))) if is a built-in primitive that will only let you execute one form in the branches, and if you want to have more than one, well, you need to use progn :: ;; one form(if (numberp 1) (print "yay, a number"));; two forms(if (numberp 1) (progn (assert-world-is-sane t) (print "phew!")))) With our new friend, my-when , we could both a) use the more appropriate verb if we don't have a false branch, and b) add an implicit sequencing operator, i.e. progn :: (my-when (numberp 1) (assert-world-is-sane t) (print "phew!")) The compiled code will never contain my-when , though, because in the first pass, all macros are expanded so there is no runtime penalty involved! Lisp> (macroexpand-1 '(my-when (numberp 1) (print "yay!")))(if (numberp 1) (progn (print "yay!"))) Note that macroexpand-1 only does one level of expansions; it's possible (most likely, in fact!) that the expansion continues further down. However, eventually you'll hit the compiler-specific implementation details which are often not very interesting. But continuing expanding the result will eventually either get you more details, or just your input s-exp back. Hope that clarifies things. Macros is a powerful tool, and one of the features in Lisp I like.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/106058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9360/" ] }
106,067
In java, which regular expression can be used to replace these,for example: before:aaabbbafter:ab before:14442345 after:142345 thanks!
In perl s/(.)\1+/$1/g; Does the trick, I assume if java has perl compatible regexps it should work too. Edit: Here is what it means s { (.) # match any charater ( and capture it ) \1 # if it is followed by itself + # One or more times}{$1}gx; # And replace the whole things by the first captured character (with g modifier to replace all occurences) Edit: As others have pointed out, the syntax in Java would become original.replaceAll("(.)\\1+", "$1"); remember to escape the \1
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/106067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18300/" ] }
106,117
Please bear with me, I'm just learning C++. I'm trying to write my header file (for class) and I'm running into an odd error. cards.h:21: error: expected unqualified-id before ')' tokencards.h:22: error: expected `)' before "str"cards.h:23: error: expected `)' before "r" What does "expected unqualified-id before ')' token" mean? And what am I doing wrong? Edit: Sorry, I didn't post the entire code. /*Card header file[Author]*/// NOTE: Lanugage Docs here http://www.cplusplus.com/doc/tutorial/#define Card#define Hand#define AppError#include <string>using namespace std;// TODO: Docs hereclass Card { // line 17 public: enum Suit {Club, Diamond, Spade, Heart}; enum Rank {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}; Card(); // line 22 Card(string str); Card(Rank r, Suit s); Edit: I'm just trying to compile the header file by itself using "g++ file.h". Edit: Closed question. My code is working now. Thanks everyone!Edit: Reopened question after reading Etiquette: Closing your posts
Your issue is your #define . You did #define Card , so now everywhere Card is seen as a token, it will be replaced. Usually a #define Token with no additional token, as in #define Token Replace will use the value 1 . Remove the #define Card , it's making line 22 read: 1(); or (); , which is causing the complaint.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16204/" ] }
106,134
Does anyone know of any tools capable of defining a declarative mapping from T-Box structures from one ontology to another, which when executed can effect translation of A-Box instance data from one ontology's form to another's? I have recently written such a tool to meet my needs, but I was wondering if I reinvented the wheel.
Your issue is your #define . You did #define Card , so now everywhere Card is seen as a token, it will be replaced. Usually a #define Token with no additional token, as in #define Token Replace will use the value 1 . Remove the #define Card , it's making line 22 read: 1(); or (); , which is causing the complaint.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19269/" ] }
106,179
Does anyone have a regular expression handy that will match any legal DNS hostname or IP address? It's easy to write one that works 95% of the time, but I'm hoping to get something that's well tested to exactly match the latest RFC specs for DNS hostnames.
You can use the following regular expressions separately or by combining them in a joint OR expression. ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";ValidHostnameRegex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$"; ValidIpAddressRegex matches valid IP addresses and ValidHostnameRegex valid host names. Depending on the language you use \ could have to be escaped with \. ValidHostnameRegex is valid as per RFC 1123 . Originally, RFC 952 specified that hostname segments could not start with a digit. http://en.wikipedia.org/wiki/Hostname The original specification ofhostnames in RFC952 ,mandated that labels could not startwith a digit or with a hyphen, andmust not end with a hyphen. However, asubsequent specification ( RFC1123 )permitted hostname labels to startwith digits. Valid952HostnameRegex = "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$";
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/106179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10452/" ] }
106,201
In the spirit of being helpful, this is a problem I had and solved, so I will answer the question here. Problem I have: An application that has to be installed on on Redhat or SuSE enterprise. It has huge system requirements and requires OpenGL. It is part of a suite of tools that need to operate together on one machine. This application is used for a time intensive task in terms of man hours. I don't want to sit in the server room working on this application. So, the question came up... how do I run this application from a remote windows machine? I'll outline my solution. Feel free to comment on alternatives. This solution should work for simpler environments as well. My case is somewhat extreme.
Solution I installed two pieces of software: PuTTY XMing-mesa The mesa part is important. PuTTY configuration Connection->Seconds Between Keepalives: 30Connection->Enable TCP Keepalives: YesConnection->SSH->X11->Enable X11 forwarding: YesConnection->SSH->X11->X display location: localhost:0:0 Lauching Run Xming which will put simply start a process and put an icon in your system tray.Launch putty, pointing to your linux box, with the above configuration.Run program Hopefully, Success!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9450/" ] }
106,206
I'm writing an import utility that is using phone numbers as a unique key within the import. I need to check that the phone number does not already exist in my DB. The problem is that phone numbers in the DB could have things like dashes and parenthesis and possibly other things. I wrote a function to remove these things, the problem is that it is slow and with thousands of records in my DB and thousands of records to import at once, this process can be unacceptably slow. I've already made the phone number column an index. I tried using the script from this post: T-SQL trim &nbsp (and other non-alphanumeric characters) But that didn't speed it up any. Is there a faster way to remove non-numeric characters? Something that can perform well when 10,000 to 100,000 records have to be compared. Whatever is done needs to perform fast . Update Given what people responded with, I think I'm going to have to clean the fields before I run the import utility. To answer the question of what I'm writing the import utility in, it is a C# app. I'm comparing BIGINT to BIGINT now, with no need to alter DB data and I'm still taking a performance hit with a very small set of data (about 2000 records). Could comparing BIGINT to BIGINT be slowing things down? I've optimized the code side of my app as much as I can (removed regexes, removed unneccessary DB calls). Although I can't isolate SQL as the source of the problem anymore, I still feel like it is.
I saw this solution with T-SQL code and PATINDEX. I like it :-) CREATE Function [fnRemoveNonNumericCharacters](@strText VARCHAR(1000))RETURNS VARCHAR(1000)ASBEGIN WHILE PATINDEX('%[^0-9]%', @strText) > 0 BEGIN SET @strText = STUFF(@strText, PATINDEX('%[^0-9]%', @strText), 1, '') END RETURN @strTextEND
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/106206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ] }
106,222
I've read on Wikipedia and other sites about OSGi , but I don't really see the big picture. It says that it's a component-based platform, and that you can reload modules at runtime. Also the "practical example" given everywhere is the Eclipse Plugin Framework. My questions are: What is the clear and simple definition of OSGi? What common problems does it solve? By "common problems" I mean problems we face everyday, like "What can OSGi do for making our jobs more efficient/fun/simple?"
I've found the following benefits from OSGi: Each plugin is a versioned artifact that has its own classloader. Each plugin depends on both specific jars that it contains and also other specific versioned plug-ins. Because of the versioning and isolated classloaders, different versions of the same artifact can be loaded at the same time. If one component of your application relies on one version of a plug-in and another depends on another version, they both can be loaded at the same time. With this, you can structure your application as a set of versioned plugin artifacts that are loaded on demand. Each plugin is a standalone component. Just as Maven helps you structure your build so it is repeatable and defined by a set of specific versions of artifacts it is created by, OSGi helps you do this at runtime.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/106222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7595/" ] }
106,234
lsof is an increadibly powerful command-line utility for unix systems. It lists open files, displaying information about them. And since most everything is a file on unix systems, lsof can give sysadmins a ton of useful diagnostic data. What are some of the most common and useful ways of using lsof, and which command-line switches are used for that?
To show all networking related to a given port : lsof -iTCP -i :portlsof -i :22 To show connections to a specific host, use @host lsof [email protected] Show connections based on the host and the port using @host:port lsof [email protected]:22 grep ping for LISTEN shows what ports your system is waiting for connections on: lsof -i| grep LISTEN Show what a given user has open using -u : lsof -u daniel See what files and network connections a command is using with -c lsof -c syslog-ng The -p switch lets you see what a given process ID has open, which is good for learning more about unknown processes: lsof -p 10075 The -t option returns just a PID lsof -t -c Mail Using the -t and -c options together you can HUP processes kill -HUP $(lsof -t -c sshd) You can also use the -t with -u to kill everything a user has open kill -9 $(lsof -t -u daniel)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/106234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683/" ] }
106,324
With the advent of new features like lambda expressions (inline code), does it mean we dont have to use delegates or anonymous methods anymore? In almost all the samples I have seen, it is for rewriting using the new syntax. Any place where we still have to use delegates and lambda expressions won't work?
Yes there are places where directly using anonymous delegates and lambda expressions won't work. If a method takes an untyped Delegate then the compiler doesn't know what to resolve the anonymous delegate/lambda expression to and you will get a compiler error. public static void Invoke(Delegate d){ d.DynamicInvoke();}static void Main(string[] args){ // fails Invoke(() => Console.WriteLine("Test")); // works Invoke(new Action(() => Console.WriteLine("Test"))); Console.ReadKey();} The failing line of code will get the compiler error "Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type".
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19306/" ] }
106,329
I've recently inherited C# console application that is in need of some pruning and clean up. Long story short, the app consists of a single class containing over 110,000 lines of code. Yup, over 110,000 lines in a single class. And, of course, the app is core to our business, running 'round the clock updating data used on a dynamic website. Although I'm told my predecessor was "a really good programmer", it obvious he was not at all into OOP (or version control). Anyway... while familiarizing myself with the code I've found plenty of methods that are declared, but never referenced. It looks as if copy/paste was used to version the code, for example say I have a method called getSomethingImportant(), chances are there is another method called getSomethingImortant_July2007() (the pattern is functionName_[datestamp] in most cases). It looks like when the programmer was asked to make a change to getSomethingImportant() he would copy/paste then rename to getSomethingImortant_Date, make changes to getSomethingImortant_Date, then change any method calls in the code to the new method name, leaving the old method in the code but never referenced. I'd like to write a simple console app that crawls through the one huge class and returns a list of all methods with the number of times each method was referenced. By my estimates there are well over 1000 methods, so doing this by hand would take a while. Are there classes within the .NET framework that I can use to examine this code? Or any other usefull tools that may help identify methods that are declared but never referenced? (Side question: Has anyone else ever seen a C# app like this, one reeeealy big class? It's more or less one huge procedural process, I know this is the first I've seen, at least of this size.)
You could try to use NDepend if you just need to extract some stats about your class. Note that this tool relies on Mono.Cecil internally to inspect assemblies.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19389/" ] }
106,336
I have a ArrayList made up of different elements imported from a db, made up of strings, numbers, doubles and ints. Is there a way to use a reflection type technique to find out what each type of data each element holds? FYI: The reason that there is so many types of data is that this is a piece of java code being written to be implemented with different DB's.
In C#: Fixed with recommendation from Mike ArrayList list = ...;// List<object> list = ...;foreach (object o in list) { if (o is int) { HandleInt((int)o); } else if (o is string) { HandleString((string)o); } ...} In Java: ArrayList<Object> list = ...;for (Object o : list) { if (o instanceof Integer)) { handleInt((Integer o).intValue()); } else if (o instanceof String)) { handleString((String)o); } ...}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/106336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13491/" ] }
106,383
Suppose I have BaseClass with public methods A and B, and I create DerivedClass through inheritance. e.g. public DerivedClass : BaseClass {} Now I want to develop a method C in DerivedClass that uses A and B. Is there a way I can override methods A and B to be private in DerivedClass so that only method C is exposed to someone who wants to use my DerivedClass?
It's not possible, why? In C#, it is forced upon you that if you inherit public methods, you must make them public. Otherwise they expect you not to derive from the class in the first place. Instead of using the is-a relationship, you would have to use the has-a relationship. The language designers don't allow this on purpose so that you use inheritance more properly. For example one might accidentally confuse a class Car to derive from a class Engine to get it's functionality. But an Engine is functionality that is used by the car. So you would want to use the has-a relationship. The user of the Car does not want to have access to the interface of the Engine. And the Car itself should not confuse the Engine's methods with it's own. Nor Car's future derivations. So they don't allow it to protect you from bad inheritance hierarchies. What should you do instead? Instead you should implement interfaces. This leaves you free to have functionality using the has-a relationship. Other languages: In C++ you simply specify a modifier before the base class of private, public or protected. This makes all members of the base that were public to that specified access level. It seems silly to me that you can't do the same in C#. The restructured code: interface I{ void C();}class BaseClass{ public void A() { MessageBox.Show("A"); } public void B() { MessageBox.Show("B"); }}class Derived : I{ public void C() { b.A(); b.B(); } private BaseClass b;} I understand the names of the above classes are a little moot :) Other suggestions: Others have suggested to make A() and B() public and throw exceptions. But this doesn't make a friendly class for people to use and it doesn't really make sense.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/106383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16866/" ] }
106,387
I am writing a bash script to deal with some installations in an automated way... I have the possibility of getting one such program in 32 or 64 bit binary... is it possible to detect the machine architecture from bash so I can select the correct binary? This will be for Ubuntu machines.
Does uname -a give you anything you can use? I don't have a 64-bit machine to test on. Note from Mike Stone: This works, though specifically uname -m Will give "x86_64" for 64 bit, and something else for other 32 bit types (in my 32 bit VM, it's "i686").
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/106387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ] }
106,412
In general, I occasionally have a chain of nested macros with a few preprocessor conditional elements in their definitions. These can be painful to debug since it's hard to directly see the actual code being executed. A while ago I vaguely remember finding a compiler (gcc) flag to expand them, but I had trouble getting this to work in practice.
gcc -E will output the preprocessed source to stdout.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3561/" ] }
106,425
How can I load an external JavaScript file using a bookmarklet? This would overcome the URL length limitations of IE and generally keep things cleaner.
2015 Update Content security policy will prevent this from working in many sites now. For example, the code below won't work on Facebook. 2008 answer Use a bookmarklet that creates a script tag which includes your external JS. As a sample: javascript:(function(){document.body.appendChild(document.createElement('script')).src='** your external file URL here **';})();
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/106425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401774/" ] }
106,437
I have a stateless bean something like: @Statelesspublic class MyStatelessBean implements MyStatelessLocal, MyStatelessRemote { @PersistenceContext(unitName="myPC") private EntityManager mgr; @TransationAttribute(TransactionAttributeType.SUPPORTED) public void processObjects(List<Object> objs) { // this method just processes the data; no need for a transaction for(Object obj : objs) { this.process(obj); } } @TransationAttribute(TransactionAttributeType.REQUIRES_NEW) public void process(Object obj) { // do some work with obj that must be in the scope of a transaction this.mgr.merge(obj); // ... this.mgr.merge(obj); // ... this.mgr.flush(); }} The typically usage then is the client would call processObjects(...), which doesn't actually interact with the entity manager. It does what it needs to do and calls process(...) individually for each object to process. The duration of process(...) is relatively short, but processObjects(...) could take a very long time to run through everything. Therefore I don't want it to maintain an open transaction. I do need the individual process(...) operations to operate within their own transaction. This should be a new transaction for every call. Lastly I'd like to keep the option open for the client to call process(...) directly. I've tried a number of different transaction types: never, not supported, supported (on processObjects) and required, requires new (on process) but I get TransactionRequiredException every time merge() is called. I've been able to make it work by splitting up the methods into two different beans: @Stateless@TransationAttribute(TransactionAttributeType.NOT_SUPPORTED)public class MyStatelessBean1 implements MyStatelessLocal1, MyStatelessRemote1 { @EJB private MyStatelessBean2 myBean2; public void processObjects(List<Object> objs) { // this method just processes the data; no need for a transaction for(Object obj : objs) { this.myBean2.process(obj); } }}@Statelesspublic class MyStatelessBean2 implements MyStatelessLocal2, MyStatelessRemote2 { @PersistenceContext(unitName="myPC") private EntityManager mgr; @TransationAttribute(TransactionAttributeType.REQUIRES_NEW) public void process(Object obj) { // do some work with obj that must be in the scope of a transaction this.mgr.merge(obj); // ... this.mgr.merge(obj); // ... this.mgr.flush(); }} but I'm still curious if it's possible to accomplish this in one class. It looks to me like the transaction manager only operates at the bean level, even when individual methods are given more specific annotations. So if I mark one method in a way to prevent the transaction from starting calling other methods within that same instance will also not create a transaction, no matter how they're marked? I'm using JBoss Application Server 4.2.1.GA, but non-specific answers are welcome / preferred.
Another way to do it is actually having both methods on the same bean - and having an @EJB reference to itself! Something like that: // supposing processObjects defined on MyStatelessRemote1 and process defined on MyStatelessLocal1@Stateless@TransationAttribute(TransactionAttributeType.NOT_SUPPORTED)public class MyStatelessBean1 implements MyStatelessLocal1, MyStatelessRemote1 { @EJB private MyStatelessLocal1 myBean2; public void processObjects(List<Object> objs) { // this method just processes the data; no need for a transaction for(Object obj : objs) { this.myBean2.process(obj); } } @TransationAttribute(TransactionAttributeType.REQUIRES_NEW) public void process(Object obj) { // do some work with obj that must be in the scope of a transaction this.mgr.merge(obj); // ... this.mgr.merge(obj); // ... this.mgr.flush(); }} This way you actually 'force' the process() method to be accessed via the ejb stack of proxies, therefore taking the @TransactionAttribute in effect - and still keeping only one class. Phew!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/106437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1458/" ] }
106,481
I have this line in a javascript block in a page: res = foo('<%= @ruby_var %>'); What is the best way to handle the case where @ruby_var has a single-quote in it? Else it will break the JavaScript code.
I think I'd use a ruby JSON library on @ruby_var to get proper js syntax for the string and get rid of the '', fex.: res = foo(<%= @ruby_var.to_json %>) (after require "json"'ing, not entirely sure how to do that in the page or if the above syntax is correct as I havn't used that templating language) (on the other hand, if JSON ever changed to be incompatible with js that'd break, but since a decent amount of code uses eval() to eval json I doubt that'd happen anytime soon)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19409/" ] }
106,508
What is a smart pointer and when should I use one?
UPDATE This answer is rather old, and so describes what was 'good' at the time, which was smart pointers provided by the Boost library. Since C++11, the standard library has provided sufficient smart pointers types, and so you should favour the use of std::unique_ptr , std::shared_ptr and std::weak_ptr . There was also std::auto_ptr . It was very much like a scoped pointer, except that it also had the "special" dangerous ability to be copied — which also unexpectedly transfers ownership. It was deprecated in C++11 and removed in C++17 , so you shouldn't use it. std::auto_ptr<MyObject> p1 (new MyObject());std::auto_ptr<MyObject> p2 = p1; // Copy and transfer ownership. // p1 gets set to empty!p2->DoSomething(); // Works.p1->DoSomething(); // Oh oh. Hopefully raises some NULL pointer exception. OLD ANSWER A smart pointer is a class that wraps a 'raw' (or 'bare') C++ pointer, to manage the lifetime of the object being pointed to. There is no single smart pointer type, but all of them try to abstract a raw pointer in a practical way. Smart pointers should be preferred over raw pointers. If you feel you need to use pointers (first consider if you really do), you would normally want to use a smart pointer as this can alleviate many of the problems with raw pointers, mainly forgetting to delete the object and leaking memory. With raw pointers, the programmer has to explicitly destroy the object when it is no longer useful. // Need to create the object to achieve some goalMyObject* ptr = new MyObject(); ptr->DoSomething(); // Use the object in some waydelete ptr; // Destroy the object. Done with it.// Wait, what if DoSomething() raises an exception...? A smart pointer by comparison defines a policy as to when the object is destroyed. You still have to create the object, but you no longer have to worry about destroying it. SomeSmartPtr<MyObject> ptr(new MyObject());ptr->DoSomething(); // Use the object in some way.// Destruction of the object happens, depending // on the policy the smart pointer class uses.// Destruction would happen even if DoSomething() // raises an exception The simplest policy in use involves the scope of the smart pointer wrapper object, such as implemented by boost::scoped_ptr or std::unique_ptr . void f(){ { std::unique_ptr<MyObject> ptr(new MyObject()); ptr->DoSomethingUseful(); } // ptr goes out of scope -- // the MyObject is automatically destroyed. // ptr->Oops(); // Compile error: "ptr" not defined // since it is no longer in scope.} Note that std::unique_ptr instances cannot be copied. This prevents the pointer from being deleted multiple times (incorrectly). You can, however, pass references to it around to other functions you call. std::unique_ptr s are useful when you want to tie the lifetime of the object to a particular block of code, or if you embedded it as member data inside another object, the lifetime of that other object. The object exists until the containing block of code is exited, or until the containing object is itself destroyed. A more complex smart pointer policy involves reference counting the pointer. This does allow the pointer to be copied. When the last "reference" to the object is destroyed, the object is deleted. This policy is implemented by boost::shared_ptr and std::shared_ptr . void f(){ typedef std::shared_ptr<MyObject> MyObjectPtr; // nice short alias MyObjectPtr p1; // Empty { MyObjectPtr p2(new MyObject()); // There is now one "reference" to the created object p1 = p2; // Copy the pointer. // There are now two references to the object. } // p2 is destroyed, leaving one reference to the object.} // p1 is destroyed, leaving a reference count of zero. // The object is deleted. Reference counted pointers are very useful when the lifetime of your object is much more complicated, and is not tied directly to a particular section of code or to another object. There is one drawback to reference counted pointers — the possibility of creating a dangling reference: // Create the smart pointer on the heapMyObjectPtr* pp = new MyObjectPtr(new MyObject())// Hmm, we forgot to destroy the smart pointer,// because of that, the object is never destroyed! Another possibility is creating circular references: struct Owner { std::shared_ptr<Owner> other;};std::shared_ptr<Owner> p1 (new Owner());std::shared_ptr<Owner> p2 (new Owner());p1->other = p2; // p1 references p2p2->other = p1; // p2 references p1// Oops, the reference count of of p1 and p2 never goes to zero!// The objects are never destroyed! To work around this problem, both Boost and C++11 have defined a weak_ptr to define a weak (uncounted) reference to a shared_ptr .
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/106508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19410/" ] }
106,509
I have a button that I would like to disable when the form submits to prevent the user submitting multiple times. I have tried naively disabling the button with javascript onclick but then if a client side validation that fails the button remains disabled. How do I disable the button when the form successfully submits not just when the user clicks? This is an ASP.NET form so I would like to hook in nicely with the asp.net ajax page lifecycle if possible.
Give this a whirl: using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Threading;public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Identify button as a "disabled-when-clicked" button... WebHelpers.DisableButtonOnClick( buttonTest, "showPleaseWait" ); } protected void buttonTest_Click( object sender, EventArgs e ) { // Emulate a server-side process to demo the disabled button during // postback. Thread.Sleep( 5000 ); }}using System;using System.Web;using System.Web.UI.WebControls;using System.Text;public class WebHelpers{ // // Disable button with no secondary JavaScript function call. // public static void DisableButtonOnClick( Button ButtonControl ) { DisableButtonOnClick( ButtonControl, string.Empty ); } // // Disable button with a JavaScript function call. // public static void DisableButtonOnClick( Button ButtonControl, string ClientFunction ) { StringBuilder sb = new StringBuilder( 128 ); // If the page has ASP.NET validators on it, this code ensures the // page validates before continuing. sb.Append( "if ( typeof( Page_ClientValidate ) == 'function' ) { " ); sb.Append( "if ( ! Page_ClientValidate() ) { return false; } } " ); // Disable this button. sb.Append( "this.disabled = true;" ); // If a secondary JavaScript function has been provided, and if it can be found, // call it. Note the name of the JavaScript function to call should be passed without // parens. if ( ! String.IsNullOrEmpty( ClientFunction ) ) { sb.AppendFormat( "if ( typeof( {0} ) == 'function' ) {{ {0}() }};", ClientFunction ); } // GetPostBackEventReference() obtains a reference to a client-side script function // that causes the server to post back to the page (ie this causes the server-side part // of the "click" to be performed). sb.Append( ButtonControl.Page.ClientScript.GetPostBackEventReference( ButtonControl ) + ";" ); // Add the JavaScript created a code to be executed when the button is clicked. ButtonControl.Attributes.Add( "onclick", sb.ToString() ); }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6600/" ] }
106,546
The arguments about the simplicity of solutions using XML-RPC or REST are easy to understand and hard to argue with. I have often also heard arguments that the increased overhead of SOAP may significantly impact used bandwidth and possibly even latency. I would like to see the results of a test that quantifies the impact. Any one know a good source for such information?
The main impact in speed of SOAP vs. REST has not to do with wire speed, but with cachability. REST suggests using the web's semantics instead of trying to tunnel over it via XML, so RESTful web services are generally designed to correctly use cache headers, so they work well with the web's standard infrastructure like caching proxies and even local browser caches. Also, using the web's semantics means that things like ETags and automatic zip compression are well understood ways to increase efficiency. ..and now you say you want benchmarks. Well, with Google's help, I found one guy whose testing shows REST to be 4-6x faster than SOAP and another paper that also favors REST.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/106546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10503/" ] }
106,555
I have a Perl script where I maintain a very simple cache using a hash table. I would like to clear the hash once it occupies more than n bytes, to avoid Perl (32-bit) running out of memory and crashing. I can do a check on the number of keys-value pairs: if (scalar keys %cache > $maxSize) { %cache = (); } But is it possible to check the actual memory occupied by the hash?
Devel::Size is the answer to your question. (Note that Devel::Size will temporarily allocate a significant amount of memory when processing a large data structure, so it's not really well suited to this purpose.) However, Cache::SizeAwareMemoryCache and Tie::Cache already implement what you're looking for (with somewhat different interfaces), and could save you from reinventing the wheel. Memoize is a module that makes it simple to cache the return value from a function. It doesn't implement a size-based cache limit, but it should be possible to use Tie::Cache as a backend for Memoize.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/106555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5734/" ] }
106,586
There is a lot of relativity involved in working with exceptions. Beyond low level APIs where exceptions cover errors raised from hardware and the OS there is a shady area where the programmer decides what constitutes an exception and what is a normal condition. How do you decide when to use exceptions? Do you have a consistent policy regarding exceptions?
Exceptions should not be used as a method of passing information internally between methods inside your object, locally you should use error codes and defensive programming. Exceptions are designed to pass control from a point where an error is detected to a place (higher up the stack) where the error can be handled, presumably because the local code does not have enough context to correct the problem and something higher up the stack will have more context and thus be able to better organize a recovery. When considering exceptions (in C++ at least) you should consider the exception guarantees that your API makes. The minimum level of guarantee should be the Basic guarantee though you should strive (where appropriate) to provide the strong guarantee. In cases where you use no external dependencies from a articular API you may even try to provide the no throw guarantee. N.B. Do not confuse exception guarantees with exception specifications. Exception Guarantees: No Guarantee: There is no guarantee about the state of the object after an exception escapes a methodIn these situations the object should no longer be used. Basic Guarantee: In nearly all situations this should be the minimum guarantee a method provides.This guarantees the object's state is well defined and can still be consistently used. Strong Guarantee: (aka Transactional Guarantee) This guarantees that the method will completely successfullyOr an Exception will be thrown and the objects state will not change. No Throw Guarantee: The method guarantees that no exceptions are allowed to propagate out of the method.All destructors should make this guarantee. | N.B. If an exception escapes a destructor while an exception is already propagating | the application will terminate
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13615/" ] }
106,591
At work today, I came across the volatile keyword in Java. Not being very familiar with it, I found this explanation . Given the detail in which that article explains the keyword in question, do you ever use it or could you ever see a case in which you could use this keyword in the correct manner?
volatile has semantics for memory visibility. Basically, the value of a volatile field becomes visible to all readers (other threads in particular) after a write operation completes on it. Without volatile , readers could see some non-updated value. To answer your question: Yes, I use a volatile variable to control whether some code continues a loop. The loop tests the volatile value and continues if it is true . The condition can be set to false by calling a "stop" method. The loop sees false and terminates when it tests the value after the stop method completes execution. The book " Java Concurrency in Practice ," which I highly recommend, gives a good explanation of volatile . This book is written by the same person who wrote the IBM article that is referenced in the question (in fact, he cites his book at the bottom of that article). My use of volatile is what his article calls the "pattern 1 status flag." If you want to learn more about how volatile works under the hood, read up on the Java memory model . If you want to go beyond that level, check out a good computer architecture book like Hennessy & Patterson and read about cache coherence and cache consistency.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/106591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16759/" ] }
106,597
And why don't they change it? Edit:The reason ask is because I'm new to emacs and I would like to use Emacs as a "programmer calculator". So, I can manipulate 32-bit & 64-bit integers and have them behave as they would on the native machine.
Emacs-Lisp is a dynamically-typed language. This means that you need type tags at runtime. If you wanted to work with numbers, you would therefore normally have to pack them into some kind of tagged container that you can point to (i.e. “box” them), as there is no way of distinguishing a pointer from a machine integer at runtime without some kind of tagging scheme. For efficiency reasons, most Lisp implementations do therefore not use raw pointers but what I think is called descriptors. These descriptors are usually a single machine word that may represent a pointer, an unboxed number (a so-called fixnum ), or one of various other hard-coded data structures (it's often worth encoding NIL and cons cells specially, too, for example). Now, obviously, if you add the type tag, you don't have the full 32 bits left for the number, so you're left with 26 bits as in MIT Scheme or 29 bits as in Emacs or any other number of bits that you didn't use up for tagging. Some implementations of various dynamic languages reserve multiple tags for fixnums so that they can give you 30-bit or even 31-bit fixnums. SBCL is one implementation of Common Lisp that does this . I don't think the complication that this causes is worth it for Emacs, though. How often do you need fast 30-bit fixnum arithmetic as opposed to 29-bit fixnum arithmetic in a text editor that doesn't even compile its Lisp code into machine code (or does it? I don't remember, actually)? Are you writing a distributed.net client in Emacs-Lisp? Better switch to Common Lisp, then! ;)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1841/" ] }
106,599
I would like to serialize and deserialize objects without having to worry about the entire class graph. Flexibility is key. I would like to be able to serialize any object passed to me without complete attributes needed throughout the entire object graph. That means that Binary Serialization is not an option as it only works with the other .NET Platforms. I would also like something readable by a person, and thus decipherable by a management program and other interpreters. I've found problems using the DataContract, JSON, and XML Serializers. Most of these errors seem to center around Serialization of Lists/Dictionaries (i.e. XML Serializable Generic Dictionary ). "Add any types not known staticallyto the list of known types - forexample, by using theKnownTypeAttribute attribute or byadding them to the list of knowntypes passed toDataContractSerializer." Please base your answers on actual experiences and not theory or reading of an article.
Have you considered serializing to JSON instead of XML? Json.NET has a really powerful and flexible serializer that has no problems with Hashtables/generic dictionaries and doesn't require any particular attributes. I know because I wrote it :) It gives you heaps of control through various options on the serializer and it allows you to override how a type is serialized by creating a JsonConverter for it. In my opinion JSON is more human readable than XML and Json.NET gives the option to write nicely formatted JSON. Finally the project is open source so you can step into the code and make modifications if you need to.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/106599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2744/" ] }
106,725
I need to package my Python application, its dependencies and Python into a single MSI installer. The end result should desirably be: Python is installed in the standard location the package and its dependencies are installed in a separate directory (possibly site-packages) the installation directory should contain the Python uncompressed and a standalone executable is not required
Kind of a dup of this question about how to make a python into an executable . It boils down to: py2exe on windows, Freeze on Linux, and py2app on Mac.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19435/" ] }
106,765
Is there a framework that can be used to enable a C# Windows Service to automatically check for a newer version and upgrade itself? I can certainly write code to accomplish this, but I am looking for a framework that has already been implemented and (most importantly) tested. [edit]Here is a link to a similar question with links to modern projects that help accomplish this: Auto-update library for .NET?
The only way to unload types is to destroy the appdomain. To do this would require separation of your hosting layer from your executing service code - this is pretty complex. (sort of like doing keyhole surgery) May be easier to either a) run a batch task or b) in-service detect updates then launch a seperate process that stops the service, updates assemblies etc. then restarts it. If you're interested in the former, the MSDN patterns and practices folk wrote an app updater block that you adapt to your service. https://web.archive.org/web/20080506103749/http://msdn.microsoft.com/en-us/library/ms978574.aspx
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4911/" ] }
106,766
A common task in programs I've been working on lately is modifying a text file in some way. (Hey, I'm on Linux. Everything's a file. And I do large-scale system admin.) But the file the code modifies may not exist on my desktop box. And I probably don't want to modify it if it IS on my desktop. I've read about unit testing in Dive Into Python, and it's pretty clear what I want to do when testing an app that converts decimal to Roman Numerals (the example in DintoP). The testing is nicely self-contained. You don't need to verify that the program PRINTS the right thing, you just need to verify that the functions are returning the right output to a given input. In my case, however, we need to test that the program is modifying its environment correctly. Here's what I've come up with: 1) Create the "original" file in a standard location, perhaps /tmp. 2) Run the function that modifies the file, passing it the path to the file in /tmp. 3) Verify that the file in /tmp was changed correctly; pass/fail unit test accordingly. This seems kludgy to me. (Gets even kludgier if you want to verify that backup copies of the file are created properly, etc.) Has anyone come up with a better way?
You're talking about testing too much at once. If you start trying to attack a testing problem by saying "Let's verify that it modifies its environment correctly", you're doomed to failure. Environments have dozens, maybe even millions of potential variations. Instead, look at the pieces ("units") of your program. For example, are you going to have a function that determines where the files are that have to be written? What are the inputs to that function? Perhaps an environment variable, perhaps some values read from a config file? Test that function, and don't actually do anything that modifies the filesystem. Don't pass it "realistic" values, pass it values that are easy to verify against. Make a temporary directory, populate it with files in your test's setUp method. Then test the code that writes the files. Just make sure it's writing the right contents file contents. Don't even write to a real filesystem! You don't need to make "fake" file objects for this, just use Python's handy StringIO modules; they're "real" implementations of the "file" interface, they're just not the ones that your program is actually going to be writing to. Ultimately you will have to test the final, everything-is-actually-hooked-up-for-real top-level function that passes the real environment variable and the real config file and puts everything together. But don't worry about that to get started. For one thing, you will start picking up tricks as you write individual tests for smaller functions and creating test mocks, fakes, and stubs will become second nature to you. For another: even if you can't quite figure out how to test that one function call, you will have a very high level of confidence that everything which it is calling works perfectly. Also, you'll notice that test-driven development forces you to make your APIs clearer and more flexible. For example: it's much easier to test something that calls an open() method on an object that came from somewhere abstract, than to test something that calls os.open on a string that you pass it. The open method is flexible; it can be faked, it can be implemented differently, but a string is a string and os.open doesn't give you any leeway to catch what methods are called on it. You can also build testing tools to make repetitive tasks easy. For example, twisted provides facilities for creating temporary files for testing built right into its testing tool . It's not uncommon for testing tools or larger projects with their own test libraries to have functionality like this.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19207/" ] }
106,770
It has always bothered me that the only way to copy a file in Java involves opening streams, declaring a buffer, reading in one file, looping through it, and writing it out to the other steam. The web is littered with similar, yet still slightly different implementations of this type of solution. Is there a better way that stays within the bounds of the Java language (meaning does not involve exec-ing OS specific commands)? Perhaps in some reliable open source utility package, that would at least obscure this underlying implementation and provide a one line solution?
As toolkit mentions above, Apache Commons IO is the way to go, specifically FileUtils . copyFile() ; it handles all the heavy lifting for you. And as a postscript, note that recent versions of FileUtils (such as the 2.0.1 release) have added the use of NIO for copying files; NIO can significantly increase file-copying performance , in a large part because the NIO routines defer copying directly to the OS/filesystem rather than handle it by reading and writing bytes through the Java layer. So if you're looking for performance, it might be worth checking that you are using a recent version of FileUtils.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/106770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17123/" ] }
106,800
Does anyone know of where to find unit testing guidelines and recommendations? I'd like to have something which addresses the following types of topics (for example): Should tests be in the same project as application logic? Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have? How should I name my test classes, methods, and projects (if they go in different projects) Should private, protected, and internal methods be tested, or just those that are publicly accessible? Should unit and integration tests be separated? Is there a good reason not to have 100% test coverage? What am I not asking about that I should be? An online resource would be best.
I would recommend Kent Beck's book on TDD. Also, you need to go to Martin Fowler's site. He has a lot of good information about testing as well. We are pretty big on TDD so I will answer the questions in that light. Should tests be in the same project as application logic? Typically we keep our tests in the same solution, but we break tests into seperate DLL's/Projects that mirror the DLL's/Projects they are testing, but maintain namespaces with the tests being in a sub namespace. Example: Common / Common.Tests Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have? Yes, your tests should be created before any classes are created, and by definition you should only test a single unit in isolation. Therefore you should have a test class for each class in your solution. How should I name my test classes, methods, and projects (if they go in different projects) I like to emphasize that behavior is what is being tested so I typically name test classes after the SUT. For example if I had a User class I would name the test class like so: public class UserBehavior Methods should be named to describe the behavior that you expect. public void ShouldBeAbleToSetUserFirstName() Projects can be named however you want but usually you want it to be fairly obvious which project it is testing. See previous answer about project organization. Should private, protected, and internal methods be tested, or just those that are publicly accessible? Again you want tests to assert expected behavior as if you were a 3rd party consumer of the objects being tested. If you test internal implementation details then your tests will be brittle. You want your test to give you the freedom to refactor without worrying about breaking existing functionality. If your test know about implementation details then you will have to change your tests if those details change. Should unit and integration tests be separated? Yes, unit tests need to be isolated from acceptance and integration tests. Separation of concerns applies to tests as well. Is there a good reason not to have 100% test coverage? I wouldn't get to hung up on the 100% code coverage thing. 100% code coverage tends to imply some level of quality in the tests, but that is a myth. You can have terrible tests and still get 100% coverage. I would instead rely on a good Test First mentality. If you always write a test before you write a line of code then you will ensure 100% coverage so it becomes a moot point. In general if you focus on describing the full behavioral scope of the class then you will have nothing to worry about. If you make code coverage a metric then lazy programmers will simply do just enough to meet that mark and you will still have crappy tests. Instead rely heavily on peer reviews where the tests are reviewed as well.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19421/" ] }
106,820
I realize that literally it translates to Java Enterprise Edition. But what I'm asking is what does this really mean? When a company requires Java EE experience, what are they really asking for? Experience with EJBs? Experience with Java web apps? I suspect that this means something different to different people and the definition is subjective.
Java EE is actually a collection of technologies and APIs for the Java platform designed to support "Enterprise" Applications which can generally be classed as large-scale, distributed, transactional and highly-available applications designed to support mission-critical business requirements. In terms of what an employee is looking for in specific techs, it is quite hard to say, because the playing field has kept changing over the last five years. It really is about the class of problems that are being solved more than anything else. Transactions and distribution are key.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/106820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/292/" ] }
106,828
I need to display a bunch of images on a web page using AJAX. All of them have different dimensions, so I want to adjust their size before displaying them. Is there any way to do this in JavaScript? Using PHP's getimagesize() for each image causes an unnecessary performance hit since there will be many images.
I was searching a solution to get height and width of an image using JavaScript. I found many, but all those solutions only worked when the image was present in browser cache. Finally I found a solution to get the image height and width even if the image does not exist in the browser cache: <script type="text/javascript"> var imgHeight; var imgWidth; function findHHandWW() { imgHeight = this.height; imgWidth = this.width; return true; } function showImage(imgPath) { var myImage = new Image(); myImage.name = imgPath; myImage.onload = findHHandWW; myImage.src = imgPath; }</script> Thanks, Binod Suman http://binodsuman.blogspot.com/2009/06/how-to-get-height-and-widht-of-image.html
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/106828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
106,862
Intel's Threading Building Blocks (TBB) open source library looks really interesting. Even though there's even an O'Reilly Book about the subject I don't hear about a lot of people using it. I'm interested in using it for some multi-level parallel applications (MPI + threads) in Unix (Mac, Linux, etc.) environments. For what it's worth, I'm interested in high performance computing / numerical methods kinds of applications. Does anyone have experiences with TBB? Does it work well? Is it fairly portable (including GCC and other compilers)? Does the paradigm work well for programs you've written? Are there other libraries I should look into?
I've introduced it into our code base because we needed a bettor malloc to use when we moved to a 16 core machine. With 8 and under it wasn't a significant issue. It has worked well for us. We plan on using the fine grained concurrent containers next. Ideally we can make use of the real meat of the product, but that requires rethinking how we build our code. I really like the ideas in TBB, but it's not easy to retrofit onto a code base. You can't think of TBB as another threading library. They have a whole new model that really sits on top of threads and abstracts the threads away. You learn to think in task, parallel_for type operations and pipelines. If I were to build a new project I would probably try to model it in this fashion. We work in Visual Studio and it works just fine. It was originally written for linux/pthreads so it runs just fine over there also.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/825/" ] }
106,864
I am using Adobe Captivate 3 and am having trouble disabling the typing noise when using a recording. Sometimes when I have this 'feature' disabled and make a recording, it doesn't make the typing sound, but when I publish the project, the typing sound returns. Also, I have other projects I am working on where the typing sound wasn't initially disabled during the recording and I can't get it to stop making that typing noise. Any suggestions on how to disable the typing sound permanently within a new or existing Captivate project?
I've introduced it into our code base because we needed a bettor malloc to use when we moved to a 16 core machine. With 8 and under it wasn't a significant issue. It has worked well for us. We plan on using the fine grained concurrent containers next. Ideally we can make use of the real meat of the product, but that requires rethinking how we build our code. I really like the ideas in TBB, but it's not easy to retrofit onto a code base. You can't think of TBB as another threading library. They have a whole new model that really sits on top of threads and abstracts the threads away. You learn to think in task, parallel_for type operations and pipelines. If I were to build a new project I would probably try to model it in this fashion. We work in Visual Studio and it works just fine. It was originally written for linux/pthreads so it runs just fine over there also.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/106864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19456/" ] }