Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
When overriding the equals() function of java.lang.Object, the javadocs suggest that, > it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes. The hashCode() method must return a **unique integer** for each object (this is easy to do when comparing objects based on memory location, simply return the **unique integer** address of the object) How should a hashCode() method be overriden so that it returns a **unique integer** for each object based only on that object's properities? ``` public class People{ public String name; public int age; public int hashCode(){ // How to get a unique integer based on name and age? } } /*******************************/ public class App{ public static void main( String args[] ){ People mike = new People(); People melissa = new People(); mike.name = "mike"; mike.age = 23; melissa.name = "melissa"; melissa.age = 24; System.out.println( mike.hasCode() ); // output? System.out.println( melissa.hashCode(); // output? } } ```
It doesn't say the hashcode for an object has to be completely unique, only that the hashcode for two equal objects returns the same hashcode. It's entirely legal to have two non-equal objects return the same hashcode. However, the more unique a hashcode distribution is over a set of objects, the better performance you'll get out of HashMaps and other operations that use the hashCode. IDEs such as IntelliJ Idea have built-in generators for equals and hashCode that generally do a pretty good job at coming up with "good enough" code for most objects (and probably better than some hand-crafted overly-clever hash functions). For example, here's a hashCode function that Idea generates for your People class: ``` public int hashCode() { int result = name != null ? name.hashCode() : 0; result = 31 * result + age; return result; } ```
I won't go in to the details of hashCode uniqueness as Marc has already addressed it. For your `People` class, you first need to decide what equality of a person means. Maybe equality is based solely on their name, maybe it's based on name and age. It will be domain specific. Let's say equality is based on name and age. Your overridden `equals` would look like ``` public boolean equals(Object obj) { if (this==obj) return true; if (obj==null) return false; if (!(getClass().equals(obj.getClass())) return false; Person other = (Person)obj; return (name==null ? other.name==null : name.equals(other.name)) && age==other.age; } ``` Any time you override `equals` you must override `hashCode`. Furthermore, `hashCode` can't use any more fields in its computation than `equals` did. Most of the time you must add or exclusive-or the hash code of the various fields (hashCode should be fast to compute). So a valid `hashCode` method might look like: ``` public int hashCode() { return (name==null ? 17 : name.hashCode()) ^ age; } ``` Note that the following is **not valid** as it uses a field that `equals` didn't (height). In this case two "equals" objects could have a different hash code. ``` public int hashCode() { return (name==null ? 17 : name.hashCode()) ^ age ^ height; } ``` Also, it's perfectly valid for two non-equals objects to have the same hash code: ``` public int hashCode() { return age; } ``` In this case Jane age 30 is not equal to Bob age 30, yet both their hash codes are 30. While valid this is undesirable for performance in hash-based collections.
How to ensure hashCode() is consistent with equals()?
[ "", "java", "object", "equals", "hashcode", "" ]
I'm trying to write a small wsgi application which will put some objects to an external queue after each request. I want to make this in batch, ie. make the webserver put the object to a buffer-like structure in memory, and another thread and/or process for sending these objects to the queue in batch, when buffer is big enough or after certain timeout, and clearing the buffer. I don't want to be in NIH syndrome and not want to bother with threading stuff, however I could not find a suitable code for this job. Any suggestions?
Examine <https://docs.python.org/library/queue.html> to see if it meets your needs.
Since you write "thread and/or *process*", see also [multiprocessing.Queue and multiprocessing.JoinableQueue](http://docs.python.org/library/multiprocessing.html#pipes-and-queues) from 2.6. Those are interprocess variants of Queue.
Implementing a buffer-like structure in Python
[ "", "python", "multithreading", "data-structures", "message-queue", "" ]
What language is Sun's `JVM` written in?
Sun actually has multiple JVMs. The [HotSpot JVM](http://OpenJDK.Java.Net/groups/hotspot/) is written largely in C++, because HotSpot is heavily based on the [Animorphic Smalltalk VM](http://Strongtalk.Org/) which is [written in C++](http://Code.Google.Com/p/strongtalk/source/browse/#svn/trunk/vm). More interesting than HotSpot is IMHO the [Maxine Research VM](http://Research.Sun.Com/projects/maxine/), which is [written (almost) completely in Java](http://Kenai.Com/projects/maxine/sources/maxine/show).
Strictly speaking, C++ (the JVM code does make use of C++ OO facilities).
What is Java written in?
[ "", "java", "jvm", "" ]
Is there a way I can write text to a file from a certain point in the file? For example, I open a file of 10 lines of text but I want to write a line of text to the 5th line. I guess one way is to get the lines of text in the file back as an array using the readalllines method, and then add a line at a certain index in the array. But there is a distinction in that some collections can only add members to the end and some at any destination. To double check, an array would always allow me to add a value at any index, right? (I'm sure one of my books said other wise). Also, is there a better way of going about this? Thanks
Oh, sigh. Look up the "master file update" algorithm. here's pseudocode: ``` open master file for reading. count := 0 while not EOF do read line from master file into buffer write line to output file count := count + 1 if count = 5 then write added line to output file fi od rename output file to replace input file ```
If you're reading/writing small files (say, under 20 megabytes--yes I consider 20M "small") and not writing them that often (as in, not several times a second) then just read/write the whole thing. Serial files like text documents aren't designed for random access. That's what databases are for.
Writing text to the middle of a file
[ "", "c#", "" ]
What are some of the biggest design flaws in C# or the .NET Framework in general? Example: there is no non-nullable string type and you have to check for DBNull when fetching values from an IDataReader.
I agree emphatically with [this post](https://stackoverflow.com/questions/411906/c-net-design-flaws/413093#413093) (for those poo-pooing the lack of ToString, there is a debugger attribute to provide a custom format for your class). On top of the above list, I would also add the following reasonable requests: 1. non-nullable reference types as a complement to nullable value types, 2. allow overriding a struct's empty constructor, 3. allow generic type constraints to specify sealed classes, 4. I agree with another poster here that requested arbitrary constructor signatures when used as constraints, ie. where `T : new(string)`, or where `T : new(string, int)` 5. I also agree with another poster here about fixing events, both for empty event lists and in the concurrent setting (though the latter is tricky), 6. operators should be defined as extension methods, and not as static methods of the class (or not just as static methods at least), 7. allow static properties and methods for interfaces (Java has this, but C# does not), 8. allow event initialization in object initializers (only fields and properties are currently allowed), 9. why is the "object initializer" syntax only usable when creating an object? Why not make it available at any time, ie. `var e = new Foo(); e { Bar = baz };` 10. [fix quadratic enumerable behaviour](https://github.com/dotnet/csharplang/issues/378), 11. all collections should have immutable snapshots for iteration (ie. mutating the collection should not invalidate the iterator), 12. tuples are easy to add, but an efficient closed algebraic type like "`Either<T>`" is not, so I'd love some way to declare a closed algebraic type and enforce exhaustive pattern matching on it (basically first-class support for the visitor pattern, but far more efficient); so just take enums, extend them with exhaustive pattern matching support, and don't allow invalid cases, 13. I'd love support for pattern matching in general, but at the very least for object type testing; I also kinda like the switch syntax proposed in another post here, 14. I agree with another post that the `System.IO` classes, like `Stream`, are somewhat poorly designed; any interface that requires some implementations to throw `NotSupportedException` is a bad design, 15. `IList` should be much simpler than it is; in fact, this may be true for many of the concrete collection interfaces, like `ICollection`, 16. too many methods throw exceptions, like IDictionary for instance, 17. I would prefer a form of checked exceptions better than that available in Java (see the research on type and effect systems for how this can be done), 18. fix various annoying corner cases in generic method overload resolution; for instance, try providing two overloaded extension methods, one that operates on reference types, and the other on nullable struct types, and see how your type inference likes that, 19. provide a way to safely reflect on field and member names for interfaces like `INotifyPropertyChanged`, that take the field name as a string; you can do this by using an extension method that takes a lambda with a `MemberExpression`, ie. `() => Foo`, but that's not very efficient, * Update: C# 6.0 added the `nameof()` operator for single member names, but it doesn't work in generics (`nameof(T) == "T"` instead of the actual type-argument's name: you still need to do `typeof(T).Name`)) - nor does it allow you to get a "path" string, e.g. `nameof(this.ComplexProperty.Value) == "Value"` limiting its possible applications. 20. allow operators in interfaces, and make all core number types implement `IArithmetic`; other useful shared operator interfaces are possible as well, 21. make it harder to mutate object fields/properties, or at the very least, allow annotating immutable fields and make the type checker enforce it (just treat it as getter-only property fer chrissakes, it's not hard!); in fact, unify fields and properties in a more sensible way since there's no point in having both; C# 3.0's automatic properties are a first step in this direction, but they don't go far enough, * Update: While C# had the `readonly` keyword, and C# 6.0 added read-only auto-properties, though it isn't as stringent as true language support for immutable types and values. 22. simplify declaring constructors; I like F#'s approach, but the other post here that requires simply "new" instead of the class name is better at least, That's enough for now I suppose. These are all irritations I've run into in the past week. I could probably go on for hours if I really put my mind to it. C# 4.0 is already adding named, optional and default arguments, which I emphatically approve of. Now for one unreasonable request: 1. it'd be **really, really** nice if C#/CLR could support type constructor polymorphism, ie. generics over generics, Pretty please? :-)
* the `Reset()` method on `IEnumerator<T>` was a mistake (for iterator blocks, the language spec even *demands* that this throws an exception) * the reflection methods that return arrays were, in Eric's view, [a mistake](http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx) * array covariance was and remains an oddity + Update: C# 4.0 with .NET 4.0 added covariant/contravariance support to generic interfaces (like `IEnumerable<out T>` and `Func<in T, out TResult>`, but not concrete types (like `List<T>`). * `ApplicationException` rather fell out of favor - was that a mistake? * synchronized collections - a nice idea, but not necessarily useful in reality: you usually need to synchronize *multiple* operations (`Contains`, then `Add`), so a collection that synchronizes distinct operations isn't all that useful + Update: [The `System.Collections.Concurrent` types](https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent?view=netframework-4.8), with `TryAdd`, `GetOrAdd`, `TryRemove`, etc were added in .NET Framework 4.0 - though methods that accept a factory delegate do not guarantee the factory will only be invoked once per key. * more use could have been made of the `using`/`lock` pattern - perhaps allowing them to share a re-usable (extensible?) syntax; you can simulate this by returning `IDisposable` and using `using`, but it could have been clearer * iterator blocks : no simple way of checking arguments ahead-of-time (rather than lazily). Sure, you can write two chained methods, but that is ugly * simpler immutability would be nice; C# 4.0 helps [a bit](http://marcgravell.blogspot.com/2008/11/immutability-and-optional-parameters.html), but not quite enough * no "this ref-type parameter cannot be null" support - although contracts (in 4.0) help with this somewhat. But syntax like `Foo(SqlConnection! connection)` (that injects a null-check / `throw`) would be nice (contrast to `int?` etc) + Update: [This is fixed in C# 8.0](https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references). * lack of support of operators and non-default constructors with generics; C# 4.0 solves this a bit with `dynamic`, or you can enable it [like this](http://www.pobox.com/~skeet/csharp/miscutil/usage/genericoperators.html) * the iterator variable being declared *outside* the while in the `foreach` expansion, meaning that anon-methods/lambdas capture the single variable, rather than one per iteration (painful with threading/async/etc) + Update: [This was fixed in C# 5.0](https://stackoverflow.com/questions/12112881/has-foreachs-use-of-variables-been-changed-in-c-sharp-5).
C# (.NET) Design Flaws
[ "", "c#", ".net", "" ]
Which one is recommended considering readability, memory usage, other reasons? **1.** ``` String strSomething1 = someObject.getSomeProperties1(); strSomething1 = doSomeValidation(strSomething1); String strSomething2 = someObject.getSomeProperties2(); strSomething2 = doSomeValidation(strSomething2); String strSomeResult = strSomething1 + strSomething2; someObject.setSomeProperties(strSomeResult); ``` **2.** ``` someObject.setSomeProperties(doSomeValidation(someObject.getSomeProperties1()) + doSomeValidation(someObject.getSomeProperties2())); ``` If you would do it some other way, what would that be? Why would you do that way?
I would probably go in-between: ``` String strSomething1 = doSomeValidation(someObject.getSomeProperties1()); String strSomething2 = doSomeValidation(someObject.getSomeProperties2()); someObject.setSomeProperties(strSomething1 + strSomething2); ``` Option #2 seems like a lot to do in one line. It's readable, but takes a little effort to parse. In option #1, each line is very readable and clear in intent, but the verbosity slows me down when I'm going over it. I'd try to balance brevity and clarity as above, with each line representing a simple "sentence" of code.
I'd go with: ``` String strSomething1 = someObject.getSomeProperties1(); String strSomething2 = someObject.getSomeProperties2(); // clean-up spaces strSomething1 = removeTrailingSpaces(strSomething1); strSomething2 = removeTrailingSpaces(strSomething2); someObject.setSomeProperties(strSomething1 + strSomething2); ``` My personal preference is to organize by action, rather than sequence. I think it just reads better.
What is preferred option for assignment and formatting?
[ "", "java", "optimization", "refactoring", "coding-style", "" ]
I have been tasked with creating a program what will create take files in specified folders and create an installer based on those files. For example, having a folder for "All User's Desktop", "Start menu", "Application Data", and "Program Files" My boss wants to put the files into each folder, then click a button and it automatically builds the installer. I am limited to what is in the default install of VS2005. I have looked into the Setup Project/Setup Wizard project templates, but it looks like they have to be created specifically for each project that is going to be used to install them. Is this possible under VS2005? **EDIT:** I like the suggestions, but I forgot to say that we cannot install another product to help.
I know it goes completely against what you're asking for, but depending on your usage it'd probably be many times more efficient to just buy a product that creates windows installers. Installer software does so much more, and if you build something with limited functionality now the chances are that your boss will then want feature X, then feature Y, etc and you'll end up reinventing the wheel at far greater cost and frustration.
Well, with C# on its own an VS2005 its going to be hard. But you could use [WiX](http://wix.sourceforge.net/) as way to go, complete the XML for the installer with c# and build it from your tool using candle and light from the wix-toolkit.
C# Generic Setup Wizard
[ "", "c#", "windows-installer", "" ]
I'm interested in how much up front validation people do in the Python they write. Here are a few examples of simple functions: ``` def factorial(num): """Computes the factorial of num.""" def isPalindrome(inputStr): """Tests to see if inputStr is the same backwards and forwards.""" def sum(nums): """Same as the built-in sum()... computes the sum of all the numbers passed in.""" ``` How thoroughly do you check the input values before beginning computation, and how do you do your checking? Do you throw some kind of proprietary exception if input is faulty (BadInputException defined in the same module, for example)? Do you just start your calculation and figure it will throw an exception at some point if bad data was passed in ("asd" to factorial, for example)? When the passed in value is supposed to be a container do you check not only the container but all the values inside it? What about situations like factorial, where what's passed in might be convertible to an int (e.g. a float) but you might lose precision when doing so?
For calculations like sum, factorial etc, pythons built-in type checks will do fine. The calculations will end upp calling **add**, **mul** etc for the types, and if they break, they will throw the correct exception anyway. By enforcing your own checks, you may invalidate otherwise working input.
I `assert` what's absolutely essential. Important: What's *absolutely* essential. Some people over-test things. ``` def factorial(num): assert int(num) assert num > 0 ``` Isn't completely correct. long is also a legal possibility. ``` def factorial(num): assert type(num) in ( int, long ) assert num > 0 ``` Is better, but still not perfect. Many Python types (like rational numbers, or number-like objects) can also work in a good factorial function. It's hard to assert that an object has basic integer-like properties without being too specific and eliminating future unthought-of classes from consideration. I never define unique exceptions for individual functions. I define a unique exception for a significant module or package. Usually, however, just an `Error` class or something similar. That way the application says `except somelibrary.Error,e:` which is about all you need to know. Fine-grained exceptions get fussy and silly. I've never done this, but I can see places where it might be necessary. ``` assert all( type(i) in (int,long) for i in someList ) ``` Generally, however, the ordinary Python built-in type checks work fine. They find almost all of the exceptional situations that matter almost all the time. When something isn't the right type, Python raises a TypeError that always points at the right line of code. BTW. I only add asserts at design time if I'm absolutely certain the function will be abused. I sometimes add assertions later when I have a unit test that fails in an obscure way.
How much input validation should I be doing on my python functions/methods?
[ "", "python", "validation", "" ]
I have the following code, which will not work. The javascript gives no errors and appears to load fine. but clicking on a link will do nothing. An example of a link is: ``` <a href="#" onclick="updateByQuery('Layer3', "Ed Hardy");">Link 1</a><li>Link 2</li> ``` and the code: ``` var xmlHttp var layername var url function update(layer, url) { var xmlHttp=GetXmlHttpObject(); //you have this defined elsewhere if(xmlHttp==null) { alert("Your browser is not supported?"); } xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById(layer).innerHTML=xmlHttp.responseText; } else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") { document.getElementById(layer).innerHTML="loading"; } //etc } xmlHttp.open("GET",url,true); xmlHttp.send(null); } function updateByPk(layer, pk) { url = "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random(); update(layer, url); } function updateByQuery(layer, query) { url = "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random(); update(layer, url); } function GetXmlHttpObject() { var xmlHttp=null; try { xmlHttp=new XMLHttpRequest(); }catch (e) { try { xmlHttp =new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } return xmlHttp; } function makewindows(){ child1 = window.open ("about:blank"); child1.document.write(<?php echo htmlspecialchars(json_encode($row2["ARTICLE_DESC"]), ENT_QUOTES); ?>); child1.document.close(); } ```
It may probably be due to the double-quote characters surrounding 'Ed Hardy'. Does this work: ``` <a href="#" onclick="updateByQuery('Layer3', 'Ed Hardy');">Link 1</a><li>Link 2</li> ```
From the wonderful [JSLint](http://jslint.com) You are missing semicolons after these ``` var xmlHttp var layername var url xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") { document.getElementById(layer).innerHTML=xmlHttp.responseText; } else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") { document.getElementById(layer).innerHTML="loading"; } //etc } ``` (e) is used 2x, change the second to 'ex'. ``` try { xmlHttp=new XMLHttpRequest(); }catch (e) { try { xmlHttp =new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } ``` Try using single quotes for EVERYTHING in JS, and use double quotes for EVERYTING in PHP. Get Firebug to see if there are any other syntax errors.
javascript wont load, no clear error
[ "", "javascript", "" ]
I would like to parse a document using SAX, and create a subdocument from some of the elements, while processing others purely with SAX. So, given this document: ``` <DOC> <small> <element /> </small> <entries> <!-- thousands here --> </entries> </DOC> ``` I would like to parse the DOC and DOC/entries elements using the SAX ContentHandler, but when I hit `<small>` I want to create a new document containing just the `<small>` and its children. Is there an easy way to do this, or do I have to build the DOM myself, by hand?
One approach is to create a `ContentHandler` that watches for events that signal the entry or exit from a `<small>` element. This handler acts as a proxy, and in "normal" mode passes the SAX events straight through to the "real" `ContentHandler`. However, when entry into a `<small>` element is detected, the proxy is responsible for the creation of a [`TransformerHandler`](http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/transform/sax/SAXTransformerFactory.html#newTransformerHandler()) (with a no-op, "null" transform), [plumbed](http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/transform/sax/TransformerHandler.html#setResult(javax.xml.transform.Result)) up to a [`DOMResult`](http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/transform/dom/DOMResult.html). The `TransformerHandler` expects all the events that a complete, well-formed document would produce; you cannot immediately send it a `startElement` event. Instead, simulate the beginning of a new document by invoking `setDocumentLocator`, `startDocument`, and other necessary events on the `TransformerHandler` instance first. Then, until the end of the `<small>` element element is detected by the proxy, all events are forwarded to this `TransformerHandler` instead of the "real" `ContentHandler`. When the closing `</small>` tag is encountered, the proxy simulates the end of a document by invoking `endDocument` on the `TransformerHandler`. A DOM is now available as the result of the `TransformerHandler`, which contains only the `<small />` fragment.
Seems to me the answer depends on whether you need the 'new document' in memory. If you do then use DOM, alternatively if you're just going to stream the 'new document' then StAX would probably fit better with the event-driven nature of SAX.
Nesting SAX ContentHandlers
[ "", "java", "xml", "dom", "parsing", "sax", "" ]
I have a bunch of Spring beans which are picked up from the classpath via annotations, e.g. ``` @Repository("personDao") public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao { // Implementation omitted } ``` In the Spring XML file, there's a [PropertyPlaceholderConfigurer](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html) defined: ``` <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="/WEB-INF/app.properties" /> </bean> ``` I want to inject one of the properties from app.properites into the bean shown above. I can't simply do something like ``` <bean class="com.example.PersonDaoImpl"> <property name="maxResults" value="${results.max}"/> </bean> ``` Because PersonDaoImpl does not feature in the Spring XML file (it is picked up from the classpath via annotations). I've got as far as the following: ``` @Repository("personDao") public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao { @Resource(name = "propertyConfigurer") protected void setProperties(PropertyPlaceholderConfigurer ppc) { // Now how do I access results.max? } } ``` But it's not clear to me how I access the property I'm interested in from `ppc`?
You can do this in Spring 3 using EL support. Example: ``` @Value("#{systemProperties.databaseName}") public void setDatabaseName(String dbName) { ... } @Value("#{strategyBean.databaseKeyGenerator}") public void setKeyGenerator(KeyGenerator kg) { ... } ``` `systemProperties` is an implicit object and `strategyBean` is a bean name. One more example, which works when you want to grab a property from a `Properties` object. It also shows that you can apply `@Value` to fields: ``` @Value("#{myProperties['github.oauth.clientId']}") private String githubOauthClientId; ``` Here is a [blog post](https://web.archive.org/web/20170609134527/http://springinpractice.com/2008/12/02/new-stuff-in-spring-30/) I wrote about this for a little more info.
Personally I love this new way in Spring 3.0 [from the docs](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/new-in-3.html): ``` private @Value("${propertyName}") String propertyField; ``` No getters or setters! With the properties being loaded via the config: ``` <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="classpath:propertyFile.properties" name="propertiesBean"/> ``` To further my glee I can even control click on the EL expression in IntelliJ and it brings me to the property definition! There's also the totally **non xml version**: ``` @PropertySource("classpath:propertyFile.properties") public class AppConfig { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } ```
How can I inject a property value into a Spring Bean which was configured using annotations?
[ "", "java", "spring", "dependency-injection", "" ]
This is driving me nuts. I am using some 3rd-party code in a Windows .lib that, in debug mode, is causing an error similar to the following: ``` Run-Time Check Failure #2 - Stack around the variable 'foo' was corrupted. ``` The error is thrown when either the object goes out of scope or is deleted. Simply allocating one of these objects and then deleting it will throw the error. I therefore think the problem is either in one of the many constructors/destructors but despite stepping through every line of code I cannot find the problem. However, this only happens when creating one of these objects in a static library. If I create one in my EXE application, the error does not appear. The 3rd-party code itself lives in a static lib. For example, this fails: ``` **3RDPARTY.LIB** class Foo : public Base { ... }; **MY.LIB** void Test() { Foo* foo = new Foo; delete foo; // CRASH! } **MY.EXE** void Func() { Test(); } ``` But this will work: ``` **3RDPARTY.LIB** class Foo : public Base { ... }; **MY.EXE** void Func() { Foo* foo = new Foo; delete foo; // NO ERROR } ``` So, cutting out the 'middle' .lib file makes the problem go away and it is this weridness that is driving me mad. The EXE and 2 libs all use the same CRT library. There are no errors linking. The 3rd-party code uses inheritance and there are 5 base classes. I've commented out as much code as I can whilst still getting it to build and I just can't see what's up. So if anyone knows why code in a .lib would act differently to the same code in a .exe, I would love to hear it. Ditto any tips for tracking down memory overwrites! I am using Visual Studio 2008.
OK, I tracked the problem down and it's a cracker, if anyone's interested. Basically, my .LIB, which exhibited the problem. had defined `_WIN32_WINNT` as `0x0501` (Windows 2000 and greater), but my EXE and the 3rd-party LIB had it defined as `0x0600` (Vista). Now, one of the headers included by the 3rd-party lib is `sspi.h` which defines a structure called `SecurityFunctionTable` which includes the following snippet: ``` #if OSVER(NTDDI_VERSION) > NTDDI_WIN2K // Fields below this are available in OSes after w2k SET_CONTEXT_ATTRIBUTES_FN_W SetContextAttributesW; #endif // greater thean 2K ``` Th cut a long story short, this meant a mismatch in object sizes between the LIBs and this was causing the Run-Time Check Failure. Class!
One possibility is that it's a [calling convention](http://en.wikipedia.org/wiki/Calling_convention) mismatch - make sure that your libraries and executables are all set to use the same default calling convention (usually \_\_cdecl). To set that, open up your project properties and go to **Configuration Properties > C/C++ > Advanced** and look at the **Calling Convention** option. If you call a function with the wrong calling convention, you'll completely mess up the stack.
Trouble tracking down a potential memory overwrite. Windows weirdness
[ "", "c++", "windows", "" ]
How can I build a numpy array out of a generator object? Let me illustrate the problem: ``` >>> import numpy >>> def gimme(): ... for x in xrange(10): ... yield x ... >>> gimme() <generator object at 0x28a1758> >>> list(gimme()) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> numpy.array(xrange(10)) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> numpy.array(gimme()) array(<generator object at 0x28a1758>, dtype=object) >>> numpy.array(list(gimme())) array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) ``` In this instance, `gimme()` is the generator whose output I'd like to turn into an array. However, the array constructor does not iterate over the generator, it simply stores the generator itself. The behaviour I desire is that from `numpy.array(list(gimme()))`, but I don't want to pay the memory overhead of having the intermediate list and the final array in memory at the same time. Is there a more space-efficient way?
Numpy arrays require their length to be set explicitly at creation time, unlike python lists. This is necessary so that space for each item can be consecutively allocated in memory. Consecutive allocation is the key feature of numpy arrays: this combined with native code implementation let operations on them execute much quicker than regular lists. Keeping this in mind, it is technically impossible to take a generator object and turn it into an array unless you either: 1. can predict how many elements it will yield when run: ``` my_array = numpy.empty(predict_length()) for i, el in enumerate(gimme()): my_array[i] = el ``` 2. are willing to store its elements in an intermediate list : ``` my_array = numpy.array(list(gimme())) ``` 3. can make two identical generators, run through the first one to find the total length, initialize the array, and then run through the generator again to find each element: ``` length = sum(1 for el in gimme()) my_array = numpy.empty(length) for i, el in enumerate(gimme()): my_array[i] = el ``` **1** is probably what you're looking for. **2** is space inefficient, and **3** is time inefficient (you have to go through the generator twice).
One google behind this stackoverflow result, I found that there is a [`numpy.fromiter(data, dtype, count)`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromiter.html). The default `count=-1` takes all elements from the iterable. It requires a `dtype` to be set explicitly. In my case, this worked: `numpy.fromiter(something.generate(from_this_input), float)`
How do I build a numpy array from a generator?
[ "", "python", "numpy", "generator", "" ]
I've been reading Bruce Eckel's [Thinking In Java](http://www.mindview.net/Books/TIJ/) and in the chapter on generics, he briefly mentions the [Nice programming language](http://nice.sourceforge.net/index.html) as something that handles parametrized types better than Java, but compiles into Java bytecode. Does anyone have any experience with this? Generics make my head hurt, so the prospect of an alternative that interoperates with Java is appealing... but I sort of feel like it would be like trying to learn both French and Quebecois and getting yelled at if I get them mixed up in the wrong context. (no offense meant so please don't ding me for not being PC) And whoever thought up the name "Nice" should be shot, since it makes it impossible to search for any websites other than the sourceforge one.
I'd also suggest looking at [Scala](http://www.scala-lang.org/), a multi-paradigm (OO and functional) language that runs on the JVM. Martin Odersky, the "father of Scala" was also a primary contributor to the implementation of generics in Java, including his work on the Pizza and GJ implementations. The current type-erasure mechanism in Java does force one to understand some implementation details to make sense of restrictions, but it is fair to say that using full-blown generic support in *any* language is going to require a learning curve. I found [Java Generics and Collections](https://rads.stackoverflow.com/amzn/click/com/0596527756) to be a well-written introduction and guide to using generics in Java 5.
Maybe the question to ask is, "Why do generics make your head hurt?" How are you using them that causes such pain? I'll agree that there are flaws with generics in Java, and there are situations (e.g., extends) that do cause problems, but what exactly is your issue? Using another language that compiles to byte code might help you in the short run, but if you're working in a team that delivers systems that others will have to maintain you might have problems introducing a technology like Nice, no matter how elegant it is.
the Nice programming language as an alternative to Java generics
[ "", "java", "generics", "nice-language", "" ]
Is that possible to have a single PHP SOAP server which will handle requests to several classes (services)? If yes, could you please show an example implementation? If not, could you please describe why?
Could you wrap the other services in a single class? Completely untested, it was just a thought... ``` class MySoapService { public function __construct() { $this->_service1 = new Service1(); $this->_service2 = new Service2(); } // You could probably use __call() here and intercept any calls, // thus avoiding the need for these declarations in the wrapper class... public function add($a, $b) { return $this->_service1->add($a, $b); } public function sub($a, $b) { return $this->_service2->sub($a, $b); } } class Service1 { public function add($a, $b) { return $a + $b; } } class Service2 { public function sub($a, $b) { return $a - $b; } } ```
If both classes had methods with identical names (but different parameters) then you could use func\_get\_args() to analyze the arguments and differentiate between the methods that way. If they take the same arguments... then you're kinda stuck. Why can't you just use two separate Web Services?
Handle requests to several classes within the same PHP SOAP server
[ "", "php", "web-services", "soap", "wsdl", "" ]
Consider the following table: ``` mysql> select * from phone_numbers; +-------------+------+-----------+ | number | type | person_id | +-------------+------+-----------+ | 17182225465 | home | 1 | | 19172225465 | cell | 1 | | 12129876543 | home | 2 | | 13049876543 | cell | 2 | | 15064223454 | home | 3 | | 15064223454 | cell | 3 | | 18724356798 | home | 4 | | 19174335465 | cell | 5 | +-------------+------+-----------+ ``` I'm trying to find those people who have home phones but not cells. This query works: ``` mysql> select h.* -> from phone_numbers h -> left join phone_numbers c -> on h.person_id = c.person_id -> and c.type = 'cell' -> where h.type = 'home' -> and c.number is null; +-------------+------+-----------+ | number | type | person_id | +-------------+------+-----------+ | 18724356798 | home | 4 | +-------------+------+-----------+ ``` but this one doesn't: ``` mysql> select h.* -> from phone_numbers h -> left join phone_numbers c -> on h.person_id = c.person_id -> and h.type = 'home' -> and c.type = 'cell' -> where c.number is null; +-------------+------+-----------+ | number | type | person_id | +-------------+------+-----------+ | 19172225465 | cell | 1 | | 13049876543 | cell | 2 | | 15064223454 | cell | 3 | | 18724356798 | home | 4 | | 19174335465 | cell | 5 | +-------------+------+-----------+ ``` The only difference between the two is the location of the `h.type = 'home'` condition - in the first it's in the `where` clause and in the second it's part of the `on` clause. Why doesn't the second query return the same result as the first?
In the second SQL, the condition h.type = 'home' is part of the outer join conditions, and is not a filter on the results. For all records where h.type='cell', the condition h.type = 'home' is FALSE and so no "matching" c row is found - so c.number is null, which is your only filtering (WHERE) condition. In pseudo-code your 2nd SQL works like this: ``` for each row in phone_numbers h /* Note this is ALL home AND cell phones */ select c.number from phone_numbers c where h.person_id = c.person_id and h.type = 'home' and c.type = 'cell'; if c.number is null (i.e. no row found) display h.* end if end loop; ```
When doing left joins I approach things this way. In the join you need to specify anny fields that actually link the two tables together and any filtering condition from the right side (2nd table in the join) of the join (with one exception, I'll get to shortly). Filtering conditions from the left side of the join(1st table) should be in the where clause or they will wrongly affect the join as you saw (and as Tony so nicely explained). The only time the right side of the join should be in the where clause is if you are looking for null values in that table (i.e., the records which are in the first table but not the second).
self join query
[ "", "sql", "mysql", "join", "self-join", "" ]
Hopefully, this will be an easy answer for someone with Javascript time behind them... I have a log file that is being watched by a script that feeds new lines in the log out to any connected browsers. A couple people have commented that what they want to see is more of a 'tail -f' behavior - the latest lines will always be at the bottom of the browser page until the viewer scrolls back up to see something. Scrolling back to the bottom should return you to the auto-scrolling behavior. My google strikeout on this one is - hopefully - just a matter of not knowing anything at all about javascript and therefore, not knowing what keywords to search for. I don't need a complete solution - just a 'close enough' that lets me jump in and get my hands dirty. EDIT: I've been attempting the scrollTop/scrollHeight idea, but am clearly missing something. I've done next to nothing with Javascript, so again I'm probably asking very low-level questions: ``` <html><body> <script type="text/javascript"> for (i=0; i<100; i++) { document.write("" + i + "<br />"); document.scrollTop = document.scrollHeight; } </script> </body></html> ``` This was one of many permutations. Obviously, I can't output the log line-by-line in javascript, but I'm just trying to see the correct behavior. What's the missing link I need here? EDIT AGAIN: This has turned into a far more interesting problem that I first expected. The code suggestion using window.scroll does do the trick. I started playing with restricting the scroll to only take place when the browser was at the bottom of the document body. This is easy enough to do in theory, but in practice it hits a snag: Every time you get new text from the server, the size of the body increases and your current scroll position is no longer at the bottom of the document. You can no longer tell the difference (using scrollHeight, clientHeight and scrollTop) whether the user has scrolled up or if the text has just shot beyond their view. I think that if this is going to work, I'm going to have to commit myself to having a JS event that fires when the user scrolls and turns off scrolling if they are above the bottom of the window, but turns it back on if they have scrolled down to the point where they are effectively at the bottom of the view. I'm looking at the onScroll event and, given that the math on the variables I mentioned works out pretty well, I think I am on the right path here. Thanks for your input, everyone!
``` x = 0; //horizontal coord y = document.height; //vertical coord window.scroll(x,y); ```
To scroll the whole document use this: ``` window.scrollTo(0, document.body.scrollHeight); ``` if you have just a single scrollable div or something then the process is different: ``` var obj = $('id'); obj.scrollTop = obj.scrollHeight; ```
Javascript mechanism to autoscroll to the bottom of a growing page?
[ "", "javascript", "browser", "scroll", "" ]
Wish to simultaneously call a function multiple times. I wish to use threads to call a function which will utilize the machines capability to the fullest. This is a 8 core machine, and my requirement is to use the machine cpu from 10% to 100% or more. My requirement is to use the boost class. Is there any way I can accomplish this using the boost thread or threadpool library? Or some other way to do it? Also, if I have to call multiple functions with different parameters each time (with separate threads), what is the best way to do this? [using boost or not using boost] and how? ``` #include <iostream> #include <fstream> #include <string.h> #include <time.h> #include <boost/thread/mutex.hpp> #include <boost/bind.hpp> using namespace std; using boost::mutex; using boost::thread; int threadedAPI1( ); int threadedAPI2( ); int threadedAPI3( ); int threadedAPI4( ); int threadedAPI1( ) { cout << "Thread0" << endl; } int threadedAPI2( ) { cout << "Thread1" << endl; } int threadedAPI3( ) { cout << "Thread2" << endl; } int threadedAPI4( ) { cout << "Thread3" << endl; } int main(int argc, char* argv[]) { boost::threadpool::thread_pool<> threads(4); // start a new thread that calls the "threadLockedAPI" function threads.schedule(boost::bind(&threadedAPI1,0)); threads.schedule(boost::bind(&threadedAPI2,1)); threads.schedule(boost::bind(&threadedAPI3,2)); threads.schedule(boost::bind(&threadedAPI4,3)); // wait for the thread to finish threads.wait(); return 0; } ``` The above is not working and I am not sure why? :-(
I suggest that you read up on the documentation for the functions you use. From your comment in James Hopkin's answer, it seems like you don't know what boost::bind does, but simply copy-pasted the code. boost::bind takes a function (call it f), and optionally a number of parameters, and returns a function which, when called, calls f with the specified parameters. That is, `boost::bind(threadedAPI1, 0)()` (creating a function which takes no arguments and calls threadedAPI1() with the argument 0, and then calling that) is equivalent to `threadedAPI1(0)`. Since your threadedAPI functions don't actually take any parameters, you can't pass any arguments to them. That is just fundamental C++. You can't call `threadedAPI1(0)`, but only `threadedAPI1()`, and yet when you call the function, you try (via boost::bind) to pass the integer 0 as an argument. So the simple answer to your question is to simply define threadedAPI1 as follows: ``` int threadedAPI1(int i); ``` However, one way to avoid the boost::bind calls is to call a functor instead of a free function when launching the thread. Declare a class something like this: ``` struct threadedAPI { threadedAPI(int i) : i(i) {} // A constructor taking the arguments you wish to pass to the thread, and saves them in the class instance. void operator()() { // The () operator is the function that is actually called when the thread starts, and because it is just a regular class member function, it can see the 'i' variable initialized by the constructor cout << "Thread" << i << endl; // No need to create 4 identical functions. We can just reuse this one, and pass a different `i` each time we call it. } private: int i; }; ``` Finally, depending on what you need, plain threads may be better suited than a threadpool. In general, a thread pool only runs a limited number of threads, so it may queue up some tasks until one of its threads finish executing. It is mainly intended for cases where you have many short-lived tasks. If you have a fixed number of longer-duration tasks, creating a dedicated thread for each may be the way to go.
You're binding parameters to functions that don't take parameters: ``` int threadedAPI1( ); boost::bind(&threadedAPI1,0) ``` Just pass the function directly if there are no parameters: ``` threads.schedule(&threadedAPI1) ```
Multithreading using the boost library
[ "", "c++", "multithreading", "boost-thread", "boost-bind", "" ]
I am looking at improving a package that I believe not to be threadsafe when its input is shared between multiple worker threads. According to TDD principles, I should write some tests that fail in the first instance, and these would certainly be useful in assessing the problem. I realise that this is not a simple thing to acheive, and that naively, multi-threaded tests will be nondeterministic as the operating system will determine scheduling and the exact order that various operations are interleaved. I have looked at and used [MultithreadedTC](http://www.cs.umd.edu/projects/PL/multithreadedtc/overview.html) in the past, and this was useful. However, in that case I knew in advance exactly where the existing implementation fell down, and thus was able to cook up a nice set of tests that covered it. However, if you're not at the point where you know exactly what the problem is, is there a good way of going about writing a test that stands a good chance of throwing up any potential problems? Are there any libraries that others have found helpful? Would I be right in thinking that from a purist point of view, a multi-threaded test case should just be the same calls and assertions as the usual single-threaded test, only run with multiple worker threads as appropriate? Any offers on tools/best practices/philosophy in general would be welcome.
Forget getting good results by testing for concurrency problems. Attempt to reduce synchronization and make the problem smaller. Then use as high as possible library support to do synchronization. And only if you really have then try to handle the concurrency yourself. When you know each worker does its work correct and all your thinking tell you that you have the concurrency problem licked then generate some interesting load. Unittest frameworks and their extensions can do that job, but know that you are not testing any units anymore. (Remember, you already had that part covered) If your concurrency model gets complicated check out tools suited for that like [SPIN](http://spinroot.com/spin/whatispin.html).
[Java Concurrency in Practice](http://jcip.net/) has some great information about how to write tests for concurrency issues. However they are not true unit tests. It is nearly impossible to write a true unit test for a concurrency issue. Basically it boils down to this. Create a bunch of test threads and start them. Each thread should * wait for a count down latch * repeatedly call some method that modifies the mutable state in question * count down on a second latch and exit The junit thread creates all the threads and starts them, then counts down on the first latch once to let them all go, then waits for the second latch, then makes some assertions about the mutable state. Even more so than other types of bugs, it's easier to write a failing unit test for a concurrency bug *after* you have found the bug.
Any satisfactory approaches to unit testing thread safety in Java?
[ "", "java", "multithreading", "thread-safety", "" ]
I am currently writing some unit tests for a business-logic class that includes validation routines. For example: ``` public User CreateUser(string username, string password, UserDetails details) { ValidateUserDetails(details); ValidateUsername(username); ValidatePassword(password); // create and return user } ``` Should my test fixture contain tests for every possible validation error that can occur in the Validate\* methods, or is it better to leave that for a separate set of tests? Or perhaps the validation logic should be refactored out somehow? My reasoning is that if I decide to test for all the validation errors that can occur within CreateUser, the test fixture will become quite bloated. And most of the validation methods are used from more than one place... Any great patterns or suggestions in this case?
Every test should only fail for one reason and only one test should fail for that reason. This helps a lot with writing a maintainable set of unit tests. I'd write a couple of tests each for ValidateUserDetails, ValidateUsername and ValidateUserPassword. Then you only need to test that CreateUser calls those functions. --- Re read your question; Seems I misunderstood things a bit. You might be interested in what J.P Boodhoo has written on his style of behaviour driven design. <http://blog.developwithpassion.com/2008/12/22/how-im-currently-writing-my-bdd-style-tests-part-2/> BDD is becoming a very overloaded term, everyone has a different definition and different tools to do it. As far as I see what JP Boodhoo is doing is splitting up test fixtures according to concern and not class. For example you could create separate fixtures for testing Validation of user details, Validation of username, Validation of password and creating users. The idea of BDD is that by naming the testfixtures and tests the right way you can create something that almost reads like documentation by printing out the testfixture names and test names. Another advantage of grouping your tests by concern and not by class is that you'll probably only need one setup and teardown routine for each fixture. I havn't had much experience with this myself though. If you're interested in reading more, JP Boodhoo has posted a lot about this on his blog (see above link) or you can also listen to the dot net rocks episode with Scott Bellware where he talks about a similar way of grouping and naming tests <http://www.dotnetrocks.com/default.aspx?showNum=406> I hope this is more what you're looking for.
You definitely need to test *validation* methods. There is no need to test other methods for all possible combinations of arguments just to make sure validation is performed. You seem to be mixing Validation and Design by Contract. **Validation** is usually performed to friendly notify user that his input is incorrect. It is very related to business logic (password is not strong enough, email has incorrect format, etc.). **Design by Contract** makes sure your code can execute without throwing exceptions later on (even without them you would get the exception, but much later and probably more obscure one). Regarding application layer that should contain validation logic, probably the best is [service layer (by Fowler)](http://martinfowler.com/eaaCatalog/serviceLayer.html) which defines application boundaries and is a good place to sanitize application input. And there should not be any validation logic inside this boundaries, only Design By Contract to detect errors earlier. So finally, write validation logic tests when you want to friendly notify user that he has mistaken. Otherwise use Design By Contract and keep throwing exceptions.
Unit-tests and validation logic
[ "", "c#", ".net", "unit-testing", "validation", "tdd", "" ]
I was wondering which was better: ``` $lookup = array( "a" => 1, "b" => 2, "c" => 3 ); return $lookup[$key]; ``` or ``` if ( $key == "a" ) return 1 else if ( $key == "b" ) return 2 else if ( $key == "c" ) return 3 ``` or maybe just a nice switch... ``` switch($key){ case "a": return 1; case "b": return 2; case "c": return 3; } ``` I always prefer the first method as I can separate the data from the code; At this scale it looks quite silly but on a larger scale with thousands of lines of lookup entries; How much longer is PHP going to take building an array and then only checking maybe 1 or 2 entries per request. I think it'd have to be tested and clocked, but I'd say the bigger and more complicated the array the slower it's going to become. PHP Should be able to handle lookups faster than I can in PHP-code, but building the array in the first place surely takes up a lot of time.
For anything with measurable performance (not only 3 entries) lookup is fastest way. That's what hash tables are for.
First, it's easy to test it yourself. Second, and more importantly, which is most appropriate for the code you're using? The amount of time you'll save is negligible in any case.
What's quicker, an array lookup (including array build) or an IF stack?
[ "", "php", "" ]
Are there any what in the Java community would be called "application servers" for .NET? Similar to Tomcat, Resin, and Jetty. I'm not interested in a JSP equivalent, I'm looking for a servlet-based technology for XML/HTTP transaction processing (no UI). If there is not a product like this, what would a good stack be to emulate this? Microsoft appears to have dodged this by saying that Window Server + .NET + IIS + your code = app server, but it seems there is a lot of plumbing code that has to be written in order to get to an equivalent place as say Tomcat.
[WCF](http://msdn.microsoft.com/en-us/netframework/aa663324.aspx) or web services (ASMX) both seem like good candidates for what you want. WCF is probably more appropriate if you don't want to go the full SOAP route. You can host WCF in IIS, a console app, or a windows service. Depending on what you need it can use SOAP, simple XML, or even Json for encodings. As for transports you can use HTTP, IP, or Message Queues.
[Dublin](http://www.microsoft.com/net/Dublin.aspx) will be what you’re looking for, I guess.
Is there a .NET analogue for Java app servers?
[ "", "java", ".net", "servlets", "" ]
I am using hudson CI to manage a straight java web project, using ant to build. I would like to mandate that the unit test coverage never be worse than the previous build, thereby making sure any new code is always tested, or at least the coverage is continually improving. Is there a hudson plugin that works this way? Edit: I am currently using Emma, but would be willing to switch to another coverage app. Also, as a clarification, I've seen the thresholds in some Hudson plugins, but that's not exactly what I'm after. For example what I'd like is that if coverage for Build #12 was 46% overall, and someone checked in Build #13 with 45% coverage, the build would break. The reason I want to do this, is that I have a codebase with low test coverage. We don't have time to go back and retroactively write unit tests, but I'd like to make sure that the coverage keeps getting better. UPDATE: Dan pointed out an edge case with my plan that will definitely be a problem. I think I need to rethink whether this is even a good idea.
Yes. Which coverage tool are you using? The Cobertura plugin for Hudson definitely supports this. On the project configuration screen you can specify thresholds. Alternatively, you can make Ant fail the build (rather than Hudson), by using the cobertura-check task. **EDIT:** I'm not sure you can do precisely what you are asking for. Even if you could, it could prove problematic. For example, assume you have an average coverage of 75% but for one class you have coverage of 80%. If you remove that 80% class and all of its tests, you reduce the overall coverage percentage even though none of the other code is any less tested than previously.
This is kind of a hack, but we use it for similar reasons with Findbugs and Checkstyle. You can set up an Ant task to do the following (this can be split out into multiple tasks, but I'm combining them for brevity): 1. Run tests with coverage 2. Parse the coverage results and get the coverage percentage 3. Read tmp/lastCoverage.txt from last build (see step #5a) 4. Compare the current coverage percentage with the percentage read from lastCoverage.txt 5. 1. If percentage DIDN'T decrease, write the new percentage over the contents of tmp/lastCoverage.txt 2. If percentage DID decrease, keep the original file and echo "COVERAGE FAILURE" (with ant's `echo` task). Note that steps 2 through 5 don't necessarily need to be done with native Ant tasks - you could use something like Ant's `javac` task to run a Java program to do this for you. Then, configure Hudson: * Under "Source code management", make sure "Use Update" is checked. This will allow your lastCoverage.txt file to be retained between builds. Note that this could be problematic if you really, really need things to be cleaned between builds. * Use the [Hudson Text Finder](http://hudson.gotdns.com/wiki/display/HUDSON/Text-finder+Plugin) plugin with a regular expression to search for "COVERAGE FAILURE" in the build output (make sure that "Also search console output" is checked for the plugin). The text finder plugin can mark the build unstable. You can obviously replace things like the file name/path and console output to whatever fits within the context of your build. As I mentioned above, this is rather hacky, but it's probably one of the few (only?) ways to get Hudson to compare things in the previous build to the current build.
Can my build stipulate that my code coverage never get worse?
[ "", "java", "hudson", "code-coverage", "continuous-integration", "" ]
``` var insInvoice = new NpgsqlCommand( @"INSERT INTO invoice_detail( invoice_id, invoice_detail_id, product_id, qty, price, amount) VALUES ( :_invoice_id, :_invoice_detail_id, :_product_id, :_qty, :_price, :_qty * :_price)", c); with(var p = insInvoice.Parameters) { p.Add("_invoice_id", NpgsqlDbType.Uuid, 0, "invoice_id"); p.Add("_invoice_detail_id", NpgsqlDbType.Uuid, 0, "invoice_detail_id"); p.Add("_product_id", NpgsqlDbType.Uuid, 0, "product_id"); p.Add("_qty", NpgsqlDbType.Integer, 0, "qty"); p.Add("_price", NpgsqlDbType.Numeric, 0, "price"); } ``` --- ``` kludge: for(var p = insInvoice.Parameters; false;) { p.Add("_invoice_id", NpgsqlDbType.Uuid, 0, "invoice_id"); p.Add("_invoice_detail_id", NpgsqlDbType.Uuid, 0, "invoice_detail_id"); p.Add("_product_id", NpgsqlDbType.Uuid, 0, "product_id"); p.Add("_qty", NpgsqlDbType.Integer, 0, "qty"); p.Add("_price", NpgsqlDbType.Numeric, 0, "price"); } ```
As you've got an "Add" method with the right form, you can use a collection initialiser for the parameters: ``` var insInvoice = new NpgsqlCommand(sql) { Parameters = { { "_invoice_id", NpgsqlDbType.Uuid, 0, "invoice_id" }, { "_invoice_detail_id", NpgsqlDbType.Uuid, 0, "invoice_detail_id" }, { "_qty", NpgsqlDbType.Integer, 0, "qty" }, { "_price", NpgsqlDbType.Numeric, 0, "price" } } }; ``` For more on object and collection initializers, you can download chapter 8 of [C# in Depth](http://manning.com/skeet/) for free.
What's the point of it, to scope the "p" variable? In that case just create a scope with curly braces and remove the with-statement all together, move the variable declaration of "p" into the new scope. This way the "p" variable is only available within the scope of the curly braces. This you can do today without needing any syntactic sugar. I'm not sure this helps in readability though, just remove the braces all together and go with just the variable. ``` //with(var p = insInvoice.Parameters) { var p = insInvoice.Parameters; p.Add("_invoice_id", NpgsqlDbType.Uuid, 0, "invoice_id"); p.Add("_invoice_detail_id", NpgsqlDbType.Uuid, 0, "invoice_detail_id"); p.Add("_product_id", NpgsqlDbType.Uuid, 0, "product_id"); p.Add("_qty", NpgsqlDbType.Integer, 0, "qty"); p.Add("_price", NpgsqlDbType.Numeric, 0, "price"); } ```
if the with keyword is bad (for C#), is this a nice alternative?
[ "", "c#", "syntactic-sugar", "" ]
Hi im learning LISP and well, all day i program php for a living, so i was messing around with php.net and found the eval function... so i started playing around! I would love to know more about how to use eval to do crazy stuff, i know you can make functions with this and everything... but i wanted to ask why the next code wont work: ``` $var = "echo \"FOZZ\";"; for($i = 0; $i < 100; $i++) $var = "eval(\"".$var."\");"; print $var; eval($var); ``` Also what other stuff is interesting with eval!
Your statement comes out to 'eval("eval("echo"FOZZ";");")'. Your double quotes are interfering with each other and causing the error. You might want to try changin the first line to $var = "echo \'FOZZ\';"; Note: Please be careful using eval.
For the common case of web programming Ive developed a library called xilla\_tags that makes it easy to write lisp-flavoured PHP code, which can be much more readable that the traditional approach. For xilla\_tags see [xilla tags sample](http://quantblog.wordpress.com/2009/10/01/xilla_tags-php-library-make-html-with-lispy-php-code/). Regarding lisp style in PHP, Jacob Hannsen has a great article on his bitchware site for a more general case.
Php and macros(lisp style)?
[ "", "php", "macros", "eval", "" ]
I am trying to return an array Data Member from one smaller 2D Array Object, and trying to insert the array into a larger 2D array object. But when attempting this, I came into two problems. First problem is that I want to return the name of the 2D array, but I do not know how to properly syntax to return 2D Array name. This is what my 2D Array data member looks like ``` private: int pieceArray[4][4]; // 2D Smaller Array ``` and I want to return this array into a function, but this one causes a compiler error: ``` int Piece::returnPiece() { return pieceArray; //not vaild // return the 2D array name } ``` I tired using this return type and it worked: ``` int Piece::returnPiece() { return pieceArray[4][4]; } ``` But I am unsure if this is what I want, as I want to return the array and all of it's content. The other problem is the InsertArray() function, where I would put the returnPiece() function in the InsertArray()'s argument. The problem with the InsertArray() is the argument, heres the code for it: ``` void Grid::InsertArray( int arr[4][4] ) //Compiler accepts, but does not work { for(int i = 0; i < x_ROWS ; ++i) { for (int j = 0; j < y_COLUMNS ; ++j) { squares[i][j] = arr[i][j]; } } } ``` The problem with this is that it does not accept my returnPiece(), and if i remove the "[4][4]", my compiler does not accept. Mostly all these are syntax errors, but how do I solve these problems? 1. Returning the whole pieceArray in returnPiece() 2. The correct syntax for the argument in InsertArray() 3. The argument of InsertArray() accepting the returnPiece() These 3 are the major problems that I need help with, and had the same problem when I attempt to use the pointer pointer method. Does anyone know how to solve these 3 problems?
When passing your array around, you have to decide whether or not you want to make a copy of the array, or if you just want to return a pointer to the array. For returning arrays, you can't (easily) return a copy - you can only return a pointer (or reference in C++). For example: ``` // Piece::returnPiece is a function taking no arguments and returning a pointer to a // 4x4 array of integers int (*Piece::returnPiece(void))[4][4] { // return pointer to the array return &pieceArray; } ``` To use it, call it like so: ``` int (*arrayPtr)[4][4] = myPiece->returnPiece(); int cell = (*arrayPtr)[i][j]; // cell now stores the contents of the (i,j)th element ``` Note the similarity between the type declaration and using it - the parentheses, dereferencing operator `*`, and brackets are in the same places. Your declaration for `Grid::InsertArray` is correct - it takes one argument, which is a 4x4 array of integers. This is call-by-value: whenever you call it, you make a copy of your 4x4 array, so any modification you make are not reflected in the array passed in. If you instead wanted to use call-by-reference, you could pass a pointer to an array instead: ``` // InsertArray takes one argument which is a pointer to a 4x4 array of integers void Grid::InsertArray(int (*arr)[4][4]) { for(int i = 0; i < x_ROWS; i++) { for(int j = 0; j < y_COLUMNS ; j++) squares[i][j] = (*arr)[i][j]; } } ``` These type declarations with pointers to multidimensional arrays can get really confusing fast. I recommend making a `typedef` for it like so: ``` // Declare IntArray4x4Ptr to be a pointer to a 4x4 array of ints typedef int (*IntArray4x4Ptr)[4][4]; ``` Then you can declare your functions much more readable: ``` IntArray4x4Ptr Piece::returnPiece(void) { ... } void Grid::InsertArray(IntArray4x4Ptr arr) { ... } ``` You can also use the [cdecl](http://gd.tuwien.ac.at/linuxcommand.org/man_pages/cdecl1.html) program to help decipher complicated C/C++ types.
It seems like you need to read up more on pointers in C++ and on pass by reference vs. pass by value. Your returnPiece method is defined as returning the value of a single cell. Given the index (e.g., [4][4]) you return a copy of the contents of that cell, so you won't be able to change it, or more correctly, changing it would change the copy. I'm sure someone will give you the correct syntax, but I would really recommend learning this stuff since otherwise you may use the code that you do get incorrectly.
C++ Returning and Inserting a 2D array object
[ "", "c++", "arrays", "syntax", "2d", "" ]
I am considering releasing one of my class libraries written in C# as open source. Before doing that, I am trying to do some refactoring so that it meets the demands of the general public :) I wonder what would be the best namespace schema to use? Basically, I see the following options: * namespace **MyTool**: This just doesn't really look like organized for me. I mean, (almost) all the namespaces in the .NET Framework are prefixed with System so I guess it is not really a standard way to do it. * namespace **MyOrganization.MyTool**: The problem with that there is just simply no "MyOrganization". It is written in my spare time. * namespace **MyName.MyTool**: I would prefer something more humble. I mean really, I don't want to have my name in the namespace. Now there are a couple of related questions on Stackoverflow already, like [this](https://stackoverflow.com/questions/240033/how-do-you-come-up-with-names-for-your-namespaces) and [this](https://stackoverflow.com/questions/123114/how-do-you-organize-your-namespaces), but none of them really answer my question. Any suggestions?
I'd go with something like: ``` namespace OpenSourceProjectCodeName.MajorFunctionalArea ``` For example: ``` namespace VideoWizardMagicThing.Audio namespace VideoWizardMagicThing.Audio.Codecs namespace VideoWizardMagicThing.Video namespace VideoWizardMagicThing.Video.Codecs ``` You don't have to go completely mad with namespaces and all you may need is one or two MajorFunctionalArea's. However without knowing how the project is structured or what it does it's hard to say.
**`MyTool`** has the problem that names aren't unique; you’re heading for name conflicts. **`MyCompany.MyTool`** doesn’t apply in your case if you don’t want to give yourself some label. I actually rather like the Java convention of reversing the URI associated with the product. For companies, this is the company website. For you – do you have a blog / personal homepage whose address isn’t likely to change soon? Then use the name, with TLD and second-level domain reversed. In my case: **`net.madrat.MyTool`**. I know a few people who use `TheirName.MyTool` which is fine. Howver, this becomes a problem as soon as there is a second contributor.
C# Open Source Project Namespace
[ "", "c#", ".net", "open-source", "namespaces", "" ]
I'd like to periodically run an arbitrary .NET exe under a specified user account from a Windows Service. So far I've got my windows service running with logic to decide what the target process is, and when to run it. The target process is started in the following manner: 1. The Windows Service is started using "administrator" credentials. 2. When the time comes, an intermediate .NET process is executed with arguments detailing which process should be started (filename, username, domain, password). 3. This process creates a new System.Diagnostics.Process, associates a ProcessStartInfo object filled with the arguments passed to it, and then calls Start() on the process object. The **first time** this happens, **the target process executes fine and then closes normally**. Every subsequent time however, as soon as the target process is started it throws the error "Application failed to initalize properly (0xc0000142)". Restarting the Windows Service will allow the process to run successfully once again (for the first execution). Naturally, the goal is to have target process execute successfully every time. Regarding step 2 above: To run a process as a different user .NET calls the win32 function CreateProcessWithLogonW. This function requires a window handle to log the specified user in. Since the Windows Service isn't running in Interactive Mode it has no window handle. This intermediate process solves the issue, as it has a window handle which can be passed to the target process. Please, no suggestions of using psexec or the windows task planner. I've accepted my lot in life, and that includes solving the problem in the manner stated above.
I seem to have a working implementation (Works On My Machine(TM)) for the following scenarios: Batch File, .NET Console Assembly, .NET Windows Forms application. Here's how: I have a windows service running as the Administrator user. I add the following policies to the Administrator user: * Log on as a service * Act as part of the operating system * Adjust memory quotas for a process * Replace a process level token These policies can be added by opening Control Panel/ Administrative Tools / Local Security Policy / User Rights Assignment. Once they are set, the policies don't take effect until next login. You can use another user instead of the Administrator, which might make things a bit safer :) Now, my windows service has the required permissions to start jobs as other users. When a job needs to be started the service executes a seperate assembly ("Starter" .NET console assembly) which initiates the process for me. The following code, located in the windows service, executes my "Starter" console assembly: ``` Process proc = null; System.Diagnostics.ProcessStartInfo info; string domain = string.IsNullOrEmpty(row.Domain) ? "." : row.Domain; info = new ProcessStartInfo("Starter.exe"); info.Arguments = cmd + " " + domain + " " + username + " " + password + " " + args; info.WorkingDirectory = Path.GetDirectoryName(cmd); info.UseShellExecute = false; info.RedirectStandardError = true; info.RedirectStandardOutput = true; proc = System.Diagnostics.Process.Start(info); ``` The console assembly then starts the target process via interop calls: ``` class Program { #region Interop [StructLayout(LayoutKind.Sequential)] public struct LUID { public UInt32 LowPart; public Int32 HighPart; } [StructLayout(LayoutKind.Sequential)] public struct LUID_AND_ATTRIBUTES { public LUID Luid; public UInt32 Attributes; } public struct TOKEN_PRIVILEGES { public UInt32 PrivilegeCount; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)] public LUID_AND_ATTRIBUTES[] Privileges; } enum TOKEN_INFORMATION_CLASS { TokenUser = 1, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, TokenStatistics, TokenRestrictedSids, TokenSessionId, TokenGroupsAndPrivileges, TokenSessionReference, TokenSandBoxInert, TokenAuditPolicy, TokenOrigin, TokenElevationType, TokenLinkedToken, TokenElevation, TokenHasRestrictions, TokenAccessInformation, TokenVirtualizationAllowed, TokenVirtualizationEnabled, TokenIntegrityLevel, TokenUIAccess, TokenMandatoryPolicy, TokenLogonSid, MaxTokenInfoClass } [Flags] enum CreationFlags : uint { CREATE_BREAKAWAY_FROM_JOB = 0x01000000, CREATE_DEFAULT_ERROR_MODE = 0x04000000, CREATE_NEW_CONSOLE = 0x00000010, CREATE_NEW_PROCESS_GROUP = 0x00000200, CREATE_NO_WINDOW = 0x08000000, CREATE_PROTECTED_PROCESS = 0x00040000, CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000, CREATE_SEPARATE_WOW_VDM = 0x00001000, CREATE_SUSPENDED = 0x00000004, CREATE_UNICODE_ENVIRONMENT = 0x00000400, DEBUG_ONLY_THIS_PROCESS = 0x00000002, DEBUG_PROCESS = 0x00000001, DETACHED_PROCESS = 0x00000008, EXTENDED_STARTUPINFO_PRESENT = 0x00080000 } public enum TOKEN_TYPE { TokenPrimary = 1, TokenImpersonation } public enum SECURITY_IMPERSONATION_LEVEL { SecurityAnonymous, SecurityIdentification, SecurityImpersonation, SecurityDelegation } [Flags] enum LogonFlags { LOGON_NETCREDENTIALS_ONLY = 2, LOGON_WITH_PROFILE = 1 } enum LOGON_TYPE { LOGON32_LOGON_INTERACTIVE = 2, LOGON32_LOGON_NETWORK, LOGON32_LOGON_BATCH, LOGON32_LOGON_SERVICE, LOGON32_LOGON_UNLOCK = 7, LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_LOGON_NEW_CREDENTIALS } enum LOGON_PROVIDER { LOGON32_PROVIDER_DEFAULT, LOGON32_PROVIDER_WINNT35, LOGON32_PROVIDER_WINNT40, LOGON32_PROVIDER_WINNT50 } #region _SECURITY_ATTRIBUTES //typedef struct _SECURITY_ATTRIBUTES { // DWORD nLength; // LPVOID lpSecurityDescriptor; // BOOL bInheritHandle; //} SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES; #endregion struct SECURITY_ATTRIBUTES { public uint Length; public IntPtr SecurityDescriptor; public bool InheritHandle; } [Flags] enum SECURITY_INFORMATION : uint { OWNER_SECURITY_INFORMATION = 0x00000001, GROUP_SECURITY_INFORMATION = 0x00000002, DACL_SECURITY_INFORMATION = 0x00000004, SACL_SECURITY_INFORMATION = 0x00000008, UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000, UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000, PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000, PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000 } #region _SECURITY_DESCRIPTOR //typedef struct _SECURITY_DESCRIPTOR { // UCHAR Revision; // UCHAR Sbz1; // SECURITY_DESCRIPTOR_CONTROL Control; // PSID Owner; // PSID Group; // PACL Sacl; // PACL Dacl; //} SECURITY_DESCRIPTOR, *PISECURITY_DESCRIPTOR; #endregion [StructLayoutAttribute(LayoutKind.Sequential)] struct SECURITY_DESCRIPTOR { public byte revision; public byte size; public short control; // public SECURITY_DESCRIPTOR_CONTROL control; public IntPtr owner; public IntPtr group; public IntPtr sacl; public IntPtr dacl; } #region _STARTUPINFO //typedef struct _STARTUPINFO { // DWORD cb; // LPTSTR lpReserved; // LPTSTR lpDesktop; // LPTSTR lpTitle; // DWORD dwX; // DWORD dwY; // DWORD dwXSize; // DWORD dwYSize; // DWORD dwXCountChars; // DWORD dwYCountChars; // DWORD dwFillAttribute; // DWORD dwFlags; // WORD wShowWindow; // WORD cbReserved2; // LPBYTE lpReserved2; // HANDLE hStdInput; // HANDLE hStdOutput; // HANDLE hStdError; //} STARTUPINFO, *LPSTARTUPINFO; #endregion struct STARTUPINFO { public uint cb; [MarshalAs(UnmanagedType.LPTStr)] public string Reserved; [MarshalAs(UnmanagedType.LPTStr)] public string Desktop; [MarshalAs(UnmanagedType.LPTStr)] public string Title; public uint X; public uint Y; public uint XSize; public uint YSize; public uint XCountChars; public uint YCountChars; public uint FillAttribute; public uint Flags; public ushort ShowWindow; public ushort Reserverd2; public byte bReserverd2; public IntPtr StdInput; public IntPtr StdOutput; public IntPtr StdError; } #region _PROCESS_INFORMATION //typedef struct _PROCESS_INFORMATION { // HANDLE hProcess; // HANDLE hThread; // DWORD dwProcessId; // DWORD dwThreadId; } // PROCESS_INFORMATION, *LPPROCESS_INFORMATION; #endregion [StructLayout(LayoutKind.Sequential)] struct PROCESS_INFORMATION { public IntPtr Process; public IntPtr Thread; public uint ProcessId; public uint ThreadId; } [DllImport("advapi32.dll", SetLastError = true)] static extern bool InitializeSecurityDescriptor(IntPtr pSecurityDescriptor, uint dwRevision); const uint SECURITY_DESCRIPTOR_REVISION = 1; [DllImport("advapi32.dll", SetLastError = true)] static extern bool SetSecurityDescriptorDacl(ref SECURITY_DESCRIPTOR sd, bool daclPresent, IntPtr dacl, bool daclDefaulted); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] extern static bool DuplicateTokenEx( IntPtr hExistingToken, uint dwDesiredAccess, ref SECURITY_ATTRIBUTES lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, TOKEN_TYPE TokenType, out IntPtr phNewToken); [DllImport("advapi32.dll", SetLastError = true)] public static extern bool LogonUser( string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken ); #region GetTokenInformation //BOOL WINAPI GetTokenInformation( // __in HANDLE TokenHandle, // __in TOKEN_INFORMATION_CLASS TokenInformationClass, // __out_opt LPVOID TokenInformation, // __in DWORD TokenInformationLength, // __out PDWORD ReturnLength //); #endregion [DllImport("advapi32.dll", SetLastError = true)] static extern bool GetTokenInformation( IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, int TokenInformationLength, out int ReturnLength ); #region CreateProcessAsUser // BOOL WINAPI CreateProcessAsUser( // __in_opt HANDLE hToken, // __in_opt LPCTSTR lpApplicationName, // __inout_opt LPTSTR lpCommandLine, // __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes, // __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, // __in BOOL bInheritHandles, // __in DWORD dwCreationFlags, // __in_opt LPVOID lpEnvironment, // __in_opt LPCTSTR lpCurrentDirectory, // __in LPSTARTUPINFO lpStartupInfo, // __out LPPROCESS_INFORMATION lpProcessInformation); #endregion [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern bool CreateProcessAsUser( IntPtr Token, [MarshalAs(UnmanagedType.LPTStr)] string ApplicationName, [MarshalAs(UnmanagedType.LPTStr)] string CommandLine, ref SECURITY_ATTRIBUTES ProcessAttributes, ref SECURITY_ATTRIBUTES ThreadAttributes, bool InheritHandles, uint CreationFlags, IntPtr Environment, [MarshalAs(UnmanagedType.LPTStr)] string CurrentDirectory, ref STARTUPINFO StartupInfo, out PROCESS_INFORMATION ProcessInformation); #region CloseHandle //BOOL WINAPI CloseHandle( // __in HANDLE hObject // ); #endregion [DllImport("Kernel32.dll")] extern static int CloseHandle(IntPtr handle); [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen); [DllImport("advapi32.dll", SetLastError = true)] internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid); [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct TokPriv1Luid { public int Count; public long Luid; public int Attr; } //static internal const int TOKEN_QUERY = 0x00000008; internal const int SE_PRIVILEGE_ENABLED = 0x00000002; //static internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; internal const int TOKEN_QUERY = 0x00000008; internal const int TOKEN_DUPLICATE = 0x0002; internal const int TOKEN_ASSIGN_PRIMARY = 0x0001; #endregion [STAThread] static void Main(string[] args) { string username, domain, password, applicationName; username = args[2]; domain = args[1]; password = args[3]; applicationName = @args[0]; IntPtr token = IntPtr.Zero; IntPtr primaryToken = IntPtr.Zero; try { bool result = false; result = LogonUser(username, domain, password, (int)LOGON_TYPE.LOGON32_LOGON_NETWORK, (int)LOGON_PROVIDER.LOGON32_PROVIDER_DEFAULT, out token); if (!result) { int winError = Marshal.GetLastWin32Error(); } string commandLine = null; #region security attributes SECURITY_ATTRIBUTES processAttributes = new SECURITY_ATTRIBUTES(); SECURITY_DESCRIPTOR sd = new SECURITY_DESCRIPTOR(); IntPtr ptr = Marshal.AllocCoTaskMem(Marshal.SizeOf(sd)); Marshal.StructureToPtr(sd, ptr, false); InitializeSecurityDescriptor(ptr, SECURITY_DESCRIPTOR_REVISION); sd = (SECURITY_DESCRIPTOR)Marshal.PtrToStructure(ptr, typeof(SECURITY_DESCRIPTOR)); result = SetSecurityDescriptorDacl(ref sd, true, IntPtr.Zero, false); if (!result) { int winError = Marshal.GetLastWin32Error(); } primaryToken = new IntPtr(); result = DuplicateTokenEx(token, 0, ref processAttributes, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out primaryToken); if (!result) { int winError = Marshal.GetLastWin32Error(); } processAttributes.SecurityDescriptor = ptr; processAttributes.Length = (uint)Marshal.SizeOf(sd); processAttributes.InheritHandle = true; #endregion SECURITY_ATTRIBUTES threadAttributes = new SECURITY_ATTRIBUTES(); threadAttributes.SecurityDescriptor = IntPtr.Zero; threadAttributes.Length = 0; threadAttributes.InheritHandle = false; bool inheritHandles = true; //CreationFlags creationFlags = CreationFlags.CREATE_DEFAULT_ERROR_MODE; IntPtr environment = IntPtr.Zero; string currentDirectory = currdir; STARTUPINFO startupInfo = new STARTUPINFO(); startupInfo.Desktop = ""; PROCESS_INFORMATION processInformation; result = CreateProcessAsUser(primaryToken, applicationName, commandLine, ref processAttributes, ref threadAttributes, inheritHandles, 16, environment, currentDirectory, ref startupInfo, out processInformation); if (!result) { int winError = Marshal.GetLastWin32Error(); File.AppendAllText(logfile, DateTime.Now.ToLongTimeString() + " " + winError + Environment.NewLine); } } catch { int winError = Marshal.GetLastWin32Error(); File.AppendAllText(logfile, DateTime.Now.ToLongTimeString() + " " + winError + Environment.NewLine); } finally { if (token != IntPtr.Zero) { int x = CloseHandle(token); if (x == 0) throw new Win32Exception(Marshal.GetLastWin32Error()); x = CloseHandle(primaryToken); if (x == 0) throw new Win32Exception(Marshal.GetLastWin32Error()); } } } ``` The basic procedure is: 1. Log the user on 2. convert the given token into a primary token 3. Using this token, execute the process 4. Close the handle when finished. This is development code fresh from my machine and no way near ready for use in production environments. The code here is still buggy - For starters: I'm not sure whether the handles are closed at the right point, and there's a few interop functions defined above that aren't required. The separate starter process also really annoys me. Ideally I'd like all this Job stuff wrapped up in an assembly for use from our API as well as this service. If someone has any suggestions here, they'd be appreciated.
Just a guess - are you using LoadUserProfile=true with the start info? CreateProcessWithLogonW does not load user registry hive by default, unless you tell it to.
Using Process.Start() to start a process as a different user from within a Windows Service
[ "", "c#", ".net", "windows-services", "process", "service", "" ]
Lets say I have a concrete class Class1 and I am creating an anonymous class out of it. ``` Object a = new Class1(){ void someNewMethod(){ } }; ``` Now is there any way I could overload the constructor of this anonymous class. Like shown below ``` Object a = new Class1(){ void someNewMethod(){ } public XXXXXXXX(int a){ super(); System.out.println(a); } }; ``` With something at xxxxxxxx to name the constructor?
From the [Java Language Specification](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.5.1), section 15.9.5.1: > An anonymous class cannot have an > explicitly declared constructor. Sorry :( EDIT: As an alternative, you can create some final local variables, and/or include an instance initializer in the anonymous class. For example: ``` public class Test { public static void main(String[] args) throws Exception { final int fakeConstructorArg = 10; Object a = new Object() { { System.out.println("arg = " + fakeConstructorArg); } }; } } ``` It's grotty, but it might just help you. Alternatively, use a proper nested class :)
That is not possible, but you can add an anonymous initializer like this: ``` final int anInt = ...; Object a = new Class1() { { System.out.println(anInt); } void someNewMethod() { } }; ``` Don't forget final on declarations of local variables or parameters used by the anonymous class, as i did it for anInt.
Accessing constructor of an anonymous class
[ "", "java", "constructor", "overloading", "anonymous-types", "" ]
What is the "cleanest" way to implement an command-line UI, similar to git's, for example: ``` git push origin/master git remote add origin git://example.com master ``` Ideally also allowing the more flexible parsing, for example, ``` jump_to_folder app theappname v2 jump_to_folder app theappname source jump_to_folder app theappname source v2 jump_to_folder app theappname build v1 jump_to_folder app theappname build 1 jump_to_folder app theappname v2 build ``` `jump_to_folder` is the scripts name, `app` is the command, `theappname` is a "fixed-location" parameter, "build" and "v2" etc are arguments (For example, possible arguments would be any number/any number prefixed with a v, or build/source/tmp/config) I could just manually parse the arguments with a series of `if`/`else`/`elifs`, but there must be a more elegant way to do this? As an entirely theoretically example, I could describe the UI schema.. ``` app: fixed: application_name optional params: arg subsection: "build" "source" "tmp" "config" arg version: integer "v" + integer ``` Then parse the supplied arguments though the above schema, and get a dictionary: ``` >>> print schema.parse(["app", "theappname", "v1", "source"]) { "application_name": "theappname", "params":{ "subsection": "source", "version":"v1" } } ``` Does such a system exist? If not, how would I go about implementing something along these lines?
[argparse](http://docs.python.org/library/argparse.html#sub-commands) is perfect for this, specifically ["sub-commands"](http://docs.python.org/library/argparse.html#sub-commands) and positional args ``` import argparse def main(): arger = argparse.ArgumentParser() # Arguments for top-level, e.g "subcmds.py -v" arger.add_argument("-v", "--verbose", action="count", default=0) subparsers = arger.add_subparsers(dest="command") # Make parser for "subcmds.py info ..." info_parser = subparsers.add_parser("info") info_parser.add_argument("-m", "--moo", dest="moo") # Make parser for "subcmds.py create ..." create_parser = subparsers.add_parser("create") create_parser.add_argument("name") create_parser.add_argument("additional", nargs="*") # Parse opts = arger.parse_args() # Print option object for debug print opts if opts.command == "info": print "Info command" print "--moo was %s" % opts.moo elif opts.command == "create": print "Creating %s" % opts.name print "Additional: %s" % opts.additional else: # argparse will error on unexpected commands, but # in case we mistype one of the elif statements... raise ValueError("Unhandled command %s" % opts.command) if __name__ == '__main__': main() ``` This can be used like so: ``` $ python subcmds.py create myapp v1 blah Namespace(additional=['v1', 'blah'], command='create', name='myapp', verbose=0) Creating myapp Additional: ['v1', 'blah'] $ python subcmds.py info --moo usage: subcmds.py info [-h] [-m MOO] subcmds.py info: error: argument -m/--moo: expected one argument $ python subcmds.py info --moo 1 Namespace(command='info', moo='1', verbose=0) Info command --moo was 1 ```
The `cmd` module would probably work well for this. Example: ``` import cmd class Calc(cmd.Cmd): def do_add(self, arg): print sum(map(int, arg.split())) if __name__ == '__main__': Calc().cmdloop() ``` Run it: ``` $python calc.py (Cmd) add 4 5 9 (Cmd) help Undocumented commands: ====================== add help (Cmd) ``` See the [Python docs](http://docs.python.org/library/cmd.html) or [PyMOTW site](http://blog.doughellmann.com/2008/05/pymotw-cmd.html) for more info.
Implementing a "[command] [action] [parameter]" style command-line interfaces?
[ "", "python", "command-line", "user-interface", "" ]
I'm writing a script in python which basically queries WMI and updates the information in a mysql database. One of those "write something you need" to learn to program exercises. In case something breaks in the middle of the script, for example, the remote computer turns off, it's separated out into functions. Query Some WMI data Update that to the database Query Other WMI data Update that to the database Is it better to open one mysql connection at the beginning and leave it open or close the connection after each update? It seems as though one connection would use less resources. (Although I'm just learning, so this is a complete guess.) However, opening and closing the connection with each update seems more 'neat'. Functions would be more stand alone, rather than depend on code outside that function.
"However, opening and closing the connection with each update seems more 'neat'. " It's also a huge amount of overhead -- and there's no actual benefit. Creating and disposing of connections is relatively expensive. More importantly, what's the actual reason? How does it improve, simplify, clarify? Generally, most applications have one connection that they use from when they start to when they stop.
I don't think that there is "better" solution. Its too early to think about resources. And since wmi is quite slow ( in comparison to sql connection ) the db is not an issue. Just make it work. And then make it better. The good thing about working with open connection here, is that the "natural" solution is to use objects and not just functions. So it will be a learning experience( In case you are learning python and not mysql).
Mysql Connection, one or many?
[ "", "python", "mysql", "" ]
Is there an easy way write to a file asynchronously in Python? I know the [file io that comes with Python](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files) is blocking; which is fine in most cases. For this particular case, I need writes not to block the application at all, or at least as minimally as possible.
Twisted has [non-blocking writes on file descriptors](http://twistedmatrix.com/documents/8.1.0/api/twisted.internet.fdesc.html). If you're writing async code, I'd expect you to be using twisted, anyway. :)
As I understand things, asynchronous I/O is not quite the same as non-blocking I/O. In the case of non-blocking I/O, once a file descriptor is setup to be "non-blocking", a `read()` system call (for instance) will return `EWOULDBLOCK` (or `EAGAIN`) if the read operation would block the calling process in order to complete the operation. The system calls `select()`, `poll()`, `epoll()`, etc. are provided so that the process can ask the OS to be told when one or more file descriptors become *available* for performing some I/O operation. Asynchronous I/O operates by queuing a request for I/O to the file descriptor, tracked independently of the calling process. For a file descriptor that supports asynchronous I/O (raw disk devcies typically), a process can call `aio_read()` (for instance) to request a number of bytes be read from the file descriptor. The system call returns immediately, whether or not the I/O has completed. Some time later, the process then polls the operating system for the *completion* of the I/O (that is, buffer is filled with data). A process (single-threaded) that only performs non-blocking I/O will be able to read or write from one file descriptor that is ready for I/O when another is not ready. But the process must still synchronously issue the system calls to perform the I/O to all the ready file descriptors. Whereas, in the asynchronous I/O case, the process is just checking for the completion of the I/O (buffer filled with data). With asynchronous I/O, the OS has the freedom to operate in parallel as much as possible to service the I/O, if it so chooses. With that, are there any wrappers for the POSIX aio\_read/write etc. system calls for Python?
Asynchronous file writing possible in python?
[ "", "python", "asynchronous", "aio-write", "" ]
I have a Div Tag which contains 4 child Div Tags ``` <Div id="Parent"> <div id="childOne">ChildOne </div> <div id="childOne">ChildTwo </div> <div id="childOne">ChildThree </div> <div id="childOne">ChildFour </div> </Div> ``` Now I would like to access these Child Div's using up and Down Arrow Keys through Javascript The above div is show on click of a TextBox.I want that the user can choose any of the child div and its selected value appears in the TextBox. I have acheived the end result by attachinh onClick event to each childDiv.
Are you looking for what is known as [auto-completion](http://www.javascript-examples.com/autocomplete-demo/) or suggestions?
Here's a library free solution to get you started. You might like to add events that hide and show the div when the textbox gains or loses focus. Perhaps [esc] should clear the selection? ( I haven't tested it in ie ) ``` <style>div.active{ background: red }</style> <input type="text" id="tb"> <div id="Parent"> <div id="childOne">ChildOne </div> <div id="childOne">ChildTwo </div> <div id="childOne">ChildThree </div> <div id="childOne">ChildFour </div> </div> <script type="text/javascript"> function autocomplete( textBoxId, containerDivId ) { var ac = this; this.textbox = document.getElementById(textBoxId); this.div = document.getElementById(containerDivId); this.list = this.div.getElementsByTagName('div'); this.pointer = null; this.textbox.onkeydown = function( e ) { e = e || window.event; switch( e.keyCode ) { case 38: //up ac.selectDiv(-1); break; case 40: //down ac.selectDiv(1); break; } } this.selectDiv = function( inc ) { if( this.pointer !== null && this.pointer+inc >= 0 && this.pointer+inc < this.list.length ) { this.list[this.pointer].className = ''; this.pointer += inc; this.list[this.pointer].className = 'active'; this.textbox.value = this.list[this.pointer].innerHTML; } if( this.pointer === null ) { this.pointer = 0; this.list[this.pointer].className = 'active'; this.textbox.value = this.list[this.pointer].innerHTML; } } } new autocomplete( 'tb', 'Parent' ); </script> ```
Access Div Contents using Up and Down Arrow Keys using javascript
[ "", "javascript", "html", "keyboard", "" ]
I have a generic Callback object which provides a (primitive) callback capability for Java, in the absence of closures. The Callback object contains a Method, and returns the parameter and return types for the method via a couple of accessor methods that just delegate to the equivalent methods in Method. I am trying to validate that a Callback I have been supplied points to a valid method. I need the return type assignment compatible with Number and all parameters to be assignment compatible with Double. My validating method looks like this: ``` static public void checkFunctionSpec(Callback cbk) { Class[] prms=cbk.getParmTypes(); Class ret =cbk.getReturnType(); if(!Number.class.isAssignableFrom(ret)) { throw new IllegalArgumentException( "A function callback must return a Number type " + "(any Number object or numeric primitive) - function '" + cbk + "' is not permitted"); } for(Class prm: prms) { if(!Double.class.isAssignableFrom(prm)) { throw new IllegalArgumentException( "A function callback must take parameters of " + "assignment compatible with double " + "(a Double or Float object or a double or float primitive) " + "- function '" + cbk + "' is not permitted"); } } } ``` The problem I encounter is that the when I try this with, e.g. Math.abs(), it's throwing an exception for the return type as follows: ``` java.lang.IllegalArgumentException: A function callback must return a Number type (any Number object or numeric primitive) - function 'public static double java.lang.Math.abs(double)' is not permitted ``` This was surprising to me because I expected primitives to simply work because (a) they are reflected using their wrapper classes, and (b) the Double.TYPE is declared to be of type Class<Double>. Does anyone know how I can achieve this without modifying my checks to be: ``` if(!Number.class.isAssignableFrom(ret) && ret!=Double.TYPE && ret!=Float.TYPE && ret!=...) { ``` --- ## Clarification When you invoke the method `double abs(double)` using Method.invoke(), you pass in a Object[]{Double} and get back a Double. However, my validation appears to be failing because Double.TYPE is not assignable to a Double. Since I require all these callbacks to return some sort of number, which will be returned by invoke() as a Number, I am trying to validate that the supplied method returns either Number or a numeric primitive. Validation of the parms is likewise. In other words, when using reflection the parm and return types Double and double are identical and I would like to validate them *easily* as such. EDIT: To further clarify: I want to validate that a Method will, when invoke() is called return an Object of type Number (from which I can call obj.doubleValue() to get the double I want).
Looking more closely at the documentation for Class.isAssignableFrom(), it specifically states that the types for a primitive do not match any class except themselves. So I will need to specifically check for == equality to Byte.TYPE, Double.TYPE, Float.TYPE, Integer.TYPE, Long.TYPE, and Short.TYPE for the return type.
Why not have the compiler do it? ``` public interface F<A, B> { public B $(A a); } ``` Then you can pass an `F<Double, Double>` to a method that expects an `F<? extends Number, ? extends Number>`. **EDIT:** You say you want to provide a single class for the type of a function with any number of arguments. This *can* be done with the Java type system. Conceptually every function has only one argument. A function with two arguments is equivalent to a function that returns another function. So here's a variable whose value is a function that takes two doubles: ``` F<Double, F<Double, Double>> f; ``` Here's a method that passes two doubles to a given function: ``` public Double operate(F<Double, F<Double, Double>> f, double a, double b) { return f.$(a).$(b); } ``` Or, consider a type `L<A extends L>` with two subclasses `C<E, T extends L<T>>` representing a "cons", and a terminator type `N`: ``` public abstract class L<A extends L<A>> { private L() {} private static final N nil = new N(); public static N nil() { return nil; } public static final class N extends L<N> { private N() {} public <E> C<E, N> cons(final E e) { return new C<E, L>(e, this); } } public static final class C<E, L extends L<L>> extends L<C<E, L>> { private E e; private L l; private C(final E e, final L l) { this.e = e; this.l = l; } public E head() { return e; } public L tail() { return l; } public <E> C<E, C<E, L>> cons(final E e) { return new C<E, C<E, L>>(e, this); } } } ``` In such a case, you can implement a function type thusly: ``` public interface F<A extends L<A>, B> { public B $(A args); } ``` The following method expects a function with two `Double` arguments (and returns a `Double`), along with two `double`s to apply it to: ``` public Double operate(F<C<Double, C<Double, N>>, Double> f, double a, double b) { return f.$(N.nil().cons(b).cons(a)); } ``` The implementation of the `F` interface would have to get the arguments from the list using `head` and `tail`. So in effect, you're implementing LISP in Java. :) Having said that, check out [Functional Java](http://functionaljava.org/), which is a library that has a lot of this stuff already. I'm sure there's also one out there that uses reflection so you don't have to write it yourself.
Validate reflected method return type and parms in Java
[ "", "java", "reflection", "types", "closures", "callback", "" ]
I am building stats for my users and dont wish the visits from bots to be counted. Now I have a basic php with mysql increasing 1 each time the page is called. But bots are also added to the count. Does anyone can think of a way? Mainly is just the major ones that mess things up. Google, Yahoo, Msn, etc.
You should filter by user-agent strings. You can find a list of about 300 common user-agents given by bots here: <http://www.robotstxt.org/db.html> Running through that list and ignoring bot user-agents before you run your SQL statement should solve your problem for all practical purposes. If you don't want the search engines to even reach the page, use a basic [robots.txt](http://www.robotstxt.org/) file to block them.
You can check the User Agent string, empty strings, or strings containing 'robot', 'spider', 'crawler', 'curl' are likely to be robots. > `preg_match('/robot|spider|crawler|curl|^$/i', $_SERVER['HTTP_USER_AGENT']));`
How to recognize bots with php?
[ "", "php", "bots", "statistics", "" ]
I would like to use java to get the source of a website (secure) and then parse that website for links that are in it. I have found how to connect to that url, but then how can i easily get just the source, preferraby as the DOM Document oso that I could easily get the info I want. Or is there a better way to connect to https site, get the source (which I neet to do to get a table of data...its pretty simple) then those links are files i am going to download. I wish it was FTP but these are files stored on my tivo (i want to programmatically download them to my computer(
You can get low level and just request it with a socket. In java it looks like ``` // Arg[0] = Hostname // Arg[1] = File like index.html public static void main(String[] args) throws Exception { SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslsock = (SSLSocket) factory.createSocket(args[0], 443); SSLSession session = sslsock.getSession(); X509Certificate cert; try { cert = (X509Certificate) session.getPeerCertificates()[0]; } catch (SSLPeerUnverifiedException e) { System.err.println(session.getPeerHost() + " did not present a valid cert."); return; } // Now use the secure socket just like a regular socket to read pages. PrintWriter out = new PrintWriter(sslsock.getOutputStream()); out.write("GET " + args[1] + " HTTP/1.0\r\n\r\n"); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(sslsock.getInputStream())); String line; String regExp = ".*<a href=\"(.*)\">.*"; Pattern p = Pattern.compile( regExp, Pattern.CASE_INSENSITIVE ); while ((line = in.readLine()) != null) { // Using Oscar's RegEx. Matcher m = p.matcher( line ); if( m.matches() ) { System.out.println( m.group(1) ); } } sslsock.close(); } ```
Extremely similar questions: * [How do I retrieve a URL from a website using Java?](https://stackoverflow.com/questions/359439/how-do-i-retrieve-a-url-from-a-web-site-using-java) * [How do you Programmatically Download a Webpage in Java](https://stackoverflow.com/questions/238547/how-do-you-programmatically-download-a-webpage-in-java) * [A good library to do URL manipulation in Java](https://stackoverflow.com/questions/218608/a-good-library-to-do-url-manipulation-in-java)
Get source of website in java
[ "", "java", "url", "" ]
Today I was looking at some code atually from Nikhil Kothari's Facebook.NET API. I just wanted to check out how he was doing some things in there for ideas. One of the things I came across was a Property that just seemed really weird to me. check this out: FacebookRequest.cs defines a property and sets it in the constructor to a new instance of a custom Class: ``` public FacebookRequest(FacebookSession session) { .... _parameters = new FacebookRequestParameterList(); } ``` private field: private FacebookRequestParameterList \_parameters; and the property: ``` public FacebookRequestParameterList Parameters { get { return _parameters; } } ``` now the FacebookRequestParameterList is actually a Generic Dictionary because it inherits & extends Dictionary: ``` public sealed class FacebookRequestParameterList : Dictionary<string, string> { ... } ``` Ok so essentially when you instantiate FacebookRequest, it therefore automatically comes with an auto-instantiated instance of the FacebookRequestParameterList class. So the Property is essentially returning an instance of FacebookRequestParameterList. Is that normal? I don't think I've seen that a lot. Seems sneaky to me or is this standard stuff here? It just seemed like an odd way to do it. I'm not posting this to bring him down but to understand if this is something standard or sneaky/evil. It seems to me it would be better to require developers to pass in an instance of FacebookRequestParameterList through the constructor of FacebookRequest instead. And then work with that by setting the private field \_parameters after you initialize it through the constructor. Why do I think this is better? Because then developers know exactly what's going on. They know that the class expects a parameter list up front. And just exposing an instance like that through a properly to me just seems odd. Am I off base here?
I don't think it's odd at all. It saves the client the trouble of having to instantiate the `FacebookRequestParameterList` instance, and the `FacebookRequest` class is guaranteed that `_parameters` contains a valid instance of the `FacebookRequestParameterList` class, and isn't `null`. It's a matter of convenience for the client, and object validity for the class itself. Nothing to see here, people, move along. (Edit: clarified the specific instance in the first paragraph)
The usage is perfectly valid. The class simply uses a `Dictionary<string,string>` internally and exposes that as a property. There's presumably no need to pass in a pre-baked dictionary to the constructor. What may be better would be to expose it as `IDictionary<string,string>` instead of an instance of a concrete class.
Exposing a null Object Instance as a Property
[ "", "c#", "coding-style", "" ]
My objective is to retry an asynchronous HttpWebRequest when it fails. When I [Abort()](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.abort.aspx) an HttpWebRequest, I cannot BeginGetResponse() again. So the only way to request again probably is recreate the HttpWebRequest object. It seems to require a lot of work since I would have to copy all properties from the old object. Is there any shortcut? Note: I think that serialization it would solve my problem, but this class won't serialize, as discussed in a [previous question](https://stackoverflow.com/questions/351265/httpwebrequest-wont-serialize). **Update** Removed example source code because it was unnecessary **Current view on this matter** There is no shortcut, the only way to redo the request is creating another HttpWebRequest object the same way you created the original one.
### It's possible! You just need to create a new `HttpWebRequest` and copy all of the properties over to it from the old object via reflection. Here's an **extension method** that does this: ``` /// <summary> /// Clones a HttpWebRequest for retrying a failed HTTP request. /// </summary> /// <param name="original"></param> /// <returns></returns> public static HttpWebRequest Clone(this HttpWebRequest original) { // Create a new web request object HttpWebRequest clone = (HttpWebRequest)WebRequest.Create(original.RequestUri.AbsoluteUri); // Get original fields PropertyInfo[] properties = original.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); // There are some properties that we can't set manually for the new object, for various reasons List<string> excludedProperties = new List<String>(){ "ContentLength", "Headers" }; // Traverse properties in HttpWebRequest class foreach (PropertyInfo property in properties) { // Make sure it's not an excluded property if (!excludedProperties.Contains(property.Name)) { // Get original field value object value = property.GetValue(original); // Copy the value to the new cloned object if (property.CanWrite) { property.SetValue(clone, value); } } } return clone; } ``` When you want to re-issue the same request, simply execute the following: ``` // Create a request HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://www.google.com/"); // Change some properties... // Execute it HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Clone the request to reissue it using our extension method request = request.Clone(); // Execute it again response = (HttpWebResponse)request.GetResponse(); ```
It's not possible. An HTTPWebRequest instance represents literally one request instance (although there are edge cases where it will retry internally), and is therefore not something which can logically be repeated. It is capable of returning exactly one response (request/response being a logical pair), and although you can inspect that response multiple times you'll get exactly the same object. Basically, you're thinking an HTTPWebRequest instance is a sort of factory, but it's really concrete. You have to create another instance.
How to request an aborted HttpWebRequest again?
[ "", "c#", ".net", "httpwebrequest", "" ]
I have a fixed-length data file need to persistence into database. I use a XML file to define the length for the fields and use a list of FieldItem class to store the data. ``` class FieldItem { public string ObjectName {get; set;} public string ObjectProperty {get; set;} public string ObjectValue {get; set;} public FieldItem() { } } ``` So the FieldItem will look like ``` var fieldItem = new FieldItem { ObjectName = "Company", ObjectProperty = "Name", ObjectValue = "ABC Corp." } ``` After get the list of FieldItem, I will do refection to create Company and other domain objects to save them into database. But before they are saved into database, I have some business rules needed to be applied to validate the data line. My data line will look like: ``` var fieldItemList = new List<FieldItem>(){ new FieldItem { ObjectName="Company", ObjectProperty = "Name", ObjectValue = "ABC" } new FieldItem{ ObjectName = "Product", ObjectProperty = "ProductCode", ObjectValue ="XYZ0123" new FieldItem{ ObjectName = "Product", ObjectProperty = "ProductName", ObjectValue ="Christmas Tree" } // other FieldItem objects... } ``` For example, my rule is to check if the company == "ABC" and ProductCode == "XYZ0123". Those rules are created by users and stored as a string in the database. What I am doing right now is to use Microsoft's System.Linq.Dynamic to evaluate the rule, such as ``` string validationRule = " (ObjectName == \"Company\" And ObjectProperty=\"CompanyName\" And ObjectValue = \"ABC Corp.\") And (ObjectName == \"Product\" And ObjectProperty=\"ProductCode\" And ObjectValue = \"XYZ0123\") "; var query = fieldItemList.AsQuerable().Where(validationRule); ``` then check if it has one row return to tell if that data row has passed the rule or not. Obviously, it is too verbose. Do you have any better suggestion? What should I do if I only like my rule expression like: "Company.CompanyName = 'ABC Corp.' and Product.ProductCode = 'XYZ001'"?
RE: "What should I do if I only like my rule expression like: "Company.CompanyName = 'ABC Corp' and Product.ProductCode = 'XYZ001'"? Map this user-friendly query: "Company.CompanyName = 'ABC Corp' **AND** Product.ProductCode = 'XYZ001'" to something that is friendly to your data structure(FieldItem): "ObjectName = 'Company' AND ObjectProperty = 'CompanyName' AND ObjectValue = 'ABC Corp' **OR** ObjectName = 'Product' AND ObjectProperty = 'ProductCode' AND ObjectValue = 'XYZ001'" How to know if the user's rules passed the rules or not? Count the number of conditions, if it matches the count of results of fieldItemList.AsQueryable().Where(itemFieldFriendlyQuery), then the data line is valid based on user's rules. --- some rudimentary mapper(use regular expression or roll your own parser to make the following code truly valid): ``` public Form3() { InitializeComponent(); string userFriendlyQuery = "Company.CompanyName = 'ABC Corp' AND Product.ProductCode = 'XYZ001'"; string[] queryConditions = userFriendlyQuery.Split(new string[]{" AND "},StringSplitOptions.None); int conditionsCount = queryConditions.Length; string itemFieldFriendlyQuery = string.Join(" OR ", queryConditions.Select(condition => { var conditionA = condition.Split(new string[] { " = " }, StringSplitOptions.None); var left = conditionA[0]; var leftA = left.Split('.'); string objectName = leftA[0]; string objectProperty = leftA[1]; var right = conditionA[1]; return string.Format("ObjectName = '{0}' AND ObjectProperty = '{1}' AND ObjectValue = {2}", objectName, objectProperty, right); } ).ToArray()); MessageBox.Show(itemFieldFriendlyQuery); // outputs: "ObjectName = 'Company' AND ObjectProperty = 'CompanyName' AND ObjectValue = 'ABC Corp' OR ObjectName = 'Product' AND ObjectProperty = 'ProductCode' AND ObjectValue = 'XYZ001'" bool isValid = fieldItemList.AsQueryable().Where(itemFieldFriendlyQuery).Count() == conditionsCount; MessageBox.Show(isValid.ToString()); } ```
Consider using the [FileHelpers](http://www.filehelpers.com) library to parse your file directly into regular .NET domain objects. I believe this, combined with your Dynamic Linq approach, will provide you with the syntax that you're looking for.
C# Dynamically apply evaluation rule on a collection
[ "", "c#", "" ]
For my Swing project, I need to support both **Java 5** and **Java 6**. I have defined a custom `JComponent` (call it `Picture`) and, after embedding it in a `JScrollPane`, I put it in a `JPanel` that uses DesignGridLayout manager. DesignGridLayout supports baseline alignment thanks to **swing-layout** open source library (implements baseline support for Java 5 and provides compatibility with the new Java 6 baseline support). My `Picture` class *overrides* `public int getBaseline(int width, int height)` so that I can define a correct baseline for it. Note that "*override*" is not completely correct: it overrides the method on Java6 but defines it in Java5. When I run my sample app **on Java5, everything is fine**: the `Picture` baseline I have defined is correctly used. However, **when I use Java6**, my `Picture#getBaseline()` method does not get called! And of course **the baseline alignment of my picture is terrible** (centered). After checking in Java6 source, I have seen that, in `BasicScrollPaneUI`, `getBaseline()` calls first `getBaselineResizeBehavior()` on the viewport component (my `Picture` instance). And it will call `getBaseline()` only if `getBaselineResizeBehavior()` returns `Component.BaselineResizeBehavior.CONSTANT_ASCENT`. Now my problem is that `getBaselineResizeBehavior()` is a Java6 method of `JComponent` that I cannot implement in Java5 because it returns an enum `Component.BaselineResizeBehavior` which does not exist in Java5. So my question (finally) is: how can I implement (or simulate?) `getBaselineResizeBehavior()` so that my class can still compile and run in a Java5 environment?
I would make a subclass of Picture, perhaps called PictureJava6, which implemented the getBaselineResizeBehaviour(), and when creating instances of Picture, do: ``` public Component pictureFactory() { if(javaVersion > "1.6") { return new PictureJava6(); } else { return new Picture(); } } ```
> how can I implement (or simulate?) > getBaselineResizeBehavior() so that my > class can still **compile** and run in a > Java5 environment? You cannot compile this method declaration with the Java 5 library because the type [Component.BaselineResizeBehaviour](http://java.sun.com/javase/6/docs/api/java/awt/Component.BaselineResizeBehavior.html) does not exist: ``` public Component.BaselineResizeBehavior getBaselineResizeBehavior() ``` You must compile using Java 6. Your classes can still run on Java 5 if you compile to a 1.5 target, but you must take care that they handle absent types/methods gracefully. Add tests for these cases as you encounter them. Ensure developers attempt to run their code on Java 5 prior to check-in. For example, this class... ``` public class MyPanel extends javax.swing.JPanel { public java.awt.Component.BaselineResizeBehavior getBaselineResizeBehavior() { return java.awt.Component.BaselineResizeBehavior.OTHER; } public static void main(String[] args) { new MyPanel(); System.out.println("OK"); } } ``` ...can be compiled and run as follows using the [javac](http://java.sun.com/javase/6/docs/technotes/tools/#basic) JDK compiler: ``` X:\fallback>javac -version javac 1.6.0_05 X:\fallback>javac -target 1.5 MyPanel.java X:\fallback>"C:\Program Files\Java\jre1.5.0_10\bin\java.exe" -cp . MyPanel OK ``` All the popular IDEs offer options for generating older class versions. You can use reflection to test for the existence of methods/types at runtime when you need to make decisions about code paths. Failure to set the target will result in errors like this: ``` Exception in thread "main" java.lang.UnsupportedClassVersionError: Bad version n umber in .class file at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$100(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClassInternal(Unknown Source) ```
Override JComponent.getBaselineResizeBehavior() but keep Java5 compatibility
[ "", "java", "swing", "baseline", "" ]
For a newcomer to .NET Web Development and programming in general, who chooses C# as there preferred language? Is it better to learn C# first, without trying to apply it to web development? It seems most literature for C# uses Console or Windows Forms as a learning platform. So would that be the best direction? Or should you practice in web development and try to learn C# alongside?
You need to understand the fundamentals of C# in order to develop anything useful, be it an ASP.NET website, windows client or web service. I would start with some good tutorials around the basics of types, classes, methods, events and so on to get to grips with C#. C# Station has some good introductory tutorials [here](http://www.csharp-station.com/Tutorial.aspx). To develop web specific skills, start with HTML and CSS. Then look at how the ASP.NET platform integrates both the C# (application code) and the HTML and CSS (presentational code). And good luck!
I've helped several people go both from previous languages (like C++) as well as no experience to using C#. Definately learn C# before you try any particular kind of development (like Web stuff). It will only confuse the newcomer. If you already know a language, reimplementing a small application from the old language to the new language can help a lot. Also there are often books for common language transitions - the C# for C++ developers books are good examples. I recommend reading them. Here's my teaching plan (in short summary): 1. Give an overview of C# language (types, methods, Main() 2. Have students write Hello World from the console. 3. Have students implement the "Simon Says" game from the console. 4. Have students implement "Simon Says" in WPF. (Using the designer. This used to be Windows Forms, but WPF is a cleaner model) 5. Give a survey of the more advanced features in C# - delegates, events, etc. 6. Have students implement "Simon Says" in ASP.NET.
C# / Web Development learning strategy
[ "", "c#", "" ]
Is it possible to specify my own default object instead of it being null? I would like to define my own default properties on certain objects. For example, if I have an object foo with properties bar and baz, instead of default returing null, I'd like it to be an instance of foo with bar set to "abc" and baz set to "def" -- is this possible?
You have to use a constructor to get that functionality. So, you can't use default. But if your goal is to ensure a certain state of the passed type in a generic class, there may still be hope. If you want to ensure the passed type is instanti-able, use a generic constraint. The new() constraint. This ensures that there is a public parameter-less constructor for type T. ``` public class GenericClass<T> where T : new() { //class definition private void SomeMethod() { T myT = new T(); //work with myT } } ``` Unfortunately, you can't use this to get constructors that have parameters, only parameter-less constructors.
No you cant. Sorry.
C#: Specifying behavior for the "default" keyword when using generics
[ "", "c#", "generics", "" ]
Can I call a function from lisp from a library written in c or c++? How can I extend lisp? This is useful when you want to do some system calls or stuff like that.
It is unusual to call non-lisp code from lisp, and rarely necessary. CLX (the X11 client implementation for CL) doesn't link to the Xlib implementation but "speaks" X11 directly. On any system, your CL implementation is likely to already have excellent operating system hooks rendering this unnecessary. That said, the answer depends on the lisp implementation: In [ECL](http://ecls.sourceforge.net/) you can actually host a CL environment under C and simply call `cl_eval()` with the code to execute. This can let you write your application (or application host) in C (or C++) and "call to" lisp code. In [CCL](http://www.clozure.com/clozurecl.html), there is a C-compatible calling interface which lets you do something like this: ``` (with-cstrs ((x "Hello World")) (#_puts x)) ``` In most other CL implementations (like SBCL; and yes this works in ECL and CCL as well) you can use UFFI (or CFFI) which simply lets you call C functions, which is what other people are talking about. If this is all you want to do, then CFFI is a good, safe place to start.
See [UFFI](http://uffi.b9.com/) and [CFFI](http://common-lisp.net/project/cffi/) and the [slicker Clozure FFI](http://trac.clozure.com/openmcl/wiki/OpenMclFfi)
Can I extend lisp with c++?
[ "", "c++", "lisp", "extend", "" ]
I was working with a online game website. There are some event which call a javascript function and the function have some action with callback. something like this, ``` <input type="button" onclick="changeSomething"/> function changeSomething() { /// some call back, which changes something } ``` now anybody who knows this can call this changeSomething from the address bar of the browser, which I do not want. Very unlikely that somebody will do it, but I want to allow it. Is there anyway to prevent situation like this ? Thanks. P.S. I tried, but still not sure whether I explained it well enought. Please let me know if you are not getting something.
You will never be able to get 100% protected from any technique you try. It's a losing game. Having said that one way to get closer to your goal is to remove the onclick attribute altogether, and bind your click handler (ie "changeSomething") via javascript: html: ``` <input id="foo" type="button" /> ``` js: ``` addEvent(document.getElementById("foo"), 'click', function() { /// some call back, which changes something }) ``` The callback becomes anonymous then (eg there is no "changeSomething" function anymore). These evil users can't call it directly if they don't know its name! There are still ways around this technique too, but we won't mention those lest we give the evil doers ideas :) (BTW addEvent is just a sample library function for adding event handlers. I'm sure you have access to one. If not [here you go](http://ejohn.org/projects/flexible-javascript-events/).)
I dont think that there is anything you can do about this. The client can run whatever they want within their own browser. The only thing to do is validate everything on the server side. This is an important concept in all web programming. Client side code can be freely modified and should be treated as an additional check to speed things up rather than a security method.
Not allowing javascript function call from the address bar
[ "", "javascript", "web-applications", "web", "" ]
I'm about to start a project where I will be the only one doing actual code and two less experienced programmers (scary to think of myself as experienced!) will be watching and making suggestions on the program in general. Is there a good (free) system that I can use to provide documentation for classes and functions based on the code I've written? It'd likely help them a lot in getting to grips with the structure of the data.
I have used [epydoc](http://epydoc.sourceforge.net/) to generate documentation for Python modules from embedded docstrings. It's pretty easy to use and generates nice looking output in multiple formats.
python.org is now using [sphinx](http://sphinx.pocoo.org/) for it's documentation. I personally like the output of sphinx over epydoc. I also feel the restructured text is easier to read in the docstrings than the epydoc markup.
Producing documentation for Python classes
[ "", "python", "data-structures", "documentation", "" ]
I'm running into an issue where granting EXECUTE permissions on a specific Stored Procedure in SQL Server 2005 is not working. Some of the testers messed around with the permissions - and found that if they also granted CONTROL permissions on the Stored Procedure - then it ran fine. They are now convinced that granting CONTROL permissions is the way to go. I know this can't be true - and in fact I think that the real problem is that the user did not have Select/Insert/Update/Delete permissions to the tables which the Stored Procedure ran against. The problem is, I can't seem to find anything online that proves it. Am I correct? Is anybody aware of any documentation that talks about this? Thanks in advance. More info in response to comments: The stored procedure is doing multiple deletes. It first deletes all of the records that would be orphaned by the "main" record being deleted, and then finally deletes the parent record. Also, the error that we see says that the user doesn't have sufficient permissions - or the Stored Procedure doesn't exist. We've already confirmed that we're using the right user, and that EXECUTE permissions were given to that user.
If the stored procedure was created using EXECUTE AS CALLER (which I believe is the default), then the caller must have all of the permissions necessary to do whatever the stored procedure does in addition to EXECUTE on the procedure. From the SQL Server documentation for EXECUTE AS: > CALLER Specifies the statements inside > the module are executed in the context > of the caller of the module. The user > executing the module must have > appropriate permissions not only on > the module itself, but also on any > database objects that are referenced > by the module. Note that because of the way SQL Server processes permission checks using ownership chains, this isn't always strictly true, and I'm guessing that granting CONTROL on the procedure (which confers ownership status to the grantee) is causing these permission checks to be bypassed. If you create the procedure with EXECUTE AS OWNER, then you should not need to grant any permissions beyond EXECUTE on the procedure.
Execute should be all that is needed. Is the stored procedure accessing a table outside of the database it is located in? If so, try setting the appropriate user permissions on the tables the stored procedure is using outside of the same database.
Should CONTROL permission be given on a Stored Procedure in SQL Server 2005?
[ "", "sql", "sql-server", "sql-server-2005", "permissions", "controls", "" ]
Are there some practical programming situations for someone to declare a class abstract when all the methods in it are concrete?
Well you could be using a template method pattern where there are multiple override points that all have default implementations but where the combined default implementations by themselves are not legal - any functional implementation must subclass. (And yes, I dislike the template method pattern ;))
An abstract class is a class that is declared abstract - it may or may not include abstract methods. They cannot be instantiated so if you have an abstract class with concrete methods then it can be subclassed and the subclass can then be instantiated.
Abstract class with all concrete methods
[ "", "java", "abstract-class", "" ]
I'm looking for a way to serialize **generic** Python objects between a CherryPy-based server and a Python client running on a Symbian phone.. Since pyS60 doesn't implement the pickle module, how would you do it? I know about [Cerealizer](http://home.gna.org/oomadness/en/cerealizer) but it requires you to register classes before use (which I'd like to avoid) and doesn't look very mature.. So, what would you use? Python 2.2's pickle module maybe, extracted from the sources? XML, JSON? Which one of the several libraries? :)
What's wrong with using the pickle module?
There is a json module someone wrote for PyS60. I'd simply grab that, serialize things into json and use that as the transfer method between the web/client app. For the json lib and a decent book on PyS60: <http://www.mobilepythonbook.org/>
Serializing a Python object to/from a S60 phone
[ "", "python", "serialization", "pickle", "pys60", "" ]
Using [NumPy](https://numpy.org/), a matrix A has n rows and m columns, and I want add a guard ring to matrix A. That guard ring is all zero. What should I do? Use Reshape? But the element is not enough to make a n+1 m+1 matrix. Or etc.? Thanks in advance ###### I mean an extra ring of cells that always contain 0 surround matrix A.Basically there is a Matrix B has n+2rows m+2columns where the first row and columns and the last row and columns are all zero,and the rest of it are same as matrix A.
Following up on your [comment](https://stackoverflow.com/questions/362489/how-do-i-add-a-guard-ring-to-a-matrix-in-numpy#362576): ``` >>> import numpy >>> a = numpy.array(range(9)).reshape((3,3)) >>> b = numpy.zeros(tuple(s+2 for s in a.shape), a.dtype) >>> b[tuple(slice(1,-1) for s in a.shape)] = a >>> b array([[0, 0, 0, 0, 0], [0, 0, 1, 2, 0], [0, 3, 4, 5, 0], [0, 6, 7, 8, 0], [0, 0, 0, 0, 0]]) ```
This is a less general but easier to understand version of [Alex's answer](https://stackoverflow.com/questions/362489/how-do-i-add-a-guard-ring-to-a-matrix-in-numpy#363040): ``` >>> a = numpy.array(range(9)).reshape((3,3)) >>> a array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> b = numpy.zeros(a.shape + numpy.array(2), a.dtype) >>> b array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]) >>> b[1:-1,1:-1] = a >>> b array([[0, 0, 0, 0, 0], [0, 0, 1, 2, 0], [0, 3, 4, 5, 0], [0, 6, 7, 8, 0], [0, 0, 0, 0, 0]]) ```
How do I add a guard ring to a matrix in NumPy?
[ "", "python", "numpy", "" ]
I'm a NetBeans 6.5 user and am searching for a way of generating a list of methods/classes that are not used within a set project group. I know I can right click on each method and select "Find Usages" but I'm looking for an automation to that process. I'm willing to look at something that runs outside of netbeans, as long as it generates a list of cruft methods/classes. Thanks.
Obfuscators like [proguard](http://proguard.sourceforge.net/) can shrink your jars by removing unused methods/classes. Maybe it is possible to get a verbose output which contains the list of removed (hence unused) classes/methods. [Here](http://proguard.sourceforge.net/manual/examples.html#deadcode) you can find more information about finding dead code with proguard.
You can switch on the [unused code rules](http://pmd.sourceforge.net/rules/unusedcode.html) in PMD (there's a NetBeans plugin), then run PMD over a whole project.
Detecting Java Project Cruft
[ "", "java", "netbeans", "refactoring", "" ]
Do class, method and variable **names get included in the MSIL** after compiling a Windows App project into an EXE? * For **obfuscation** - less names, harder to reverse engineer. * And for **performance** - shorter names, faster access. *e.g.* So if methods ARE called via name: * Keep names **short**, better performance for named-lookup. * Keep names **cryptic**, harder to decompile.
Yes, they're in the IL - fire up [Reflector](http://www.red-gate.com/products/reflector/) and you'll see them. If they didn't end up in the IL, you couldn't build against them as libraries. (And yes, you can reference .exe files as if they were class libraries.) However, this is all resolved once in JIT. Keep names **readable** so that you'll be able to maintain the code in the future. The performance issue is unlikely to make *any* measurable difference, and if you want to obfuscate your code, don't do it at the source code level (where *you're* the one to read the code) - do it with a purpose-built obfuscator. EDIT: As for what's included - why not just launch Reflector or ildasm and find out? From memory, you lose local variable names (which are in the pdb file if you build it) but that's about it. Private method names and private variable names are still there.
Yes, they do. I do not think that there will be notable performance gain by using shorter names. There is no way that gain overcomes the loss of readability.
Do method names get compiled into the EXE?
[ "", "c#", "methods", "performance", "obfuscation", "cil", "" ]
I'm trying to make a form invisible for x amount of time in c#. Any ideas? Thanks, Jon
BFree has posted similar code in the time it took me to test this, but here's my attempt: ``` this.Hide(); var t = new System.Windows.Forms.Timer { Interval = 3000 // however long you want to hide for }; t.Tick += (x, y) => { t.Enabled = false; this.Show(); }; t.Enabled = true; ```
Quick and dirty solution taking advantage of closures. No `Timer` required! ``` private void Invisibilize(TimeSpan Duration) { (new System.Threading.Thread(() => { this.Invoke(new MethodInvoker(this.Hide)); System.Threading.Thread.Sleep(Duration); this.Invoke(new MethodInvoker(this.Show)); })).Start(); } ``` Example: ``` // Makes form invisible for 5 seconds. Invisibilize(new TimeSpan(0, 0, 5)); ```
Using a Timer in C#
[ "", "c#", "timer", "" ]
I've been profiling an application all day long and, having optimized a couple bits of code, I'm left with this on my todo list. It's the activation function for a neural network, which gets called over a 100 million times. According to dotTrace, it amounts to about 60% of the overall function time. How would you optimize this? ``` public static float Sigmoid(double value) { return (float) (1.0 / (1.0 + Math.Pow(Math.E, -value))); } ```
Try: ``` public static float Sigmoid(double value) { return 1.0f / (1.0f + (float) Math.Exp(-value)); } ``` **EDIT:** I did a quick benchmark. On my machine, the above code is about 43% faster than your method, and this mathematically-equivalent code is the teeniest bit faster (46% faster than the original): ``` public static float Sigmoid(double value) { float k = Math.Exp(value); return k / (1.0f + k); } ``` **EDIT 2:** I'm not sure how much overhead C# functions have, but if you `#include <math.h>` in your source code, you should be able to use this, which uses a float-exp function. It might be a little faster. ``` public static float Sigmoid(double value) { float k = expf((float) value); return k / (1.0f + k); } ``` Also if you're doing millions of calls, the function-calling overhead might be a problem. Try making an inline function and see if that's any help.
If it's for an activation function, does it matter terribly much if the calculation of e^x is completely accurate? For example, if you use the approximation (1+x/256)^256, on my Pentium testing in Java (I'm assuming C# essentially compiles to the same processor instructions) this is about 7-8 times faster than e^x (Math.exp()), and is accurate to 2 decimal places up to about x of +/-1.5, and within the correct order of magnitude across the range you stated. (Obviously, to raise to the 256, you actually square the number 8 times -- don't use Math.Pow for this!) In Java: ``` double eapprox = (1d + x / 256d); eapprox *= eapprox; eapprox *= eapprox; eapprox *= eapprox; eapprox *= eapprox; eapprox *= eapprox; eapprox *= eapprox; eapprox *= eapprox; eapprox *= eapprox; ``` Keep doubling or halving 256 (and adding/removing a multiplication) depending on how accurate you want the approximation to be. Even with n=4, it still gives about 1.5 decimal places of accuracy for values of x beween -0.5 and 0.5 (and appears a good 15 times faster than Math.exp()). P.S. I forgot to mention -- you should obviously not *really* divide by 256: multiply by a constant 1/256. Java's JIT compiler makes this optimisation automatically (at least, Hotspot does), and I was assuming that C# must do too.
Math optimization in C#
[ "", "c#", "optimization", "neural-network", "performance", "" ]
I have a stored procedure in my database that calculates the distance between two lat/long pairs. This stored procedure is called "DistanceBetween". I have a SQL statement allows a user to search for all items in the Items table ordered by the distance to a supplied lat/long coordinate. The SQL statement is as follows: ``` SELECT Items.*, dbo.DistanceBetween(@lat1, @lat2, Latitude, Longitude) AS Distance FROM Items ORDER BY Distance ``` How do I go about using this query in NHibernate? The Item class in my domain doesn't have a "Distance" property since there isn't a "Distance" column in my Items table. The "Distance" property really only comes into play when the user is performing this search.
There are basically three approaches that can be used, some of which have already been discussed: 1. Use an HQL query or `CreateCriteria`/`ICriteria` query; *downsides:* it is not part of the entities/DAL; *upsides:* it is flexible; 2. Use a property mapping with a `formula`; *downsides:* it is not always feasible or possible, performance can degrade if not careful; *upsides:* it the calculation an integral part of your entities; 3. Create a separate XML HBM mapping file and map to a separate (to be created) entity; *downsides:* it is not part of the base entities; *upsides:* you only call the SP when needed, full control of mapping / extra properties / extensions, can use partial or abstract classes to combine with existing entities. I'll briefly show an example of option 2 and 3 here, I believe option 1 has been sufficiently covered by others earlier in this thread. Option two, as in this example, is particularly useful when the query can be created as a subquery of a select statement and when all needed parameters are available in the mapped table. It also helps if the table is not mutable and/or is cached as read-only, depending on how heavy your stored procedure is. ``` <class name="..." table="..." lazy="true" mutable="false> <cache usage="read-only" /> <id name="Id" column="id" type="int"> <generator class="native" /> </id> <property name="Latitude" column="Latitude" type="double" not-null="true" /> <property name="Longitude" column="Longitude" type="double" not-null="true" /> <property name="PrijsInstelling" formula="(dbo.DistanceBetween(@lat1, @lat2, Latitude, Longitude))" type="double" /> ... etc </class> ``` If the above is not possible due to restrictions in the mappings, problems with caching or if your current cache settings retrieve one by one instead of by bigger amounts and you cannot change that, you should consider an alternate approach, for instance a separate mapping of the whole query with parameters. This is quite close to the CreateSqlQuery approach above, but forces the result set to be of a certain type (and you can set each property declaratively): ``` <sql-query flush-mode="never" name="select_Distances"> <return class="ResultSetEntityClassHere,Your.Namespace" alias="items" lock-mode="read" > <return-property name="Id" column="items_Id" /> <return-property name="Latitude" column="items_Latitude" /> <return-property name="Longitude" column="items_Longitude" /> <return-property name="Distance" column="items_Distance" /> </return> SELECT Items.*, dbo.DistanceBetween(@lat1, @lat2, Latitude, Longitude) AS Distance FROM Items WHERE UserId = :userId </sql-query> ``` You can call this query as follows: ``` List<ResultSetEntityClassHere> distanceList = yourNHibernateSession.GetNamedQuery("select_Distances") .SetInt32("userId", currentUserId) /* any params go this way */ .SetCacheable(true) /* it's usually good to cache */ .List<ResultSetEntityClassHere>(); /* must match the class of sql-query HBM */ ``` Depending on your needs, you can choose an approach. I personally use the following rule of thumb to decide what approach to use: * Is the calculation light or can it be cached? *Use `formula` approach;* * Are parameters needed to be sent to the SP/SQL? *Use `sql-query` + mapping approach;* * Is the structure of the query (very) variable? *Use `ICriteria` or HQL approach through code.* About the ordering of the data: when you choose the "formula" or the "sql-query mapping" approach you'll have to do the ordering when you retrieve the data. This is not different then with retrieving data through your current mappings. **Update:** terrible edit-mistake corrected in the sql-query XML.
You could try: ``` session.CreateSqlQuery(@"SELECT {item.*}, dbo.DistanceBetween(:lat1, :lat2, {item}.Latitude, {item}.Longitude) AS Distance FROM Items {item} ORDER BY Distance") .AddEntity("item", typeof(Item)) .SetDecimal("lat1", lat1) .SetDecimal("lat2", lat2) .List<Item>() ``` NHibernate is finicky about table & column aliases in the query, so you need to let it expand them using the {} syntax. Also, use the HQL named parameter syntax (:lat1 instead of @lat1), and change SetDecimal() to the correct data type.
NHibernate query with distance calculation stored proc
[ "", "sql", "nhibernate", "" ]
Let's say I have a table *tbl* with columns *id* and *title*. I need to change all values of title column: 1. from 'a-1' to 'a1', 2. from 'a.1' to 'a1', 3. from 'b-1' to 'b1', 4. from 'b.1' to 'b1'. Right now, I'm performing two UPDATE statements: ``` UPDATE tbl SET title='a1' WHERE title IN ('a-1', 'a.1') UPDATE tbl SET title='b1' WHERE title IN ('b-1', 'b.1') ``` This isn't at all a problem, if the table is small, and the single statement completes in less than a second and you only need a few statements to execute. You probably guested it - I have a huge table to deal with (one statement completes in about 90 seconds), and I have a huge number of updates to perform. So, is it possible to merge the updates so it would only scan the table once? Or perhaps, there's a better way to deal with in a situation like this. EDIT: Note, that the real data I'm working with and the changes to the data I have to perform are not really that simple - the strings are longer and they don't follow any pattern (it is user data, so no assumptions can be made - it can be anything).
In a more general case, where there could be many hundreds of mappings to each of the new values, you would create a separate table of the old and new values, and then use that in the UPDATE statement. In one dialect of SQL: ``` CREATE TEMP TABLE mapper (old_val CHAR(5) NOT NULL, new_val CHAR(5) NOT NULL); ...multiple inserts into mapper... INSERT INTO mapper(old_val, new_val) VALUES('a.1', 'a1'); INSERT INTO mapper(old_val, new_val) VALUES('a-1', 'a1'); INSERT INTO mapper(old_val, new_val) VALUES('b.1', 'b1'); INSERT INTO mapper(old_val, new_val) VALUES('b-1', 'b1'); ...etcetera... UPDATE tbl SET title = (SELECT new_val FROM mapper WHERE old_val = tbl.title) WHERE title IN (SELECT old_val FROM mapper); ``` Both select statements are crucial. The first is a correlated sub-query (not necessarily fast, but faster than most of the alternatives if the mapper table has thousands of rows) that pulls the new value out of the mapping table that corresponds to the old value. The second ensures that only those rows which have a value in the mapping table are modified; this is crucial as otherwise, the title will be set to null for those rows without a mapping entry (and those were the records that were OK before you started out). For a few alternatives, the CASE operations are OK. But if you have hundreds or thousands or millions of mappings to perform, then you are likely to exceed the limits of the SQL statement length in your DBMS.
You can use one statement and a number of case statements ``` update tbl set title = case when title in ('a-1', 'a.1') then 'a1' when title in ('b-1', 'b.1') then 'b1' else title end ``` Of course, this will cause a write on every record, and with indexes, it can be an issue, so you can filter out only the rows you want to change: ``` update tbl set title = case when title in ('a-1', 'a.1') then 'a1' when title in ('b-1', 'b.1') then 'b1' else title end where title in ('a.1', 'b.1', 'a-1', 'b-1') ``` That will cut down the number of writes to the table.
Is it possible to perform multiple updates with a single UPDATE SQL statement?
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "optimization", "" ]
I work at a company that has some very non-standardized SQL conventions (They were written by Delphi Developers years ago). Where is the best place that I can find SQL industry standard convention definitions that are most commonly used?
In his book "[SQL Programming Style](https://rads.stackoverflow.com/amzn/click/com/0120887975)," Joe Celko suggests a number of conventions, for example that a collection (e.g. a table) should be named in the plural, while a scalar data element (e.g. a column) should be named in the singular. He cites [ISO-11179-4](http://en.wikipedia.org/wiki/ISO/IEC_11179) as a standard for metadata naming, which supports this guideline.
1. there aren't any 2. it there were, they'd be obsolete 3. if they're not obsolete, you won't like them 4. if you like them, they're insufficient 5. if they're sufficient, no one else will like them seriously, strive for readability, i.e. use meaningful field and table names; nothing else is really necessary (ok some common prefixes like usp and udf and udt may be useful, but not required)
Where can I find/learn industry standard SQL Conventions?
[ "", "sql", "sql-server", "t-sql", "" ]
I just started with the WCF REST Starter Kit. I created a simple service that return an array of an object. Using the browser, everything works fine but when I use a WCF client, I get an ArgumentException. I'm not using IIS and here is the code: **The contract:** ``` [ServiceContract] public interface IGiftService { [WebGet(UriTemplate="gifts")] [OperationContract] List<Gift> GetGifts(); } public class GiftService : IGiftService { public List<Gift> GetGifts() { return new List<Gift>() { new Gift() { Name = "1", Price = 1.0 }, new Gift() { Name = "2", Price = 1.0 }, new Gift() { Name = "3", Price = 1.0 } }; } } [DataContract] public class Gift { [DataMember] public string Name { get; set; } [DataMember] public double Price { get; set; } } ``` **To start the service:** ``` WebServiceHost2 host = new WebServiceHost2( typeof(GiftService), true, new Uri("http://localhost:8099/tserverservice")); host.Open(); Console.WriteLine("Running"); Console.ReadLine(); host.Close(); ``` **To start the client:** ``` WebChannelFactory<IGiftService> factory = new WebChannelFactory<IGiftService>( new Uri("http://localhost:8099/tserverservice")); IGiftService service = factory.CreateChannel(); List<Gift> list = service.GetGifts(); Console.WriteLine("-> " + list.Count); foreach (var item in list) { Console.WriteLine("-> " + item.Name); } ``` The server and the client are in the same solution and I'm using the same interface in both (to describe the service contract). The exception says: "A property with the name 'UriTemplateMatchResults' already exists." and that is the stack trace: **Class firing the exception** -> Microsoft.ServiceModel.Web.WrappedOperationSelector **Stack trace:** ``` at System.ServiceModel.Channels.MessageProperties.UpdateProperty(String name, Object value, Boolean mustNotExist) at System.ServiceModel.Channels.MessageProperties.Add(String name, Object property) at System.ServiceModel.Dispatcher.WebHttpDispatchOperationSelector.SelectOperation(Message& message, Boolean& uriMatched) at System.ServiceModel.Dispatcher.WebHttpDispatchOperationSelector.SelectOperation(Message& message) at Microsoft.ServiceModel.Web.WrappedOperationSelector.SelectOperation(Message& message) in C:\Program Files\WCF REST Starter Kit\Microsoft.ServiceModel.Web\WrappedOperationSelector.cs:line 42 at Microsoft.VisualStudio.Diagnostics.ServiceModelSink.ServiceMethodResolver.GetOperation() at Microsoft.VisualStudio.Diagnostics.ServiceModelSink.ServiceMethodResolver..ctor(ContractDescription contract, DispatchRuntime runtime, Message request, InstanceContext instanceContext) ``` What am I doing wrong? **UPDATE:** I disabled the help page and the service is working now. Is it a bug? ``` host.EnableAutomaticHelpPage = false; ``` Thank you! André Carlucci
Had the same problem, disabled the help page and it fixed it. The exception was being thrown if some REST urls were called in a sequence very quickly. It was fine when waiting between the calls. ``` protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { return new WebServiceHost2(serviceType, true, baseAddresses) {EnableAutomaticHelpPage = false}; } ```
I had the same probem, but I wanted to see the help page so disabling it wasn't a solution for me. I found out that URITemplating in the WCF REST Toolkit is causing those problem, when it sees that it already have this template in the template tables. Basically you will only need a template when the URL to your method is different according to the requested data, after all, that's what the templates are for. I had the same URITemplates for my POST operations, so the URLs did not differ between separate queries which causes this error. then I found out that I actually didn't need any templating at all, at least for the POST operations, moreover youvannot make a POST query though the URL if your method requires a complex object to be passed as a parameter. So I removed the URITemplate named parameter from the WebInvoke attribute in the service interface, I think that solved the problem. Of course if you make GET queries to the server and rely on URITemplating you'll still have to either put up with or leave away the help page.
WCF REST Starter Kit - A property with the name 'UriTemplateMatchResults' already exists
[ "", "c#", "wcf", "rest", "wcf-client", "" ]
How should exceptions be dispatched so that error handling and diagnostics can be handled in a centralized, user-friendly manner? For example: * A DataHW class handles communication with some data acquisition hardware. * The DataHW class may throw exceptions based on a number of possible errors: intermittent signal, no signal, CRC failure, driver error. Each type of error gets its own exception class. * The DataHW class is called by a number of different pieces of code that do different types of acquisition and analysis. The proper error handling strategy depends on the type of exception and the operation being attempted. (On intermittent signal, retry X times then tell the user; on a driver error, log an error and restart the driver; etc.) How should this error handling strategy be invoked? * Coding error recovery into each exception class: This would result in exception classes that are rather large and contain high-level UI and system management code. This seems bad. * Providing a separate `catch` block for each type of exception: Since the DataHW class is called from many different places, each `catch` block would have to be duplicated at each call site. This seems bad. * Using a single `catch` block that calls some `ExceptionDispatch` function with a giant RTTI-based `switch` statement: RTTI and `switch` usually indicates a failure to apply OO design, but this seems the least bad alternative.
Avoid duplicating the catch blocks at each call site by catching (...) and calling a shared handler function which rethrows and dispatches: ``` f() { try { // something } catch (...) { handle(); } } void handle() { try { throw; } catch (const Foo& e) { // handle Foo } catch (const Bar& e) { // handle Bar } // etc } ```
An idea I keep running into is that exceptions should be caught by levels which can handle them. For example, a CRC error might be caught by the function that transmits the data, and upon catching this exception, it might try to retransmit, whereas a "no signal" exception might be caught in a higher level and drop or delay the whole operation. But my guess is that most of these exceptions will be caught around the same function. It *is* a good idea to catch and handle them seperately (as in soln #2), but you say this causes a lot of duplicate code (leading to soln #3.) My question is, if there is a lot of code to duplicate, why not make it into a function? I'm thinking along the lines of... ``` void SendData(DataHW* data, Destination *dest) { try { data->send(dest); } catch (CRCError) { //log error //retransmit: data->send(dest); } catch (UnrecoverableError) { throw GivingUp; } } ``` I guess it would be like your ExceptionDispatch() function, only instead of `switch`ing on the exception type, it would wrap the exception-generating call itself and `catch` the exceptions. Of course, this function is overly simplified - you might need a whole wrapper class around DataHW; but my point is, it would be a good idea to have a centralized point around which all DataHW exceptions are handled - if the way different users of the class would handle them are similar.
Dispatching exceptions in C++
[ "", "c++", "oop", "exception", "" ]
In a Swing app a method should continue only after user enters a correct answer. The correct answer is stored in a `String` with user answer being set by a listener to another `String`. So, the code is ``` while (!correctAnswer.equals(currentAnswer)) { // wait for user to click the button with the correct answer typed into the textfield } // and then continue ``` Is everything fine with this approach or would you somehow refactor it? Doesn't it impose extra penalty on CPU? Here's a somewhat [similar question](https://stackoverflow.com/questions/244445/best-refactoring-for-the-dreaded-while-true-loop "Best refactoring for the dreaded While (True) loop").
Are you new to UI programming? The reason I ask is that your answer is predicated on a procedural style of coding, which isn't what UIs are about. It tends to be event-driven. In this case the solution is pretty easy: add an event listener (`ActionListener`) to the submit button and check the result there. If its OK, go on. If not, say so and let them try again.
As others have suggested, you'll want to use assign a listener to the button, which will be called when the button is pressed. Here's a incomplete example illustrating how to use an [`ActionListener`](http://java.sun.com/javase/6/docs/api/java/awt/event/ActionListener.html) and implementing its [`actionPerformed`](http://java.sun.com/javase/6/docs/api/java/awt/event/ActionListener.html#actionPerformed(java.awt.event.ActionEvent)) method which is called when the button is pressed: ``` ... final JTextField textField = new JTextField(); final JButton okButton = new JButton("OK"); okButton.addActionListner(new ActionListener() { public void actionPerformed(ActionEvent e) { if ("some text".equals(textField.getText())) System.out.println("Yes, text matches."); else System.out.println("No, text does not match."); } }); ... ``` You may just want to implement [`ActionListener`](http://java.sun.com/javase/6/docs/api/java/awt/event/ActionListener.html) in the class where the button and text field resides, so you don't need to declare the two objects as `final`. (I just used an anonymous inner class to keep the example short.) For more information, you may want to take a look at [How to Write an Action Listener](http://java.sun.com/docs/books/tutorial/uiswing/events/actionlistener.html) from [The Java Tutorials](http://java.sun.com/docs/books/tutorial/index.html). Also, for general information on how events work in Java, the [Lesson: Writing Event Listeners](http://java.sun.com/docs/books/tutorial/uiswing/events/index.html) from The Java Tutorials may be useful. **Edit:** Changed the expression inside `if` statement from `textField.getText().equals("some text")` to `"some text".equals(textField.getText())` in order to prevent a `NullPointerException` if `textField` was `null`, per suggestion from Mr. Shiny and New's comment.
The correct way of waiting for strings to become equal
[ "", "java", "while-loop", "cpu-cycles", "" ]
I have a very simple html page here: <http://www.nomorepasting.com/getpaste.php?pasteid=22407> And I have 4 layers on the page. The reason for this is it is the framework oif a much more complicated site, I have simplified it to ask my question. Basically, I want to be able to click on different links in layer 2 and have the image in layer1 change, however The way I have found to do this: ``` <script type="text/javascript"><!-- function sbox(boxName,xname) { theBox = document.getElementById(boxName); theBox.className = xname; } //--> </script> ``` Results in the text nto going away, which I need, as well as a way to click and replace whatever image is there with the text. I found alternative javascript code, but could not apply it to my html page. ``` <script type="text/javascript"> function toggleImg(myid) { objtxt = document.getElementById(myid); objimg = document.getElementById(myid+'_img'); if( objtxt.style.display == 'block' ) { // Show image, hide text objtxt.style.display = 'none'; objimg.style.display = 'block'; } else { // Hide image, show text objimg.style.display = 'none'; objtxt.style.display = 'block'; } } </script> ``` What is the easiest way to do this without changing the design of my page? note: I do not want to use a framework, I want to understand how this is done and do it for myself. My additional question is on if layers should replace tables: Is it always bad to use tables when css could be used instead? Is it easy to use layers to make row and column equivalents just to format text data, not the structure of a site?
(In response to Joshxtothe4's comment... I needed more space to respond) Changing the class back to class1 will not show the text again, unfortunately. The code I gave will hide the text, always, if it's found in a span. You could do something like below, and add another CSS statement that will hide the span if class4 is used. Then you don't have to have that code in javascript. Probably a cleaner solution: ``` <html> <head> <style type="text/css"> .class1{color:#000;} .class2{color:#00f;} .class3{color:#0f0;} .class4{color:#f00; background-image:url('someimage.jpg');} .class4 span { display: none;} </style> </head> <body> <script type="text/javascript"> function sbox(divid, classname) { document.getElementById(divid).className=classname; } </script> <div> <a href="#" onclick="sbox('div1','class1');return false;">Reset</a><br/> <a href="#" onclick="sbox('div1','class2');return false;">Test Div1, Class2(blue)</a><br/> <a href="#" onclick="sbox('div1','class3'); return false;">Test Div1, Class3(green)</a><br/> <a href="#" onclick="sbox('div1','class4');return false;">Test Div1, Class4(red)</a> </div> <div id="div1" class="class1"><span id="div1_text">Blah blah blah</span></div> </body> </html> ``` As far as having the image as a background, that's probably your best bet. The only problem was that setting background images doesn't hide foreground text. You'd always have to hide that text somehow
Tables are for tabular data (think Excel). If you have a grid of data to display use a table. When it comes to page lyouts, use CSS positioning. Also, obsessive DIV use isn't the best way to use CSS. Getting into the habit of wrapping everything up in a DIV is a practice known as "div mania" and you can Google for reasons why it's not good.
An image and text query
[ "", "javascript", "html", "css", "" ]
I've been learning C++, coming from C#, where I've gotten used to using service providers: basically a Dictionary<Type, object>. Unfortunately, I can't figure out how to do this in C++. So the questions are basically: 1. How would I make a dictionary in C++. 2. How would I use 'Type' with it, as far as I know there is no 'Type' in C++. 3. Same as above, but with 'object'. Thanks!
I'm assuming that you're trying to map a type to a single object instance. You could try something along these lines: ``` #include <typeinfo> #include <map> #include <string> using namespace std; class SomeClass { public: virtual ~SomeClass() {} // virtual function to get a v-table }; struct type_info_less { bool operator() (const std::type_info* lhs, const std::type_info* rhs) const { return lhs->before(*rhs) != 0; } }; class TypeMap { typedef map <type_info *, void *, type_info_less> TypenameToObject; TypenameToObject ObjectMap; public: template <typename T> T *Get () const { TypenameToObject::const_iterator iType = ObjectMap.find(&typeid(T)); if (iType == ObjectMap.end()) return NULL; return reinterpret_cast<T *>(iType->second); } template <typename T> void Set(T *value) { ObjectMap[&typeid(T)] = reinterpret_cast<void *>(value); } }; int main() { TypeMap Services; Services.Set<SomeClass>(new SomeClass()); SomeClass *x = Services.Get<SomeClass>(); } ``` In C++ types are not first-class objects in their own right, but at least the type-name is going to be unique, so you can key by that. Edit: The names aren't actually guaranteed to be unique, so hold on to the type\_info pointers and use the before method to compare them.
You probably want to look at the [STL map template](http://www.cplusplus.com/reference/stl/map/). C++ certainly does have types (hard to have inheritance without it), just no specific defined "Type" class.
C++ Service Providers
[ "", "c++", "dictionary", "service", "" ]
I want to convert function object to function. I wrote this code, but it doesn't work. ``` #include <iostream> typedef int (*int_to_int)(int); struct adder { int n_; adder (int n) : n_(n) {} int operator() (int x) { return x + n_; } operator int_to_int () { return this->*&adder::operator(); } }; int main(void) { adder add_two(2); int_to_int add_fn = add_two; std::cout << add_two(3) << std::endl; // expect 5 std::cout << add_fn(3) << std::endl; // expect 5 add_fn = adder(5); std::cout << add_fn(3) << std::endl; // expect 8 return 0; } ``` and I got message from g++, says `invalid use of non-static member function`. How do I get pointer to member function of instance? **Edit**:My original problem is about Win32 API. I'm forced to write windows program with old Win32 API at school. but I don't want to write horrible switch statement like some example codes on text. Then, I decided to write wrapper in C++. I want to write the window class like ... ``` class Window { public: LRESULT update (HWND, UINT, WPARAM, LPARAM); void run(); // below methods are called by update() virtual void onclick(int, int); virtual void ondraw(); // ... and more methods }; ``` and I'm willing to write my application class with deriving this class and overloading some methods. Finally, my actual probrem is how to do this in C++. ``` // on initializing my window object, // I must register window class with callback which is // not a C++ function object. // I try to explain what I want to do with psudocode mixing C++ and javascript. WNDCLASS wndclass; Window *self = this; wndclass.lpfnWndProc = function () { return self.update.apply(self, argunemts); }; ``` In other word, I have to make closure into function pointer. I don't know how to do this, but I can't believe this can't do in C++. **Edit**: The original title of this question was *How to get pointer-to-member-function of instance*. But this title and my question didn't tell my actual problem enough. Sorry to early answerers, and litb, thank you for suggestion and very useful answer!
**Update**: You told us what you want. I found this question here on SO: [Best method for storing this pointer for use in WndProc](https://stackoverflow.com/questions/117792/best-method-for-storing-this-pointer-for-use-in-wndproc) . I'm not a Windows Programmer, but the Adam Rosenfield guy seem to be right in using SetWindowLongPtr and GetWindowLongPtr. So, you use it like this: ``` LRESULT CALLBACK my_callback(HWND hwnd, UINT ui, WPARAM wp, LPARAM lp) { Window * self = reinterpret_cast<Window*>( GetWindowLongPtr(hwnd, 0)); return self->update(hwnd, ui, wp, lp); // handle it. } ``` Register that function as the wnd-proc and store the `this` pointer of your Window object using SetWindowLongPtr. In the `WNDCLASSEX` structure, there is a `cbWndExtra` field that you assign `sizeof(Window*)` to, which is enough storage to just contain the this pointer. Then you can call ``` SetWindowLongPtr(my_hwnd, 0, reinterpret_cast<LONG_PTR>(this)); ``` to put the this pointer into that region. Then receive it like the above and delegate to the real member function. You could in theory also use a static member function. But you have to be careful. Calling a static member function from C code can cause bugs, because the calling convention might be different between C code and C++ code. For Windows, that may not be an issue - I don't know. So better check yourself in addition. --- The thing you try is invalid. You try to return a pointer to the function call operator, but there is no object provided when the call is made, beside that your conversion operator has the wrong type. The type that the conversion operator returns has function pointer type, but not member function pointer type. The closest you can get to is to use the proper type: ``` struct adder; typedef int (adder::*int_to_int)(int); struct adder { int n_; adder (int n) : n_(n) {} int operator() (int x) { return x + n_; } operator int_to_int () { return &adder::operator(); } }; ``` Now, your conversion operator is not even considered, because it has to be called like this: ``` adder a(10); cout << (a.*(int_to_int)a)(2); // expected: 12 ``` And manually like this: ``` // note, we just get the member function pointer using the conversion operator. // Nothing is related to the actual temporary adder object. int_to_int i = adder(5); cout << (adder(10).*i)(2); // expected: 12 ``` The usual function call syntax does not cope with that. In short, what you try is not possible. I think another question is, why the heck do you want to do that? I think we can help you better when we know what the original problem is. If you are trying to make it look and work like a function call, you don't need any conversion operators at all: ``` struct adder { int n_; adder (int n) : n_(n) {} int operator() (int x) { return x + n_; } }; adder a(10); cout << a(2); // expected: 12 ```
Instance method pointers are a bit tricky and are completely different beasts compared to 'normal' function pointers. See what the [C++ FAQ lite section 33](http://www.parashift.com/c++-faq-lite/pointers-to-members.html) has to say about it. Also see [this](http://www.goingware.com/tips/member-pointers.html) and [this](http://www.codeproject.com/KB/cpp/FastDelegate.aspx) for concrete examples.
On writing win32 api wrapper with C++, how to pass this pointer to static function
[ "", "c++", "winapi", "function", "pointers", "" ]
Does using Multiple .NET Languages (Delphi, VB.NET, C#) into the same application (but in differents class library of course) can **down peformances** compared to a **full C# application** for example ?
I'm not an expert on the CLR, but I would guess that you will have very similar performance. All the languages compile to MSIL which runs on the CLR. There could be differences in performance depending on the MSIL generated from the compilers. i.e. It's possible that similar code in VB.NET would compile to less (or more) optimized MSIL than the C# compiler.
Although I don't have any benchmarks off hand, I would say that for the most part it shouldn't. Those different languages all compile the code into CIL, so you should be fine. One place where this would be different is with the languages that are run on the DLR (IronPython, IronRuby, etc.). They're compiling in the use of some features that aren't present in the CLR and that are more costly operations.
Cross .NET Languages Performances
[ "", "c#", ".net", "" ]
I currently have a unittest.TestCase that looks like.. ``` class test_appletrailer(unittest.TestCase): def setup(self): self.all_trailers = Trailers(res = "720", verbose = True) def test_has_trailers(self): self.failUnless(len(self.all_trailers) > 1) # ..more tests.. ``` This works fine, but the `Trailers()` call takes about 2 seconds to run.. Given that `setUp()` is called before each test is run, the tests now take almost 10 seconds to run (with only 3 test functions) What is the correct way of caching the `self.all_trailers` variable between tests? Removing the setUp function, and doing.. ``` class test_appletrailer(unittest.TestCase): all_trailers = Trailers(res = "720", verbose = True) ``` ..works, but then it claims "Ran 3 tests in 0.000s" which is incorrect.. The only other way I could think of is to have a cache\_trailers global variable (which works correctly, but is rather horrible): ``` cache_trailers = None class test_appletrailer(unittest.TestCase): def setUp(self): global cache_trailers if cache_trailers is None: cache_trailers = self.all_trailers = all_trailers = Trailers(res = "720", verbose = True) else: self.all_trailers = cache_trailers ```
How about using a class member that only gets initialized once? ``` class test_appletrailer(unittest.TestCase): all_trailers = None def setup(self): # Only initialize all_trailers once. if self.all_trailers is None: self.__class__.all_trailers = Trailers(res = "720", verbose = True) ``` Lookups that refer to `self.all_trailers` will go to the next step in the [MRO](http://www.python.org/download/releases/2.3/mro/) -- `self.__class__.all_trailers`, which will be initialized.
An alternative to the proposed solution would be to use a more featured test runner like [Nose](https://nose.readthedocs.io/en/latest/). With Nose, you can have module-level setup functions which will be run once for a test module. Since it is entirely compatible with unittest, you wouldn't have to change any code. From the Nose manual: > nose supports fixtures at the package, > module, class, and test case level, **so** > **expensive initialization can be done** > **as infrequently as possible**. Fixtures are [described in detail here](https://pythontesting.net/framework/nose/nose-fixture-reference/). Of course, apart from fulfilling your use-case, I can also strongly recommend it as a general testing tool. None of my projects will leave home without it.
Caching result of setUp() using Python unittest
[ "", "python", "unit-testing", "" ]
Currently I am working on a project where goto statements are heavely used. The main purpose of goto statements is to have one cleanup section in a routine rather than multiple return statements. Like below: ``` BOOL foo() { BOOL bRetVal = FALSE; int *p = NULL; p = new int; if (p == NULL) { cout<<" OOM \n"; goto Exit; } // Lot of code... Exit: if(p) { delete p; p = NULL; } return bRetVal; } ``` This makes it much easier as we can track our clean up code at one section in code, that is, after the Exit label. However, I have read many places it's bad practice to have goto statements. Currently I am reading the *[Code Complete](https://en.wikipedia.org/wiki/Code_Complete)* book, and it says that we need to use variables close to their declarations. If we use goto then we need to declare/initialize all variables before first use of goto otherwise the compiler will give errors that initialization of xx variable is skipped by the goto statement. Which way is right? --- From Scott's comment: It looks like using goto to jump from one section to another is bad as it makes the code hard to read and understand. But if we use goto just to go forward and to one label then it should be fine(?).
I am not sure what do you mean by clean up code but in C++ there is a concept called "*resource acquisition is initialization*" and it should be the responsibility of your destructors to clean up stuff. (Note that in C# and Java, this is usually solved by try/finally) For more info check out this page: <http://www.research.att.com/~bs/bs_faq2.html#finally> **EDIT**: Let me clear this up a little bit. Consider the following code: ``` void MyMethod() { MyClass *myInstance = new MyClass("myParameter"); /* Your code here */ delete myInstance; } ``` **The problem**: What happens if you have multiple exits from the function? You have to keep track of each exit and delete your objects at all possible exits! Otherwise, you will have memory leaks and zombie resources, right? **The solution**: Use object references instead, as they get cleaned up automatically when the control leaves the scope. ``` void MyMethod() { MyClass myInstance("myParameter"); /* Your code here */ /* You don't need delete - myInstance will be destructed and deleted * automatically on function exit */ } ``` Oh yes, and use [`std::unique_ptr`](http://en.cppreference.com/w/cpp/memory/unique_ptr) or something similar because the example above as it is is obviously imperfect.
I've never had to use a goto in C++. Ever. EVER. If there is a situation it should be used, it's incredibly rare. If you are actually considering making goto a standard part of your logic, something has flown off the tracks.
To GOTO or not to GOTO?
[ "", "c++", "goto", "" ]
I have a `Dictionary<string,int>` that has the potential to contain upwards of 10+ million unique keys. I am trying to reduce the amount of memory that this takes, while still maintaining the functionality of the dictionary. I had the idea of storing a hash of the string as a long instead, this decreases the apps memory usage to an acceptable amount (~1.5 gig to ~.5 gig), but I don't feel very good about my method for doing this. ``` long longKey= BitConverter.ToInt64(cryptoTransformSHA1.ComputeHash(enc.GetBytes(strKey)), 0); ``` Basically this chops off the end of a SHA1 hash, and puts the first chunk of it into a long, which I then use as a key. While this works, at least for the data I'm testing with, I don't feel like this is a very reliable solution due to the increased possibility for key collisions. Are there any other ways of reducing the Dictionary's memory footprint, or is the method I have above not as horrible as I think it is? [edit] To clarify, I need to maintain the ability to lookup a value contained in the Dictionary using a string. Storing the actual string in the dictionary takes way to much memory. What I would like to do instead is to use a `Dictionary<long,int>` where the long is the result of a hashing function on the string.
So I have done something similar recently and for a certain set of reasons that are fairly unique to my application did not use a database. In fact I was try to stop using a database. I have found that GetHashCode is significantly improved in 3.5. One important note, NEVER STORE PERSISTENTLY THE RESULTS FROM GetHashCode. NEVER EVER. They are not guaranteed to be consistent between versions of the framework. So you really need to conduct an analysis of your data since different hash functions might work better or worse on your data. You also need to account for speed. As a general rule cryptographic hash functions should not have many collisions even as the number of hashes moves into the billions. For things that I need to be unique I typically use SHA1 Managed. In general the CryptoAPI has terrible performance, even if the underlying hash functions perform well. For a 64bit hash I currently use Lookup3 and FNV1, which are both 32 bit hashes, together. For a collision to occur both would need to collide which is mathematically improbable and I have not seen happen over about 100 million hashes. You can find the code to both publicly available on the web. Still conduct your own analysis. What has worked for me may not work for you. Actually inside of my office different applications with different requirements actually use different hash functions or combinations of hash functions. I would avoid any unproven hash functions. There are as many hash functions as people who think that they should be writing them. Do your research and test test test.
With 10 million-odd records, have you considered using a database with a non-clustered index? Databases have a lot more tricks up their sleeve for this type of thing. Hashing, by definition, and under any algorithm, has the potential of collisions - especially with high volumes. Depending on the scenario, I'd be very cautious of this. Using the strings might take space, but it is reliable... if you are on x64 this needn't be too large (although it definitely counts as "big" ;-p)
C# Dictionary Memory Management
[ "", "c#", "data-structures", "memory-management", "dictionary", "" ]
I'm trying to connect to an Oracle DB which is currently offline. When it's online it's not a problem, however, now that it's offline my program is getting hung up on the $connection = oci\_connect() line and timing out. How do I simply check the connectio and bail out if it's not there?
Try this (fill in your ip and port): ``` if ( @fsockopen($db_ip,$db_port ) ) { //connect to database } else { // didn't work } ```
This gives you both a manual error, plus will return the actual error. ``` $connection = oci_connect() or die("Critical Error: Could not connect to database.\n\n". oci_error()); ``` Make sure to test this as hopefully the Oracle error doesn't do something stupid like return the connection string (with your DB password) but I wouldn't assume until you see for yourself.
How do I test for an Oracle connection
[ "", "php", "oracle", "" ]
My application performs time consuming work independently on several files. I created a BackgroundWorker to pass the work off to on each file, but it appears the backgroundworker is only capable of performing asynchronous work. Is it possible to do several asynchronous tasks in unison with it, or is there a similar object for performing synchronous operations?
The background worker is usually used to update the UI and/or to pass off work so you don't freeze the UI when a long running process takes place. This means that you "pass" the background worker process the "file work" and then use a callback to update the UI(usually) all during which your APP remains responsive. If the items are independent then you might want to spool up a few threads to split the work. Again, if I am understanding you correctly. If I am then you might want to look at [Jon Skeet's](http://www.yoda.arachsys.com/csharp/threads/) threading article.
While you can use the BackgroundWorker, I think you should simply spin off a few threads to do the work. One thread (probably the main thread) will create and start these worker threads and then perform a Join on all the workers in order to wait for processing to complete. Alternatively, have a look a the [Parallel Extensions for .Net](http://www.microsoft.com/downloads/details.aspx?FamilyId=348F73FD-593D-4B3C-B055-694C50D2B0F3&displaylang=en) if you are using .Net 3.5. The Task object from that library is probably perfect for your situation.
Synchronous work in a BackgroundWorker
[ "", "c#", "multithreading", "backgroundworker", "" ]
Why is the compiler unable to infer the correct type for the result from Collections.emptySet() in the following example? ``` import java.util.*; import java.io.*; public class Test { public interface Option<A> { public <B> B option(B b, F<A,B> f); } public interface F<A,B> { public B f(A a); } public Collection<String> getColl() { Option<Integer> iopt = null; return iopt.option(Collections.emptySet(), new F<Integer, Collection<String>>() { public Collection<String> f(Integer i) { return Collections.singleton(i.toString()); } }); } } ``` Here's the compiler error message: ``` knuttycombe@knuttycombe-ubuntu:~/tmp/java$ javac Test.java Test.java:16: <B>option(B,Test.F<java.lang.Integer,B>) in Test.Option<java.lang.Integer> cannot be applied to (java.util.Set<java.lang.Object>, <anonymous Test.F<java.lang.Integer,java.util.Collection<java.lang.String>>>) return iopt.option(Collections.emptySet(), new F<Integer, Collection<String>>() { ^ 1 error ``` Now, the following implementation of getColl() works, of course: ``` public Collection<String> getColl() { Option<Integer> iopt = null; Collection<String> empty = Collections.emptySet(); return iopt.option(empty, new F<Integer, Collection<String>>() { public Collection<String> f(Integer i) { return Collections.singleton(i.toString()); } }); } ``` and the whole intent of the typesafe methods on Collections is to avoid this sort of issue with the singleton collections (as opposed to using the static variables.) So is the compiler simply unable to perform inference across multiple levels of generics? What's going on?
Java needs a lot of hand holding with its inference. The type system could infer better in a lot of cases but in your case the following will work: ``` print("Collections.<String>emptySet();"); ```
First you can narrow down your problem to this code: ``` public class Test { public void option(Collection<String> b) { } public void getColl() { option(Collections.emptySet()); } } ``` This does not work, you need a temporary variable or else the compiler cannot infer the type. Here is a good explanation of this problem: [Why do temporary variables matter in case of invocation of generic methods?](http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#Why%20do%20temporary%20variables%20matter%20in%20case%20of%20invocation%20of%20parameterized%20methods?)
Why can't the Java compiler figure this out?
[ "", "java", "generics", "collections", "" ]
Using SQL Server 2005 and Management Studio how do I insert a picture into an `Image` type column of a table? Most importantly how do I verify if it is there?
``` CREATE TABLE Employees ( Id int, Name varchar(50) not null, Photo varbinary(max) not null ) INSERT INTO Employees (Id, Name, Photo) SELECT 10, 'John', BulkColumn FROM Openrowset( Bulk 'C:\photo.bmp', Single_Blob) as EmployeePicture ```
For updating a record: ``` UPDATE Employees SET [Photo] = (SELECT MyImage.* from Openrowset(Bulk 'C:\photo.bmp', Single_Blob) MyImage) where Id = 10 ``` **Notes:** * Make sure to add the 'BULKADMIN' Role Permissions for the login you are using. * Paths are not pointing to your computer when using SQL Server Management Studio. If you start SSMS on your local machine and connect to a SQL Server instance on server X, the file C:\photo.bmp will point to hard drive C: on server X, not your machine!
Insert Picture into SQL Server 2005 Image Field using only SQL
[ "", "sql", "sql-server", "sql-server-2005", "image", "" ]
I have an asp:ImageButton that is supposed to popup a save dialog when clicked. When I put it outside the UpdatePanel, it works fine, but when I put it inside the UpdatePanel, the dialog does not popup.
I had a similar problem in a GridView, but solved it by uing an Image inside a LinkButton. <http://netpl.blogspot.com/2008/01/imagebutton-in-templatefield-does-not.html> for more information.
Response.Write often doesn't work inside of UpdatePanels. Assuming you're just running some javascript in the onclick event on the client, you're probably better off just adding your javascript code server-side to the OnClientClick property.
asp:ImageButton is not firing in an asp.net UpdatePanel?
[ "", "c#", "asp.net", "" ]
I have a set of files. The set of files is read-only off a NTFS share, thus can have many readers. Each file is updated occasionally by one writer that has write access. How do I ensure that: 1. If the write fails, that the previous file is still readable 2. Readers cannot hold up the single writer I am using Java and my current solution is for the writer to write to a temporary file, then swap it out with the existing file using `File.renameTo()`. The problem is on NTFS, `renameTo` fails if target file already exists, so you have to delete it yourself. But if the writer deletes the target file and then fails (computer crash), I don't have a readable file. nio's FileLock only work with the same JVM, so it useless to me. How do I safely update a file with many readers using Java?
According to the [JavaDoc](http://java.sun.com/javase/6/docs/api/java/nio/channels/FileLock.html): > This file-locking API is intended to > map directly to the native locking > facility of the underlying operating > system. Thus the locks held on a file > should be visible to all programs that > have access to the file, regardless of > the language in which those programs > are written.
I don't know if this is applicable, but if you are running in a pure Vista/Windows Server 2008 solution, I would use TxF (transactional NTFS) and then make sure you open the file handle and perform the file operations by calling the appropriate file APIs through JNI. If that is not an option, then I think you need to have some sort of service that all clients access which is responsible to coordinate the reading/writing of the file.
How to safely update a file that has many readers and one writer?
[ "", "java", "concurrency", "filesystems", "ntfs", "atomic", "" ]
I've just upgraded some old Java source which has been running on a Sun Java 1.4.2 VM to Sun Java (JRE) 6 VM. More or less the only thing I had to change was to add explicit datatypes for some abstract objects (Hashmap's, Vector's and so on). The code itself it quite memory intensive, using up to 1G of heap memory (using -Xmx1024m as a parameter to start the VM). Since I read alot about better performance on newer Java VM's, this was one of the reasons I did this upgrade. 1. Can anyone think of a reason why the performance is worse in my case now (just in general, of course, since you can't take a look at the code)? 2. Has anyone some advice for a non Java guru what to look for if I wanted to optimize (speed wise) existing code? Any hints, recommended docs, tools? Thanks.
Not much information here. But here are a couple of things you might want to explore: * Start the VM with Xmx and Xms as the same value (in your case 1024M) * Ensure that the server jvm dll is being used to start the virtual machine. * Run a profiler to see what objects are hogging memory or what objects are not being garbage collected * Hook up your VM with the jconsole and trace through the objects
If your application nearly runs out of free space, garbage collection time may dominate computation time. Enable gc debugging to look for this. Or, even better, simply start jconsole and attach it to your program.
Updating from Java 1.4.2 to Java 6 (both Sun VMs) results in slower performance
[ "", "java", "performance", "jvm", "sun", "" ]
I wanted to set a CSS class in my master page, which depends on the current controller and action. I can get to the current controller via `ViewContext.Controller.GetType().Name`, but how do I get the current action (e.g. `Index`, `Show` etc.)?
Use the `ViewContext` and look at the `RouteData` collection to extract both the controller and action elements. But I think setting some data variable that indicates the application context (e.g., "editmode" or "error") rather than controller/action reduces the coupling between your views and controllers.
In the RC you can also extract route data like the action method name like this ``` ViewContext.Controller.ValueProvider["action"].RawValue ViewContext.Controller.ValueProvider["controller"].RawValue ViewContext.Controller.ValueProvider["id"].RawValue ``` --- ### Update for MVC 3 ``` ViewContext.Controller.ValueProvider.GetValue("action").RawValue ViewContext.Controller.ValueProvider.GetValue("controller").RawValue ViewContext.Controller.ValueProvider.GetValue("id").RawValue ``` ### Update for MVC 4 ``` ViewContext.Controller.RouteData.Values["action"] ViewContext.Controller.RouteData.Values["controller"] ViewContext.Controller.RouteData.Values["id"] ``` ### Update for MVC 4.5 ``` ViewContext.RouteData.Values["action"] ViewContext.RouteData.Values["controller"] ViewContext.RouteData.Values["id"] ```
How can I return the current action in an ASP.NET MVC view?
[ "", "c#", "asp.net-mvc", "" ]
I am trying to work out a code sample to demonstrate the debugging functionality in Visual Studio 2008 with C#. I'm trying to build a code sample which would have a 'not so obvious' mistake in it, which would result in unexpected output. A non working example would be: ``` static void Main(string[] args) { int a, b; a = args[0]; b = args[1]; if (a = b) Console.WriteLine("They are equal!"); else if (a < b) Console.WriteLine("Number 1 is smaller!"); else Console.WriteLine("Number 1 is larger!"); } ``` Something like this would not be too obvious when just reading over the code, but it could easily be detected with debugging. I'm looking for such an example which would work in Visual Studio 2008 with C#. Thanks for the help!
Here's a snippet you can throw in... ``` string a = "foo"; a.Replace("foo", "bar"); Console.WriteLine(a); ```
You could use a common programming error like: * [fencepost error](http://en.wikipedia.org/wiki/Off-by-one_error) * forgetting about [immutable objects](http://codebetter.com/blogs/patricksmacchia/archive/2008/01/13/immutable-types-understand-them-and-use-them.aspx) * using [== instead of Equals()](http://dotnetguts.blogspot.com/2007/07/difference-between-and-equals-method.html) I think that a fencepost error might work best for a debugging example. The code could appear to run through a for-loop over an entire array/collection/whatever, but maybe it uses obj.length instead of obj.length-1.
C#/Visual Studio Debugging example
[ "", "c#", "visual-studio", "debugging", "" ]
I'm writng a small application in PHP + MySQL and have come to the point where there is an object that has a couple (8 so far but not expected to increase) of flags associated with it. The flags are pretty much unrelated although there are some combinations that would make no sense. The object represents a row in a DB (has some methods for saving/loading it too) so the question also applies to choosing a storage method. The question is - **how to best represent them both in code and DB?** I can think of several ways: One way to store them in the DB is in a single integer field as bitwise flags. On the PHP side then I can imagine several ways of representing them: * Simply export the integer value and define a couple of flag constants; Let every place that needs the flags do their own bitwise magic; * Define class methods `GetFlag()`, `SetFlag()` and `UnsetFlag()` that do the bitwise magic on a private integer variable; These methods would then be passed one of the flag constants as a parameters. * Define methods `GetFlagA()`, `GetFlagB()` etc. (along with Set and Unset counterparts); * Define a bunch of member variables that each represent one flag; Set them on loading from the DB and gather them when saving. * Create a member variable that is an array of all the flag values. Use predefined constants as array indices to access each flag. Also fill/gather the array on loading/saving. Another way would be to store them in the DB as separate BIT fields. In PHP that would then translate to several member variables. IMHO this would complicate the queries. And the last way would be to define anothed table for all the flags and an intermediate table for many-to-many relationship between flags and the original objects. IMHO the messiest of all solutions, considering that there would be only like 3 tables otherwise. I haven't done much PHP development so I don't know what the best practice would be. In C# I would probably store them as bitwise flags and make properties that do the bitwise magic on a private integer. But PHP doesn't have properties (I'm using latest stable version)...
In your [model](http://en.wikipedia.org/wiki/Entity-relationship_model), the object has 8 boolean properties. That implies 8 boolean (TINYINT for MySQL) columns in your database table and 8 getter/setter methods in your object. Simple and conventional. Rethink your current approach. Imagine what the next guy who has to maintain this thing will be saying. ``` CREATE TABLE mytable (myfield BIT(8)); ``` OK, looks like we're going to have some binary data happening here. ``` INSERT INTO mytable VALUES (b'00101000'); ``` Wait, somebody tell me again what each of those 1s and 0s stands for. ``` SELECT * FROM mytable; +------------+ | mybitfield | +------------+ | ( | +------------+ ``` What? ``` SELECT * FROM mytable WHERE myfield & b'00101000' = b'00100000'; ``` WTF!? WTF!? *stabs self in face* --- -- meanwhile, in an alternate universe where fairies play with unicorns and programmers don't hate DBAs... -- ``` SELECT * FROM mytable WHERE field3 = 1 AND field5 = 0; ``` Happiness and sunshine!
If you really have to use bit flags, then use a SET column to store them in the DB, an associative array in the code, and methods to turn flags on/off. Add separate methods to convert the array to/from a single integer if you need it in that format. There's nothing to be gained by using low-level bit operators, so you might as well make the code readable.
Best practices for bit flags in PHP
[ "", "php", "mysql", "flags", "" ]
I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>.
``` #!/usr/bin/python import random import string digits = "".join( [random.choice(string.digits) for i in xrange(8)] ) chars = "".join( [random.choice(string.letters) for i in xrange(15)] ) print digits + chars ``` EDIT: liked the idea of using random.choice better than randint() so I've updated the code to reflect that. Note: this assumes lowercase and uppercase characters are desired. If lowercase only then change the second list comprehension to read: ``` chars = "".join( [random.choice(string.letters[:26]) for i in xrange(15)] ) ``` Obviously for uppercase only you can just flip that around so the slice is [26:] instead of the other way around.
See an example - [Recipe 59873: Random Password Generation](http://code.activestate.com/recipes/59873/) . Building on the recipe, here is a solution to your question : ``` from random import choice import string def GenPasswd2(length=8, chars=string.letters + string.digits): return ''.join([choice(chars) for i in range(length)]) >>> GenPasswd2(8,string.digits) + GenPasswd2(15,string.ascii_letters) '28605495YHlCJfMKpRPGyAw' >>> ```
Generating random text strings of a given pattern
[ "", "python", "string", "random", "" ]
Quite often, in programming we get situations where `null` checks show up in particularly large numbers. I'm talking about things like: ``` if (doc != null) { if (doc.Element != null) { ... and so on } else throw new Exception("Element cannot be null"); } else { throw new Exception("document cannot be null"); } ``` Basically, the whole thing turns into an unreadable nightmare, so I'm wondering: is there an easier way to describe what I'm trying to do above? (In addition to null checks, I get things like `string.IsNullOrEmpty` from time to time.) **Accepted answer:** I accepted the answer that has [this link](http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation/) because the approach described is innovative, and is precisely what I want. Thanks Shawn!
Check out this article: [A fluent approach to C# parameter validation](http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation) It's written by one of the Paint.NET Developers. He uses extension methods to simplify and clean up null checking code.
Push them forward to the beginning of the function, and keep them out of the part of the code that does the work. Like this: ``` if (doc == null) throw new ArgumentNullException("doc"); if (doc.Element == null) throw new ArgumentException("Element cannot be null"); AndSoOn(); ```
How can I manage the onslaught of null checks?
[ "", "c#", ".net", "" ]
Let's say I have a page called `display.php` and the user is viewing `display.php?page=3`. I want to allow the user to do an action like voting via a POST request and then bring them back to the page they were on. So, If I do a POST request to `display.php?page=3` would the page information also be available to the script?
The simple answer is 'yes'. You can use a GET-style URL as the submission URL for a POST form. PHP will have both the POST and GET information available to it in the usual ways when the form is submitted. This is not to say that you *should* do this, but it will work.
In PHP, you can get request variables from the special global arrays: ``` $_GET['page'] (for GET requests) $_POST['page'] (for POST requests) $_REQUEST['page'] (for either) ``` It sounds like you are looking for "Redirect after Post", I would suggest separating display.php and vote.php into separate files. Vote looks something like this: ``` <?php //vote.php $page_number = (int)$_REQUEST['page']; vote_for_page($page_number); //your voting logic header('Location: display.php?page=' . $page_number); //return to display.php ``` Note that blindly accepting unsanitized form data can be hazardous to your app. Edit: Some folks consider it bad form to use $\_REQUEST to handle both cases. The hazard is that you may want to signal an error if you receive a GET when you expect a POST. Typically GET is reserved for viewing and POST is reserved for making changes (create/update/delete operations). Whether this is really a problem depends on your application.
What happens if you go to a GET style url with a POST request?
[ "", "php", "post", "get", "" ]
I've built a form with Netbeans's visual editor. When I press one of the buttons it should do the following : * set it to disabled * perform a task that takes some time * when the task finishes the button will be enabled again However, the following happens: * the button remains in a pressed state until the task finishes * when the task finishes, the enabling/disabling of buttons will be very fast (they will happen, but you won't notice them) This behaviour is not something I want. I tried using repaint on the JButton, on the JFrame and even on the JPanel containing the button, but I can't seem to get it to do what I want. Some hints?
When you do work in a button callback, you are stalling the GUI painting thread until it completes. What you need to do is spawn a thread to do the long running task, and then have that thread use `SwingUtilities.invokeLater()` to update the UI when it completes. Not using `invokeLater` is not thread safe, and is generally bad mojo. A basic example is: ``` button.setEnabled(false); new Thread(new Runnable() { public void run() { // Do heavy lifting here SwingUtilies.invokeLater(new Runnable() { public void run() { button.setEnabled(true); } }); } }).start(); ```
When you do things in a button callback, you are essentially stalling the gui painting thread - not just for the button, but for ANY gui painting. (Try covering the interface with another window and then exposing it again - it won't repaint until the task is finished!) What you need to do is spawn a thread to do the long running task, and then have that thread use SwingUtilities.invokeLater() to do the enabling of the button. invokeLater forces the button enable to happen in the gui painting thread. You may want to set a busy cursor or otherwise lock the interface while the long-running thread is operating.
Swing buttons don't react immediately! How can I change that?
[ "", "java", "swing", "" ]
I'm looking for an implementation of CRC32 in C or C++ that is explicitly licensed as being no cost or public domain. The implementation [here](http://www.networkdls.com/Software/View/CRC32) seems nice, but the only thing it says about the license is "source code", which isn't good enough. I'd prefer non LGPL so I don't have to fool around with a DLL (my app is closed source). I saw the adler32 implementation in zlib, but I'm checking small chunks of data, which adler is not good for.
Use the [Boost C++ libraries](http://www.boost.org/). There is a [CRC](http://www.boost.org/doc/libs/release/libs/crc/index.html) included there and the [license](http://www.boost.org/LICENSE_1_0.txt) is good.
The [SNIPPETS C Source Code Archive](http://web.archive.org/web/20080217222203/http://c.snippets.org/) has a [CRC32 implementation](http://web.archive.org/web/20080303102530/http://c.snippets.org/snip_lister.php?fname=crc_32.c) that is freely usable: ``` /* Copyright (C) 1986 Gary S. Brown. You may use this program, or code or tables extracted from it, as desired without restriction.*/ ``` (Unfortunately, c.snippets.org seems to have died. Fortunately, the [Wayback Machine](http://web.archive.org/) has it archived.) In order to be able to compile the code, you'll need to add typedefs for `BYTE` as an unsigned 8-bit integer and `DWORD` as an unsigned 32-bit integer, along with the header files [crc.h](http://web.archive.org/web/20080303093609/http://c.snippets.org/snip_lister.php?fname=crc.h) & [sniptype.h](http://web.archive.org/web/20080303103500/http://c.snippets.org/snip_lister.php?fname=sniptype.h). The only critical item in the header is this macro (which could just as easily go in CRC\_32.c itself: ``` #define UPDC32(octet, crc) (crc_32_tab[((crc) ^ (octet)) & 0xff] ^ ((crc) >> 8)) ```
CRC32 C or C++ implementation
[ "", "c++", "c", "crc32", "" ]
I created a custom autocomplete control, when the user press a key it queries the database server (using Remoting) on another thread. When the user types very fast, the program must cancel the previously executing request/thread. I previously implemented it as AsyncCallback first, but i find it cumbersome, too many house rules to follow (e.g. AsyncResult, AsyncState, EndInvoke) plus you have to detect the thread of the BeginInvoke'd object, so you can terminate the previously executing thread. Besides if I continued the AsyncCallback, there's no method on those AsyncCallbacks that can properly terminate previously executing thread. EndInvoke cannot terminate the thread, it would still complete the operation of the to be terminated thread. I would still end up using Abort() on thread. So i decided to just implement it with pure Thread approach, sans the AsyncCallback. Is this thread.abort() normal and safe to you? ``` public delegate DataSet LookupValuesDelegate(LookupTextEventArgs e); internal delegate void PassDataSet(DataSet ds); public class AutoCompleteBox : UserControl { Thread _yarn = null; [System.ComponentModel.Category("Data")] public LookupValuesDelegate LookupValuesDelegate { set; get; } void DataSetCallback(DataSet ds) { if (this.InvokeRequired) this.Invoke(new PassDataSet(DataSetCallback), ds); else { // implements the appending of text on textbox here } } private void txt_TextChanged(object sender, EventArgs e) { if (_yarn != null) _yarn.Abort(); _yarn = new Thread( new Mate { LookupValuesDelegate = this.LookupValuesDelegate, LookupTextEventArgs = new LookupTextEventArgs { RowOffset = offset, Filter = txt.Text }, PassDataSet = this.DataSetCallback }.DoWork); _yarn.Start(); } } internal class Mate { internal LookupTextEventArgs LookupTextEventArgs = null; internal LookupValuesDelegate LookupValuesDelegate = null; internal PassDataSet PassDataSet = null; object o = new object(); internal void DoWork() { lock (o) { // the actual code that queries the database var ds = LookupValuesDelegate(LookupTextEventArgs); PassDataSet(ds); } } } ``` ### NOTES The reason for cancelling the previous thread when the user type keys in succession, is not only to prevent the appending of text from happening, but also to cancel the previous network roundtrip, so the program won't be consuming too much memory resulting from successive network operation. I'm worried if I avoid thread.Abort() altogether, the program could consume too much memory. here's the code without the thread.Abort(), using a counter: ``` internal delegate void PassDataSet(DataSet ds, int keyIndex); public class AutoCompleteBox : UserControl { [System.ComponentModel.Category("Data")] public LookupValuesDelegate LookupValuesDelegate { set; get; } static int _currentKeyIndex = 0; void DataSetCallback(DataSet ds, int keyIndex) { if (this.InvokeRequired) this.Invoke(new PassDataSet(DataSetCallback), ds, keyIndex); else { // ignore the returned DataSet if (keyIndex < _currentKeyIndex) return; // implements the appending of text on textbox here... } } private void txt_TextChanged(object sender, EventArgs e) { Interlocked.Increment(ref _currentKeyIndex); var yarn = new Thread( new Mate { KeyIndex = _currentKeyIndex, LookupValuesDelegate = this.LookupValuesDelegate, LookupTextEventArgs = new LookupTextEventArgs { RowOffset = offset, Filter = txt.Text }, PassDataSet = this.DataSetCallback }.DoWork); yarn.Start(); } } internal class Mate { internal int KeyIndex; internal LookupTextEventArgs LookupTextEventArgs = null; internal LookupValuesDelegate LookupValuesDelegate = null; internal PassDataSet PassDataSet = null; object o = new object(); internal void DoWork() { lock (o) { // the actual code that queries the database var ds = LookupValuesDelegate(LookupTextEventArgs); PassDataSet(ds, KeyIndex); } } } ```
No, it **is not** safe. `Thread.Abort()` is sketchy enough at the best of times, but in this case your control has no (heh) control over what's being done in the delegate callback. You don't know what state the rest of the app will be left in, and may well find yourself in a world of hurt when the time comes to call the delegate again. Set up a timer. Wait a bit after the text change before calling the delegate. Then wait for it to return before calling it again. If it's *that* slow, or the user is typing *that* fast, then they probably don't expect autocomplete anyway. ### Regarding your updated (Abort()-free) code: You're now launching a new thread for (potentially) *every keypress*. This is not only going to kill performance, it's unnecessary - if the user isn't pausing, they probably aren't looking for the control to complete what they're typing. I touched on this earlier, but [P Daddy said it better](https://stackoverflow.com/questions/421389/is-this-thread-abort-normal-and-safe#421445): > You'd be better off just implementing > a one-shot timer, with maybe a > half-second timeout, and resetting it > on each keystroke. Think about it: a fast typist might create a score of threads before the first autocomplete callback has had a chance to finish, even with a fast connection to a fast database. But if you delay making the request until a short period of time after the last keystroke has elapsed, then you have a better chance of hitting that sweet spot where the user has typed all they want to (or all they know!) and is *just* starting to wait for autocomplete to kick in. Play with the delay - a half-second might be appropriate for impatient touch-typists, but if your users are a bit more relaxed... or your database is a bit more slow... then you may get better results with a 2-3 second delay, or even longer. The most important part of this technique though, is that you `reset the timer on every keystroke`. And unless you expect database requests to actually *hang*, don't bother trying to allow multiple concurrent requests. If a request is currently in-progress, wait for it to complete before making another one.
[There](http://blogs.msdn.com/ankur/archive/2005/11/30/498293.aspx) [are](http://msmvps.com/blogs/senthil/archive/2008/12/17/the-dangers-of-thread-abort.aspx) [many](http://www.manning-sandbox.com/message.jspa?messageID=33703) [warnings](http://www.interact-sw.co.uk/iangblog/2004/11/12/cancellation) [all over](http://haacked.com/archive/2004/11/12/how-to-stop-a-thread.aspx) [the net](http://www.google.com/search?q=Thread.Abort) about using `Thread.Abort`. I would recommend avoiding it unless it's really needed, which in this case, I don't think it is. You'd be better off just implementing a one-shot timer, with maybe a half-second timeout, and resetting it on each keystroke. This way your expensive operation would only occur after a half-second or more (or whatever length you choose) of user inactivity.
Is this thread.abort() normal and safe?
[ "", "c#", "multithreading", "" ]
Basically like using the out keyword. But the problem is with the out keyword, you still have to declare a variable outside the method call, like: ``` double result; Double.TryParse ( "76", out result ); ``` where as I want something like: ``` Double.TryParse ( "76", out result ); ``` and there I get a new variable called result. Is there a way to do this (by using out or not)?
You can use [C# tuples](http://rabdullin.com/journal/2008/9/30/using-tuples-in-c-functions-and-dictionaries.html) to **compose multiple variables into one**.
No, you have to declare the variable first because you are passing it to the method, the only difference is that you are explicitly requiring the method to fill it out before returning.
Is there a way to create and return new variables from a method in C#?
[ "", "c#", ".net", "" ]
We are invoking Asp.Net ajax web service from the client side. So the JavaScript functions have calls like: // The function to alter the server side state object and set the selected node for the case tree. ``` function JSMethod(caseId, url) { Sample.XYZ.Method(param1, param2, OnMethodReturn); } function OnMethodReturn(result) { var sessionExpiry = CheckForSessionExpiry(result); var error = CheckForErrors(result); ... process result } ``` And on the server side in the ".asmx.cs" file: namespace Sample ``` [ScriptService] class XYZ : WebService { [WebMethod(EnableSession = true)] public string Method(string param1, string param2) { if (SessionExpired()) { return sessionExpiredMessage; } . . . } } ``` The website is setup to use form based authentication. Now if the session has expired and then the JavaScript function "JSMethod" is invoked, then the following error is obtained: Microsoft JScript runtime error: Sys.Net.WebServiceFailedException: The server method 'Method' failed with the following error: System.InvalidOperationException-- Authentication failed. This exception is raised by method "function Sys$Net$WebServiceProxy$invoke" in file "ScriptResource.axd": ``` function Sys$Net$WebServiceProxy$invoke { . . . { // In debug mode, if no error was registered, display some trace information var error; if (result && errorObj) { // If we got a result, we're likely dealing with an error in the method itself error = result.get_exceptionType() + "-- " + result.get_message(); } else { // Otherwise, it's probably a 'top-level' error, in which case we dump the // whole response in the trace error = response.get_responseData(); } // DevDiv 89485: throw, not alert() throw Sys.Net.WebServiceProxy._createFailedError(methodName, String.format(Sys.Res.webServiceFailed, methodName, error)); } ``` So the problem is that the exception is raised even before "Method" is invoked, the exception occurs during the creation of the Web Proxy. Any ideas on how to resolve this problem
You have a callback method (OnMethodReturn) specified in the WebMethod call, but not an error handler method. You need to create one and pass it into as you do the callback method. Then you can handle your failed WebMethod calls in there.
This problem occurs even before the Ajax framework can invoke the target method, it fails while creating the web proxy. Anyway I solved the problem by enabling Anonymous access to the Web Service folder and checking for Session explicitly in the Web Service methods
How do I fix: InvalidOperationException upon Session timeout in Ajax WebService call
[ "", "javascript", "web-services", "exception", "session", "asp.net-ajax", "" ]
In the Java snippet: ``` SyndFeedInput fr = new SyndFeedInput(); SyndFeed sf = fr.build(new XmlReader(myInputStream)); List<SyndEntry> entries = sf.getEntries(); ``` the last line generates the warning "The expression of type `List` needs unchecked conversion to conform to `List<SyndEntry>`" What's an appropriate way to fix this?
Since `getEntries` returns a raw `List`, it could hold anything. The warning-free approach is to create a new `List<SyndEntry>`, then cast each element of the `sf.getEntries()` result to `SyndEntry` before adding it to your new list. `Collections.checkedList` does *not* do this checking for you—although it would have been possible to implement it to do so. By doing your own cast up front, you're "complying with the warranty terms" of Java generics: if a `ClassCastException` is raised, it will be associated with a cast in the source code, not an invisible cast inserted by the compiler.
This is a common problem when dealing with pre-Java 5 APIs. To automate the [solution from erickson](https://stackoverflow.com/questions/367626/how-do-i-fix-the-expression-of-type-list-needs-unchecked-conversion/367673#367673), you can create the following generic method: ``` public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) { List<T> r = new ArrayList<T>(c.size()); for(Object o: c) r.add(clazz.cast(o)); return r; } ``` This allows you to do: ``` List<SyndEntry> entries = castList(SyndEntry.class, sf.getEntries()); ``` Because this solution checks that the elements indeed have the correct element type by means of a cast, it is safe, and does not require `SuppressWarnings`.
How do I fix "The expression of type List needs unchecked conversion...'?
[ "", "java", "warnings", "unchecked-conversion", "" ]
What are all the common undefined behaviours that a C++ programmer should know about? Say, like: ``` a[i] = i++; ```
### Pointer * Dereferencing a `NULL` pointer * Dereferencing a pointer returned by a "new" allocation of size zero * Using pointers to objects whose lifetime has ended (for instance, stack allocated objects or deleted objects) * Dereferencing a pointer that has not yet been definitely initialized * Performing pointer arithmetic that yields a result outside the boundaries (either above or below) of an array. * Dereferencing the pointer at a location beyond the end of an array. * Converting pointers to objects of incompatible types * [Using `memcpy` to copy overlapping buffers](https://stackoverflow.com/a/11211519/241536). ### Buffer overflows * Reading or writing to an object or array at an offset that is negative, or beyond the size of that object (stack/heap overflow) ### Integer Overflows * Signed integer overflow * Evaluating an expression that is not mathematically defined * Left-shifting values by a negative amount (right shifts by negative amounts are implementation defined) * Shifting values by an amount greater than or equal to the number of bits in the number (e.g. `int64_t i = 1; i <<= 72` is undefined) ### Types, Cast and Const * Casting a numeric value into a value that can't be represented by the target type (either directly or via static\_cast) * Using an automatic variable before it has been definitely assigned (e.g., `int i; i++; cout << i;`) * Using the value of any object of type other than `volatile` or `sig_atomic_t` at the receipt of a signal * Attempting to modify a string literal or any other const object during its lifetime * Concatenating a narrow with a wide string literal during preprocessing ### Function and Template * Not returning a value from a value-returning function (directly or by flowing off from a try-block) * Multiple different definitions for the same entity (class, template, enumeration, inline function, static member function, etc.) * Infinite recursion in the instantiation of templates * Calling a function using different parameters or linkage to the parameters and linkage that the function is defined as using. ### OOP * Cascading destructions of objects with static storage duration * The result of assigning to partially overlapping objects * Recursively re-entering a function during the initialization of its static objects * Making virtual function calls to pure virtual functions of an object from its constructor or destructor * Referring to nonstatic members of objects that have not been constructed or have already been destructed ### Source file and Preprocessing * A non-empty source file that doesn't end with a newline, or ends with a backslash (prior to C++11) * A backslash followed by a character that is not part of the specified escape codes in a character or string constant (this is implementation-defined in C++11). * Exceeding implementation limits (number of nested blocks, number of functions in a program, available stack space ...) * Preprocessor numeric values that can't be represented by a `long int` * Preprocessing directive on the left side of a function-like macro definition * Dynamically generating the defined token in a `#if` expression ### To be classified * Calling exit during the destruction of a program with static storage duration
The order that function parameters are evaluated is ***unspecified* behavior**. (This won't make your program crash, explode, or order pizza... unlike ***undefined* behavior**.) The only requirement is that all parameters must be fully evaluated before the function is called. --- This: ``` // The simple obvious one. callFunc(getA(),getB()); ``` Can be equivalent to this: ``` int a = getA(); int b = getB(); callFunc(a,b); ``` Or this: ``` int b = getB(); int a = getA(); callFunc(a,b); ``` It can be either; it's up to the compiler. The result can matter, depending on the side effects.
What are all the common undefined behaviours that a C++ programmer should know about?
[ "", "c++", "undefined", "undefined-behavior", "c++-faq", "" ]
I was reading some Java recently and came across something (an idiom?) new to me: in the program, classes with multiple constructors would also always include a blank constructor. For example: ``` public class Genotype { private boolean bits[]; private int rating; private int length; private Random random; public Genotype() { // <= THIS is the bandit, this one right here random = new Random(); } /* creates a Random genetoype */ public Genotype(int length, Random r) { random = r; this.length = length; bits = new boolean[length]; for(int i=0;i<length;i++) { bits[i] =random.nextBoolean(); } } /* copy constructor */ public Genotype(Genotype g,Random r) { random = r; bits = new boolean[g.length]; rating = g.rating; length = g.length; for(int i=0;i<length;i++) { bits[i] = g.bits[i]; } } } ``` The first constructor doesn't seem to be a "real" constructor, it seems as though in every case one of the other constructors will be used. So why is that constructor defined at all?
I am not sure that the code you were reading was high quality (I've reviewed some bioinformatics code in the past and it is unfortunately often not written by professional developers). For example, that third constructor is not a copy constructor and generally there are problems in this code, so I wouldn't "read too much into it". The first constructor is a default constructor. It only initializes the bare minimum and lets users set the rest with getters and setters. Other constructors are often "convenience constructors" that help create objects with less calls. However, this can often lead to inconsistencies between constructors. In fact, there is recent research that shows that a default constructor with subsequent calls to setters is preferable. There are also certain cases where a default constructor is critical. For example, certain frameworks like digester (used to create objects directly from XML) use default constructors. JavaBeans in general use default constructors, etc. Also, some classes inherit from other classes. you may see a default constructor when the initialization of the parent object is "good enough". In this specific case, if that constructor was not defined, one would have to know all the details in advance. That is not always preferable. And finally, some IDEs automatically generate a default constructor, it is possible that whoever wrote the class was afraid to eliminate it.
Is the object [Serializable](http://java.sun.com/j2se/1.5.0/docs/api/java/io/Serializable.html)? > To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime. > > During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream
Why might one also use a blank constructor?
[ "", "java", "coding-style", "constructor", "" ]
I am dynamically creating a table which I want to have clickable rows. When the user clicks on one of the rows I want to redirect to a page specific to the item of that row. My question is how on the server side can I wire the "onclick" event to a routine that will then allow me to build a url based on some of the data included in the row they clicked? for example I would want to do this on click: `Response.Redirect("SomePage.aspx?" itemType + "&" + COLUMN1VALUE)`; where COLUMN1VALUE would be the first column in the row that was clicked.
It sounds like your actual goal is simply to display/edit the row on another page. If this is the case, you could simply add a javascript event handler to the table row when you create it. ``` <tr onclick="window.location='DetailPage.aspx?id=<%= IdFromDb %>'"> <!-- etc......--> </tr> ``` If you use a GridView to create the table you can inject this in the RowDataBound event: ``` protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { string OnClickCmd = "window.location='DetailPage.aspx?id="; if (e.Row.RowType == DataControlRowType.DataRow) { OnClickCmd += DataBinder.Eval(e.Row.DataItem, "IdFromDb").ToString() + "'"; e.Row.Attributes.Add("onclick", OnClickCmd); } } ``` Unless you need to do something in the postback, there is no need to redirect. Further, you could just create a hyperlink when you create the row eliminating the need for javascript, you don't need the full row clicking experience.
I would build the link in the table as an actual anchor tag to your SomePage.aspx (while you're building your table, you should know what the query string would be for each table row), opposed to a server side control that redirects on postback
Working with the "onclick" of a server side dynamically created TableRow
[ "", "c#", "asp.net", "controls", "" ]
I'm trying to write a notification service (for completely legit non-spam purposes) in .NET using SmtpClient. Initially I just looped through each message and sent it, however this is slow and I would like to improve the speed. So, I switched to using 'SendAsync', but now get the following error on the second call: ``` An asynchronous call is already in progress. ``` I read this to mean that MS crippled System.Net.Mail to prevent mass-mailers. Is this correct? If so, is there a better way to do this in .NET, and still be able to log the results of each email(which is important to our client). If not, why can SendAsync only be called once?
According to the [documentation](http://msdn.microsoft.com/en-us/library/x5x13z6h.aspx): > After calling SendAsync, you must wait > for the e-mail transmission to > complete before attempting to send > another e-mail message using Send or > SendAsync. So to send multiple mails at the same time you need multiple SmtpClient instances.
You might be able to use the following: ``` ThreadPool.QueueUserWorkItem(state => client.Send(msg)); ``` This should allow your messages to be queued and sent as threads become available.
Why can SmtpClient.SendAsync only be called once?
[ "", "c#", "smtpclient", "system.net.mail", "" ]
In Z80 machine code, a cheap technique to initialize a buffer to a fixed value, say all blanks. So a chunk of code might look something like this. ``` LD HL, DESTINATION ; point to the source LD DE, DESTINATION + 1 ; point to the destination LD BC, DESTINATION_SIZE - 1 ; copying this many bytes LD (HL), 0X20 ; put a seed space in the first position LDIR ; move 1 to 2, 2 to 3... ``` The result being that the chunk of memory at DESTINATION is completely blank filled. I have experimented with memmove, and memcpy, and can't replicate this behavior. I expected memmove to be able to do it correctly. **Why do memmove and memcpy behave this way?** **Is there any reasonable way to do this sort of array initialization?** I am already aware of char array[size] = {0} for array initialization I am already aware that memset will do the job for single characters. What other approaches are there to this issue?
I believe this goes to the design philosophy of C and C++. As [Bjarne Stroustrup](http://en.wikipedia.org/wiki/Bjarne_Stroustrup) once [said](http://www.research.att.com/~bs/crc.pdf), one of the major guiding principles of the design of C++ is "What you don’t use, you don’t pay for". And while [Dennis Ritchie](http://en.wikipedia.org/wiki/Dennis_Ritchie) may not have said it in exactly those same words, I believe that was a guiding principle informing his design of C (and the design of C by subsequent people) as well. Now you may think that if you allocate memory it should automatically be initialized to NULL's and I'd tend to agree with you. But that takes machine cycles and if you're coding in a situation where every cycle is critical, that may not be an acceptable trade-off. Basically C and C++ try to stay out of your way--hence if you want something initialized you have to do it yourself.
There was a quicker way of blanking an area of memory using the stack. Although the use of LDI and LDIR was very common, David Webb (who pushed the ZX Spectrum in all sorts of ways like full screen number countdowns including the border) came up with this technique which is 4 times faster: * saves the Stack Pointer and then moves it to the end of the screen. * LOADs the HL register pair with zero, * goes into a massive loop PUSHing HL onto the Stack. * The Stack moves up the screen and down through memory and in the process, clears the screen. The explanation above was taken from the [review of David Webbs game Starion](http://www.users.globalnet.co.uk/~jg27paw4/yr15/yr15_36.htm). The Z80 routine might look a little like this: ``` DI ; disable interrupts which would write to the stack. LD HL, 0 ADD HL, SP ; save stack pointer EX DE, HL ; in DE register LD HL, 0 LD C, 0x18 ; Screen size in pages LD SP, 0x4000 ; End of screen PAGE_LOOP: LD B, 128 ; inner loop iterates 128 times LOOP: PUSH HL ; effectively *--SP = 0; *--SP = 0; DJNZ LOOP ; loop for 256 bytes DEC C JP NZ,PAGE_LOOP EX DE, HL LD SP, HL ; restore stack pointer EI ; re-enable interrupts ``` However, that routine is a little under twice as fast. LDIR copies one byte every 21 cycles. The inner loop copies two bytes every 24 cycles -- 11 cycles for `PUSH HL` and 13 for `DJNZ LOOP`. To get nearly 4 times as fast simply unroll the inner loop: ``` LOOP: PUSH HL PUSH HL ... PUSH HL ; repeat 128 times DEC C JP NZ,LOOP ``` That is very nearly 11 cycles every two bytes which is about 3.8 times faster than the 21 cycles per byte of LDIR. Undoubtedly the technique has been reinvented many times. For example, it appeared earlier in [sub-Logic's Flight Simulator 1 for the TRS-80](http://www.trs-80.org/t80-fs1/ "sub-Logic's Flight Simulator 1 for the TRS-80") in 1980.
Why is there no Z80 like LDIR functionality in C/C++/rtl?
[ "", "c++", "c", "z80", "" ]
Okay so a continuation from [this question](https://stackoverflow.com/questions/409913/can-php-be-installed-on-a-local-machine), where you experts intro'd me to [WAMP](http://www.wampserver.com/en/presentation.php), which can basically execute PHP within a Windows XP environment. So now I've got it installed, but the **tray icon forever shows YELLOW**, and when I visit any PHP page in my browser, it just shows me the PHP source! Also, when I visit "<http://localhost/>" in IE7 it gives me a **404 Not Found**, FF3 just shows a **blank** page. --- BTW I've tried "Restart All Services" and restarting my machine, but it still won't work. Any ideas? Any of you had this problem and **solved it?** Please help me here, I'm desperate to execute PHP client-side and I'm just reverting to testing on-server for now!
Skype reserves port 80 for its incoming connection which conflicts with WAMP, so simply configure Skype to use another port by doing the following: In Skype go to Tools|Options|Advanced|Connection uncheck the option --> Use port 80 and 443 as alternatives for incoming connections, that's it For this change to take effect restart Skype and Restart all services on WAMP by doing the following: Left-click WAMP tray icon > Restart All Services" Now Wamp and Skype can co-exist together, hope this solves your problem!!
Got it! Under the **WAMP tray icon**, left-click context menu > **Apache** > **Service** > **Test Port 80**, it said : > "Your **port 80 is actually used** by - Info not available, Must be **Skype**" Well, so **off** goes Skype, **WAMP > Restart All Services**, and [Localhost](http://localhost/) shows ["WAMP5 Homepage":](http://www.wampserver.com/en/data/image_accueil_wamp.gif) [![Localhost WAMP CP](https://i.stack.imgur.com/eEUEd.gif)](https://i.stack.imgur.com/eEUEd.gif) (source: [wampserver.com](http://www.wampserver.com/en/data/image_accueil_wamp.gif)) And, [phpMyAdmin](http://www.phpmyadmin.net/) works, **PHP scripts** execute too. **Wow!** So now I can dubug in the proper fashion! Thank you [StackOverflow!](https://stackoverflow.com/questions/409913/can-php-be-installed-on-a-local-machine)
WAMP Server not working
[ "", "php", "localhost", "wamp", "" ]
When you run a php script in the command line, does is execute with the read/write permissions of the current user or what?
Yes, it does.
Yes, it runs with the permissions of the current user. Just like executing any other command-line program.
PHP-CLI + File Permissions
[ "", "file-permissions", "php", "" ]
I'm curious as I begin to adopt more of the boost idioms and what appears to be best practices I wonder at what point does my c++ even remotely look like the c++ of yesteryear, often found in typical examples and in the minds of those who've not been introduced to "Modern C++"?
Just a few off the top of my head: * Navigating around in memory-mapped files. * Windows API calls where you have to over-allocate (like a LPBITMAPINFOHEADER). * Any code where you're munging around in arbitrary memory (VirtualQuery() and the like). * Just about any time you're using reinterpret\_cast<> on a pointer. * Any time you use placement-new. The common thread here is "any situation in which you need to treat a piece of memory as something other than a resource over which you have allocation control".
I don't use `shared_ptr` almost at all, because I avoid shared ownership in general. Therefore, I use something like `boost::scoped_ptr` to "own" an object, but all other references to it will be raw pointers. Example: ``` boost::scoped_ptr<SomeType> my_object(new SomeType); some_function(my_object.get()); ``` But `some_function` will deal with a raw pointer: ``` void some_function(SomeType* some_obj) { assert (some_obj); some_obj->whatever(); } ```
Once you've adopted boost's smart pointers, is there any case where you use raw pointers?
[ "", "c++", "boost", "smart-pointers", "" ]
What's the best way to merge 2 or more dictionaries (`Dictionary<TKey, TValue>`) in C#? (3.0 features like LINQ are fine). I'm thinking of a method signature along the lines of: ``` public static Dictionary<TKey,TValue> Merge<TKey,TValue>(Dictionary<TKey,TValue>[] dictionaries); ``` or ``` public static Dictionary<TKey,TValue> Merge<TKey,TValue>(IEnumerable<Dictionary<TKey,TValue>> dictionaries); ``` Regarding the handling of duplicate keys: In case of collision, it doesn't matter which value is saved to the dictionary as long as it's consistent.
This partly depends on what you want to happen if you run into duplicates. For instance, you could do: ``` var result = dictionaries.SelectMany(dict => dict) .ToDictionary(pair => pair.Key, pair => pair.Value); ``` Or, more succintly, in .NET 8: ``` var result = dictionaries.SelectMany(dict => dict) .ToDictionary(); ``` That will throw an exception if you get any duplicate keys. EDIT: If you use ToLookup then you'll get a lookup which can have multiple values per key. You *could* then convert that to a dictionary: ``` var result = dictionaries.SelectMany(dict => dict) .ToLookup(pair => pair.Key, pair => pair.Value) .ToDictionary(group => group.Key, group => group.First()); ``` It's a bit ugly - and inefficient - but it's the quickest way to do it in terms of code. (I haven't tested it, admittedly.) You could write your own ToDictionary2 extension method of course (with a better name, but I don't have time to think of one now) - it's not terribly hard to do, just overwriting (or ignoring) duplicate keys. The important bit (to my mind) is using [`SelectMany`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.selectmany), and realising that a dictionary supports iteration over its key/value pairs.
I would do it like this: ``` dictionaryFrom.ToList().ForEach(x => dictionaryTo.Add(x.Key, x.Value)); ``` Simple and easy. According to [this blog post](https://codeblog.jonskeet.uk/2009/01/29/for-vs-foreach-on-arrays-and-lists/) it's even faster than most loops as its underlying implementation accesses elements by index rather than enumerator [(see this answer)](https://stackoverflow.com/a/226029/2857326). It will of course throw an exception if there are duplicates, so you'll have to check before merging.
Merging dictionaries in C#
[ "", "c#", "dictionary", "merge", "" ]
An integer's max value in Java is 2147483647, since Java integers are signed, right? 0xff000000 has a numeric value of 4278190080. Yet I see Java code like this: ``` int ALPHA_MASK = 0xff000000; ``` Can anyone enlighten me please?
The high bit is a sign bit. Setting it denotes a negative number: -16777216. Java, like most languages, stores signed numbers in [2's complement](http://en.wikipedia.org/wiki/Two%27s_complement) form. In this case, subtracting 231, or 2147483648 from 0x7F000000, or 2130706432, yields -16777216.
Just an addition to erickson's answer: As he said, signed integers are stored as two's complements to their respective positive value on most computer architectures. That is, the whole 2^32 possible values are split up into two sets: one for positive values starting with a 0-bit and one for negative values starting with a 1. Now, imagine that we're limited to 3-bit numbers. Let's arrange them in a funny way that'll make sense in a second: ``` 000 111 001 110 010 101 011 100 ``` You see that all numbers on the left-hand side start with a 1-bit whereas on the right-hand side they start with a 0. By our earlier decision to declare the former as negative and the latter as positive, we see that 001, 010 and 011 are the only possible positive numbers whereas 111, 110 and 101 are their respective negative counterparts. Now what do we do with the two numbers that are at the top and the bottom, respectively? 000 should be zero, obviously, and 100 will be the lowest negative number of all which doesn't have a positive counterpart. To summarize: ``` 000 (0) 111 001 (-1 / 1) 110 010 (-2 / 2) 101 011 (-3 / 3) 100 (-4) ``` You might notice that you can get the bit pattern of -1 (111) by negating 1 (001) and adding 1 (001) to it: 001 (= 1) -> 110 + 001 -> 111 (= -1) Coming back to your question: 0xff000000 = 1111 1111 0000 0000 0000 0000 0000 0000 We don't have to add further zeros in front of it as we already reached the maximum of 32 bits. Also, it's obviously a negative number (as it's starting with a 1-bit), so we're now going to calculate its absolute value / positive counterpart: This means, we'll take the two's complement of ``` 1111 1111 0000 0000 0000 0000 0000 0000 ``` which is ``` 0000 0000 1111 1111 1111 1111 1111 1111 ``` Then we add ``` 0000 0000 0000 0000 0000 0000 0000 0001 ``` and obtain ``` 0000 0001 0000 0000 0000 0000 0000 0000 = 16777216 ``` Therefore, 0xff000000 = -16777216.
Why is Java able to store 0xff000000 as an int?
[ "", "java", "hex", "int", "" ]
I came across some Enumerators that inherited `uint`. I couldn't figure out why anyone would do this. Example: ``` Enum myEnum : uint { ... } ``` Any advantage or specific reason someone would do this? Why not just leave it as defaultint?
One reason I can think of is that range checking is easier. Given that most enumerations start at 0, you'd only have to check the upper bound.
if the enumeration values are greater than 2,147,483,647 and non-negative.
What is the reason for specifying an Enum as uint?
[ "", "c#", "" ]
Learning from my [last question](https://stackoverflow.com/questions/413311/c-do-method-names-get-compiled-into-the-exe), most **member names** seem to get included in the Project Output. Looking at some decompilers like [9rays](http://www.9rays.net/products/Spices.Decompiler/), [Salamander](http://www.remotesoft.com/salamander/), [Jungle](http://www.junglecreatures.com/DesktopDefault.aspx), many obfuscating techniques seem to have been already defeated, there's this one particularly scary claim: > Automatically removes string encryptions injected by obfuscators ~ [Salamander](http://www.remotesoft.com/salamander/) So is manual, **source-code level obfuscating more effective** than post-compile / mid-compile lathered, 'superficial' obfuscation by well known (easily defeated??) obfuscating programs?
Obfuscating source-code is going to be self-defeating in terms of maintenance. If your project is so 'secret', I guess you have two choices: * Place the 'secret' proprietry code behind a service on a server that you control * Code it in a language so not easy to decompile such as C/C++
Maybe, debatably, but you'll destroy maintainability to do so. Is this really worth it? Actually this just comes down to **security through obscurity**, i.e. it's not security at all it's just an inconvenience. you should work fromt he assumption that any party interested enough *will* decompile your code if they can access it. It's not worth the pain you'll inflict on yourself to make it very slightly more time consuming for the evil haxxors. Deal with the real security problems of access.
Obfuscation at source-code level more effective than obfuscators?
[ "", "c#", "obfuscation", "" ]
I am creating an ATL 8.0 based ActiveX control in C++ using Visual Studio 2008. I need to create a sub-window and attach it to the ActiveX control. How do I get access to the HWND that is owned by the ActiveX control? Which ATL function can I override in order to use the HWND after the control's window has been created?
After some trial and error and I found the answer I was after. In the constructor of your ATL ActiveX control you to add the following line of code: ``` m_bWindowOnly = true; ``` This causes the window for the control to be created (rather than just reusing the HWND of the parent window). After this the m\_hWnd member of the control class can be used to access the HWND for the control's window.
ActiveX would allow you to define your own methods on your own interface (to address Brians assumption), but that likely won't help here. The ActiveX control might very well be created by another component. ATL too is irrelevant - it's a C++ template library that wraps COM interfaces. The function you need here is IOleWindow::GetWindow. I'm not sure what you mean by "override an ATL function to use the HWMD". Once you have retrieved the HWND, you can pass it to any function that uses an HWND. For instance, as the parent in SetParent(child, parent)
How do I get the HWND for an ActiveX control after the control has been initialised/activated?
[ "", "c++", "activex", "atl", "" ]
I have the following situation I think would be best to show in sample program code. I have a Java class that extends `JPanel`. In this class are two objects which are two more `JPanels`. In one of the `JPanel` objects is a `JTable` object. I added a listener to this `JTable` that detects a double click. When it detects a double click, I want to fire a method in the top class. How do I reference this method in Java? ``` public class TopPanel extends JPanel { JPanel OnePanel; JPanel TwoPanel; public void MethodToFire; } public class OnePanel extends JPanel { JTable TheTable; } public class TheTable extends JTable { public TheTable { this.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ if (e.getClickCount() == 2){ SYNTAX CALLING THE METHOD IN TopPanel } } } ); } } ```
One way to solve this is to use composition instead of inheritance. You could pass the JPanel into your subclass of the JTable. ``` public class TopPanel extends JPanel { private TheTable table; public TopPanel() { table = new TheTable(this); } public void methodToFire() { } } public class TheTable extends JTable { private TopPanel panel; public TheTable(TopPanel panel) { this.panel = panel; this.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { doThing(); } } ); } private void doThing() { this.panel.methodToFire(); } } ```
To access a method on the Outer class, you need to use the syntax of Outer.this.method(). So in this case, to access a method on the "TheTable" class from the listener, you should use `TheTable.this.callMethod()`. I assume that `TopPanel` has added to it the `TheTable`. In this case, you could do something like: ``` mouseClicked(...) { TopTable t = (TopTable)TheTable.this.getParent(); t.MethodToFire(); } ``` This is a direct answer to the question, not necessarily the "best" way to do it. A type-safe composition approach would be a better long-term solution.
Calling methods of "parent" component in Java
[ "", "java", "class", "methods", "" ]
Yes, I do understand the difference between them. What I want to know is: why OVERRIDE a method? What is the good in doing it? In case of overload: the only advantage is you haven't to think in different names to functions?
*Overloading* generally means that you have two or more functions in the same scope having the same name. The function that better matches the arguments when a call is made wins and is called. Important to note, as opposed to calling a virtual function, is that the function that's called is selected at compile time. It all depends on the static type of the argument. If you have an overload for `B` and one for `D`, and the argument is a reference to `B`, but it really points to a `D` object, then the overload for `B` is chosen in C++. That's called *static dispatch* as opposed to *dynamic dispatch*. You overload if you want to do the same as another function having the same name, but you want to do that for another argument type. Example: ``` void print(Foo const& f) { // print a foo } void print(Bar const& bar) { // print a bar } ``` they both print their argument, so they are overloaded. But the first prints a foo, and the second prints a bar. If you have two functions that do different things, it's considered bad style when they have the same name, because that can lead to confusion about what will happen actually when calling the functions. Another usecase for overloading is when you have additional parameters for functions, but they just forward control to other functions: ``` void print(Foo & f, PrintAttributes b) { /* ... */ } void print(Foo & f, std::string const& header, bool printBold) { print(f, PrintAttributes(header, printBold)); } ``` That can be convenient for the caller, if the options that the overloads take are often used. *Overriding* is something completely different. It doesn't compete with overloading. It means that if you have a virtual function in a base class, you can write a function with the same signature in the derived class. The function in the derived class *overrides* the function of the base. Sample: ``` struct base { virtual void print() { cout << "base!"; } } struct derived: base { virtual void print() { cout << "derived!"; } } ``` Now, if you have an object and call the `print` member function, the print function of the derived is always called, because it overrides the one of the base. If the function `print` wasn't virtual, then the function in the derived wouldn't override the base function, but would merely *hide* it. Overriding can be useful if you have a function that accepts a base class, and every one that's derived from it: ``` void doit(base &b) { // and sometimes, we want to print it b.print(); } ``` Now, even though at compile time the compiler only knows that b is at least base, print of the derived class will be called. That's the point of virtual functions. Without them, the print function of the base would be called, and the one in the derived class wouldn't override it.
This will add some more clarity to thoughts.![enter image description here](https://i.stack.imgur.com/xmKaT.gif)
Override and overload in C++
[ "", "c++", "overriding", "overloading", "" ]