Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Alright, I find the code below to be quite repetitive and annoying. Any other way to refactor the code without using an array as a starting point (that is, to avoid using `array[x]`, `array[y]`, `array[z]` later on in the code as a result of starting with an array because `x`,`y`,`z` are completely unrelated and it makes no sense to group them for the sake of readability) ``` var x = ""; var y = ""; var z = ""; ... ...variables get set if(x != undefined && x != "") doSomethingHere(); if(y != undefined && y != "") doSomethingThere(); if(z != undefined && z != "") doSomethingElse(); ... ```
In addition to what joel said you could also do the following: ``` function doOnValid(x, func){ if(x != undefined && x != "") func(); } ``` Then you could do: ``` doOnValid(x, doSomething); doOnValid(y, doSomethingElse); doOnvalid(z, function() { /*Yay lambda function*/ }); ```
At very least you can factor out your validation rules to their own function: ``` function IsValid(x) { return (x != undefined && x != ""); } var x = ""; var y = ""; var z = ""; //... //...variables get set if(IsValid(x)) doSomething(); if(IsValid(y)) doSomething(); if(IsValid(z)) doSomething(); ```
How to check several local variables for the same if conditions
[ "", "javascript", "" ]
I've trying to use Eclipse JDT AST parsing classes. After including the initial JAR, and sorting out a couple more dependencies, it is with 7+ JARs and I still having NoClassDefFoundError exceptions. This situation arises whenever I'm trying to test libraries with little or no documentation. Trial and error seems a very dumb (and annoying) approach to solve this problem. Is there a way to automatically sort this out using Eclipse? --- *Update:* Later I found that adding all the JARs you have, and using Ctrl-T (to view/locate types), lets you manually locate the JAR. [That was the solution](http://dev.eclipse.org/newslists/news.eclipse.newcomer/msg21071.html) that Google provided so far. Is there a better way?
If you refer to this SO question [Finding unused jars used in an eclipse project](https://stackoverflow.com/questions/248589), you also have: **[ClassPathHelper](http://classpathhelper.sourceforge.net/)**, which can quickly focus on unresolved classes: ![unresolved](https://i.stack.imgur.com/szz1W.jpg) It automatically identifies orphan jars, blocked (obscured) classes, and much more. The only limit is dependencies that are not defined in classes, e.g. in dependency injection framework configuration files.
I have found setting up a workspace exclusively for browsing the eclipse source code incredibly useful. In this manner, you can use PDE tools like the Plug-in Spy, bundle dependency analysis, browsing the documentation, etc much like you would your own plugin projects. I found [this article at Vogella](http://www.vogella.de/articles/EclipseCodeAccess/article.html) a very useful guide. If you know which bundle your desired class is you can generate the transitive closure of dependencies by creating a new OSGi launch configuration, with just the single bundle selected. By hitting the `Add Required` button, you can see all bundles necessary to use the one you're interested in. **Edit**: * From your question it wasn't clear as to the environment you want to run the compiler in. If you're interested in an embeddable Java compiler to be run outside of an OSGi environment, may I suggest [Janino](http://www.janino.net/).
How do you figure out with Eclipse which JARs depend on which one?
[ "", "java", "eclipse", "jar", "dependencies", "" ]
How is `parseInt()` different from `valueOf()` ? They appear to do exactly the same thing to me (also goes for `parseFloat()`, `parseDouble()`, `parseLong()` etc, how are they different from `Long.valueOf(string)` ? Also, which one of these is preferable and used more often by convention?
Well, the API for [`Integer.valueOf(String)`](http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#valueOf(java.lang.String)) does indeed say that the `String` is interpreted exactly as if it were given to [`Integer.parseInt(String)`](http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#parseInt(java.lang.String)). However, `valueOf(String)` returns a **`new`** `Integer()` object whereas `parseInt(String)` returns a primitive `int`. If you want to enjoy the potential caching benefits of [`Integer.valueOf(int)`](http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#valueOf(int)), you could also use this eyesore: ``` Integer k = Integer.valueOf(Integer.parseInt("123")) ``` Now, if what you want is the object and not the primitive, then using `valueOf(String)` may be more attractive than making a new object out of `parseInt(String)` because the former is consistently present across `Integer`, `Long`, `Double`, etc.
From [this forum](http://www.coderanch.com/t/378048/Java-General-intermediate/java/What-differece-bw-Parseint-ValueOf#1650781): > **`parseInt()`** returns primitive integer > type (*int*), whereby **`valueOf`** returns > *java.lang.Integer*, which is the object > representative of the integer. There > are circumstances where you might want > an Integer object, instead of > primitive type. > > Of course, another obvious difference > is that **intValue** is an instance method > whereby **parseInt** is a static method.
Difference between parseInt() and valueOf() in Java?
[ "", "java", "integer", "parseint", "value-of", "" ]
I have large data sets (10 Hz data, so 864k points per 24 Hours) which I need to plot in real time. The idea is the user can zoom and pan into highly detailed scatter plots. The data is not very continuous and there are spikes. Since the data set is so large, I can't plot every point each time the plot refreshes. But I also can't just plot every nth point or else I will miss major features like large but short spikes. Matlab does it right. You can give it a 864k vector full of zeros and just set any one point to 1 and it will plot correctly in real-time with zooms and pans. How does Matlab do it? My target system is Java, so I would be generating views of this plot in Swing/Java2D.
You should try the file from MATLAB Central: <https://mathworks.com/matlabcentral/fileexchange/15850-dsplot-downsampled-plot> ![](https://mathworks.com/matlabcentral/mlc-downloads/downloads/submissions/15850/versions/2/screenshot.gif) **From the author:** This version of "plot" will allow you to visualize data that has very large number of elements. Plotting large data set makes your graphics sluggish, but most times you don't need all of the information displayed in the plot. Your screen only has so many pixels, and your eyes won't be able to detect any information not captured on the screen. This function will downsample the data and plot only a subset of the data, thus improving the memory requirement. When the plot is zoomed in, more information gets displayed. Some work is done to make sure that outliers are captured. Syntax: ``` dsplot(x, y) dsplot(y) dsplot(x, y, numpoints) ``` Example: ``` x =linspace(0, 2*pi, 1000000); y1=sin(x)+.02*cos(200*x)+0.001*sin(2000*x)+0.0001*cos(20000*x); dsplot(x,y1); ```
I don't know how Matlab does it, but I'd start with [Quadtrees](http://en.wikipedia.org/wiki/Quadtree). Dump all your data points into the quadtree, then to render at a given zoom level, you walk down the quadtree (starting with the areas that overlap what you're viewing) until you reach areas which are comparable to the size of a pixel. Stick a pixel in the middle of that area. added: Doing your drawing with OpenGL/JOGL will also help you get faster drawing. Especially if you can predict panning, and build up the points to show in a display list or something, so that you don't have to do any CPU work for the new frames.
How to plot large data vectors accurately at all zoom levels in real time?
[ "", "java", "matlab", "plot", "zooming", "large-data-volumes", "" ]
I have been using dean edwards [ie7/8 script](http://code.google.com/p/ie7-js/). Not sure if it's my implementation or not but sometimes I would experience ie6 issues that weren't quite fixed or [required special handling](http://code.google.com/p/ie7-js/issues/detail?id=114) which meant I would be back where I started, caring about ie6. So, I was wondering if ie7/8 is still the go or if some other practice/solution was better.
**Update**: I expanded my answer here with a tutorial on my site, which will probably be more helpful than my answer here. [Ultimate IE6 Cheatsheet: How To Fix 25+ Internet Explorer 6 Bugs](http://www.virtuosimedia.com/tutorials/ultimate-ie6-cheatsheet-how-to-fix-25-internet-explorer-6-bugs) Here's how I tackle IE6: * I validate both my XHTML and CSS. * I keep my designs simple, even the complicated ones. * I don't use hacks that invalidate my CSS. * I use a JavaScript framework/library (I like MooTools, but you'll get a lot of votes for jQuery, Prototype, YUI, Dojo, and many others) that handles most of my cross-browser JavaScript problems. * I progressively enhance my pages so that they first work without JavaScript and then add all the bells and whistles. * For some of the double margin problems, I use display:inline; * If I absolutely have to, I use a separate stylesheet, though I'm finding I have to do this less and less. * I try to avoid transparent images in my layouts. If I absolutely need them, I use a PNG8 with alpha transparency, which IE6 actually does support. * To get at the min-height problem, I do the following: This for IE6, which interprets height as min-height: ``` .classNameHere {height:300px;} ``` This for for everything else: ``` div>div .classNameHere {min-height:300px; height:auto;} ``` Incidentally, if you need to isolate IE6 with CSS, that's a good way to do it, as it doesn't support child selectors.
I try not to support IE6
How are programmers tackling ie6 bugs these days?
[ "", "javascript", "internet-explorer", "browser", "internet-explorer-6", "" ]
How can I obtain the command line arguments of another process? Using static functions of the `System.Diagnostics.Process` class I can obtain a list of running processes, e.g. by name: ``` Process[] processList = Process.GetProcessesByName(processName); ``` However, there is no way to access the command line used to start this process. How would one do that?
> If you did not use the Start method to start a process, the StartInfo property does not reflect the parameters used to start the process. For example, if you use GetProcesses to get an array of processes running on the computer, the StartInfo property of each Process does not contain the original file name or arguments used to start the process. (source: [MSDN](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.startinfo.aspx)) Stuart's WMI suggestion is a good one: ``` string wmiQuery = string.Format("select CommandLine from Win32_Process where Name='{0}'", processName); ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery); ManagementObjectCollection retObjectCollection = searcher.Get(); foreach (ManagementObject retObject in retObjectCollection) Console.WriteLine("[{0}]", retObject["CommandLine"]); ```
If you're targeting Windows XP or later and you can afford the overhead of WMI, a possibility would be to look up the target process using WMI's [WIN32\_Process class](http://msdn.microsoft.com/en-us/library/aa394372(VS.85).aspx), which has a CommandLine property.
How to read command line arguments of another process in C#?
[ "", "c#", "process", "diagnostics", "" ]
I need to strikeout the entire text(even the whitespace between text/cells) in a row in the RowDataBound event of the GridView. Is it possible?
C# on RowDataBound event ``` e.Row.Style.Value = "text-decoration:line-through;" ``` this is how your GridView will be rendered, it works ! ``` <table> <tr style="text-decoration:line-through;"> <td>some text</td> <td>some text</td> </tr> <tr style="text-decoration:line-through;"> <td>some text</td> <td>some text</td> </tr> <tr style="text-decoration:line-through;"> <td>some text</td> <td>some text</td> </tr> </table> ```
Yes, you can put all your rows cell's content into <strike> tag. Example, ``` row.Cell[0].Text = "<strike>cell content from row.DataItem</strike>"; ``` But it will only strike text in the cells. If you have cellpadding and cellspacing set to the row's table, then it might now look nice.
ASP.NET: GRIDVIEW: How to strikeout the entire text in a row
[ "", "c#", "asp.net", "gridview", "" ]
What is the advantage of local classes in Java or in any other language that makes use of this feature?
They allow you to take logic out of the parent class and objectify it. This removes functionality from where it doesn't belong and puts it into its own class. But what if this new object is only needed for a short time, only for the duration of a single block of code? Well, that's where a local class fits in.
Here's an example of how an anonymous inner class, a local inner class, and a regular inner class might be present in a program. The example is looking at a `myMethod` method and a `InnerClass` class present in `MyClass` class. For the sake of discussion, those classes will all be implementing the `Runnable` interface: ``` public class MyClass { public void myMethod() { // Anonymous inner class Runnable r = new Runnable() { public void run() {} }; // Local inner class class LocalClass implements Runnable { public void run() {} } } // ... // // Inner class class InnerClass implements Runnable { public void run() {} } } ``` The **anonymous inner class** can be used to simply to make an class that implements `Runnable` without actually having to write out the class and naming it, and as [krosenvold](https://stackoverflow.com/questions/478804/advantage-of-local-classes-java#478874) mentioned in his post, it is used as a "poor man's closure" in Java. For example, a very very simple way to start a `Thread` using an anonymous inner class would be: ``` new Thread(new Runnable() { public void run() { // do stuff } }).start(); ``` An **local inner class** can be used to make a class that is within the local scope -- it won't be able to be accessed from other methods outside of `myMethod`. If there was another method and we tried to make an instance of the `LocalClass` that is located inside the `myMethod` method, we won't be able to do so: ``` public void anotherMethod() { // LocalClass is out of scope, so it won't be found, // therefore can't instantiate. new Thread(new LocalClass()).start(); } ``` An **inner class** is part of the class that the inner class is located in. So, for example, the inner class `InnerClass` can be accessed from other classes by `MyClass.InnerClass`. Of course, it also means that another method in `MyClass` can instantiate an inner class as well. ``` public void anotherMethod() { // InnerClass is part of this MyClass. Perfectly instantiable. new Thread(new InnerClass()).start(); } ``` Another thing about the anonymous inner class and local inner class is that it will be able to access `final` variables which are declared in the `myMethod`: ``` public void myMethod() { // Variable to access from anonymous and local inner classes. final int myNumber = 42; // Anonymous inner class Runnable r = new Runnable() { public void run() { System.out.println(myNumber); // Works } }; // Local inner class class LocalClass implements Runnable { public void run() { System.out.println(myNumber); // Works } } // ... // ``` So, what are the advantages? Using anonymous inner classes and local inner classes instead of having a separate full-blown inner class or class will allow the former to have access to `final` variables in the method in which they are declared, and at the same time, the classes are local to the method itself, so it can't be accessed from outside classes and other methods within the same class.
Advantage of Local Classes Java
[ "", "java", "oop", "class", "local", "" ]
I am reading a text file with this format: > grrr,some text,45.4321,54.22134 I just have my double valued stored in a string variable. Why is it only giving me the first digit of the string? If I start over with just one while loop and a text file of this new format: > 21.34564 it works as it should. The thing is, `sLine` has the the same value as the one when I started over. What is different is the three nested for loops that most likely is causing the problem. Here is the code that gets me what I want: ``` #include <iostream> #include <fstream> #include <string> #include <vector> #include <iomanip> #include <cstdlib> #include <sstream> using namespace std; int main() { string usrFileStr, fileStr = "test.txt", // declaring an obj string literal sBuffer, sLine, str; double dValue ; int lineCount = 1; int nStart; istringstream issm; fstream inFile; // declaring a fstream obj // cout is the name of the output stream cout << "Enter a file: "; cin >> usrFileStr; inFile.open( usrFileStr.c_str(), ios::in ); // at this point the file is open and we may parse the contents of it while ( getline ( inFile, sBuffer ) && inFile.eof() ) { cout << "Original String From File: " << sBuffer << endl; cout << "Modified Str from File: " << fixed << setprecision(2) << dValue << endl; } fgetc( stdin ); return 0; } ``` So there it works just like it should. But i cant get it to work inside a for loop or when i have multiple feilds in my text file... ``` With this code, why is it taken off the decimal? #include <iostream> #include <fstream> #include <string> #include <vector> #include <iomanip> #include <cstdlib> #include <sstream> #include <errno.h> using namespace std; int main() { string usrFileStr, myFileStr = "myFile.txt", // declaring an obj string literal sBuffer, sLine = ""; istringstream inStream; int lineCount = 1; int nStart; double dValue = 0, dValue2 = 0; float fvalue; fstream inFile; // declaring a fstream obj // cout is the name of the output stream cout << "Enter a file: "; cin >> usrFileStr; inFile.open( usrFileStr.c_str(), ios::in ); // at this point the file is open and we may parse the contents of it if ( !inFile ) { cout << "Not Correct " << endl; } while ( getline ( inFile, sBuffer ) ) { nStart = -1 ; for ( int x = nStart + 1; x < sBuffer.length(); x++ ) { if ( sBuffer[ x ] == ',' ) { nStart = x; break; } cout << sBuffer[ x ]; } for ( int x = nStart + 1; x < sBuffer.length(); x++ ) { if ( sBuffer[ x ] == ',' ) { nStart = x; break; } cout << sBuffer[ x ]; } for ( int x = nStart + 1; x < sBuffer.length(); x++ ) { if ( sBuffer[ x ] == ',' ) { nStart = x; break; } sLine = sBuffer[ x ]; inStream.clear(); inStream.str( sLine ); if ( inStream >> dValue ) cout << setprecision(1) << dValue; } for ( int x = nStart + 1; x < sBuffer.length(); x++ ) { if ( sBuffer[ x ] == ',' ) { nStart = x; break; } sLine = sBuffer[ x ]; inStream.clear(); inStream.str( sLine ); if ( inStream >> dValue2 ) cout << setprecision(1) << dValue2; } cout << ") \n"; lineCount++; } cout << "There are a Total of: " << lineCount -1 << " line(s) in the file." << endl; inFile.clear(); // clear the file of any errors inFile.close(); // at this point we are done with the file and may close it fgetc( stdin ); return 0; } ``` I don't have any other characters to loop over in the first code because im just reading a nice little double value. In my second code, i have many characters to get to before the one that i want. But regardless, it is still isolated from the other characters and it is still in its own varaible. im to sick to realize what the problem is :/ although i think its the for loops. I have also tried atof but i get a '0' where the decimal should be. and strtod is hard because i need im not reading data into a const char \*cPtr
Using ***instream>>dvalue*** is certainly the **right** way to do things. But sometimes what's right isn't always easiest or necessarily best. We could do something like this: ``` int main() { string s = "grrr,some text,45.4321,54.22134"; double a,b; ASSERT_IS( 2, sscanf( s.c_str(), "%*[^,],%*[^,],%lf,%lf", & a, & b ) ); cout << setprecision(8); SHOW(a); SHOW(b); } ``` Or perhaps something like this, while less efficient, might be easier to understand... ``` int main() { string s = "grrr,some text,45.4321,54.22134"; vector<string> v; StringSplit( & v, s, "," ); cout << setprecision(8); SHOW(v); SHOW(atof( v[2].c_str())); SHOW(strtod(v[3].c_str(), (char**)NULL)); } ``` Assuming: ``` #define SHOW(X) cout << # X " = " << (X) f << endl /* A quick & easy way to print out vectors... */ template<class TYPE> inline ostream & operator<< ( ostream & theOstream, const vector<TYPE> & theVector ) { theOstream << "Vector [" << theVector.size() << "] {" << (void*)(& theVector) << "}:" << endl; for ( size_t i = 0; i < theVector.size(); i ++ ) theOstream << " [" << i << "]: \"" << theVector[i] << "\"" << endl; return theOstream; } inline void StringSplit( vector<string> * theStringVector, /* Altered/returned value */ const string & theString, const string & theDelimiter ) { UASSERT( theStringVector, !=, (vector<string> *) NULL ); UASSERT( theDelimiter.size(), >, 0 ); size_t start = 0, end = 0; while ( end != string::npos ) { end = theString.find( theDelimiter, start ); // If at end, use length=maxLength. Else use length=end-start. theStringVector -> push_back( theString.substr( start, (end == string::npos) ? string::npos : end - start ) ); // If at end, use start=maxSize. Else use start=end+delimiter. start = ( ( end > (string::npos - theDelimiter.size()) ) ? string::npos : end + theDelimiter.size() ); } } ```
Your code is a little tough to read. You probably want to think some point about encapsulation and breaking it up into functions. Additionally, I would try to avoid reading in single characters and use the various functions and methods for reading data in fields - you can read a whole floating point or integer number using the `>>` stream extractors. Finally, a useful skill to learn is how to use a debugger. You can step through the code and inspect the values of variables as you go. That said, it looks like your problem is here: ``` if ( sBuffer[ x ] == ',' ) { nStart = x; break; } **** sLine = sBuffer[ x ]; inStream.clear(); inStream.str( sLine ); if ( inStream >> dValue2 ) cout << setprecision(1) << dValue2; ``` On the line marked with "\*\*\*\*", you place exactly one character into the variable called "sLine". Having done so, you convert that one character into a double precision variable dValue2 and then output it. It should be obvious why this one character is converted into the first digit of the number you want.
StringStream loop fails
[ "", "c++", "" ]
I have an associative array (object) of the following construction ``` var menu = new Object('Submenu A','Submenu B','Submenu C','Submenu D'); menu['Submenu A']=new Object(); menu['Submenu A']['Option A']= 'foo blah text'; menu['Submenu A']['Option B']= 'blah more text'; menu['Submenu B']['Option A']= 'blah blah'; menu['Submenu B']['Option B']= 'texty text'; ... etc. ``` This is iterated over a for..in loop which breaks when using prototype due to extending the class with methods like toJSON() and camelise() I've attempted using Prototype's .each method however it errors out reporting that menu['Submenu A'] is undefined, it can't seem to locate the options that are defined under it. What is the proper way to iterate over an associative array in prototype? Further clarification (thanks for the answers so far). I'm slowly migrating a project over to using prototype, but it has large amounts of code that aren't prototype compatible yet. The code in question is in a library used by several other files. The code as is called by a function, initialize\_menu and contains the code ``` for (var i=0; i < menu.length; i++) { populate_sub_menu(menu[i]) } ``` The submenu function is structured like this ``` function populate_sub_menu(subMenu){ for (var option in menu[subMenu]) { html+=menu[subMenu][option]+'html'+subMenu+option; } } ``` I'm leaving out code regarding getting html elements and such that aren't related to the problem.
To create a new object with no properties, use: ``` var menu = new Object(); ``` The Object constructor actually takes one optional argument. Now let's look at what you have: ``` var menu = new Object('Submenu A','Submenu B','Submenu C','Submenu D'); ``` Only the first argument (`'Submenu A'`) is being used while the others are simply ignored. However, passing a string literal to the Object constructor causes a new `String` object being returned instead of an `Object` object. I'm speculating that, that may be reason Prototype's `each()` is acting up (if it's really failing because of this). You mentioned that "it errors out reporting that menu['SubmenuA'] is undefined". Does your question have a typo? You're setting the "Submenu A" property, with a space before the "A", while the error you reported seems to lack the space. You also seem to be taking the long route in setting the object properties. Using the object literal syntax will be a lot shorter and less error-prone: ``` var menu = { "Submenu A": { "Option A": "foo blah text", "Option B": "blah more text" }, "Submenu B": { "Option A": "blah blah", "Option B": "texty text" } }; ```
You want Prototype's [Hash](http://www.prototypejs.org/api/hash).
Prototype.js and associative arrays
[ "", "javascript", "prototypejs", "" ]
I'm attempting to issue two concurrent AJAX requests. The first call (/ajax\_test1.php) takes a very long time to execute (5 seconds or so). The second call (/ajax\_test2.php) takes a very short time to execute. The behavior I'm seeing is that I /ajax\_test2.php returns and the handler gets called (updateTwo()) with the contents from /ajax\_test2.php. Then, 5 seconds later, /ajax\_test1.php returns and the handler gets called (updateOne()) *with the contents from /ajax\_test2.php still!!!* Why is this happening? Code is here: <http://208.81.124.11/~consolibyte/tmp/ajax.html>
This line:- ``` req = new XMLHttpRequest(); ``` should be:- ``` var req = new XMLHttpRequest(); ```
As AnthonyWJones stated, your javascript is declaring the second AJAX object which first overwrites the req variable (which is assumed global since there is no var) and you are also overwriting the ajax variable. You should separate your code i.e: ``` function doOnChange() { var ajax1 = new AJAX('ajax_test1.php', 'one', updateOne); var ajax2 = new AJAX('ajax_test2.php', 'two', updateTwo); } function AJAX(url, action, handler) { if (typeof XMLHttpRequest == "undefined") { XMLHttpRequest = function() { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {} try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {} throw new Error( "This browser does not support XMLHttpRequest." ) }; } url = url + '?action=' + action + '&rand=' + Math.random() var req = new XMLHttpRequest(); req.onreadystatechange = function() { if (req.readyState == 4) { if (req.status == 200) { alert('' + handler.name + '("' + req.responseText + '") ') handler(req.responseText) } } } req.open("GET", url, true); req.send(null); } ``` Regards Gavin
Strange javascript behavior - multiple active XMLHttpRequests at once? Long running scripts?
[ "", "javascript", "ajax", "" ]
I have following classes. ``` class A { public: void fun(); } class B: public A { } class C: public A { } A * ptr = new C; ``` Is it ok to do something like below? Will i have some problems if introduce some virtual functions in the baseclass? ``` ((B *)ptr)->fun(); ``` This may look stupid, but i have a function that calls A's function through B and i don't want to change that.
You can't cast an A\* pointing to Class C as a B\* because Class C doesn't have any relation with Class B. You'll get undefined behavior which will probably be the wrong function called and stack corruption. If you intended for class C to derive from class B then you could. However, you wouldn't need to. If class C doesn't have fun() defined, it will inherit A's. You didn't declare fun() virtual though so you'll get strange behavior if you even implement C::fun() or B::fun(). You almost certainly want fun() to be declared virtual.
You can cast from A \* to B \*, and it should work if the original pointer was B \*. ``` A* p = new B; B* q = static_cast<B*>(p); // Just work (tm) ``` But in this case it is a C \*, and it is not guaranteed to work, you will end with a dangling pointer, if you are lucky you will get an access violation, if not you man end up silently corrupting your memory. ``` A* p = new C; B* q = static_cast<B*>(p); // Owned (tm) ```
calling base class functions
[ "", "c++", "" ]
I have a string that looks like "(3) New stuff" where 3 can be any number. I would like to add or subtract to this number. I figured out the following way: ``` var thenumber = string.match((/\d+/)); thenumber++; string = string.replace(/\(\d+\)/ ,'('+ thenumber +')'); ``` Is there a more elegant way to do it?
I believe Gumbo was on the right track ``` "(42) plus (1)".replace(/\((\d+)\)/g, function(a,n){ return "("+ (+n+1) +")"; }); ```
Another way: ``` string = string.replace(/\((\d+)\)/ , function($0, $1) { return "(" + (parseInt($1, 10) + 1) + ")"; }); ```
JavaScript: add or subtract from number in string
[ "", "javascript", "regex", "" ]
is there an easy way to hook to an event that is triggered on change of global screen resolution?
Handle the following event: ``` Microsoft.Win32.SystemEvents.DisplaySettingsChanged ``` You may refer to [this](http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.displaysettingschanged.aspx) page for more details. You may also wanna see the [msdn article](http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.aspx) on SystemEvents class.
Sure you don't have to unsubscribe to static events (or any events) if your program (process) is dying. The OS will take care of releasing all memory of your process to the OS. However, if you subscribe to a static event or to any event pointing to an object with a longer lifetime than your object subscribing, and you want that object to be eligible for GC - you need to unsubscribe (-=) to the event. AND it is always good practice to always unsubscribe to all events. You never know when the lifetime of your objects are changed (by someone else) during the lifespan of your source code / product...
Detect change of resolution c# WinForms
[ "", "c#", ".net", "winforms", "" ]
I am learning templates. Which book is worth buying for doing template programming? I already have [The C++ Programming Language](http://en.wikipedia.org/wiki/The_C%2B%2B_Programming_Language) and [Effective C++](http://en.wikipedia.org/wiki/Scott_Meyers#Publications).
Those two books are pretty good in my opinion and they helped me a lot > * [*C++ Templates: The Complete Guide* by David Vandevoorde and Nicolai M. > Josuttis](https://rads.stackoverflow.com/amzn/click/com/0201734842) > * [*Modern C++ Design* by Andrei Alexandrescu](https://rads.stackoverflow.com/amzn/click/com/0201704315) ``` ![](https://i.stack.imgur.com/IdUks.jpg) ![](https://i.stack.imgur.com/BKFbd.jpg) ``` The first one explains how templates work. The second book is more about *how* to use them. I recommend you to read the first book before starting with Modern C++ Design because that's heavy stuff.
Maybe a bit mind-boggling if you are just learning, but after the books you mention, you may want to read Andrei Alexandrescu's [Modern C++ Design](https://rads.stackoverflow.com/amzn/click/com/0201704315), if only to learn what can be accomplished through templates. Besides, it discusses many advanced aspects of templates wonderfully.
Suggestion for template book for C++?
[ "", "c++", "templates", "resources", "" ]
My Python application currently uses the [python-memcached API](http://www.tummy.com/Community/software/python-memcached/) to set and get objects in memcached. This API uses Python's native [pickle module](http://docs.python.org/library/pickle.html) to serialize and de-serialize Python objects. This API makes it simple and fast to store nested Python lists, dictionaries and tuples in memcached, and reading these objects back into the application is completely transparent -- it just works. But I don't want to be limited to using Python exclusively, and if all the memcached objects are serialized with pickle, then clients written in other languages won't work. Here are the cross-platform serialization options I've considered: 1. XML - the main benefit is that it's human-readable, but that's not important in this application. XML also takes a lot space, and it's expensive to parse. 2. JSON - seems like a good cross-platform standard, but I'm not sure it retains the character of object types when read back from memcached. For example, according to [this post](https://stackoverflow.com/questions/408866/python-human-readable-object-serialization) tuples are transformed into lists when using [simplejson](http://pypi.python.org/pypi/simplejson/); also, it seems like adding elements to the JSON structure could break code written to the old structure 3. [Google Protocol Buffers](http://code.google.com/apis/protocolbuffers/docs/overview.html) - I'm really interested in this because it seems very fast and compact -- at least 10 times smaller and faster than XML; it's not human-readable, but that's not important for this app; and it seems designed to support growing the structure without breaking old code Considering the priorities for this app, what's the ideal object serialization method for memcached? 1. Cross-platform support (Python, Java, C#, C++, Ruby, Perl) 2. Handling nested data structures 3. Fast serialization/de-serialization 4. Minimum memory footprint 5. Flexibility to change structure without breaking old code
I tried several methods and settled on compressed JSON as the best balance between speed and memory footprint. Python's native Pickle function is slightly faster, but the resulting objects can't be used with non-Python clients. I'm seeing 3:1 compression so all the data fits in memcache and the app gets sub-10ms response times including page rendering. Here's a comparison of JSON, Thrift, Protocol Buffers and YAML, with and without compression: <http://bouncybouncy.net/ramblings/posts/more_on_json_vs_thrift_and_protocol_buffers/> Looks like this test got the same results I did with compressed JSON. Since I don't need to pre-define each structure, this seems like the fastest and smallest cross-platform answer.
**One major consideration is "do you want to have to specify each structure definition"**? If you are OK with that, then you could take a look at: 1. [Protocol Buffers - http://code.google.com/apis/protocolbuffers/docs/overview.html](http://code.google.com/apis/protocolbuffers/docs/overview.html) 2. [Thrift - http://developers.facebook.com/thrift/](http://developers.facebook.com/thrift/) (more geared toward services) Both of these solutions require supporting files to define each data structure. --- If you would prefer not to incur the developer overhead of pre-defining each structure, then take a look at: 1. JSON (via python cjson, and native PHP json). Both are really really fast if you don't need to transmit binary content (such as images, etc...). 2. Yet Another Markup Language @ <http://www.yaml.org/>. Also really fast if you get the right library. However, I believe that both of these have had issues with transporting binary content, which is why they were ruled out for our usage. **Note:** YAML may have good binary support, you will have to check the client libraries -- see here: <http://yaml.org/type/binary.html> --- At our company, we rolled our own library (Extruct) for cross-language serialization with binary support. We currently have (decently) fast implementations in Python and PHP, although it isn't very human readable due to using base64 on all the strings (binary support). Eventually we will port them to C and use more standard encoding. Dynamic languages like PHP and Python get really slow if you have too many iterations in a loop or have to look at each character. C on the other hand shines at such operations. If you'd like to see the implementation of Extruct, please let me know. (contact info at <http://blog.gahooa.com/> under "About Me")
What's the best serialization method for objects in memcached?
[ "", "python", "serialization", "xml-serialization", "memcached", "protocol-buffers", "" ]
I'm trying to write a static member function in C# or find one in the .NET Framework that will re-case a file path to what the filesystem specifies. Example: ``` string filepath = @"C:\temp.txt"; filepath = FileUtility.RecaseFilepath(filepath); // filepath = C:\Temp.TXT // Where the real fully qualified filepath in the NTFS volume is C:\Temp.TXT ``` I've tried the following code below and many variants of it and it still doesn't work. I know Windows is case-insensitive in general but I need to pass these file paths to ClearCase which considers file path casing since it's a Unix and Windows application. ``` public static string GetProperFilePathCapitalization(string filepath) { string result = ""; try { result = Path.GetFullPath(filepath); DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(result)); FileInfo[] fi = dir.GetFiles(Path.GetFileName(result)); if (fi.Length > 0) { result = fi[0].FullName; } } catch (Exception) { result = filepath; } return result; } ```
This is a pretty simple implementation that assumes that the file and directories all exist and are accessible: ``` static string GetProperDirectoryCapitalization(DirectoryInfo dirInfo) { DirectoryInfo parentDirInfo = dirInfo.Parent; if (null == parentDirInfo) return dirInfo.Name; return Path.Combine(GetProperDirectoryCapitalization(parentDirInfo), parentDirInfo.GetDirectories(dirInfo.Name)[0].Name); } static string GetProperFilePathCapitalization(string filename) { FileInfo fileInfo = new FileInfo(filename); DirectoryInfo dirInfo = fileInfo.Directory; return Path.Combine(GetProperDirectoryCapitalization(dirInfo), dirInfo.GetFiles(fileInfo.Name)[0].Name); } ``` There is a bug with this, though: Relative paths are converted to absolute paths. Your original code above did the same, so I'm assuming that you do want this behavior.
The below works fine to the extent I tested... only catch is that the API used is available only in Vista. ``` static void Main(string[] args) { using (FileStream fs = File.OpenRead(@"D:\temp\case\mytest.txt")) { StringBuilder path = new StringBuilder(512); GetFinalPathNameByHandle(fs.SafeFileHandle.DangerousGetHandle(), path, path.Capacity, 0); Console.WriteLine(path.ToString()); } } [DllImport("kernel32.dll", SetLastError = true)] static extern int GetFinalPathNameByHandle(IntPtr handle, [In, Out] StringBuilder path, int bufLen, int flags); ```
C# Filepath Recasing
[ "", "c#", ".net", "filenames", "case-sensitive", "filepath", "" ]
I have a class (class A) that is designed to be inherited by other classes written by other people. I also have another class (class B), that also inherits from A. B has to access some A's member functions that shouldn't be accessed by other inheriting classes. So, these A's member functions should be public for B, but private for others. How can I solve it without using 'friend' directive? Thank you. EDIT: Example why I need it. ``` class A { public: void PublicFunc() { PrivateFunc(); // and other code } private: virtual void PrivateFunc(); }; class B : public class A { private: virtual void PrivateFunc() { //do something and call A's PrivateFunc A::PrivateFunc(); // Can't, it's private! } }; ```
What you say is: there are two sets of subclasses of A. One set should have access, the other set shouldn't. It feels wrong to have only one brand of subclasses (i.e. B) 'see' A's members. If what you mean is: only *we* can use *this* part of functionality, while our clients can't, there are other resorts. (Functionality reuse by inheritance often corners you with this kind of problems. If you go towards reuse by aggregation, you may get around it.) A suggestion: ``` // separate the 'invisible' from the 'visible'. class A_private_part { protected: int inherited_content(); public: int public_interface(); }; class B_internal : public A_private_part { }; class A_export : private A_private_part { public: int public_interface() { A_private_part::public_interface(); } }; // client code class ClientClass : public A_export { }; ``` But better would be to go the aggregation way, and split the current "A" into a visible and an invisible part: ``` class InvisibleFunctionality { }; class VisibleFunctionality { }; class B { InvisibleFunctionality m_Invisible; VisibleFunctionality m_Visible; }; // client code uses VisibleFunctionality only class ClientClass { VisibleFunctionality m_Visible; }; ```
You can't. That's what friend is for. An alternative would be to change the design/architecture of your program. But for hints on this I'd need some more context.
Public and private access for the same member functions
[ "", "c++", "inheritance", "private", "" ]
I have a legacy MySQL table called `lnk_lists_addresses` with columns `list_id` and `address_id`. I'd like to write a query that reports all the cases where the same `list_id`-`address_id` combination appears more than once in the table with a count. I tried this... ``` SELECT count(*), list_id, address_id FROM lnk_lists_addresses GROUP BY list_id, address_id ORDER BY count(*) DESC LIMIT 20 ``` It works, sort of, because there are fewer than 20 duplicates. But how would I return only the counts greater than 1? I tried adding "`WHERE count(*) > 1`" before and after `GROUP BY` but got errors saying the statement was invalid.
``` SELECT count(*), list_id, address_id FROM lnk_lists_addresses GROUP BY list_id, address_id HAVING count(*)>1 ORDER BY count(*) DESC ``` To combine mine and Todd.Run's answers for a more "complete" answer. You want to use the HAVING clause: <http://dev.mysql.com/doc/refman/5.1/en/select.html>
You want to use a "HAVING" clause. Its use is explained in the MySQL manual. <http://dev.mysql.com/doc/refman/5.1/en/select.html>
MySQL query to return only duplicate entries with counts
[ "", "sql", "mysql", "" ]
Is there an event I can use to tell if a child form has been added or removed from the MDI parent?
No, there is not. You would have to subclass Form and expose specific events that would indicate when the child is added and then route all attachments of child forms through a method that would wire up the child form, as well as raise the event.
Yes. On your main MDI form, wire up to the MdiChildActivated Event. Like so: ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); this.MdiChildActivate += new EventHandler(Form1_MdiChildActivate); } void Form1_MdiChildActivate(object sender, EventArgs e) { MessageBox.Show("Activated"); } private void addToolStripMenuItem_Click(object sender, EventArgs e) { Form form2 = new Form2(); form2.MdiParent = this; form2.Show(); } } ``` And that event will fire when the child form is both activated or deactivated.
MDI Form detecting with a child form is added or removed
[ "", "c#", "winforms", ".net-3.5", "mdi", "" ]
In my project I need to create a business object validation layer that will take my object and run it against a set of rules and return either pass or fail and it's list of failure reasons. I know there are quite a few options out there for accomplishing this. From Microsoft: * [Enterprise Library Validation Application Block](http://www.google.com/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fmsdn.microsoft.com%2Fen-us%2Flibrary%2Fcc309509.aspx&ei=LAGOSYrcN5CCNcTMiZIL&usg=AFQjCNGYSsoNq_hV223GKaGvO0EMTfN4Pw&sig2=AtQJwf8KrUATfYvTMD9q4g) * [Windows Workflow Foundation Rules Engine](http://www.google.com/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fmsdn.microsoft.com%2Fen-us%2Flibrary%2Faa480193.aspx&ei=SAGOSfbtGpCCNbXMiZIL&usg=AFQjCNFAKrvKAmkMkprSsL-YDtXcP5_m4A&sig2=FHQuHQpcyQSxhJvM08ovtg) Open Source: * [Drools.NET](http://droolsdotnet.codehaus.org/) * [Simple Rule Engine(SRE)](http://sourceforge.net/projects/sdsre/) * [NxBRE](http://nxbre.wiki.sourceforge.net/) Has anyone had any particularly great successes or failures with any of these technologies (or any that I didn't list) or any opinions on what they feel is best suited for business rules validation. **Edit:** I'm not just asking about generic validations string length < 200, zip code is 5 digits or 5+4 but assume that the rules engine would actually be leveraged.
The code-versus-rules-engine decision is a matter of trade-offs, IMHO. A few examples are: ### Advantages of code * Potentially higher performance. * Uses developers' existing skills. * No need for separate tools, run-time engines, etc. ### Advantages of rule engine (Features vary across the various rule engines.) * Rule DSL that is writable (or at least readable) by business users. * Effective- and expiration-date properties that allow automatic scheduling of rules. * Flexible reporting from rule repository supports improved analysis and auditing of system behavior. * Just as data-base engines isolate data content/relationship issues from the rest of the system, rules engines isolate validation and policy from the remainder of the system.
A modified version of the CSLA framework rules. Many of the other rules engines have the promise that goes like "The end user can modify the rules to fit their needs." Bahh. Very few users are going to learn the complexities of the rules document format or be able to understand the complexities and ramifications of their changes. The other promise is you can change the rules without having to change the code. I say so what? Changing a rule even as simple as "this field must not be blank" can have a very negative impact on the application. If those fields where previously allowed to be blank you now have a bunch of invalid data in the data store. Plus modern applications are either web based or distributed/updated via technologies like click=once. So you updating a couple of components is just as easy as updating a rules file. So, because the developer is going to modify them anyway and because they are core to the Business objects operations just locate them in one place and use the power of modern languages and frameworks.
What would you use for a business validation layer?
[ "", "c#", "validation", "nxbre", "" ]
Is there a way to programmatically create PowerPoint presentations? If possible, I'd like to use C# and create PowerPoint 2003 presentations.
Yes, you can. You will want to look into MSDN which has a pretty good introduction to it. I might give you a word of warning, Microsoft Office interop is compatible with an API which is now more than 10 years old. Because of this, it is downright nasty to use sometimes. If you have the money to invest in a good book or two, I think it would be money well spent. Here's a starting point for you. Use the search feature on MSDN [MSDN Webpage](http://msdn.microsoft.com). It's good for any Microsoft C# .NET style stuff. Specifically in regards to your question, this link should help: [Automate PowerPoint from C#](http://support.microsoft.com/kb/303718/). EDIT LINK NOW DEAD :(. These two links are fairly close to the original KB article: [Automate Powerpoint from C# 1/2](https://code.msdn.microsoft.com/office/CSAutomatePowerPoint-b312d416) [Automate Powerpoint from C# 2/2](https://code.msdn.microsoft.com/office/How-to-Automate-control-23cd2a8f) Finally, to whoever downvoted this: We were all learning one day, how to do something as a beginner is most definitely programming related, regardless of how new someone might be.
[OpenXML](http://msdn.microsoft.com/en-us/library/bb448854%28v=office.15%29.aspx) looks like the way to go from a web app. Using the interop libraries is not recommended, as others have stated.
Creating PowerPoint presentations programmatically
[ "", "c#", "ms-office", "powerpoint", "" ]
Occasionally I search for some JavaScript help and I come upon the term "Server-side JavaScript". When would you use JavaScript server-side? And how? My experiences of JavaScript have been in the browser. Is there a compiled version of JS?
There's the project [Phobos](https://phobos.java.net/), which is a server side JavaScript framework. Back In The Day, the Netscape web server offered server-side java script as well. In both of these cases, JavaScript is used just like you'd use any language on the server. Typically to handle HTTP requests and generate content. [Rhino](http://www.mozilla.org/rhino/), which is Mozilla's JavaScript system for Java, compiles JavaScript in to Java byte codes, which the JVM can choose to JIT. Other systems use other means for executing java script, even to the point that some are JIT compiling their java script internal codes. I foresee that there will be more and more JavaScript on the server. When you're writing "thick" applications in JavaScript on the client, then you may as well be able to write your logic in JavaScript on the server in order to not have to make the cognitive leaps from one language to another. The environments will be different, but much of your code and knowledge will be shareable. Finally, JavaScript is probably the singular language that has the most money pointing at it right now in terms of implementations. From Apple, Mozilla, Google, and even Microsoft as well as the efforts to make it an even more advanced language (i.e. basically a Scheme with Algol syntax sans macros). Most of those implementation are buried in the browser, but that's not to say that there's no value on the server side as well. The tooling is the biggest place where JavaScript is lacking, especially on the server side, but if you consider something like Phobos, where you can debug your server side JavaScript in the IDE, that's a great advancement. Personally, I'm tossing JavaScript around in my applications like white paint. It offers cheap extensibility for very little cost and is a great enabler.
It's not AJAX, unless people are using the term improperly. As its name suggests, SSJS is JavaScript that runs on the server, interpreted by a standalone (i.e., browser-independent) JavaScript engine, like SpiderMonkey. Why bother? Well, one area I currently see it underutilized in is in data validation. With SSJS you write one piece of code that then gets used on both the server and the client. Thus you get immediate user feedback from the client-side JS that will automatically match the data checking taking place on the server.
When and how do you use server side JavaScript?
[ "", "javascript", "server-side", "" ]
If I put this tag in my HTML: ``` <img src="http://server/imageHandler.php?image=someImage.jpg" /> ``` instead of ``` <img src="http://server/images/someImage.jpg" /> ``` and use the imageHandler.php script to read the image file, output expire headers and print the image data, i expect it to be slower. Is this a viable way to manipulate image headers or the performance penalty is too much since images are all around. Are there other ways to set expire headers on images through my php code?
Yes, running any PHP script is slower than serving a static file. Instead, you can set expire headers using Apache configuration directives. See the documentation for [`mod_expires`](http://httpd.apache.org/docs/2.2/mod/mod_expires.html). For example, you can put the following directives in an Apache httpd.conf or .htaccess file: ``` # enable expirations ExpiresActive On # expire JPG images after a month in the client's cache ExpiresByType image/jpg A2592000 ```
Try something like ``` header("Expires: <the date>"); http_send_file("someImage.jpg"); ``` from <https://www.php.net/manual/en/function.http-send-file.php> The http\_send\_file function (if it works the way I think it does) copies the file directly from disk to the network interface, so it sends the image itself about as fast as the server would natively. (Of course, the time taken to run the PHP interpreter will still make the overall request a little slower than serving a static file.) As at least one other answer has mentioned, probably the best way to set an Expires header (or any other header), if you're running Apache, is to use an `.htaccess` file, or better yet if you have access to the main configuration files of the server, put the Expires configuration there. Have a look at [mod\_expires](http://httpd.apache.org/docs/2.2/mod/mod_expires.html).
Is putting a php script in the src of the image tag slower than normal and by how much?
[ "", "php", "image", "header", "" ]
I'm creating my own JavaScript Array-like object and I have methods that call closures. I was just wondering where was the most efficient place to define a closure. For example, imagine I have a map function and a chop function: ``` MyObject.prototype = { map: function(fn) { ... applies fn to each element ... }; chop: function() { this.map( function(element) { ... chop off last character ... } )}; } ``` Is it more efficient to do this instead? ``` MyObject.prototype = { map: function(fn) { ... applies fn to each element ... }; __chop: function(element) { ... chop off last character ... } chop: function() { this.map(this.__chop) }; } ```
The second one is more efficient. This ``` chop: function() { map( function(element) { ... chop off last character ... } )} ``` will create a new function object on each call to `chop()` with the respective runtime and memory overhead. As there won't be any lingering references to the new object, it can be immediately gargage collected, but it's still bad practice to create more objects than necessary. I'd suggest the following pattern: ``` MyObject.prototype = (function() { function map(fn) { ... } function chopElement(element) { ... } function chop() { this.map(chopElement); } return { map : map, chop : chop }; })(); ```
Neither creating the function, nor looking it up are costly operations in JavaScript, so if you have an "array" with a decent # of elements in it, the difference between either method will be negligible.
Where should I define my Javascript closure?
[ "", "javascript", "closures", "" ]
There's the (almost religious) discussion, if you should use LIKE or '=' to compare strings in SQL statements. * Are there reasons to use LIKE? * Are there reasons to use '='? * Performance? Readability?
To see the performance difference, try this: ``` SELECT count(*) FROM master..sysobjects as A JOIN tempdb..sysobjects as B on A.name = B.name SELECT count(*) FROM master..sysobjects as A JOIN tempdb..sysobjects as B on A.name LIKE B.name ``` Comparing strings with '=' is much faster.
`LIKE` and the equality operator have different purposes, they don't do the same thing: `=` is much faster, whereas `LIKE` can interpret wildcards. Use `=` wherever you can and `LIKE` wherever you must. ``` SELECT * FROM user WHERE login LIKE 'Test%'; ``` Sample matches: > TestUser1 > TestUser2 > TestU > Test
Use '=' or LIKE to compare strings in SQL?
[ "", "sql", "comparison", "" ]
I've installed the Web Tools Project for Eclipse version 3.4. I've been trying to get refactoring working the way I think it should and have had no success. I have one Java project that contains the Java classes for the jar that is put into the /WEB-INF/lib for a web site. Another project (a Dynamic Web project) has the JSP files for the same site. The Dynamic Web project is set up with the Java project as a required project in the build path. I have also set the Project References option for the Dynamic Web project to refer to the Java Project. If I use refactoring to change a method name in one of the Java classes, I would expect that references to that method in the JSPs would be renamed. But it does not work. References in the Java project that contains the class and other Java projects that use that class have the references changed are refactored, but not references to the method inside the JSPs. I've been fiddling with it for days, trying different versions of Eclipse and WTP. Deleting all my projects and files and setting them up again. Nothing makes any difference. Does this work for anyone else? Is there something special I need to set to get this working?
Sorry, this is not directly answering your question but nevertheless addressing your problem... maybe it helps, otherwise please ignore: As matt b suggested, you should not place java code in a jsp. Instead 'simply' use Tags. If you're using the [standard tag library](https://tomcat.apache.org/taglibs/standard/), there's almost everything there that you need. For things that you must handle yourself, it's very simple to write your own tags once you know what tags are about. With this trick you'll get a better application (view) architecture, opportunity for tests (hope you like them), adhere to the DRY (dont repeat yourself) principle and place all Java code in .java files, so that they will easily be picked up by *any* tool. There's even an option for web.xml to enforce disabling scripting, leaving tags working, but if you already have a huge investment in scripted jsps, this might not be what you need... ``` <jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <scripting-invalid>true</scripting-invalid> </jsp-property-group> </jsp-config> ``` Another answer to a question that you didn't ask is that IntelliJ Idea handles the scenario that you talk about very well (though I'm using eclipse myself day to day, this is one of the differences between both IDEs)
My experiences with how WTP (or any flavor of Eclipses) treats Java code in scriptlet blocks in a JSP file has always been horrible: it never works well or the way you expect. I've seen Eclipse add `<jsp:import>` statements in the middle of the JSP file, and do all other sorts of weird formatting. My only advice is to stay away from editing a code in a JSP inside Eclipse. (My other piece of advice would be to **not** put Java code directly in a JSP file, and move to a MVC architecture, but that's a subject for another day...)
Does the Eclipse Web Tools Project handle refactoring inside JSPs?
[ "", "java", "eclipse", "jsp", "refactoring", "eclipse-wtp", "" ]
I'm designing a really simple GUI but without any luck. Basically the outer layout has two columns which is a splitter pane (this is for an IRC client I'm writing). On the left-hand side is the server/channel/user tree and on the right is the chat pane. Now I break this down so on the right-hand side there's the output pane at the top, and a single-lined input box at the bottom. This is the code for creating the GUI on a whole (this is just a snippet) ``` ChatModel cm = new ChatModel(); ChatView cv = new ChatView(cm); treeViewChatSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, serverTreeView, cv); treeViewChatSplitPane.setSize(500, 500); treeViewChatSplitPane.setBorder(null); treeViewChatSplitPane.setDividerSize(3); this.getContentPane().add(treeViewChatSplitPane); this.setSize(500, 500); ``` The ChatView constructor has this in it (it extends java.awt.Container) ``` this.model = model; this.setLayout(new BorderLayout()); mainTextArea = new JTextArea(); mainTextArea.setLineWrap(true); mainTextArea.setBackground(new Color(255, 255, 255)); inputField = new JTextField(); this.add(mainTextArea, BorderLayout.CENTER); this.add(inputField, BorderLayout.PAGE_END); ``` Now it looks fine initially, but the problem I'm having with it is that you can move the splitter to the left, but not to the right. In fact, if you move it left, you can no longer move it right. I did have it working earlier, but the implementation wasn't as good and I've forgotten what I had done. Any ideas? I can't see why this wouldn't work.
If I remember correctly, `JSplitPanes` always respect the minimum size of their components. Try explicitly setting the minimum size of the `ChatView` to `(0,0)` and see if that helps. If so, you can then look at each of the components inside it to see which is causing the problem.
In any place do you set minimum size for the ChatView? If so, isn't this minimum equals to the frame size ( 500 x 500 ) ? It is kind of hard to troubleshot with the information provided, but the following advice have ALWAYS worked for me ( and for the people who use it ) * Create the simplest frame that could possible work and add a SplitPane with two buttons. * Resize in there. * In everything goes ok, process replacing one of your components. * Then the other. * Detect which one is causing the strange behavior. * On that one, start doing the same, replace it for the minimum component you can think of ( replace it with a JPanel for instance ) BTW, probably it would be better to replace java.awt.Container with javax.swing.JComponent The idea is to start from the simplest thing that could possible work and evolve from there. Most of the times the problem is in some silly property we set and by cleaning up everything it came up. It should take less than 1 hr. for this.
Java GUI Problems
[ "", "java", "swing", "" ]
I have some extremely weird behavior that seems to result in silent exceptions. How can I write a general try catch where I can debug all exceptions. Something along the lines of: ``` try: # something that fails except e: print e ``` A bit more about the problem at hand in detail: I have a Django app that on my computer (Ubuntu Linux 8.10) works fine both through runserver and mod-python. On the deploy server (Ubuntu Linux 8.10) it works fine through runserver, but fails via apache in mod-python. I have reduced the cause down to a part off the app that uses Berkeley DB (bsddb.db), and secondary keys. The callback method for secondary keys uses pickle to format the keys. It fails when I call pickle on a single value. However, it only fails when I use cPickle, and using pickle on the same values outside the callback function also works. I just want to know why it fails with cPickle.
Exceptions are already printed by default before program termination. If you want to send the error somewhere else (not print it) you can do this: ``` try: something() except Exception as e: send_somewhere(traceback.format_exception(*sys.exc_info())) raise # reraises the exception ``` note that this format using the `as` keyword is for python > 2.6. The old way was: ``` except Exception, e: ```
The [traceback module](http://docs.python.org/library/traceback.html) is quite useful for formatting tracebacks. You can then write it to a logfile.
Generic catch for python
[ "", "python", "exception", "" ]
I need to implement something similar to [wikilinks](http://en.wikipedia.org/wiki/Help:Link#Wikilinks) on my site. The user is entering plain text and will enter [[asdf]] wherever there is an internal link. Only the first five examples are really applicable in the implementation I need. Would you use regex, what expression would do this? Is there a library out there somewhere that already does this in C#?
On the pure regexp side, the expression would rather be: ``` \[\[([^\]\|\r\n]+?)\|([^\]\|\r\n]+?)\]\]([^\] ]\S*) \[\[([^\]\|\r\n]+?)\]\]([^\] ]\S*) ``` By replacing the `(.+?)` [suggested by David](https://stackoverflow.com/questions/478857#478963) with `([^\]\|\r\n]+?)`, you ensure to only capture legitimate wiki links texts, without closing square brackets or newline characters. `([^\] ]\S+)` at the end ensures the wiki link expression is not followed by a closing square bracket either. I am note sure if there is C# libraries already implementing this kind of detection. However, to make that kind of detection really full-proof with regexp, you should use the [**pushdown automaton**](http://en.wikipedia.org/wiki/Pushdown_automaton) present in the C# regexp engine, as [illustrated here.](http://blog.stevenlevithan.com/archives/balancing-groups)
I don't know if there are existing libraries to do this, but if it were me I'd probably just use regexes: * match `\[\[(.+?)\|(.+?)\]\](\S+)` and replace with `<a href="\2">\1\3</a>` * match `\[\[(.+?)\]\](\S+)` and replace with `<a href="\1">\1\2</a>` Or something like that, anyway.
Wikilinks - turn the text [[a]] into an internal link
[ "", "c#", "regex", "wikipedia", "" ]
i have a table called category in which i have main category ids and names and each main category has sub category ids and names.i also have a product table with a category id column which either has a numeric sub category id or a 2 letter main category id eg:EL for electronics..my problem is how to get top categories ie., number of products in each category in descending order. ``` category { sub_cat_id - numeric sub_cat_name - varchar main_cat_id - varchar (2 characters) main_cat_name } products { categoryid,//this can be either main_cat_id or sub_cat_id } ``` pls help....
if there is no namespace clash between main category id and sub category id, you could : ``` select main_cat_id , count(*) as total from category where ( main_cat_id in (select categoryid from products) OR sub_cat_id in (select categoryid from products) ) group by main_cat_id order by total desc ``` however , prima facie there seems to be a problem with the design of the category table. sub\_cat should be a different table with appropriate constraints.
Seems like it should be straight-forward, can you post the "CREATE TABLE" statements and a few sample rows (I wasn't able to "reverse engineer" the "CREATE TABLE" from your syntax above...)
mysql query to get the count of each element in a column
[ "", "sql", "mysql", "" ]
I'm trying to convert a date string into an age. The string is like: "Mon, 17 Nov 2008 01:45:32 +0200" and I need to work out how many days old it is. I have sucessfully converted the date using: ``` >>> time.strptime("Mon, 17 Nov 2008 01:45:32 +0200","%a, %d %b %Y %H:%M:%S +0200") (2008, 11, 17, 1, 45, 32, 0, 322, -1) ``` For some reason %z gives me an error for the +0200 but it doesn't matter that much. I can get the current time using: ``` >>> time.localtime() (2009, 2, 3, 19, 55, 32, 1, 34, 0) ``` but how can I subtract one from the other without going though each item in the list and doing it manually?
You need to use the module `datetime` and the object [`datetime.timedelta`](http://docs.python.org/library/datetime.html#datetime.timedelta) ``` from datetime import datetime t1 = datetime.strptime("Mon, 17 Nov 2008 01:45:32 +0200","%a, %d %b %Y %H:%M:%S +0200") t2 = datetime.now() tdelta = t2 - t1 # actually a datetime.timedelta object print tdelta.days ```
In Python, `datetime` objects natively support subtraction: ``` from datetime import datetime age = datetime.now() - datetime.strptime(...) print age.days ``` The result is a [timedelta](http://docs.python.org/library/datetime.html#datetime.timedelta) object.
Python time to age
[ "", "python", "datetime", "" ]
**UPDATE:** Rephrasing the question to ask, 'are there too many' static methods (I realize that right now there are only 4 but I originally started with 2) in this class structure? If so, any suggestions on how to refactor these classes to use some sort of Finder class so that I can remove the static functions from the Model classes? I have the following abstract class: ``` abstract class LP_Model_Abstract { protected static $_collectionClass = 'LP_Model_Collection'; protected $_row = null; protected $_data = array(); public function __construct($row = null) { $this->_row = $row; } public function __get($key) { if(method_exists($this, '_get' . ucfirst($key))) { $method = '_get' . ucfirst($key); return $this->$method(); } elseif(isset($this->_row->$key)) { return $this->_row->$key; } else { foreach($this->_data as $gateway) { if(isset($gateway->$key)) { return $gateway->$key; } } } } public function __set($key, $val) { if(method_exists($this, '_set' . ucfirst($key))) { $method = '_set' . ucfirst($key); return $this->$method($val); } elseif(isset($this->_row->$key)) { $this->_row->$key = $val; return $this->_row->$key; } else { foreach($this->_data as $gateway) { if(isset($this->_data[$gateway]->$key)) { $this->_data[$gateway]->$key = $val; return $this->_data[$gateway]->$key; } } } } public function __isset($key) { return isset($this->_row->$key); } public function save() { $this->_row->save(); } abstract public static function get($params); abstract public static function getCollection($params = null); abstract public static function create($params); ``` } And then this class which provides additional functionality for class table inheritance schemes (where type is important in determining additional functionality in a factory fashion): ``` abstract class LP_Model_Factory_Abstract extends LP_Model_Abstract { protected static $_collectionClass = 'LP_Model_Collection_Factory'; abstract public static function factory($row); } ``` These ultimately result in the following type of class declaration: ``` class Model_Artifact extends LP_Model_Factory_Abstract { protected static $_artifactGateway = 'Model_Table_Artifact'; public static function create($params) { } public static function get($params) { $gateway = new self::$_artifactGateway(); $row = $gateway->fetchArtifact($params); return self::factory($row); } public static function getCollection($params = null) { $gateway = new self::$_artifactGateway(); $rowset = $gateway->fetchArtifacts($params); $data = array( 'data' => $rowset, 'modelClass' => __CLASS__ ); return new self::$_collectionClass($data); } public static function factory($row) { $class = 'Model_Artifact_' . $row->fileType; } } ``` When do you know that you have too many static methods in a class? And how would you refactor the existing design so that the static methods are perhaps encapsulated in some sort of Finder class?
Personally I find that any number of static methods are a sign of trouble. If your class has instance methods and static methods, then most likely you could split the class into two separate entities and change the static methods to instance methods. Think of a class as a special kind of object, with the distinctive property that it is global by nature. Since it's a global variable, it implies a very strong level of coupling, so you would want to reduce any references to it. Static members will need to be referred, meaning that your code will get a strong level of coupling to the class.
I'd have to agree with Brubaker and add that to my thinking it isn't the number of methods so much as the functionality of said methods. If you start thinking that your class has to many methods (static or otherwise) then you might find they can be re-grouped and refactored into a more intuitive architecture.
How Many Static Methods is Too Many For One Class?
[ "", "php", "oop", "static", "" ]
I'm looking for a way to insert a `<style>` tag into an HTML page with JavaScript. The best way I found so far: ``` var divNode = document.createElement("div"); divNode.innerHTML = "<br><style>h1 { background: red; }</style>"; document.body.appendChild(divNode); ``` This works in Firefox, Opera and Internet Explorer but not in Google Chrome. Also it's a bit ugly with the `<br>` in front for IE. Does anyone know of a way to create a `<style>` tag that 1. Is nicer 2. Works with Chrome? Or maybe 1. This is a non-standard thing I should avoid 2. Three working browsers are great and who uses Chrome anyway?
Try adding the `style` element to the `head` rather than the `body`. This was tested in IE (7-9), Firefox, Opera and Chrome: ``` var css = 'h1 { background: red; }', head = document.head || document.getElementsByTagName('head')[0], style = document.createElement('style'); head.appendChild(style); style.type = 'text/css'; if (style.styleSheet){ // This is required for IE8 and below. style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } ```
`<style>` tags should be placed within the `<head>` element, and each added tag should be added to the bottom of the `<head>` tag. Using [insertAdjacentHTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML) to inject a style tag into the document [head tag](https://developer.mozilla.org/en-US/docs/Glossary/Head): ### Native DOM: ``` document.head.insertAdjacentHTML("beforeend", `<style>body{background:red}</style>`) ``` --- ### jQuery: ``` $('<style>').text("body{background:red}").appendTo(document.head) ``` ``` <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> ```
How to create a <style> tag with Javascript?
[ "", "javascript", "html", "css", "" ]
Had a coworker ask me this, and in my brain befuddled state I didn't have an answer: Why is it that you can do: ``` string ham = "ham " + 4; ``` But not: ``` string ham = 4; ``` If there's an implicit cast/operation for string conversion when you are *concatenating*, why not the same when *assigning* it as a string? (Without doing some operator overloading, of course)
When concatenating the compiler turns the statement `"ham" + 4` into a call to `String.Concat`, which takes two `object` parameters, so the value `4` is boxed and then `ToString` is called on that. For the assignment there is no implicit conversion from `int` to `string`, and thus you cannot assign `4` to a `string` without explicitly converting it. In other words the two assignments are handled very differently by the compiler, despite the fact that they look very similar in C#.
> Binary + operators are predefined for > numeric and string types. For numeric > types, + computes the sum of its two > operands. When one or both operands > are of type string, + concatenates the > string representations of the > operands. [Reference](http://msdn.microsoft.com/en-us/library/k1a63xkz.aspx) > The assignment operator (=) stores the > value of its right-hand operand in the > storage location, property, or indexer > denoted by its left-hand operand and > returns the value as its result. The > operands must be of the same type (or > the right-hand operand must be > implicitly convertible to the type of > the left-hand operand). [Reference](http://msdn.microsoft.com/en-us/library/sbkb459w.aspx)
Strings and ints, implicit and explicit
[ "", "c#", "string", "int", "implicit", "explicit", "" ]
I have a server application that uses "a lot" of threads. Without wanting to get into an argument about how many threads it really should be using, it would be nice to be able to see some descriptive text in the debugger "threads" window describing what each one is, without having to click through to it and determine from the context what it is. They all have the same start address so generally the threads window says something like "thread\_base::start" or something similar. I'd like to know if there is an API call or something that allows me to customise that text.
Use [SetThreadName](http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.71).aspx)
Here is the code I use. This goes in a header file. ``` #pragma once #define MS_VC_EXCEPTION 0x406d1388 #pragma warning(disable: 6312) #pragma warning(disable: 6322) typedef struct tagTHREADNAME_INFO { DWORD dwType; // must be 0x1000 LPCSTR szName; // pointer to name (in same addr space) DWORD dwThreadID; // thread ID (-1 caller thread) DWORD dwFlags; // reserved for future use, most be zero } THREADNAME_INFO; inline void SetThreadName(DWORD dwThreadID, LPCSTR szThreadName) { #ifdef _DEBUG THREADNAME_INFO info; info.dwType = 0x1000; info.szName = szThreadName; info.dwThreadID = dwThreadID; info.dwFlags = 0; __try { RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(DWORD), (DWORD *)&info); } __except (EXCEPTION_CONTINUE_EXECUTION) { } #else dwThreadID; szThreadName; #endif } ``` Then I call it like this inside the threads proc. ``` SetThreadName(GetCurrentThreadId(), "VideoSource Thread"); ``` It is worth noting that this is the exact code that David posted a link to (Thanks! I had forgotten where I got it). I didn't delete this post because I'd like the code to still be available if MSDN decides to reorganize its links (again).
How to change the name of a thread
[ "", "c++", "multithreading", "winapi", "" ]
I have some JS code which generates the following object, ``` return { "type": "some thing", "width": 2, "colour": "#AA12BB", "values": [2,3,4] } ``` The creation of this isn't a problem. In writing the test for the method that returns this am having a problem accessing the width/type attributes: the following assertions fail (it leads to a execution/syntax error, which go away when i comment them). ``` assertEquals('some thing', jsonObj.type); assertEquals(2, jsonObj.width); ``` while ``` assertEquals('#AA12BB', jsonObj.colour); ``` passes Since I cannot change the key names for what I am doing, is there any way to access these values?
Try this: ``` assertEquals('some thing', jsonObj["type"]); assertEquals(2, jsonObj["width"]); ```
Your example works fine for me. ‘width’ and ‘type’ are *not* reserved words in JavaScript (although ‘typeof’ is).
Javascript reserved words?
[ "", "javascript", "" ]
If I am setting the Text property of a Form from a non-UI thread, then I need to use Invoke to avoid a cross-thread error. But, I can read the Text property without using Invoke. Is this safe? If I try to read the Handle property of a Form I get a cross-threading error. If I read the IsDisposed property of a Form it works fine. How can I tell when I need to use Invoke? Should I **always** be using Invoke to read and write property values?
Whenever you are in a thread other from the UI thread you should use [`Invoke`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invoke.aspx) when accessing UI objects. Use [`InvokeRequired`](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx) property to find out if you are in fact, in a different thread.
The easiest way is to use: ``` Delegate Sub SetTextCallback(ByVal [text] As String) Private Sub SetText(ByVal [text] As String) ' InvokeRequired required compares the thread ID of the ' calling thread to the thread ID of the creating thread. ' If these threads are different, it returns true. If Me.lboxResults.InvokeRequired Then Dim d As New SetTextCallback(AddressOf SetText) Me.Invoke(d, New Object() {[text]}) Else Me.lboxResults.Items.Add([text]) End If ``` End Sub Sorry for the VB Code...
How to tell if Invoke is required for a property?
[ "", "c#", "multithreading", "invoke", "" ]
C# has syntax for declaring and using properties. For example, one can declare a simple property, like this: ``` public int Size { get; set; } ``` One can also put a bit of logic into the property, like this: ``` public string SizeHex { get { return String.Format("{0:X}", Size); } set { Size = int.Parse(value, NumberStyles.HexNumber); } } ``` Regardless of whether it has logic or not, a property is used in the same way as a field: ``` int fileSize = myFile.Size; ``` I'm no stranger to either Java or C# -- I've used both quite a lot and I've always missed having property syntax in Java. I've read in [this question](https://stackoverflow.com/questions/36701/struct-like-objects-in-java) that "it's highly unlikely that property support will be added in Java 7 or perhaps ever", but frankly I find it too much work to dig around in discussions, forums, blogs, comments and JSRs to find out why. So my question is: can anyone sum up why Java isn't likely to get property syntax? * Is it because it's not deemed important enough when compared to other possible improvements? * Are there technical (e.g. JVM-related) limitations? * Is it a matter of politics? (e.g. *"I've been coding in Java for 50 years now and I say we don't need no steenkin' properties!"*) * Is it a case of [bikeshedding](http://en.wikipedia.org/wiki/Parkinson%27s_Law_of_Triviality)?
I think it's just Java's general philosophy towards things. Properties are somewhat "magical", and Java's philosophy is to keep the core language as simple as possible and avoid magic like the plague. This enables Java to be a *lingua franca* that can be understood by just about any programmer. It also makes it very easy to reason about what an arbitrary isolated piece of code is doing, and enables better tool support. The downside is that it makes the language more verbose and less expressive. This is not necessarily the right way or the wrong way to design a language, it's just a tradeoff.
For 10 years or so, sun has resisted any significant changes to the language as hard as they could. In the same period C# has been trough a riveting development, adding a host of new cool features with every release. I think the train left on properties in java a long time ago, they would have been nice, but we have the java-bean specification. Adding properties now would just make the language even more confusing. While the javabean specification IMO is nowhere near as good, it'll have to do. And in the grander scheme of things I think properties are not really that relevant. The bloat in java code is caused by other things than getters and setters. There are far more important things to focus on, such as getting a decent closure standard.
Absence of property syntax in Java
[ "", "java", "syntax", "properties", "" ]
Let me preface by saying I am not knocking .Net (it helps me earn my living)... I recently heard of a site were the developer/owner bragged that he had minimal hardware to support his site (plentyoffish.com). This site is listed as being in the top 50 in terms of traffic on Alexa. I am struggling to wrap my head around how something like that can be acomplished by doing what the developer/owner claims, a single developer writing a site (it took him 2 weeks to get the intial site up) using minimal hardware that gets 2 million hits per hour (peak). Larger companies have huge web farms to handle traffic like that... How do you write code so efficient, with limited hardware resources (he claims he uses only three DB servers)? Has anyone worked on or developed a site that efficient?
The Microsoft stack is remarkably fast if you avoid all the drag/drop garbage that gives ASP.NET a bad name. * IIS is a good web server. * SQL Server is a good database. * C# compiles to fast code. (qualifications probably needed here :) * ASP.NET can be quite lightweight if you use it correctly That's the whole stack. It's all good. You can say what you like about Microsoft, its business practices and its consumer products, but their development tools and servers are top notch. My personal experience with their web stack includes a site that sees ~500 pageviews/second and seldom spikes the server above 15%. That's fast enough for most operations.
It's more than just the code: doing something like this requires a cooperative effort from developers, DBAs and IT. Each member of the team has to recognize the impact that their work has on the other areas of the team. When a developer writes a query that does a table scan on a heavy OLTP system, he has to understand why it won't scale. When the DBA sees a table scan, he has to understand how to fix it at the database level or at the code level. When the sysadmin sees heavy read activity on the drives, he has to understand the underlying causes of it (things like table scans) in order to decide whether to fix it with better code or throwing more drives at it. Well-performing systems are the result of each person doing a great job, AND communicating really well with the other team members. If just one member of the team is out to throw everybody else under the bus, the system won't perform. And it sounds like you're already doing it by throwing .NET and SQL Server under the bus. ;-)
Writing efficient .Net/SQL Server code
[ "", "c#", "asp.net", "sql-server", "performance", "" ]
Alright, I'm trying to get arguments to work properly with a small test application. My code is below. I'm not too experienced at C++, so I'm not sure why when I launch test with -print (or --print) it automatically states "Not a valid option" and then finishes up. ``` #include <iostream> int main(int argc, char* argv[]) { int option; option = 1; char* argument; argument = argv[option]; while (option < argc) { if (argument == "-print") { std::cout << "Printing Extra Text"; } else { std::cout << "Not a valid option" << std::endl; } option++; } std::cout << "Printing normal text" << std::endl; return 0; } ``` Am I doing this right? Thanks in advance.
You're comparing the memory address of the string "-print" to the memory address of `argument`. This won't work! Use `strcmp()` to compare string values. Instead of: ``` if (argument == "-print") ``` do ``` if (strcmp(argument, "-print") == 0) ```
The following line is at fault: ``` if (argument == "-print") ``` Here you're comparing pointers, not string values. Replace with: ``` if (strcmp(argument, "-print") == 0) ``` C/C++ behave differently than Java or C# regarding string handling. Strings are not a native type or object but just glorified pointers to arrays of chars. Alternatively, and if your option list becomes more complicated, consider using a dedicated option parsing library such as [Boost](http://www.boost.org/)'s [Program\_options](http://www.boost.org/doc/libs/1_37_0/doc/html/program_options.html). It will handle all the aspects including validation and user messages.
Commandline arguments not working - Skips over them completely
[ "", "c++", "command-line", "arguments", "" ]
I need to program kind of configuration registry for Django-based application. Requirements: 1. Most likely `param_name` : `param_value` structure 2. Editable via admin interface 3. Has to work with syncdb. How to deal with a situation in which other apps depend on configuration model and the model itself has not been initialized yet in DB? Let's say I would like to have configurable model fields properties, i.e. the default value setting? Any ideas or suggestions would be appreciated.
I have found [djblets.siteconfig](http://www.chipx86.com/blog/?p=261) very useful. Works great with the Admin app, and very easy to use. Highly recommended.
Once a while (year ago) I used [dbsettings](http://code.google.com/p/django-values/) to have some sort of business configuration accessible via admin interface, but I cann't say how it fits today.
What is the best approach to implement configuration app with Django?
[ "", "python", "django", "configuration", "django-models", "django-admin", "" ]
I was looking for a solution for client side printing of reports and pre formatted forms from a PHP web based app. Note that these are not printing of HTML pages. Rather nicely aligned fixed formated Receipts, Order Forms, Ledger etc. Something that I have though of. Using PDF: Is there a simple one click way to print the report from client side? The obvious choice of opening the PDF in a window, then select File -> Print seems too cumbersome. Using Flash: I saw some site providing single click printing through flash. Not sure what's working in the background. Any insight on this regard will be helpful. Active-X/Silverlight(?): I won’t want to constraint my users on IE only. But this one-click printing requirement is so rigid that I would rather switch to MS only platforms if it achieves the task. Note that it’s ok for the single click to bring up the print dialog box and user clicking a second time for printing. But any more complexity than that is a disadvantage.
If the format is so rigid you need a format like PDF. HTML/CSS is so variable you'll never get it the same on all browsers. Plug Web pages have no real concept of pages (although there is some support for things like CSS print media styling). Also not all people actually have a printer. Trying to force something to be printed is really the wrong approach and will generally put some of your customers off. The minimal solution is to create a receipt page with the emdia print CSS to make it appear responable most of the time. If that's not enough you need to go PDF. Unfortunately that then becomes hard as [this question regarding HTML+CSS to PDF conversion illustrates](https://stackoverflow.com/questions/391005/convert-html-css-to-pdf-with-php#434391). [PrinceXML](http://www.princexml.com/) does an outstanding job at this conversion but it's not cheap. [Html2PDF](http://www.tufat.com/s_html2ps_html2pdf.htm) is the best of the open source bunch but has issues (see that answer for more detail). I've had this same problem in the Java space and for invoices there ending up using [Jasper Reports](http://jasperforge.org/plugins/project/project_home.php?group_id=102). I haven't really seen an equivalent reporting solution for PHP though. Python has [reportlab](http://www.reportlab.org/rl_toolkit.html), which seems a likely candidate for doing that kind of job too. Perhaps your best option is to generate the PDF directly. It's a bit more tedious but it avoids the many pitfalls of HTML to PDF conversion. [This tutorial](http://devzone.zend.com/article/1254-PDF-Generation-Using-Only-PHP---Part-1) ([Part 2](http://devzone.zend.com/article/1255-PDF-Generation-Using-Only-PHP---Part-2)) explains how.
``` <a href = "#" onclick = "window.print(); return false;">Print!</a> ```
Client side report printing from PHP web apps
[ "", "php", "flash", "pdf", "printing", "reporting", "" ]
I've heard many people say that if the number of expected elements in the container is relatively small, it is better to use `std::vector` instead of `std::map` even if you were to use the container for lookups only and not iterating. What is the real reason behind this? Obviously the lookup performance of `std::map` cannot be worse than `std::vector` (although it may differ in nanoseconds/microseconds) so does it have something to do with memory usage? Does `std::vector` fare any better/worse than `std::map` in fragmenting the virtual address space? I am using the STL library that comes along with Visual Studio (i.e. Microsoft's implementation). Does that make any difference compared to other implementations?
I presume you're comparing `map<A, B>` with `vector<pair<A, B> >`. Firstly, finding an item in a very small vector can easily be faster than the same thing in a map, because all the memory in a vector is always contiguous (and so plays more nicely with computers' caches and such things), and the number of comparisons needed to find something in a vector might be about the same as for a map. Finding an element in a map needs fewer operations in the limit of very large containers. The point where maps become faster than vectors depends on the implementation, on your processor, what data is in the map, and subtle things like what memory is in the processor's cache. Typically, the point where map becomes faster would be about 5-30 elements. An alternative is to use a hash container. They are often named `hash_map` or `unordered_map`. Classes named `hash_map` are not part of the official standard (and there are a few variants out there); `std::tr1::unordered_map` is. A hash map is often faster than a normal map for lookups, regardless of how many elements are in it, but whether it is actually faster depends on what the key is, how it is hashed, what values you have to deal with, and how the key is compared in std::map. It doesn't keep things in a specific order like std::map, but you've said that you don't care about that. I'd recommend hash maps particularly if the keys are integers or pointers, because these hash very quickly.
"By default, use vector when you need a container" - Bjarne Stroustrup. Otherwise, I find this little flow chart to be of very good help (**edited** - probably a valid live new link): <https://ngoduyhoa.blogspot.com/2015/06/summary-of-different-containers.html>
vector or map, which one to use?
[ "", "c++", "performance", "stl", "" ]
Does anyone have a simple and successful demo implementation of facebook connect in an asp.net application. I am developing an asp.net web application and want facebook connect to be the primary method for logging in.
I was having troubles as well, but found that [this stackoverflow question](https://stackoverflow.com/questions/323019/facebook-connect-and-asp-net) got me on the right track as far as the server side stuff is concerned However, First you have to get the facebook connect button working from here [Facebook Wiki](http://wiki.developers.facebook.com/index.php/Logging_In_And_Connecting) Then detect if they are logged in or not and redirect them appropriately to a welcome page. [Detect login via Javascript](http://wiki.developers.facebook.com/index.php/Detecting_Connect_Status) Most other actions can be done via serverside with the Facebook ToolKit. (eg get their information, friends, etc..) The last thing I think I should mention is logging the user out, so take a look at this. [Facebook Wiki: Logout](http://wiki.developers.facebook.com/index.php/Logging_Out_And_Disconnecting) Hope this helps
As I see, all the above examples and links are really outdated. The new Facebook Graph API makes the whole process a lot easier, without the need for any other components: <http://area72.ro/general-it/how-to-login-via-facebook-in-asp-net.html>
Simple Facebook Connect Demo in ASP.NET
[ "", "c#", "asp.net", "openid", "facebook", "" ]
i'm currently experiencing a little problem. I'm using nhibernate with around 40 entities mapped to a sql server database. however, due to performance reasons some operations are done via stored procedure. i have a stored procedure that takes 3 parameters. one entity ID and 2 DateTime's. now, when i have a Date like the 10th of Dezember 2008, Nhibernate makes ``` '10.12.2008 00:00:00.000' ``` out of it. (German Culture) But Sql Server 2008 doesn't interpret it correctly as it swaps Day and Month. When i manually change the datetime text to ``` '2008-12-10 00:00:00.000' ``` i didn't encounter this problem when using the session in a "normal" way or when using NHibernate.linq. just when using a sql-query to execute the stored procedure. is there a way to manually overcome the way NHibernate transforms DateTime objects to their textual representation?
NHibernate shouldn't be transforming DateTimes into their textual representation at all, IMO - it should be asking the database driver to pass that DateTime along in whatever form it wants to. Is your stored procedure declared to receive the parameter *as* DateTimes (or whatever the SQL type is) or varchar? If if's declared as receiving a DateTime and NHibernate knows that, then it *should* just be using parameterised call as normal.
i pass the datetimes with .SetDateTime(name,datetimeValue) to the IQuery, therefore i thought nhibernate should take care of it. the stored procedure expects DateTime parameters. i just saw this textual representation when i turned show\_sql on
Nhibernate Datetime issues
[ "", "c#", "sql-server", "nhibernate", "" ]
I have a series of Python classes in a file. Some classes reference others. My code is something like this: ``` class A(): pass class B(): c = C() class C(): pass ``` Trying to run that, I get `NameError: name 'C' is not defined`. Fair enough, but is there any way to make it work, or do I have to manually re-order my classes to accommodate? In C++, I can create a class prototype. Does Python have an equivalent? (I'm actually playing with Django models, but I tried not complicate matters).
In Python you don't create a prototype per se, but you do need to understand the difference between "class attributes" and instance-level attributes. In the example you've shown above, you are declaring a class attribute on class B, not an instance-level attribute. This is what you are looking for: ``` class B(): def __init__(self): self.c = C() ```
Actually, all of the above are great observations about Python, but none of them will solve your problem. Django needs to introspect stuff. The *right* way to do what you want is the following: ``` class Car(models.Model): manufacturer = models.ForeignKey('Manufacturer') # ... class Manufacturer(models.Model): # ... ``` Note the use of the class name as a *string* rather than the literal class reference. Django offers this alternative to deal with exactly the problem that Python doesn't provide forward declarations. This question reminds me of the classic support question that you should always ask any customer with an issue: "What are you *really* trying to do?"
Does Python have class prototypes (or forward declarations)?
[ "", "python", "class", "oop", "prototype", "" ]
I have a Foo object, and a std::list holding instances of it. My problem is that when I add a new instance to the list, it first calls the ctor but then also the dtor. And then the dtor on another instance (according to the this pointer). A single instance is added to the list but since its dtor (along with its parents) is called, the object cant be used as expected. Heres some simplified code to illustrate the problem: ``` #include <iostream> #include <list> class Foo { public: Foo() { int breakpoint = 0; } ~Foo() { int breakpoint = 0; } }; int main() { std::list<Foo> li; li.push_back(Foo()); } ```
When you push\_back() your Foo object, the object is **copied** to the list's internal data structures, therefore the Dtor and the Ctor of another instance are called. All standard STL container types in C++ take their items by value, therefore copying them as needed. For example, whenever a vector needs to grow, it is possible that all values in the vector get copied. Maybe you want to store **pointers** instead of objects in the list. By doing that, only the pointers get copied instead of the object. But, by doing so, you have to make sure to delete the objects once you are done: ``` for (std::list<Foo*>::iterator it = list.begin(); it != list.end(); ++it) { delete *it; } list.clear(); ``` Alternatively, you can try to use some kind of 'smart pointer' class, for example from the Boost libraries.
You are creating a temporary Foo here: ``` li.push_back( Foo() ) ``` push\_back copies that Foo into its internal data structures. The temporary Foo is destroyed after push\_back has been executed, which will call the destructor. You will need a proper copy constructor that increases some reference count on the class members that you do not want to destroy early -- or make it private to force yourself on the pointer solution.
Destructor called on object when adding it to std::list
[ "", "c++", "constructor", "stdlist", "" ]
A DBA that my company hired to troubleshoot deadlock issues just told me that our OLTP databases locking problems will improve if we set the transaction level to READ COMMITTED from READ UNCOMMITTED. Isn't that just 100% false? READ COMMITTED will cause more locks, correct? --- More Details: Our data is very "siloed" and user specific. 99.9999999 % of all user interactions work with your own data and our dirty read scenarios, if they happen, can barely effect what the user is trying to do. --- Thanks for all the answers, the dba in question ended up being useless, and we fixed the locking issues by adding a single index. --- I regret that I didn't specify the locking problems were occurring for update statements and not regular selects. From my googing the two different query types have distinct solutions when dealing with locking issues.
That does sound like a bit of a rash decision, however without all the details of your environment it is difficult to say. You should advise your DBA to consider the use of SQL Server's advanced isolation features, i.e. the use of Row Versioning techniques. This was introduced to SQL Server 2005 to specifically address issues with OLTP database that experience high locking. The following white paper contains quite complicated subject matter but it is a must read for all exceptional DBA's. It includes example of how to use each of the additional isolation levels, in different types of environments i.e. OLTP, Offloaded Reporting Environment etc. <http://msdn.microsoft.com/en-us/library/ms345124.aspx> In summary it would be both foolish and rash to modify the transaction isolation for all of your T-SQL queries without first developing a solid understanding of how the excessive locking is occuring within your environment. I hope this helps but please let me know if you require further clarification. Cheers!
It the data is siloed and you are still getting deadlocks then you may simply need to add rowlock hints to the queries that are causing the problem so that the locks are taken at the row level and not the page level (which is the default). READ UNCOMMITTED will reduce the number of locks if you are locking data because of SELECT statements. If you are locking data because of INSERT, UPDATE and DELETE statements then changing the isolation level to READ UNCOMMITTED won't do anything for you. READ UNCOMMITTED has the same effect as adding WITH (NOLOCK) to your queries.
Sql 2005 Locking for OLTP - Committed or Uncommitted?
[ "", "sql", "sql-server-2005", "locking", "deadlock", "" ]
I've been playing with jquery and I've run myself into a time problem. I've got 3 time input select boxes, one for hours, one for minutes, and one for the Meridian. I need to convert this time into a 24 hour string format and then stick it into a hidden input. ``` var time = ""; time += $("#EventCloseTimeHour option:selected").text(); time += ":" + $("#EventCloseTimeMin option:selected").text() + ":00"; time += " " + $("#EventCloseTimeMeridian option:selected").text(); $("#ConditionValue").val(time); ``` This gives me "1:30:00 pm" where I need "13:30:00". Any quick javascript time tips?
Example of [tj111](https://stackoverflow.com/users/12605/) suggestion: ``` $("#ConditionValue").val( ( new Date( "01/01/2000 " + $("#EventCloseTimeHour option:selected").text() + $("#EventCloseTimeMin option:selected").text() + ":00" + " " + $("#EventCloseTimeMeridian option:selected").text() ) ).toTimeString().slice(0,8)) ; ``` Or you can use: ``` hour = hour %12 + (meridian === "AM"? 0 : 12); hour = hour < 10 ? "0" + hour : hour; ```
You should look into the native [JavaScript Date Object](http://www.w3schools.com/jsref/jsref_obj_date.asp) methods.
What's a simple way to convert between an am/pm time to 24 hour time in javascript
[ "", "javascript", "jquery", "time", "" ]
How do I remove duplicates from a list, while preserving order? Using a set to remove duplicates destroys the original order. Is there a built-in or a Pythonic idiom?
Here you have some alternatives: <http://www.peterbe.com/plog/uniqifiers-benchmark> Fastest one: ``` def f7(seq): seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] ``` Why assign `seen.add` to `seen_add` instead of just calling `seen.add`? Python is a dynamic language, and resolving `seen.add` each iteration is more costly than resolving a local variable. `seen.add` could have changed between iterations, and the runtime isn't smart enough to rule that out. To play it safe, it has to check the object each time. If you plan on using this function a lot on the same dataset, perhaps you would be better off with an ordered set: <http://code.activestate.com/recipes/528878/> *O*(1) insertion, deletion and member-check per operation. (Small additional note: `seen.add()` always returns `None`, so the *`or`* above is there only as a way to attempt a set update, and not as an integral part of the logical test.)
The best solution varies by Python version and environment constraints: #### Python 3.7+ (and most interpreters supporting 3.6, as an implementation detail): First introduced in PyPy 2.5.0, and adopted in CPython 3.6 as an implementation detail, before being made a language guarantee in Python 3.7, plain `dict` is insertion-ordered, and even more efficient than the (also C implemented as of CPython 3.5) `collections.OrderedDict`. So the fastest solution, by far, is also the simplest: ``` >>> items = [1, 2, 0, 1, 3, 2] >>> list(dict.fromkeys(items)) # Or [*dict.fromkeys(items)] if you prefer [1, 2, 0, 3] ``` Like `list(set(items))` this pushes all the work to the C layer (on CPython), but since `dict`s are insertion ordered, `dict.fromkeys` doesn't lose ordering. It's slower than `list(set(items))` (takes 50-100% longer typically), but *much* faster than any other order-preserving solution (takes about half the time of [hacks involving use of `set`s in a listcomp](https://stackoverflow.com/a/480227/364696)). **Important note**: The `unique_everseen` solution from `more_itertools` (see below) has some unique advantages in terms of laziness and support for non-hashable input items; if you need these features, it's the *only* solution that will work. #### Python 3.5 (and all older versions if performance isn't *critical*) As Raymond [pointed out](https://stackoverflow.com/a/39835527/336527), in CPython 3.5 where `OrderedDict` is implemented in C, ugly list comprehension hacks are slower than `OrderedDict.fromkeys` (unless you actually need the list at the end - and even then, only if the input is very short). So on both performance and readability the best solution for CPython 3.5 is the `OrderedDict` equivalent of the 3.6+ use of plain `dict`: ``` >>> from collections import OrderedDict >>> items = [1, 2, 0, 1, 3, 2] >>> list(OrderedDict.fromkeys(items)) [1, 2, 0, 3] ``` On CPython 3.4 and earlier, this will be slower than some other solutions, so if profiling shows you need a better solution, keep reading. #### Python 3.4 and earlier, if performance is critical and third-party modules are acceptable As [@abarnert](https://stackoverflow.com/a/19279812/1219006) notes, the [`more_itertools`](https://more-itertools.readthedocs.io/en/stable/api.html) library (`pip install more_itertools`) contains a [`unique_everseen`](https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.unique_everseen) function that is built to solve this problem without any **unreadable** (`not seen.add`) **mutations** in list comprehensions. This is the fastest solution too: ``` >>> from more_itertools import unique_everseen >>> items = [1, 2, 0, 1, 3, 2] >>> list(unique_everseen(items)) [1, 2, 0, 3] ``` Just one simple library import and no hacks. The module is adapting the itertools recipe [`unique_everseen`](https://docs.python.org/3/library/itertools.html#itertools-recipes) which looks like: ``` def unique_everseen(iterable, key=None): "List unique elements, preserving order. Remember all elements ever seen." # unique_everseen('AAAABBBCCDAABBB') --> A B C D # unique_everseen('ABBCcAD', str.lower) --> A B C D seen = set() seen_add = seen.add if key is None: for element in filterfalse(seen.__contains__, iterable): seen_add(element) yield element else: for element in iterable: k = key(element) if k not in seen: seen_add(k) yield element ``` but unlike the `itertools` recipe, it supports non-hashable items (at a performance cost; if all elements in `iterable` are non-hashable, the algorithm becomes `O(n²)`, vs. `O(n)` if they're all hashable). **Important note**: Unlike all the other solutions here, `unique_everseen` can be used lazily; the peak memory usage will be the same (eventually, the underlying `set` grows to the same size), but if you don't `list`ify the result, you just iterate it, you'll be able to process unique items as they're found, rather than waiting until the entire input has been deduplicated before processing the first unique item. #### Python 3.4 and earlier, if performance is critical *and* third party modules are unavailable You have two options: 1. Copy and paste in [the `unique_everseen` recipe](https://docs.python.org/3/library/itertools.html#itertools-recipes) to your code and use it per the `more_itertools` example above 2. Use ugly hacks to allow a single listcomp to both check and update a `set` to track what's been seen: ``` seen = set() [x for x in seq if x not in seen and not seen.add(x)] ``` at the expense of relying on the **ugly hack**: ``` not seen.add(x) ``` which relies on the fact that `set.add` is an in-place method that always returns `None` so `not None` evaluates to `True`. Note that *all* of the solutions above are `O(n)` (save calling `unique_everseen` on an iterable of non-hashable items, which is `O(n²)`, while the others would fail immediately with a `TypeError`), so all solutions are performant enough when they're not the hottest code path. Which one to use depends on which versions of the language spec/interpreter/third-party modules you can rely on, whether or not performance is critical (don't assume it is; it usually isn't), and most importantly, readability (because if the person who maintains this code later ends up in a murderous mood, your clever micro-optimization probably wasn't worth it).
How do I remove duplicates from a list, while preserving order?
[ "", "python", "list", "duplicates", "list-comprehension", "unique", "" ]
I have an unordered list like this one: ``` <a href="#" id="myList-toggle">Show the rest</a> <ul id="myList"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> <li>Item 6</li> <li>Item 7</li> <li>Item 8</li> <li>Item 9</li> <li>Item 10</li> </ul> ``` and this jQuery code: ``` var list = $('#myList li:gt(4)'); list.hide(); $('a#myList-toggle').click(function() { list.slideToggle(400); return false; }); ``` The problem is that it slides each individual li item, i need to slide the rest of the list, like i would slide the whole list. How can I do that?
Pretty clumsy solution IMHO, but if it works for you - it works for you... For the list to collapse and expand by clicking on the same link: ``` $(document).ready(function() { var list = $('ul#myList'); var original_height = list.height(); var new_height = $('#myList li').height()*5; list.css({height:new_height}); $('a#myList-toggle').click(function() { if( list.height() == original_height ) { list.animate({height:new_height}); } else { list.animate({height:original_height}); } return false; }); }); ```
your method didn't work because it would find the height with height: auto. After a lot of fail and try, I came up with something that works, almost. Do you have any comment on my code, I would really appreciate it. And how would I do it, if I want the same link to collapse the list again ``` <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var list = $('ul#myList'); var original_height = list.height(); list.css({height:$('#myList li').height()*5}); $('a#myList-toggle').click(function() { list.animate({height:original_height}) return false; }); }); </script> <style type="text/css"> ul#myList { overflow: hidden; } </style> </head> <body> <a href="#" id="myList-toggle">Show the rest</a> <ul id="myList"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> <li>Item 6</li> <li>Item 7</li> <li>Item 8</li> <li>Item 9</li> <li>Item 10</li> </ul> </body> </html> ```
Expand list with slideToggle
[ "", "javascript", "jquery", "html", "" ]
On our embedded device, we currently use PHP for its web interface, and unfortunately it's quite slow. We've been experimenting with Python, but is seems (at least on FPU-less ARM architecture) to be as slow as PHP. Therefore we're thinking about implementing web interface in some compiled language like C++, but so far the only thing we've found is [Wt](http://www.webtoolkit.eu/wt), which looks more like desktop than web framework and it's documentation is rather complicated for a beginner. So my question is: do you know about any good web frameworks for C/C++? What would make me totally happy would be something like C++ Django, but I doubt such thing exists :-)
If I were you, I would give [Wt](http://www.webtoolkit.eu/) a try. I don't think you will find another solution as complete and easy to use as Wt with similar performance. The mailinglist are active, and has regular posts of people who use it on embedded devices. The Wiki ([here](http://www.webtoolkit.eu/wt/wiki/index.php/Wt_embedded)) of the project mentions some numbers for embedded deployment and performance on ARM.
What is the reason your site is slow in PHP? Have you profiled the code to figure out the bottle necks? Replacing the entire codebase with another language is likely to be too large a tool for the job. Perhaps if some portion is computationally intensive, then maybe you can implement a PHP module in C++ to do the job.
Are there any web frameworks for compiled languages like C++?
[ "", "c++", "frameworks", "embedded", "" ]
This question is self explanatory if you know how to use JMockit: How do I mock a method that has generics on it? I want to mock this method: public T save(T entity) but it always throws an exception like this: ``` mockit.RealMethodNotFoundForMockException: Corresponding real methods not found for the following mocks: Object save(Object) at mockit.internal.RedefinitionEngine.modifyRealClass(RedefinitionEngine.java:130) at mockit.internal.RedefinitionEngine.modifyRealClass(RedefinitionEngine.java:88) at mockit.internal.RedefinitionEngine.redefineMethods(RedefinitionEngine.java:72) at mockit.Mockit.setUpMocks(Mockit.java:197) at com.mytest.MyTest.setUp(AdminManagerImplTest.java:83) ```
it does work for me, example ``` package a; import junit.framework.TestCase; import mockit.Mockit; public class JMockitCoreExampleTest extends TestCase { public class MockMe { public T save(T t) { return null; } } public void testDoOperationAbc() { Mockit.redefineMethods(MockMe.class, SayThatYouMockMe.class); MockMe mock = new MockMe(); System.out.println(mock.save("aaa")); } public static class SayThatYouMockMe { public T save(T t) { return t; } } } ``` output ``` Loaded external tool: mockit.integration.junit3.JUnitTestCaseDecorator Loaded external tool: mockit.integration.junit4.JUnit4ClassRunnerDecorator aaa ``` maybe you are mocking hibernate's save method? if so try using jmockit's hibernate3emul.jar
Just for the sake of completeness: I had a similar issue with Java 1.7 in Java 1.6 mode, TestNG and jMockit 1.5 and 1.16, using in-method MockUp<...> of a class. My class: `public class MyCache extends AbstractLazyCache<ExchangeObject> {...}` The mocked method: ``` public abstract class AbstractLazyCache<CachedObject> extends AbstractCache { // ... protected void putCachedObject(String tenantId, String objectId, CachedObject o, Date expiryDate) {...} } ``` Original mocking attempt: ``` new MockUp<MyCache>() { // invoked once manually, once on expired cache @Mock(invocations = 2) public void putCachedObject(Invocation inv, String tenantId, String objectId, RangeExchange o, Date expiryDate) { // expire one second in the future inv.proceed(tenantId, objectId, o, new Date(System.currentTimeMillis() + waitTimeMillis)); } }; ``` I got a similar exception. By adding an **additional generic parameter after public**, my test case finally succeeded: ``` new MockUp<MyCache>() { // invoked once manually, once on expired cache @Mock(invocations = 2) public <RangeExchange> void putCachedObject(Invocation inv, String tenantId, String objectId, RangeExchange o, Date expiryDate) { // expire one second in the future inv.proceed(tenantId, objectId, o, new Date(System.currentTimeMillis() + waitTimeMillis)); } }; ```
How do I mock a method with generic objects in JMockit?
[ "", "java", "generics", "mocking", "jmockit", "" ]
I am looking for a way to get the output of a command when it is run from within a C++ program. I have looked at using the `system()` function, but that will just execute a command. Here's an example of what I'm looking for: ``` std::string result = system("./some_command"); ``` I need to run an arbitrary command and get its output. I've looked at [boost.org](https://www.boost.org/), but I have not found anything that will give me what I need.
``` #include <cstdio> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include <array> std::string exec(const char* cmd) { std::array<char, 128> buffer; std::string result; std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose); if (!pipe) { throw std::runtime_error("popen() failed!"); } while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe.get()) != nullptr) { result += buffer.data(); } return result; } ``` Pre-C++11 version: ``` #include <iostream> #include <stdexcept> #include <stdio.h> #include <string> std::string exec(const char* cmd) { char buffer[128]; std::string result = ""; FILE* pipe = popen(cmd, "r"); if (!pipe) throw std::runtime_error("popen() failed!"); try { while (fgets(buffer, sizeof buffer, pipe) != NULL) { result += buffer; } } catch (...) { pclose(pipe); throw; } pclose(pipe); return result; } ``` Replace `popen` and `pclose` with `_popen` and `_pclose` for Windows.
Getting both stdout and stderr (and also writing to stdin, not shown here) is easy peasy with my [pstreams](http://pstreams.sourceforge.net/) header, which defines iostream classes that work like `popen`: ``` #include <pstream.h> #include <string> #include <iostream> int main() { // run a process and create a streambuf that reads its stdout and stderr redi::ipstream proc("./some_command", redi::pstreams::pstdout | redi::pstreams::pstderr); std::string line; // read child's stdout while (std::getline(proc.out(), line)) std::cout << "stdout: " << line << '\n'; // if reading stdout stopped at EOF then reset the state: if (proc.eof() && proc.fail()) proc.clear(); // read child's stderr while (std::getline(proc.err(), line)) std::cout << "stderr: " << line << '\n'; } ```
How do I execute a command and get the output of the command within C++ using POSIX?
[ "", "c++", "process", "posix", "system", "return-value", "" ]
I have a Silverlight application that communications with an ASP.NET backend through WCF. I have a set of DataContract objects that I defined that (for the most part) match my LINQ to SQL generated types that my ASP.NET backend works with. My WCF code generates instances of my DataContract objects from LINQ to SQL generator types when I need to transfer data to my Silverlight client. My question is the following: What are the security implications of exposing an index (which is used as the primary key in the database) through my DataContract objects? An example table (Position) in my database has the following columns: * PositionIndex : int (primary key) * PositionName : string * PositionType : int And the corresponding object is (more or less) this: ``` public class Position { public int PositionIndex { get; set; } public string PositionName { get; set; } public int PositionTYpe { get; set; } } ``` I'm concerned because I know how easy it is to reverse engineer Silverlight DLLs through Reflection - any potential bad guy will know I'm giving a database index to the client, and since they can reverse engineer Silverlight DLLs, they can easily get the URL of my WCF services and try to break them. Now, I've been good and taken the advice of the many who came before me and I've made many, many checks on the ASP.NET side to verify that my WCF services are getting legal input, but I'm still concerned that I'm doing something bad by giving potential bad guys some, not much, but some, insight into how the backend of my system is designed, and I've been around long enough to know that's more than enough for a determined person to start with. What do you guys think? If I'm doing something bad by using the index in my DataContracts, can you suggest an alternative? I'm finding it difficult to come up with a design that doesn't provide that index, as I have a need for the Silverlight client to update rows already in my database, and having the index is the best way I can think to help the ASP.NET side determine which row in the database it needs to update.
<https://stackoverflow.com/questions/>**454771**/is-it-safe-to-expose-database-indices-to-silverlight-clients It is standard practice to use primary keys in URLs and such. What you have to be careful about is to make sure the client is permitted to view the resource before sending it back. :)
One thing that would help would be to have some kind of authorization in place so that you keep track of what clients "own" what keys, so that they can't alter records they're not supposed to alter.
Is it safe to expose database indices to Silverlight clients?
[ "", "c#", "database", "wcf", "silverlight", "security", "" ]
After these instructions in the Python interpreter one gets a window with a plot: ``` from matplotlib.pyplot import * plot([1,2,3]) show() # other code ``` Unfortunately, I don't know how to continue to interactively explore the figure created by `show()` while the program does further calculations. Is it possible at all? Sometimes calculations are long and it would help if they would proceed during examination of intermediate results.
Use `matplotlib`'s calls that won't block: Using `draw()`: ``` from matplotlib.pyplot import plot, draw, show plot([1,2,3]) draw() print('continue computation') # at the end call show to ensure window won't close. show() ``` Using interactive mode: ``` from matplotlib.pyplot import plot, ion, show ion() # enables interactive mode plot([1,2,3]) # result shows immediatelly (implicit draw()) print('continue computation') # at the end call show to ensure window won't close. show() ```
Use the keyword 'block' to override the blocking behavior, e.g. ``` from matplotlib.pyplot import show, plot plot(1) show(block=False) # your code ``` to continue your code.
Is there a way to detach matplotlib plots so that the computation can continue?
[ "", "python", "matplotlib", "plot", "" ]
The Apache module [mod\_autoindex](http://httpd.apache.org/docs/2.0/mod/mod_autoindex.html) generates "directory indexes" that show users a crude hyperlinked list of the files and directories inside a directory (when there is no index.html or other [DirectoryIndex](http://httpd.apache.org/docs/2.0/mod/mod_dir.html#directoryindex) file). I have a directory on an Apache webserver where I want to provide an automatic directory listing, including the full filenames, sorted most-recently-modified-first, with file sizes displayed, using simple and attractive presentation. I cannot use mod\_autoindex or other Apache features. I am therefore looking for a simple script that does much the same thing as mod\_autoindex. In other words I want a script I can put in a directory that outputs an HTML document to STDOUT that contains a hyperlinked list of the files in the directory. The script should present its output in a simple & attractive way (non-technical people will be using it), consist of one file that I can edit if required, and preferably be OS-independent (so I can use it again later). Extra features would be great, but ease of install is all-important (though I am happy to tweak the code if I have to). My preference is for a perl script (i.e. an index.pl file), but PHP would be acceptable (index.php). Those are the only DirectoryIndex options on the server. **Update** I have decided to use [snif](http://www.bitfolge.de/snif-en.html) in preference to [AutoIndex](http://autoindex.sourceforge.net/) to solve the current problem, but I am still interested in finding a perl implementation, so if you know of one please post it. Thanks.
snif is nice and I think meets all your needs. [Link](http://www.bitfolge.de/index.php?option=com_content&view=article&id=66:snif-simple-and-nice-index-file&catid=38:eigene&Itemid=59)
I guess [AutoIndex](http://autoindex.sourceforge.net/) could solve your problem.
Simple script to replace Apache's mod_autoindex with a user-friendly directory listing
[ "", "php", "perl", "apache", "directory-listing", "mod-autoindex", "" ]
I'm stuck on a portion of the Java tutorial, specifically [this exercise](http://java.sun.com/docs/books/tutorial/java/javaOO/QandE/creating-questions.html). The exercise asks you to: > 1- Write a class whose instances > represent a single playing card from a > deck of cards. Playing cards have two > distinguishing properties: rank and > suit. Be sure to keep your solution as > you will be asked to rewrite it in > Enum Types. > > Hint: You can use the > assert statement to check your > assignments. You write: ``` assert(boolean expression to test); ``` > If the boolean expression is false, you will > get an error message. For example, ``` assert toString(ACE) == "Ace"; ``` > should return true, so there will be no error > message. > > 2- Write a class whose instances represent a full deck of cards. You > should also keep this solution. > > 3- Write a small program to test your deck and card classes. The program can > be as simple as creating a deck of > cards and displaying its cards. I'd really like to do this exercise, but the problem is I have never played cards so I have no idea at all how to create this program and what properties the cards should have, etc. I looked this up on wikipedia but got very limited knowledge, which will never enable me to build the required classes: [Card.java](http://java.sun.com/docs/books/tutorial/java/javaOO/examples/Card.java) , [Deck.java](http://java.sun.com/docs/books/tutorial/java/javaOO/examples/Deck.java) , and the program [DisplayDeck.java](http://java.sun.com/docs/books/tutorial/java/javaOO/examples/DisplayDeck.java). What will be a good alternate exercise to do for someone with no knowledge of cards, but which will test the same concepts that the above mentioned exercise would? (Probably static and instance variables and such) Thanks. By the way, this **not** a homework question, i'm learning Java for a commercial project.
I think it's worth the time to be familiar with the example, since it's frequently used to describe programming concepts. Let me try to distill the description of playing cards for you: First, keep [this picture](http://en.wikipedia.org/wiki/File:Set_of_playing_cards_52.JPG) of the **deck** (the whole collection of cards) open for reference. Going vertically down the rows, you have {**Spades** ♠, **Diamonds** ◇, **Clubs** ♣, **Hearts** ♡} = 4 **suits**. Going horizontally across the columns, you have {**2**, **3**, ..., **10**, **Jack**, **Queen**, **King**, **Ace**} = 13 **ranks**. Altogether, there are 4 x 13 = 52 cards in the **deck**. Each card is identified by the pair **(rank, suit)**, e.g. (Ace, Spades ♠) and (10, Diamonds ◇) which we read as "Ace of Spades" and "Ten of Diamonds", respectively.
Based on the description above, it doesn't really seem to require knowing *how* to play cards, just knowing how they look. As you mentioned above, this means that the Card class will have 2 properties (defined by Enums) rank and suit, where rank is one of: { ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, king } And suit is one of: { spades, hearts, diamonds, and clubs } A Deck would just be a collection structure holding every combination of rank and suite.
Stuck on Card/Deck exercise from Java official tutorial
[ "", "java", "oop", "" ]
I know at first glance (due to the title) this looks like one of the "Did you try searching Google before posting?" questions, but I can't seem to find an answer for the specific issue I'm experiencing. Sorry if I'm a noob.... still learning :) I need to simulate a pause in javascript, but the setTimeout(function\_call, timeout) function is not working for me. Reason being... when that setTimeout function is called, it then makes the function call asynchronously. A little background: I'm trying to simulate text being typed into a div at randomly timed intervals. I want it to appear as if a person is actually typing a message while the user is viewing the page. Since the timeout is a random interval and the function call is made asynchronously, the text ends up being printed in a random order. Here is a snippet of what I have thus far: ``` typeString: function(s) { for(var i=0;i<s.length;i++) { var c = s.charAt(i); var temp = setTimeout("MessageType.typeChar('" + c + "')", this.genRandomTime()); } } ``` Thanks in advance for your help. CJAM UPDATE: By adding the timer delay to a varialbe, it enabled me to offset timeOut for the asynchronous calls. Thank you all for your quick responses. Here is the updated code: ``` typeString: function(s) { var delay = 0; for(var i=0;i<s.length;i++) { var c = s.charAt(i); setTimeout("GoogleTyper.typeChar('"+c+"')", delay += this.genRandomTime()); } } ```
Have you tried cumulatively setting the timeout? Stick a variable outside of your loop and initialize it to 0. Let's call it timeout for now. Add a random amount of time to this variable at the beginning of each iteration of your loop, and make the timeout work off of that. This way, you are ensured that functions are being called in order.
Your problem is you are using one all your times are delayed starting from now - the next timer needs to be fired after the previous. Simply add the previous timer delay to the new timer. ``` typeString: function(s) { var delay = 0; for(var i=0;i<s.length;i++) { var c = s.charAt(i); delay = delay + this.genRandomTime(); var temp = setTimeout("MessageType.typeChar('" + c + "')", delay ); } } ```
Sequentially firing multiple random timeouts in JavaScript
[ "", "javascript", "random", "timeout", "" ]
In Swing, is there a way to define mouseover text (or tool tip text) for each item in a JComboBox?
There is a much better way to do this than the `ToolTipComboBox` answer already given. First, make a custom `ListCellRenderer`: ``` package com.example; import javax.swing.*; import java.awt.*; import java.util.List; public class ComboboxToolTipRenderer extends DefaultListCellRenderer { List<String> tooltips; @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JComponent comp = (JComponent) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (-1 < index && null != value && null != tooltips) { list.setToolTipText(tooltips.get(index)); } return comp; } public void setTooltips(List<String> tooltips) { this.tooltips = tooltips; } } ``` Then use it like this: ``` JComboBox comboBox = new JComboBox(); ComboboxToolTipRenderer renderer = new ComboboxToolTipRenderer(); comboBox.setRenderer(renderer); ... //make a loop as needed comboBox.addItem(itemString); tooltips.add(tooltipString); ... renderer.setTooltips(tooltips); ```
I like the simplicity of MountainX's solution but not the lack of encapsulation. An alternate solution which has more moving parts, but they are pretty simple and reusable. An interface: ``` public interface ToolTipProvider { public String getToolTip(); } ``` A wrapper class: ``` public class ToolTipWrapper implements ToolTipProvider { final Object value; final String toolTip; public ToolTipWrapper(Object value, String toolTip) { this.value = value; this.toolTip = toolTip; } @Override public String getToolTip() { return toolTip; } @Override public String toString() { return value.toString(); } } ``` And a variant of MountainX's renderer: ``` public class ToolTipRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JComponent component = (JComponent) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); String tip = null; if (value instanceof ToolTipProvider) { ToolTipProvider ttp = (ToolTipProvider) value; tip = ttp.getToolTip(); } list.setToolTipText(tip); return component; } } ``` with the adding now: ``` combobox.addItem(new ToolTipWrapper(itemString,tooltipString) ); ```
Java Swing: Mouseover text on JComboBox items?
[ "", "java", "swing", "" ]
I'm working on a Data Warehouse which, in the end, will require me to create reports based on business hours. Currently, my time dimension is granular to the hour. I'm wondering if I should be modifying my Time dimension to include a bit field for "business hour" or should I be creating some sort of calculated measure for it on the analysis end? Any examples would be super magnificent?
Use a bit (or even another column) to specify whether an hour is a business hour at the time it is stored. Otherwise when you change the business hours you will become unable to reproduce historical reports.
Is all of your sales data in the same time zone? For example, are you tracking sales for outlets in different time zones, or end users in different time zones? If so, you may want to create that bit field for "business hour" in the sales fact table, because it'll be pretty difficult to calculate that on the fly for users and outlets in different time zones. Plus, you only want to calculate this once - when the sale is imported into the data warehouse - because this data is not likely to change very often. It's not like you're going to say, "This sale used to be in business hours, but it no longer is."
Data Warehouse - business hours
[ "", "sql", "data-warehouse", "" ]
What I am trying to achieve is to merge three strings. Two are provided as strings; firstname and lastname, while the third is a simple comma/space separator. Given the following lines of code: ``` //Working code var sep = ", "; var fullName = myNewBO[0].LastName + sep + myNewBO[0].FirstName; //Erronous code var fullName = myNewBO[0].LastName + ", " + myNewBO[0].FirstName; ``` The string is returned to a cell in a DataGridView. While the first bit of code performs as expcted the latter does not. The string does not show in the cell as expected. Can someone tell me why the latter does not work? Also if you have a better solution to the problem please provide one. EDIT: **Solved.** As suspected, and pointed out by several answers the problem was elsewhere in my code and the two alternatives do the exact same thing. Thanks for the syntax suggestions though :)
I suspect you have something else happening in your code, and you're mistaking where the error is occurring. I can't for the life of me see why those two would behave differently at all. I suggest you log the value after the assignment for both cases - I'm sure you'll find they're the same.
I prefer using `string.Format("{0}, {1}",myNewBO[0].LastName,myNewBO[0].FirstName)` Now you can abstract out the format string if you want it be "First Last" for example you can use a different formatting string. # Edit In response to your actual error, I like others here don't see what is wrong the line of code you have should work so the question becomes: "How are you binding this value to the grid?" Are you doing this in an Eval() or code behind etc.... One suggestion would to add a ToString(string) method which takes a format string in, then you can bind to the evaluation of the method. And should your business requirements change you just change the formatting string.
String syntax question
[ "", "c#", "string", "" ]
Is there a norm for AJAX security? When making an XMLHttpRequest, if querying an HTTPS url, will the browser handle all the certificate business and properly encrypt the request (or use an already existing authenticated tunnel)? Are there any security flaws in this model? Then there's also user authentication issues with AJAX. This made me think that using the user's password to encrypt part or all of an AJAX request could solve some authentication issues. I've seen some impressive javascript based encryption tools. It seems like there'd be lots of potential there to build a single system that takes care of both encryption and authentication(host level and application user level). I have however not seen anything that seems 'tried an true'. **My question can be summed up as:** > Is there a norm for secure AJAX either > using browser technologies or client > side javascript? What > is it? And if not, what's preventing > us from building one using javascript? Thank you, as always.
SSL through HTTPS is sort of a cooperative venture with the destination server. The destination server will report its identity with its identity certificate (sent back to the client). This is part of the protocol that will encrypt the data stream between the client and the server. However, this just encrypts the stream, it does nothing about several other security issues. Identification and authentication of the user entity making a request is handled through other means. If you're encrypting the stream with SSL, it should be safe to use HTTP basic auth. After that, the response to authentication should be a session id sent back to the client that will pass it back on all subsequent requests. Application servers typically manage the creation of those session ids.
> Ajax does not inherently introduce new > security vulnerabilities in the realm > of web applications. Instead, the > applications face the same security > issues as classic web applications. > Unfortunately, common Ajax best > practices have not been developed, > which leaves plenty of room to get > things wrong. from: <http://www.securityfocus.com/infocus/1868>
AJAX Security Norm
[ "", "javascript", "ajax", "security", "encryption", "" ]
Whats wrong with the following c# code? Compiler reports this error: Inconsistent accessibility: parameter type 'ClassLibrary1.Interface1' is less accessible than method 'ClassLibrary1.Class1.Class1(ClassLibrary1.Interface1)' with the following code: ``` interface Interface1<T> { bool IsDataValid(); /* Other interfaces */ } public class Class1<T> { public Interface1<T> interface1; public Class1(Interface1<T> interface1) { this.interface1 = interface1; } } ``` I've since designed my code differently using inheritence to but if anyone could tell me what the above is wrong I'd greatly appreciate it.
your "Interface1" isn't public.. ``` public interface Interface1<T> { bool IsDataValid(); /* Other interfaces */ } ```
Mark your interface as public: `public interface Interface1<T>` If you leave out the accessibility label, it defaults to `internal`, that is, only accessible to other classes within the assembly.
Inconsistent accessibility error with the following c# code. Why?
[ "", "c#", "" ]
In a C++ MD2 file loader, I have a lot of frames, each with a name that ends with a number, such as * stand0 * stand1 * stand2 * stand3 * stand4 * ... * stand10 * stand11 * run0 * run1 * run2 etc. How do I get what the string is without the number behind? e.g. a function that changed "stand10" to just "stand"
Just to complete it, one with find\_first\_of: ``` string new_string = str.substr(0, str.find_first_of("0123456789")); ``` just one line :) Also, for these things, I like to use regular expressions (althought this case is very simple): ``` string new_string = boost::regex_replace(str, boost::regex("[0-9]+$"), ""); ```
**string::find\_last\_not\_of**("0123456789") and then **string::substr()** that gives you the position of the last non digit/number. Just take all the preceding characters and that is the base name. Increment by one to get the start of the number sequence at the end of the string. Note: no error checking or other tests. ``` #include <string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { string test = "hellothere4"; size_t last_char_pos = test.find_last_not_of("0123456789"); string base = test.substr(0, last_char_pos + 1); ``` EDIT there is a problem with ALL the solutions when your "base name" has a number at the end. for example, if the base string is "base1" then you can never get the proper base name. I assume you already are aware of this. Or am I missing something? As long as the base name can't have a number at the end just before the postfix number it will work fine.
check what number a string ends with in C++
[ "", "c++", "string", "numbers", "integer", "" ]
Why would an event handler work one day, and then stop working the next day without *any* code changes? I have run into the problem many times, but always have to play around and somehow the event handler magically works again. Below is an example where this happened to me again today. Do you know a quick way to fix this type of problem? ``` <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click"> Link </asp:LinkButton> ``` I set a breakpoint on this method and it never gets hit. ``` protected void LinkButton1_Click(object sender, EventArgs e) { // snip } ``` I have tried cleaning the solution, rebuilding all, etc. Any insight here? Edit: Yes, AutoEventWireup is set to true. No other system/development environment changes were made. I'm using .NET 3.5.
Kieran was right with his comment... Something actually had changed! Big wow there... The TFS Check-in alert ended up in my Junk E-mail folder and stupid me didn't do a comparison on the history of the file. The EnableViewState was set to false in the codebehind by a coworker. As a side note: he did this because it dropped the response size to 10% of what it had been with viewstate enabled. I ended up solving the same problem by using a querystring variable in place of the event handling. However, thanks for all the ideas. Good thing I didn't waste too much time on this thing.
I know you said that no code had changed but you ought to check to make sure that `AutoEventWireup` is set to `true` on this page. Also check the web.config to make sure that this attribute is not `false` for the whole application. Edit: The best thing you can do is not to rely on `AutoEventWireup` as you are here. You really ought to add an explicit event wireup in your `OnInit` override of the page as this is clearer provides better performance. I am not sure why you are seeing the errors you are seeing but I can almost guarantee that they will go away if you do something like this: ``` protected override void OnInit(EventArgs e) { this.LinkButton1.Click += new EventHandler(this.LinkButton1_Click); } ```
Why do event handler methods randomly stop working?
[ "", "c#", "asp.net", "event-handling", "viewstate", "" ]
Is it possible to make a simple query to count how many records I have in a determined period of time like a year, month, or day, having a `TIMESTAMP` field, like: ``` SELECT COUNT(id) FROM stats WHERE record_date.YEAR = 2009 GROUP BY record_date.YEAR ``` Or even: ``` SELECT COUNT(id) FROM stats GROUP BY record_date.YEAR, record_date.MONTH ``` To have a monthly statistic. Thanks!
``` GROUP BY YEAR(record_date), MONTH(record_date) ``` Check out the [date and time functions](http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_month) in MySQL.
``` GROUP BY DATE_FORMAT(record_date, '%Y%m') ``` --- ***Note** (primarily, to potential downvoters). Presently, this may not be as efficient as other suggestions. Still, I leave it as an alternative, and a one, too, that can serve in seeing how faster other solutions are. (For you can't really tell fast from slow until you see the difference.) Also, as time goes on, changes could be made to MySQL's engine with regard to optimisation so as to make this solution, at some (perhaps, not so distant) point in future, to become quite comparable in efficiency with most others.*
MySQL Query GROUP BY day / month / year
[ "", "mysql", "sql", "date", "datetime", "group-by", "" ]
I'm using the Unity IOC container and I'm just wondering what is the best best way to access the container for multiple classes. Should every class have an IUnityContainer member and then pass the container in by constructor? Should there be a singleton class with an IOC container? How about asp.net development? Could somebody guide me in the right direction? Thanks.
Put the IOC container at the highest level / entry point in the process and use it to inject dependencies in everything underneath it.
IMHO it is not advisable to inject the entire container into a class or to have an application wide static IoC service locator. You want to be able to see from the constructor of a class (lets call it Foo), what kind of services/objects it is using to get the work done. This improves clarity, testability and degubability. Lets say Foo only needs the email service, but I pass in the whole container and somewhere in the code the email service gets resolved from the container. In this case it will be very hard to follow. Instead it is better to inject the email service directly to state Foo's dependencies clearer. If Foo needs to create multiple instances of the email service, it is better to create and inject an EmailServiceFactory (via the IoC container), which will create the required instances on the fly. In the latter case, Foo's dependencies are still indicated as specific as possible - only the ones, that the EmailServiceFactory can create. Had I injected the whole container, it would not be clear what services provided by it are Foo's exact dependencies. Now, if I later want to provide different instances of the email service, I swap it out inside the EmailServiceFactory. I could swap out the whole factory as well, if all the services it creates need to be swapped (e.g. during testing). So at the cost of creating one extra class (the factory), I get much cleaner code and won't have to worry about curious bugs that may occur when global statics are used. Additionally when supplying mocks for testing, I know exactly what mocks it needs and don't have to mock out an entire container's types. This approach also has the advantage, that now, when a module is initialized (only applies to Prism / Modularity), it doesn't have to register all of the types of objects it supplies with the IoC container. Instead it can just register its ServiceFactory which then supplies those objects. To be clear, the module's initialization class (implements IModule) should still receive the application wide IoC container in its constructor in order to supply services, that are consumed by other modules, but the container should not invade into the module's classes. Finally, what we have here is another fine example of how an extra layer of indirection solves a problem.
Best Practices for IOC Container
[ "", "c#", "inversion-of-control", "unity-container", "" ]
I have written a program with both a Advanced Mode and a Beginner Mode to allow the user to get the hang of my program before it is actually used. The Advanced Mode is almost identical to the Beginner Mode apart from one or two methods needing to be replaced by another, so I have decided to create a general Mode class for both Advanced Mode and Beginner Mode classes to use instead of just coping code: Here is the class structure if my explanation isn't very clear: * GUI Class * General Mode Class + Beginner Mode + Advanced Mode Let's say that the General Mode class has the following code: ``` public class GeneralMode { private int range; private String id; public GeneralMode() { } public int getRange() { return range; } public String getID() { return id; } public void doStuff() { } } ``` The GeneralMode class is where all the work gets done for the program. Now, I would like to make it so that the Advanced Mode class can take the input from the GUI class and use it in the same way as the GeneralMode class does. Thank you for all your help!
Make 'GeneralMode' class, an abstract class, with abstract methods that have to be implemented by the concrete 'advanced' and 'beginner' classes. The functionality that both modes have in common, can be implemented in the 'GeneralMode' class. Then, in your GUI class, instantiate the correct concrete class, and put it in a 'GeneralMode' variable. Then, you can use it without you having to know whether your program is running in beginner mode or in advanced mode. pseudocode: ``` GeneralMode mode = (UseAdvancedMode == true)? new AdvancedMode() : new BeginnerMode(); ```
making the `GeneralMode` an abstract class definitely is the way to go to get the polimorphic behavior straight (as correctly explained by Frederik Gheysels). one other important OO paradigm is to > favor composition over inheritance ([Item 14, 'Effective Java' by Josh Bloch](http://books.google.ch/books?id=ZZOiqZQIbRMC&pg=PA71)) if your bulleted list represents your current inheritance hierarchy (ignore my comment if it doesn't...), i would strongly encourage you to change it so that your `GUI Class` is ***composed of*** a mode (rather than the mode being an extension of it -- the classical *"is a"* vs *"has a"* question). extracting whatever GUI settings into a parameter object which you will then pass to the modes to do their work would reduce the coupling even further.
Java: Basic OOP Question
[ "", "java", "oop", "" ]
We're considering switching our site from Prototype to jQuery. Being all-too-familiar with Prototype, I'm well aware of the things about Prototype that I find limiting or annoying. My question for jQuery users is: After working with jQuery for a while, what do you find frustrating? Are there things about jQuery that make you think about switching (back) to Prototype?
Probably the only real issue I've ever ran into is $(this) scope problems. For example, if you're doing a nested for loop over elements and sub elements using the built in JQuery .each() function, what does $(this) refer to? In that case it refers to the inner-most scope, as it should be, but its not always expected. The simple solution is to just cache $(this) to a variable before drilling further into a chain: ``` $("li").each(function() { // cache this var list_item = $(this); // get all child a tags list_item.find("a").each(function() { // scope of this now relates to a tags $(this).hide("slow"); }); }); ```
I think the only that gets me is that when I do a selection query for a single element I have to remember that it returns an array of elements even though I know there is only one. Normally, this doesn't make any difference unless you want to interact with the element directly instead of through jQuery methods.
What jQuery annoyances should I be aware of as a Prototype user?
[ "", "javascript", "jquery", "frameworks", "prototypejs", "" ]
I want to use a ComboBox with the DropDownList style (the one that makes it look like a button so you can't enter a value) to insert a value into a text box. I want the combobox to have a text label called 'Wildcards' and as I select a wildcard from the list the selected value is inserted in to a text box and the combobox text remains 'Wildcard'. My first problem is I can't seem to set a text value when the combobox is in DropDownList style. Using the properties pallet doesn't work the text value is simply cleared when you click off, adding comboBox.Text = "Wildcards"; to form\_load doesn't work either. Can anyone help?
The code you specify: ``` comboBox.Text = "Wildcards"; ``` ...should work. The only reason it would not is that the text you specify is not an item within the comboBox's item list. When using the DropDownList style, you can only set Text to values that actually appear in the list. If it is the case that you are trying to set the text to Wildcards and that item does not appear in the list, and an alternative solution is not acceptable, you may have to be a bit dirty with the code and add an item temporarily that is removed when the drop-down list is expanded. For example, if you have a form containing a combobox named "comboBox1" with some items and a button named "button1" you could do something like this: ``` private void button1_Click(object sender, EventArgs e) { if (!comboBox1.Items.Contains("Wildcards")) { comboBox1.Items.Add("Wildcards"); } comboBox1.Text = "Wildcards"; } private void comboBox1_DropDown(object sender, EventArgs e) { if (comboBox1.Items.Contains("Wildcards")) comboBox1.Items.Remove("Wildcards"); } ``` That's pretty quick and dirty but by capturing the DropDownClosed event too you could clean it up a bit, adding the "Wildcards" item back as needed.
You can select one of items on formload or in form constructor: ``` public MyForm() { InitializeComponent(); comboBox.SelectedIndex = 0; } ``` or ``` private void MyForm_Load(object sender, EventArgs e) { comboBox.SelectedIndex = 0; } ```
C# ComboBox in DropDownList style, how do I set the text?
[ "", "c#", ".net", "combobox", "" ]
If I have ``` List<String> text ``` how can I create a sub-list of all continious elements within a specific range e.g. ``` List<String> subList = /* all elements within text bar the first 2*/ ``` Also are there any other useful List manipulation tips & tricks that might be useful?
This will work even without LINQ: ``` List<String> subList = text.GetRange(2, text.Count - 2); ``` **Edit:** Fixed a typo.
``` subList = text.Skip(2).ToList() ``` Skip(n) returns an IEnumerable<> with all elements except the first n. When you really need a list after that, ToList() converts it back.
c# List manipulation
[ "", "c#", "list", "list-manipulation", "" ]
You have a method on a class that has 2 parameters, one of which is a file path, the other is irrelevant. ``` InterestingResult result = foo.Bar(irrelevant, filePathInfo); ``` In the spirit of having fast snappy unit tests, you find yourself considering refactoring this method to pull out the file path to remove the IO requirements of this test...most likely putting it into another method, so that now you would call ``` string dataInFile = foo.GetDataInFile(filePathInfo); InterestingResult result = foo.Bar(irrelevant, dataInFile); ``` Are you crazy?...or was this a good thing?
How about using a Stream as argument instead? That way you can pass a [MemoryStream](http://msdn.microsoft.com/de-de/library/system.io.memorystream(VS.80).aspx) in your unit test, and a [FileStream](http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx) in production code.
As a general rule I would avoid changing an interface only for testing purposes. The interfaces should reflect the user's needs, not the developer's or the tester's.
unit testing, refactoring, IO
[ "", "c#", "unit-testing", "refactoring", "" ]
I've been looking through the ANTLR v3 documentation (and my trusty copy of "The Definitive ANTLR reference"), and I can't seem to find a clean way to implement escape sequences in string literals (I'm currently using the Java target). I had hoped to be able to do something like: ``` fragment ESCAPE_SEQUENCE : '\\' '\'' { setText("'"); } ; STRING : '\'' (ESCAPE_SEQUENCE | ~('\'' | '\\'))* '\'' { // strip the quotes from the resulting token setText(getText().substring(1, getText().length() - 1)); } ; ``` For example, I would want the input token "`'Foo\'s House'`" to become the String "`Foo's House`". Unfortunately, the `setText(...)` call in the `ESCAPE_SEQUENCE` fragment sets the text for the entire `STRING` token, which is obviously not what I want. Is there a way to implement this grammar without adding a method to go back through the resulting string and manually replace escape sequences (e.g., with something like `setText(escapeString(getText()))` in the `STRING` rule)?
Here is how I accomplished this in the JSON parser I wrote. ``` STRING @init{StringBuilder lBuf = new StringBuilder();} : '"' ( escaped=ESC {lBuf.append(getText());} | normal=~('"'|'\\'|'\n'|'\r') {lBuf.appendCodePoint(normal);} )* '"' {setText(lBuf.toString());} ; fragment ESC : '\\' ( 'n' {setText("\n");} | 'r' {setText("\r");} | 't' {setText("\t");} | 'b' {setText("\b");} | 'f' {setText("\f");} | '"' {setText("\"");} | '\'' {setText("\'");} | '/' {setText("/");} | '\\' {setText("\\");} | ('u')+ i=HEX_DIGIT j=HEX_DIGIT k=HEX_DIGIT l=HEX_DIGIT {setText(ParserUtil.hexToChar(i.getText(),j.getText(), k.getText(),l.getText()));} ) ; ```
For ANTLR4, Java target and standard escaped string grammar, I used a dedicated singleton class : CharSupport to translate string. It is available in antlr API : ``` STRING : '"' ( ESC | ~('"'|'\\'|'\n'|'\r') )* '"' { setText( org.antlr.v4.misc.CharSupport.getStringFromGrammarStringLiteral( getText() ) ); } ; ``` As I saw in V4 documentation and by experiments, @init is no longer supported in lexer part!
How to handle escape sequences in string literals in ANTLR 3?
[ "", "java", "string", "antlr", "escaping", "" ]
I have a python client which pushes a great deal of data through the standard library's httlib. Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using. Could I improve performance by replacing httplib with something else? I've seen that twisted offers a HTTP client. It seems to be very basic compared to their other protocol offerings. PyCurl might be a valid alternative, however it's use seems to be very un-pythonic, on the other hand if it's performance is really good then I can put up with a bit of un-pythonic code. So if you have experience of better HTTP client libraries of python please tell me about it. I'd like to know what you thought of the performance relative to httplib and what you thought of the quality of implementation. UPDATE 0: My use of httplib is actually very limited - the replacement needs to do the following: ``` conn = httplib.HTTPConnection(host, port) conn.request("POST", url, params, headers) compressedstream = StringIO.StringIO(conn.getresponse().read()) ``` That's all: No proxies, redirection or any fancy stuff. It's plain-old HTTP. I just need to be able to do it as fast as possible. UPDATE 1: I'm stuck with Python2.4 and I'm working on Windows 32. Please do not tell me about better ways to use httplib - I want to know about some of the alternatives to httplib.
Often when I've had performance problems with httplib, the problem hasn't been with the httplib itself, but with how I'm using it. Here are a few common pitfalls: (1) Don't make a new TCP connection for every web request. If you are making lots of request to the same server, instead of this pattern: ``` conn = httplib.HTTPConnection("www.somewhere.com") conn.request("GET", '/foo') conn = httplib.HTTPConnection("www.somewhere.com") conn.request("GET", '/bar') conn = httplib.HTTPConnection("www.somewhere.com") conn.request("GET", '/baz') ``` Do this instead: ``` conn = httplib.HTTPConnection("www.somewhere.com") conn.request("GET", '/foo') conn.request("GET", '/bar') conn.request("GET", '/baz') ``` (2) Don't serialize your requests. You can use threads or asynccore or whatever you like, but if you are making multiple requests from different servers, you can improve performance by running them in parallel.
> Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using. > > Could I improve performance by replacing httplib with something else? Do you *suspect* it or are you *sure* that that it's `httplib`? Profile before you do anything to improve the performance of your app. I've found my own intuition on where time is spent is often pretty bad (given that there isn't some code kernel executed millions of times). It's really disappointing to implement something to improve performance then pull up the app and see that it made no difference. If you're not profiling, you're shooting in the dark!
A replacement for python's httplib?
[ "", "python", "http", "curl", "twisted", "" ]
When displaying my DateTime values, I want them to be formatted like so: "February 9, 2009 7:00 AM" I am using the following code, but am concerned that the date may display incorrectly in other cultures. Can anyone tell me if this is the case or not, and if it is how can I fix it? ``` Date.ToString("MMMM dd, yyyy hh:mm tt"); ``` Thanks!
> I am using the following code, but am concerned that the date may display incorrectly in other cultures. What exactly is ‘correct’? Are you a normal client-side app? If so, you'll get localised month names. Is that ‘incorrect’? Depends what you're looking for. If you *do* want locale-friendly times in a client-side app then using the default long date format will give you the smoothest results. In my locale I wouldn't want to see 12-hour clock or the month before the day, though I'd surely understand it. If you're a server-side app you don't want to use any default-localised anything, because the locale will be your server's rather than your users', and you'll have a weird portability problem. In this case you'll have to either allow the user to pick out their own locale, or use your own date formatting functions with built-in English month names. (Or, to avoid the problem, no month names. In which case ISO-8601 format “YYYY-mm-dd HH:MM:SS” would be the default choice.)
I prefer the ISO 8601 format (and yes without the "T") : you don't have to juggle among different representations depending on who is reading your data. Less code, less bugs. I keep finding documents originally written in english that get "translated" but with dates that stay "as is" and so become completely wrong. As an added bonus, ISO formatted dates sort just like ordinary strings !
Does this custom DateTime format break in other cultures?
[ "", "c#", "datetime", "formatting", "culture", "" ]
Is there a tool to import/convert COM type libraries into C# code rather than generating an assembly? The TLBIMP tool and the TypeLibaryConverter class only generate assemblies. I've had some success ripping the C# `ComImport` definitions by running Reflector over the generated Interop assembly and copying a pasting the disassembled source, but this usually requires quite a bit of manual patching up before it'll compile. Desired goal is a single EXE without satellite Interop DLLs, so perhaps the answer is to use ILMerge to effectively embed the interop DLL in the EXE. I was sure in the past I'd come across such a tool - but maybe it dreamt it :-)
As I originally suspected the best solution is going with [ILMerge](http://www.microsoft.com/downloads/details.aspx?FamilyID=22914587-b4ad-4eae-87cf-b14ae6a939b0). I can't be selective about parts of a COM API to embed, but it works well enough. Here is the Post Build Event Command Line I'm using, which should be easy enough to reuse: ``` set MERGEFILES=Interop.Foo.dll Interop.Bar.dll if "$(ConfigurationName)" == "Release" ( ren "$(TargetFileName)" "_$(TargetFileName)" "$(ProgramFiles)\Microsoft\ILMerge\ILMerge.exe" /out:"$(TargetFileName)" "_$(TargetFileName)" %MERGEFILES% del "_$(TargetFileName)" del %MERGEFILES% ) ```
I'm not so sure it is going to be useful to you, but the source code for a managed version of Tlbimp.exe has been released on [CodePlex](http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=17579). VS2010 will definitely solve your problem.
Tool to import Type Libraries as C# code
[ "", "c#", "com-interop", "tlbimp", "" ]
I'm dynamically adding a custom user control to the page as per [this post](https://stackoverflow.com/questions/213429/programmatically-adding-user-controls-inside-an-updatepanel). However, i need to set a property on the user control as i add it to the page. How do I do that? Code snippet would be nice :) Details: I have a custom user control with a public field (property ... e.g. public int someId;) As I add a UserControl to a page, its type is UserControl. Do i just cast it into MyCustomUCType and set a property on a cast control? p.s. looks like I've answered my own question after all.
Ah, I answered before you added the additional clarification. The short answer is, yes, just cast it as your custom type. I'll leave the rest of my answer here for reference, though it doesn't appear you'll need it. --- Borrowing from the code in the other question, and assuming that all your User Controls can be made to inherit from the same base class, you could do this. Create a new class to act as the base control: ``` public class MyBaseControl : System.Web.UI.UserControl { public string MyProperty { get { return ViewState["MyProp"] as string; } set { ViewState["MyProp"] = value; } } } ``` Then update your user controls to inherit from your base class instead of UserControl: ``` public partial class SampleControl2 : MyBaseControl { .... ``` Then, in the place where you load the controls, change this: ``` UserControl uc = (UserControl)LoadControl(controlPath); PlaceHolder1.Controls.Add(uc); ``` to: ``` MyBaseControl uc = (MyBaseControl)LoadControl(controlPath); uc.MyProperty = "foo"; PlaceHolder1.Controls.Add(uc); ```
> "As I add a UserControl to a page, its > type is UserControl. Do i just cast it > into MyCustomUCType and set a property > on a cast control?" That's what I'd do. If you're actually using the example code where it loads different controls, I'd use an if(x is ControlType) as well. > ``` > if(x is Label) > { > Label l = x as Label; > l.Text = "Batman!"; > } > else > //... > ``` **Edit**: Now it's 2.0 compatible
Set properties on dynamically added UserControl
[ "", "c#", ".net", "asp.net", "user-controls", ".net-2.0", "" ]
I'm working on an application that will gather data through HTTP from several places, cache the data locally and then serve it through HTTP. So I was looking at the following. My application will first create several threads that will gather data at a specified interval and cache that data locally into a SQLite database. Then in the main thread start a CherryPy application that will query that SQLite database and serve the data. My problem is: how do I handle connections to the SQLite database from my threads and from the CherryPy application? If I'd do a connection per thread to the database will I also be able to create/use an in memory database?
Short answer: Don't use Sqlite3 in a threaded application. Sqlite3 databases scale well for size, but rather terribly for concurrency. You will be plagued with "Database is locked" errors. If you do, you will need a connection per thread, and you have to ensure that these connections clean up after themselves. This is traditionally handled using thread-local sessions, and is performed rather well (for example) using SQLAlchemy's ScopedSession. I would use this if I were you, even if you aren't using the SQLAlchemy ORM features.
This test is being done to determine the best way to write and read from SQLite database. We follow 3 approaches below 1. Read and write without any threads (the methods with the word normal on it) 2. Read and write with Threads 3. Read and write with processes Our sample dataset is a dummy generated OHLC dataset with a symbol, timestamp, and 6 fake values for ohlc and volumefrom, volumeto Reads 1. Normal method takes about 0.25 seconds to read 2. Threaded method takes 10 seconds 3. Processing takes 0.25 seconds to read **Winner: Processing and Normal** Writes 1. Normal method takes about 1.5 seconds to write 2. Threaded method takes about 30 seconds 3. Processing takes about 30 seconds **Winner: Normal** **Note:** All records are not written using the threaded and processed write methods. Threaded and processed write methods obviously run into database locked errors as the writes are queued up SQlite only queues up writes to a certain threshold and then throws sqlite3.OperationalError indicating database is locked. The ideal way is to retry inserting the same chunk again but there is no point as the method execution for parallel insertion takes more tine than a sequential read even without retrying the locked/failed inserts Without retrying, 97% of the rows were written and still took 10x more time than a sequential write **Strategies to takeaway:** 1. Prefer reading SQLite and writing it in the same thread 2. If you must do multithreading, use multiprocessing to read which has more or less the same performance and defer to single threaded write operations 3. **DO NOT USE THREADING** for reads and writes as it is 10x slower on both, you can thank the GIL for that Here is the code for the complete test ``` import sqlite3 import time import random import string import os import timeit from functools import wraps from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import threading import os database_file = os.path.realpath('../files/ohlc.db') create_statement = 'CREATE TABLE IF NOT EXISTS database_threading_test (symbol TEXT, ts INTEGER, o REAL, h REAL, l REAL, c REAL, vf REAL, vt REAL, PRIMARY KEY(symbol, ts))' insert_statement = 'INSERT INTO database_threading_test VALUES(?,?,?,?,?,?,?,?)' select = 'SELECT * from database_threading_test' def time_stuff(some_function): def wrapper(*args, **kwargs): t0 = timeit.default_timer() value = some_function(*args, **kwargs) print(timeit.default_timer() - t0, 'seconds') return value return wrapper def generate_values(count=100): end = int(time.time()) - int(time.time()) % 900 symbol = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) ts = list(range(end - count * 900, end, 900)) for i in range(count): yield (symbol, ts[i], random.random() * 1000, random.random() * 1000, random.random() * 1000, random.random() * 1000, random.random() * 1e9, random.random() * 1e5) def generate_values_list(symbols=1000,count=100): values = [] for _ in range(symbols): values.extend(generate_values(count)) return values @time_stuff def sqlite_normal_read(): """ 100k records in the database, 1000 symbols, 100 rows First run 0.25139795300037804 seconds Second run Third run """ conn = sqlite3.connect(os.path.realpath('../files/ohlc.db')) try: with conn: conn.execute(create_statement) results = conn.execute(select).fetchall() print(len(results)) except sqlite3.OperationalError as e: print(e) @time_stuff def sqlite_normal_write(): """ 1000 symbols, 100 rows First run 2.279409104000024 seconds Second run 2.3364172020001206 seconds Third run """ l = generate_values_list() conn = sqlite3.connect(os.path.realpath('../files/ohlc.db')) try: with conn: conn.execute(create_statement) conn.executemany(insert_statement, l) except sqlite3.OperationalError as e: print(e) @time_stuff def sequential_batch_read(): """ We read all the rows for each symbol one after the other in sequence First run 3.661222331999852 seconds Second run 2.2836898810001003 seconds Third run 0.24514851899994028 seconds Fourth run 0.24082150699996419 seconds """ conn = sqlite3.connect(os.path.realpath('../files/ohlc.db')) try: with conn: conn.execute(create_statement) symbols = conn.execute("SELECT DISTINCT symbol FROM database_threading_test").fetchall() for symbol in symbols: results = conn.execute("SELECT * FROM database_threading_test WHERE symbol=?", symbol).fetchall() except sqlite3.OperationalError as e: print(e) def sqlite_threaded_read_task(symbol): results = [] conn = sqlite3.connect(os.path.realpath('../files/ohlc.db')) try: with conn: results = conn.execute("SELECT * FROM database_threading_test WHERE symbol=?", symbol).fetchall() except sqlite3.OperationalError as e: print(e) finally: return results def sqlite_multiprocessed_read_task(symbol): results = [] conn = sqlite3.connect(os.path.realpath('../files/ohlc.db')) try: with conn: results = conn.execute("SELECT * FROM database_threading_test WHERE symbol=?", symbol).fetchall() except sqlite3.OperationalError as e: print(e) finally: return results @time_stuff def sqlite_threaded_read(): """ 1000 symbols, 100 rows per symbol First run 9.429676861000189 seconds Second run 10.18928106400017 seconds Third run 10.382290903000467 seconds """ conn = sqlite3.connect(os.path.realpath('../files/ohlc.db')) symbols = conn.execute("SELECT DISTINCT SYMBOL from database_threading_test").fetchall() with ThreadPoolExecutor(max_workers=8) as e: results = e.map(sqlite_threaded_read_task, symbols, chunksize=50) for result in results: pass @time_stuff def sqlite_multiprocessed_read(): """ 1000 symbols, 100 rows First run 0.2484774920012569 seconds!!! Second run 0.24322178500005975 seconds Third run 0.2863524549993599 seconds """ conn = sqlite3.connect(os.path.realpath('../files/ohlc.db')) symbols = conn.execute("SELECT DISTINCT SYMBOL from database_threading_test").fetchall() with ProcessPoolExecutor(max_workers=8) as e: results = e.map(sqlite_multiprocessed_read_task, symbols, chunksize=50) for result in results: pass def sqlite_threaded_write_task(n): """ We ignore the database locked errors here. Ideal case would be to retry but there is no point writing code for that if it takes longer than a sequential write even without database locke errors """ conn = sqlite3.connect(os.path.realpath('../files/ohlc.db')) data = list(generate_values()) try: with conn: conn.executemany("INSERT INTO database_threading_test VALUES(?,?,?,?,?,?,?,?)",data) except sqlite3.OperationalError as e: print("Database locked",e) finally: conn.close() return len(data) def sqlite_multiprocessed_write_task(n): """ We ignore the database locked errors here. Ideal case would be to retry but there is no point writing code for that if it takes longer than a sequential write even without database locke errors """ conn = sqlite3.connect(os.path.realpath('../files/ohlc.db')) data = list(generate_values()) try: with conn: conn.executemany("INSERT INTO database_threading_test VALUES(?,?,?,?,?,?,?,?)",data) except sqlite3.OperationalError as e: print("Database locked",e) finally: conn.close() return len(data) @time_stuff def sqlite_threaded_write(): """ Did not write all the results but the outcome with 97400 rows written is still this... Takes 20x the amount of time as a normal write 1000 symbols, 100 rows First run 28.17819765000013 seconds Second run 25.557972323000058 seconds Third run """ symbols = [i for i in range(1000)] with ThreadPoolExecutor(max_workers=8) as e: results = e.map(sqlite_threaded_write_task, symbols, chunksize=50) for result in results: pass @time_stuff def sqlite_multiprocessed_write(): """ 1000 symbols, 100 rows First run 30.09209805699993 seconds Second run 27.502465319000066 seconds Third run """ symbols = [i for i in range(1000)] with ProcessPoolExecutor(max_workers=8) as e: results = e.map(sqlite_multiprocessed_write_task, symbols, chunksize=50) for result in results: pass sqlite_normal_write() ```
Python, SQLite and threading
[ "", "python", "multithreading", "sqlite", "" ]
I have a function that I use to add vectors, like this: ``` public static Vector AddVector(Vector v1, Vector v2) { return new Vector( v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z); } ``` Not very interesting. However, I overload the '+' operator for vectors and in the overload I call the AddVector function to avoid code duplication. I was curious whether this would result in two method calls or if it would be optimized at compile or JIT time. I found out that it did result in two method calls because I managed to gain 10% in **total** performance by duplicating the code of the AddVector as well as the dot product method in the '+' and '\*' operator overload methods. Of course, this is a niche case because they get called tens of thousands of times per second, but I didn't expect this. I guess I expected the method to be inlined in the other, or something. And I suppose it's not just the overhead of the method call, but also the copying of the method arguments into the other method (they're structs). It's no big deal, I can just duplicate the code (or perhaps just remove the AddVector method since I never call it directly) but it will nag me a lot in the future when I decide to create a method for something, like splitting up a large method into several smaller ones.
Don't assume that `struct` is the right choice for performance. The copying cost can be significant in some scenarios. Until you measure you don't know. Furthermore, `struct`s have [spooky](https://stackoverflow.com/questions/370859/why-isnan-is-a-static-method-on-the-double-class-instead-of-an-instance-property/370996#370996) behaviors, especially if they're mutable, but even if they're not. In addition, what others have said is correct: * Running under a debugger will disable JIT optimizations, making your performance measurements invalid. * Compiling in Debug mode also makes performance measurements invalid.
If you compile into debug mode or begin the process with a debugger attatched (though you can add one later) then a large class of JIT optimisations, including inlining, won't happen. Try re-running your tests by compiling it in Release mode and then running it without a debugger attatched (Ctrl+F5 in VS) and see if you see the optimisations you expected.
Why can't this be optimized?
[ "", "c#", "performance", "optimization", "methods", "" ]
I'm using C#.Net and the Socket class from the System.Net.Sockets namespace. I'm using the asynchronous receive methods. I understand this can be more easily done with something like a web service; this question is borne out of my curiosity rather than a practical need. My question is: assume the client is sending some binary-serialized object of an unknown length. On my server with the socket, how do I know the entire object has been received and that it is ready for deserialization? I've considered prepending the object with the length of the object in bytes, but this seems unnecessary in the .Net world. What happens if the object is larger than the buffer? How would I know, 'hey, gotta resize the buffer because the object is too big'?
You *either* need the protocol to be self-terminating (like XML is, effectively - you know when you've finished receiving an XML document when it closes the root element) *or* you need to length-prefix the data, *or* you need the other end to close the stream when it's done. In the case of a self-terminated protocol, you need to have enough hooks in so that the reading code can tell when it's finished. With binary serialization you may well not have enough hooks. Length-prefix is by far the easiest solution here.
If you use pure sockets, you need to know the length. Otherwise, the size of the buffer is not relevant, because even if you have a buffer of the size of the whole data, it still may not read all into it - check Stream.Read method, it returns the nr of bites actually read, so you need to loop until all data is received.
c# stream received all data?
[ "", "c#", "sockets", "serialization", "" ]
To put it simple: a swing app that uses sqlitejdbc as backend. Currently, there's no problem launching multiple instances that work with the same database file. And there should be. The file is locked (can't delete it while the app is running) so the check should be trivial. Turns out not. ``` File f = new File("/path/to/file/db.sqlite"); FileChannel channel = new RandomAccessFile(f, "rw").getChannel(); System.out.println(channel.isOpen()); System.out.println(channel.tryLock()); ``` results in ``` true sun.nio.ch.FileLockImpl[0:9223372036854775807 exclusive valid] ``` No matter whether the app is running or not. Am I missing the point? TIA.
FileLocks are exclusive to the JVM, not an individual thread. So if you ran that code inside the same process as your Swing app, you would get the lock because it is shared by the JVM. If your Swing app is not running, no other process is contending for the lock so you will obtain it there is well.
A File System level lock interacts with other applications. You get one of these from FileChannel. So what you do in your example code will make the file seem locked to another process, for example vi. However, other Java threads or processes within the JVM will NOT see the lock. The key sentence is *"File locks are held on behalf of the entire Java virtual machine. They are not suitable for controlling access to a file by multiple threads within the same virtual machine."* You are not seeing the lock, so you are running sqlitejdbc from within the same JVM as your application. So the question is how do you see whether your JVM has already acquired a lock on a file (assuming you don't control the code acquiring the lock)? One suggestion I would have is try and acquire an exclusive lock on a different subset of the file, for example with this code: ``` fc.tryLock(0L, 1L, false) ``` If there is already a lock you should get an OverlappingFileLockException. This is a bit hacky but might work.
FileChannel & RandomAccessFile don't seem to work
[ "", "java", "file-io", "locking", "nio", "" ]
The accepted answer to the question [C++ Library for image recognition: images containing words to string](https://stackoverflow.com/questions/462860/c-library-for-image-recognition-images-containing-words-to-string) recommended that you: 1. Upsize/Downsize your input image to 300 DPI. How would I do this... I was under the impression that DPI was for monitors, not image formats.
I think the more accurate term here is **[resampling](http://en.wikipedia.org/wiki/Resampling)**. You want a pixel resolution high enough to support accurate OCR. Font size (e.g. in [points](http://en.wikipedia.org/wiki/Point_%28typography%29)) is typically measured in units of length, not pixels. Since 72 points = 1 inch, we need 300/72 pixels-per-point for a resolution of 300 dpi ("pixels-per-inch"). That means a typical 12-point font has a height (or more accurately, base-line to base-line distance in single-spaced text) of 50 pixels. Ideally, your source documents should be scanned at an appropriate resolution for the given font size, so that the font in the image is about 50 pixels high. If the resolution is too high/low, you can easily resample the image using a graphics program (e.g. [GIMP](http://www.gimp.org/)). You can also do this programmatically through a graphics library, such as [ImageMagick](http://www.imagemagick.org/script/index.php) which has interfaces for many programming languages.
DPI makes sense whenever you're relating an image in pixels to a physical device with a picture size. In the case of OCR, it usually means the resolution of the scan, i.e. how many pixels will you get for each inch of your scan. A 12-point font is meant to be printed at 12/72 inches per line, and an upper-case character might fill about 80% of that; thus it would be approximately 40 pixels tall when scanned at 300 DPI. Many image formats have a DPI recorded in them. If the image was scanned, this should be the exact setting from the scanner. If it came from a digital camera, it always says 72 DPI, which is a default value mandated by the EXIF specification; this is because a camera can't know the original size of the image. When you create an image with an imaging program, you might have the opportunity to set the DPI to any arbitrary value. This is a convenience for you to specify how you want the final image to be used, and has no bearing on the detail contained in the image. Here's a previous question that asks the details of resizing an image: [How do I do high quality scaling of a image?](https://stackoverflow.com/questions/353039/how-do-i-do-high-quality-scaling-of-a-image)
How do I enlarge a picture so that it is 300 DPI?
[ "", "c++", "image-processing", "computer-vision", "tesseract", "" ]
I'm supporting an existing application written by another developer and I have a question as to whether the choices the data type the developer chose to store dates is affecting the performance of certain queries. Relevant information: The application makes heavy use of a "Business Date" field in one of our tables. The data type for this business date is nvarchar(10) rather than a datetime data type. The format of the dates is "MM/DD/YYYY", so Christmas 2007 is stored as "12/25/2007". Long story short, we have some heavy duty queries that run once a week and are taking a very long time to execute. I'm re-writing this application from the ground up, but since I'm looking at this, I want to know if there is a performance difference between using the datetime data type compared to storing dates as they are in the current database.
You will both save disk-space and increase performance if you use datetime instead of nvarchar(10). If you use the date-fields to do date-calculation (*DATEADD* etc) you will see a massive increase in query-execution-speed, because the fields do not need to be converted to datetime at runtime.
Operations over `DATETIME`s are faster than over `VARCHAR`s converted to `DATETIME`s. If your dates appear anywhere but in `SELECT` clause (like, you add them, `DATEDIFF` them, search for them in `WHERE` clause etc), then you should keep them in internal format.
DB Performance and data types
[ "", "sql", "sql-server", "database-design", "datetime", "" ]
**I wish to write a windows app which does something when I become disconnected from the internet**. I was thinking of writing a very simple C#/Delphi app which simply polls every 20 seconds to see if I'm still connected. If I have to poll I'd really like a solution other than trying to download a web page from the net. I can't assume that a download attempt failing means "not online" since there may be other apps eating up the internet bandwidth. Plus I'm sure constantly connecting/downloading from a particular site is going to get my IP blocked. I'm sure there's a **way to tell if you're online without downloading/connecting to a remote server** but I'm not sure how.
Beware that connected to the Internet does not really mean anything: what if you are connected to your ISP, but the backbone is down, or all the sites you want to access are in a country that went off the grid like recently? Having a connection does not mean you can do what you want. Anyway, as stated before you can use the `InternetGetConnectedState` API to test that you have a valid Internet connection configured. As an example, the following routine told me correctly I had a LAN Connection, but failed to detect that I had my ZoneAlarm firewall set to block "All Internet Activity", which means that you effectively lost all Internet connectivity. Delphi routine: ``` procedure IsConnected; var dwFlags: DWORD; begin if InternetGetConnectedState(@dwFlags, 0) then begin if (dwFlags and INTERNET_CONNECTION_MODEM) = INTERNET_CONNECTION_MODEM then ShowMessage('Modem Connection') else if (dwFlags and INTERNET_CONNECTION_LAN) = INTERNET_CONNECTION_LAN then ShowMessage('LAN Connection') else if (dwFlags and INTERNET_CONNECTION_PROXY) = INTERNET_CONNECTION_PROXY then ShowMessage('Connection thru Proxy') else if (dwFlags and INTERNET_CONNECTION_OFFLINE) = INTERNET_CONNECTION_OFFLINE then ShowMessage('Local system in offline mode') else if (dwFlags and INTERNET_CONNECTION_CONFIGURED) = INTERNET_CONNECTION_CONFIGURED then ShowMessage('Valid connection exists, but might or might not be connected') end else ShowMessage('Not Connected. Try to connect and risk of being prompted to dial into another Internet Service Provider.'); end; ```
Call the [`InternetGetConnectedState`](http://msdn.microsoft.com/en-us/library/aa384702(VS.85).aspx) function. This [knowledgebase article](http://support.microsoft.com/kb/242558) explains how to do it.
How to tell if connected to internet
[ "", "c#", "delphi", "delphi-7", "" ]
Suppose I have an array of a objects of user defined class. Wanted to know how do I extract the elements of the array in PHP. ``` // class definition class User { public $fname; public $lname; } // array of objects of the class defined above $objUser1 = new User(): $objUser2 = new User(): $objUser3 = new User(): $objUser4 = new User(): $alUser = array(); $alUser[] = $objUser1; $alUser[] = $objUser2; $alUser[] = $objUser3; $alUser[] = $objUser4; // trying to iterate and extract values using typcasting - this does not work, what is the alternative. foreach($alUser as $user) { $obj = (User) $user; // gives error - unexpected $user; } ``` Thats how I used to do in java while extracting objects from the Java ArrayList, hence thought the PHP way might be similar. Can anyone explain it.
``` foreach ($alUser as $user) { $obj = $user; } ``` Why do you need typecasting for this?
PHP is a dynamically typed language. There is no need to cast in most cases. It is impossible to cast to a User: see PHP's documentation on [type juggling and casting](https://www.php.net/manual/en/language.types.type-juggling.php). This example would print "`$user is a object (User)`" four times. ``` foreach($alUser as $user) { echo '$user is a ' . get_type($user); if(is_object($user)) { echo ' (' . get_class($user) . ')'; echo "\n"; } ```
PHP Array extracting object
[ "", "php", "arrays", "extract", "javabeans", "casting", "" ]
I have a Linux C++ application and I'd like to test an object pointer for validity before dereferencing it. However try/catch doesn't work for this on Linux because of the segmentation fault. How can this be done?
If you have a scenario where many pointers across your app reference the same limited-lifetime objects, a popular solution is to use [boost smart pointers](http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/smart_ptr.htm). **Edit: in C++11, both of these types are available in the standard library** You would want to use [`shared_ptr`](http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm) for pointer(s) that are responsible for the lifetime of your object and [`weak_ptr`](http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/weak_ptr.htm) for the other pointers, which may become invalid. You'll see that `weak_ptr` has the validity check you're asking for built in.
A segmentation fault is not an Exception (like Java's NullPointerException); it is a signal sent from the OS to the process. Have a look at [the manpage for sigaction](http://www.manpagez.com/man/2/sigaction/) for pointers on how to install a handler for the segmentation fault (SIGSEGV).
Try/Catch a segmentation fault on Linux
[ "", "c++", "linux", "pointers", "segmentation-fault", "" ]
I'm using a `QTabWidget` to render multiple documents in a window, and I want to draw a close button on each tab. I'm using *Vista* and *Qt4*, so the tab widget is a native windows control; this may affect the feasibility. Does anyone know if it is possible to do this using the `QTabWidget` control, or do I have to create a custom widget? If creating a new widget is the only option, any pointers would be much appreciated; I'm relatively new to Qt.
Currently there is no way to do this with the stock QTabWidget, however the upcoming Qt 4.5 (planned to be released in March 2009) will have the [ability to add close buttons](http://labs.trolltech.com/blogs/2008/07/02/some-qtabbar-qtabwidget-love/) to tabs either manually or by setting a `QTabBar.TabsClosable` property. Until then, the only way to get close buttons is to subclass `QTabWidget` or `QTabBar` and add it manually (possible, but not trivial).
**Since Qt 4.5**. If you just call `setTabsClosable(true)` on `QTabWidget`, you will have the close buttons but they won't be bound to an action. You have to connect the tabCloseRequested(int) signal to one of your own slots if you want the buttons to do something. ``` MainWindow::MainWindow() m_tabs = new QTabWidget(); m_tabs->setTabsClosable(true); connect(m_tabs, SIGNAL(tabCloseRequested(int)), this, SLOT(closeTab(int))); void MainWindow::closeTab(const int& index) { if (index == -1) { return; } QWidget* tabItem = m_tabs->widget(index); // Removes the tab at position index from this stack of widgets. // The page widget itself is not deleted. m_tabs->removeTab(index); delete(tabItem); tabItem = nullptr; } ```
Putting a close button on QTabWidget
[ "", "c++", "windows", "qt", "qtabwidget", "" ]
T4 template files are automatically recognizable by the IDE under C# projects, but I have no clue on how they can be integrated into C++ projects (other than using make files). Any ideas?
T4 Template files can be integrated into C++ projects, but it's a bit more work than with a C#/VB project. Create a new text file in your C++ project and give it a .tt extension. Then write your template as normal. A C++ project then needs further work to get it to transform the templates. The quick and dirty way I got it to work was to add a custom build step and have it call "C:\Program Files\Common Files\Microsoft Shared\TextTemplating\1.1\TextTransform.exe" directly. Another way I found was to add a custom MSBuild task. Instructions can be found [here](https://web.archive.org/web/20200803154046/http://geekswithblogs.net/EltonStoneman/archive/2008/07/25/an-msbuild-task-to-execute-t4-templates.aspx) [This](https://www.hanselman.com/blog/t4-text-template-transformation-toolkit-code-generation-best-kept-visual-studio-secret) page has more information and some good links to other pages on using T4 code generation.
MSBuild Task will not work as this is a vcproj file (C++) so vcbuild is used. The easiest way to get the tt compiled is to add a custom build step like below.. ``` "C:\Program Files (x86)\Common Files\Microsoft Shared\TextTemplating\1.1\TextTransform.exe" -out "$(ProjectDir)\VSProject.cpp" -I "$(ProjectDir)" "$(ProjectDir)\VSProject.tt" ``` I spent several hours investigating the MSBuild Task solution above and it's pretty good for managed code but I can't see any way to use it for C++ (bar converting the vcproj to csproj eek)
How to use T4 code generation templates with VS C++ projects?
[ "", "c++", "visual-studio", "t4", "" ]
Let me start out by saying that I'm not a JavaScript developer so this question may be rather basic. When simulating IE's nonstandard [`all`](http://msdn.microsoft.com/en-us/library/aa752281.aspx) property I'm using `getElementsByTagName("*")`, is there a significant performance difference between both methods?
Essentially there should be no noticeable performance hit, and the use of `document.all` is unacceptable anyway. There is however a question as to *why* you would be interested in collecting a set of every element anyway? I can't think of a single use case for that off-hand that couldn't be handled better another way.
For Interest, you may find this lecture by John Resig interesting. Its relevant to new and experienced users alike when using dom methods like you are. * <http://ejohn.org/blog/the-dom-is-a-mess/> It discusses many lovely caveats of dom methods in many browsers. One such, is that `getElementsByTagName(“*”)` will return **no** elements in IE5, and does [weird things](http://webbugtrack.blogspot.com/2007/09/bug-204-getelementsbytagname-doesnt.html) with Objects + `getElementsByTagName("*")` under IE7, and according to the talk, it makes this: ``` <a id="length"></a> ``` Perform as if somebody had done: ``` var a = getElementsByTagName("a"); a.length = ""; # This overrides the arrays length attribute :/ ``` So that you can't iterate the array. I don't know which javascript libraries circumvent this flaw, but you really should use one to avoid cross-browser headaches.
What are the performance implications of getElementsByTagName("*")?
[ "", "javascript", "cross-browser", "" ]
I want to create a list of lambda objects from a list of constants in Python; for instance: ``` listOfNumbers = [1,2,3,4,5] square = lambda x: x * x listOfLambdas = [lambda: square(i) for i in listOfNumbers] ``` This will create a list of lambda objects, however, when I run them: ``` for f in listOfLambdas: print f(), ``` I would expect that it would print ``` 1 4 9 16 25 ``` Instead, it prints: ``` 25 25 25 25 25 ``` It seems as though the lambdas have all been given the wrong parameter. Have I done something wrong, and is there a way to fix it? I'm in Python 2.4 I think. EDIT: a bit more of trying things and such came up with this: ``` listOfLambdas = [] for num in listOfNumbers: action = lambda: square(num) listOfLambdas.append(action) print action() ``` Prints the expected squares from 1 to 25, but then using the earlier print statement: ``` for f in listOfLambdas: print f(), ``` still gives me all `25`s. How did the existing lambda objects change between those two print calls? Related question: [Why results of map() and list comprehension are different?](https://stackoverflow.com/questions/139819/why-results-of-map-and-list-comprehension-are-different)
I'm guessing that the lambda you're creating in the list comprehension is bound to the variable i which eventually ends up at 5. Thus, when you evaluate the lambdas after the fact, they're all bound to 5 and end up calculating 25. The same thing is happening with num in your second example. When you evaluate the lambda inside the loop it's num hasn't changed so you get the right value. After the loop, num is 5... I'm not quite sure what you're going for, so I'm not sure how to suggest a solution. How about this? ``` def square(x): return lambda : x*x listOfLambdas = [square(i) for i in [1,2,3,4,5]] for f in listOfLambdas: print f() ``` This gives me the expected output: ``` 1 4 9 16 25 ``` Another way to think of this is that a lambda "captures" its lexical environment at the point where it is created. So, if you give it **num** it doesn't actually resolve that value until its invoked. This is both confusing and powerful.
You have: ``` listOfLambdas = [lambda: i*i for i in range(6)] for f in listOfLambdas: print f() ``` Output: ``` 25 25 25 25 25 25 ``` You need currying! Aside from being delicious, use this default value "hack". ``` listOfLambdas = [lambda i=i: i*i for i in range(6)] for f in listOfLambdas: print f() ``` Output: ``` 0 1 4 9 16 25 ``` Note the `i=i`. That's where the magic happens.
How do I create a list of lambdas (in a list comprehension/for loop)?
[ "", "python", "lambda", "scope", "closures", "list-comprehension", "" ]
I am wondering what it would take to make something like this work: ``` using System; class Program { static void Main() { var f = new IFoo { Foo = "foo", Print = () => Console.WriteLine(Foo) }; } } interface IFoo { String Foo { get; set; } void Print(); } ``` The anonymous type created would look something like this: ``` internal sealed class <>f__AnonymousType0<<Foo>j__TPar> : IFoo { readonly <Foo>j__TPar <Foo>i__Field; public <>f__AnonymousType0(<Foo>j__TPar Foo) { this.<Foo>i__Field = Foo; } public <Foo>j__TPar Foo { get { return this.<Foo>i__Field; } } public void Print() { Console.WriteLine(this.Foo); } } ``` Is there any reason that the compiler would be unable to do something like this? Even for non-void methods or methods that take parameters the compiler should be able to infer the types from the interface declaration. **Disclaimer:** While I do realize that this is not currently possible and it would make more sense to simply create a concrete class in this instance I am more interested in the theoretical aspects of this.
There would be a few issues with overloaded members, indexers, and explicit interface implementations. However, you could probably define the syntax in a way that allows you to resolve those problems. Interestingly, you can get pretty close to what you want with C# 3.0 by writing a library. Basically, you could do this: ``` Create<IFoo> ( new { Foo = "foo", Print = (Action)(() => Console.WriteLine(Foo)) } ); ``` Which is pretty close to what you want. The primary differences are a call to "Create" instead of the "new" keyword and the fact that you need to specify a delegate type. The declaration of "Create" would look like this: ``` T Create<T> (object o) { //... } ``` It would then use Reflection.Emit to generate an interface implementation dynamically at runtime. This syntax, however, does have problems with explicit interface implementations and overloaded members, that you couldn't resolve without changing the compiler. An alternative would be to use a collection initializer rather than an anonymous type. That would look like this: ``` Create { new Members<IFoo> { {"Print", ((IFoo @this)=>Console.WriteLine(Foo))}, {"Foo", "foo"} } } ``` That would enable you to: 1. Handle explicit interface implementation by specifying something like "IEnumerable.Current" for the string parameter. 2. Define Members.Add so that you don't need to specify the delegate type in the initializer. You would need to do a few things to implement this: 1. Writer a small parser for C# type names. This only requires ".", "[]", "<>",ID, and the primitive type names, so you could probably do that in a few hours 2. Implement a cache so that you only generate a single class for each unique interface 3. Implement the Reflection.Emit code gen. This would probably take about 2 days at the most.
It requires c# 4, but the opensource framework [impromptu interface](http://code.google.com/p/impromptu-interface/) can fake this out of the box using DLR proxies internally. The performance is good although not as good as if the change you proposed existed. ``` using ImpromptuInterface.Dynamic; ``` ... ``` var f = ImpromptuGet.Create<IFoo>(new{ Foo = "foo", Print = ReturnVoid.Arguments(() => Console.WriteLine(Foo)) }); ```
C# feature request: implement interfaces on anonymous types
[ "", "c#", "compiler-construction", "anonymous-types", "" ]
I have a class that contains an array. I want this array to be set at the length of a constant: ``` // Entities.h class Entities { private: const int maxLimit; int objects[maxLimit]; int currentUsage; public: Entities(); bool addObject(int identifier); void showStructure(); }; ``` The main problem I'm having is with the constructor. I thought: ``` // Entities.cpp Entities::Entities() : maxLimit(50) { currentUsage = 0; cout << "Entities constructed with max of 50" << endl; } ``` would have been sufficient...but not so. I don't know if I can use the initialiser list for array initialisation. How can I initialise the `objects` array using the `maxLimit` const? I'm relatively new to classes in C++ but I have experience with Java. I'm mainly testing out this phenomenon of 'constness'.
The array must have a constant length. I mean a length that is the same for all objects of that class. That is because the compiler has to know the size of each object, and it must be the same for all objects of that particular class. So, the following would do it: ``` class Entities { private: static const int maxLimit = 50; int objects[maxLimit]; int currentUsage; public: Entities(); bool addObject(int identifier); void showStructure(); }; ``` And in the cpp file: ``` const int Entities::maxLimit; ``` I prefer to use an enumeration for that, because i won't have to define the static in the cpp file then: ``` class Entities { private: enum { maxLimit = 50 }; int objects[maxLimit]; int currentUsage; public: Entities(); bool addObject(int identifier); void showStructure(); }; ``` If you want to have a per-object size of the array, then you can use a dynamic array. `vector` is such one: ``` class Entities { private: const int maxLimit; std::vector<int> objects; int currentUsage; public: Entities(); bool addObject(int identifier); void showStructure(); }; // Entities.cpp Entities::Entities(int limit) : maxLimit(limit), objects(limit), currentUsage(0) { cout << "Entities constructed with max of 50" << endl; } ``` Best is to do as much initialization in the initialization list as possible.
You can use template argument if you need to set array size at compile time: ``` template<size_t maxLimit> class Entities { int objects[maxLimit]; public: Entities() {} ... }; Entities<1000> inst; ```
C++ Array Member of Constant Length (Initialisation of)
[ "", "c++", "" ]
What's the fastest and easiest to read implementation of calculating the sum of digits? I.e. Given the number: 17463 = 1 + 7 + 4 + 6 + 3 = 21
You could do it arithmetically, without using a string: ``` sum = 0; while (n != 0) { sum += n % 10; n /= 10; } ```
I use ``` int result = 17463.ToString().Sum(c => c - '0'); ``` It uses only 1 line of code.
Sum of digits in C#
[ "", "c#", "algorithm", "sum-of-digits", "" ]
I realize that SOAP webservices in .NET return XML representation of whatever object the web method returns, but if I want to return data formatting in XML what is the best object to store it in? I am using the [answer](https://stackoverflow.com/questions/220867/how-to-deal-with-xml-in-c/220981#220981) to [this question](https://stackoverflow.com/questions/220867/how-to-deal-with-xml-in-c) to write my XML, here is the code: ``` XmlWriter writer = XmlWriter.Create(pathToOutput); writer.WriteStartDocument(); writer.WriteStartElement("People"); writer.WriteStartElement("Person"); writer.WriteAttributeString("Name", "Nick"); writer.WriteEndElement(); writer.WriteStartElement("Person"); writer.WriteStartAttribute("Name"); writer.WriteValue("Nick"); writer.WriteEndAttribute(); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); ``` Now I can return this output as a String to my calling webmethod, but it shows up as `<string> XML HERE </string>`, is there anyway to just return the full xml? Please in your answer, give an example of how to use said object with either XmlWriter or another internal object (if you consider XmlWriter to be a poor choice). The System.Xml package (namespace) has many objects, but I haven't been able to uncover decent documentation on how to use the objects together, or what to use for what situations.
This is how I ended up doing it; ``` StringBuilder sb = new StringBuilder(); XmlWriter writer = XmlWriter.Create(sb, settings); writer.WriteStartDocument(); writer.WriteStartElement("People"); writer.WriteStartElement("Person"); writer.WriteAttributeString("Name", "Nick"); writer.WriteEndElement(); writer.WriteStartElement("Person"); writer.WriteStartAttribute("Name"); writer.WriteValue("Nick"); writer.WriteEndAttribute(); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(sb.ToString()); return xmlDocument; ``` May not be the best method, but it appears to be working. Let me know if you have a better method. Thanks.
Just return a XmlDocument. e.g. ``` [WebMethod] public XmlDocument Quux() { } ```
Returning XML natively in a .NET (C#) webservice?
[ "", "c#", ".net", "xml", "web-services", "" ]
Okay, `mkstemp` is the preferred way to create a temp file in POSIX. But it opens the file and returns an `int`, which is a file descriptor. From that I can only create a FILE\*, but not an `std::ofstream`, which I would prefer in C++. (Apparently, on AIX and some other systems, you can create an `std::ofstream` from a file descriptor, but my compiler complains when I try that.) I know I could get a temp file name with `tmpnam` and then open my own ofstream with it, but that's apparently unsafe due to race conditions, and results in a compiler warning (g++ v3.4. on Linux): ``` warning: the use of `tmpnam' is dangerous, better use `mkstemp' ``` So, is there any portable way to create an `std::ofstream` to a temp file?
I think this should work: ``` char *tmpname = strdup("/tmp/tmpfileXXXXXX"); ofstream f; int fd = mkstemp(tmpname); f.attach(fd); ``` **EDIT:** Well, this might not be portable. If you can't use attach and can't create a ofstream directly from a file descriptor, then you have to do this: ``` char *tmpname = strdup("/tmp/tmpfileXXXXXX"); mkstemp(tmpname); ofstream f(tmpname); ``` As *mkstemp* already creates the file for you, race condition should not be a problem here.
I've done this function: ``` #include <stdlib.h> #include <fstream> #include <iostream> #include <vector> std::string open_temp(std::string path, std::ofstream& f) { path += "/XXXXXX"; std::vector<char> dst_path(path.begin(), path.end()); dst_path.push_back('\0'); int fd = mkstemp(&dst_path[0]); if(fd != -1) { path.assign(dst_path.begin(), dst_path.end() - 1); f.open(path.c_str(), std::ios_base::trunc | std::ios_base::out); close(fd); } return path; } int main() { std::ofstream logfile; open_temp("/tmp", logfile); if(logfile.is_open()) { logfile << "hello, dude" << std::endl; } } ``` You should probably make sure to call umask with a proper file creation mask (I would prefer 0600)- the manpage for mkstemp says that the file mode creation mask is not standardized. It uses the fact that mkstemp modifies its argument to the filename that it uses. So, we open it and close the file it opened (so, to not have it opened twice), being left with a ofstream that is connected to that file.
How to create a std::ofstream to a temp file?
[ "", "c++", "file", "file-io", "mkstemp", "" ]
We're building a Silverlight application which will be offered as SaaS. The end product is a Silverlight client that connects to a WCF service. As the number of clients is potentially large, updating needs to be easy, preferably so that all instances can be updated in one go. Not having implemented multi tenancy before, I'm looking for opinions on how to achieve * Easy upgrades * Data security * Scalability Three different models to consider are listed on [msdn](http://msdn.microsoft.com/en-us/library/aa479086.aspx) 1. Separate databases. This is not easy to maintain as all schema changes will have to be applied to each customer's database individually. Are there other drawbacks? A pro is data separation and security. This also allows for slight modifications per customer (which might be more hassle than it's worth!) 2. Shared Database, Separate Schemas. A TenantID column is added to each table. Ensuring that each customer gets the correct data is potentially dangerous. Easy to maintain and scales well (?). 3. Shared Database, Separate Schemas. Similar to the first model, but each customer has its own set of tables in the database. Hard to restore backups for a single customer. Maintainability otherwise similar to model 1 (?). Any recommendations on articles on the subject? Has anybody explored something similar with a Silverlight SaaS app? What do I need to consider on the client side?
Depends on the type of application and scale of data. Each one has downfalls. 1a) Separate databases + single instance of WCF/client. Keeping everything in sync will be a challenge. How do you upgrade X number of DB servers at the same time, what if one fails and is now out of sync and not compatible with the client/WCF layer? 1b) "Silos", separate DB/WCF/Client for each customer. You don't have the sync issue but you do have the overhead of managing many different instances of each layer. Also you will have to look at SQL licensing, I can't remember if separate instances of SQL are licensed separately ($$$). Even if you can install as many instances as you want, the overhead of multiple instances will not be trivial after a certain point. 3) Basically same issues as 1a/b except for licensing. 2) Best upgrade/management scenario. You are right that maintaining data isolation is a huge concern (1a technically shares this issue at a higher level). The other issue is if your application is data intensive you have to worry about data scalability. For example if every customer is expected to have tens/hundreds millions rows of data. Then you will start to run into issues and query performance for individual customers due to total customer base volumes. Clients are more forgiving for slowdowns caused by their own data volume. Being told its slow because the other 99 clients data is large is generally a no-go. Unless you know for a fact you will be dealing with huge data volumes from the start I would probably go with #2 for now, and begin looking at clustering or moving to 1a/b setup if needed in the future.
We also have a SaaS product and we use solution #2 (Shared DB/Shared Schema with TenandId). Some things to consider for Share DB / Same schema for all: 1. As mention above, high volume of data for one tenant may affect performance of the other tenants if you're not careful; for starters index your tables properly/carefully and never ever do queries that force a table scan. Monitor query performance and at least plan/design to be able to partition your DB later on based some criteria that makes sense for your domain. 2. Data separation is very very important, you don't want to end up showing a piece of data to some tenant that belongs to other tenant. every query must have a WHERE TenandId = ... in it and you should be able to verify/enforce this during dev. 3. Extensibility of the schema is something that solutions 1 and 3 may give you, but you can go around it by designing a way to extend the fields that are associated with the documents/tables in your domain that make sense (ie. Metadata for tables as the msdn article mentions)
Multi-tenancy with SQL/WCF/Silverlight
[ "", "sql", "sql-server", "wcf", "silverlight", "saas", "" ]
I have the following code, which is the basis for pagination in a larger application. However, it does not work, as although I should be obtaining the value of pg from the url, pg never goes higher than 2. For some reason, next = pg+1; seems to always see pg as 1, regardless of what is passed on the url. It is a similar problem with last. I assume I am overriding the value obtained from GET, but I am unsure where. The problem seems to be in how I am working out $max and the limit, as instead of 0, 10, -10, 10 gets passed. Also the ifcode before $max does not seem to succeed in stopping pg from being 0. ``` <?php if (isset($_GET["pg"])) { $pg = $_GET["pg"]; } else $pg = 1; $con = mysql_connect("localhost","",""); if(!$con) { die('Connection failed because of' .mysql_error()); } mysql_select_db("ebay",$con); if ($pg < 1) { $pg = 1; } elseif ($pg > $last) { $pg = $last; } $table = 'AUCTIONS'; $page_rows = 10; $max = ' limit ' .($pg - 1) * $page_rows .', ' .$page_rows; $rows = getRowsByArticleSearch($query, $table, $max); $rowcount = count($rows); echo $rowcount; $last = ceil($rowcount/$page_rows); $page_rows = 10; $rowcount = 2; // Would normally obtain the number of rows returned, but database stuff is snipped for brevity $last = ceil($rowcount/$page_rows); if ($pg < 1) { $pg = 1; } elseif ($pg > $last) { $pg = $last; } $self = htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'utf-8'); echo " <a href='$self?pg=1'> <<-First</a> "; $previous = $pg-1; echo " <a href='$self?pg=$previous'> <-Previous</a> "; echo "---------------------------"; $next = $pg+1; echo " <a href='$self?pg=$next'>Next -></a> "; echo " <a href='$self?pg=$last'>Last ->></a> "; ```
based on the now revised question: ``` $rowcount = count($rows); ``` will naturally always return 10, as you're limiting the result ``` ... LIMIT 10; ``` But this might help: [SQL CALC FOUND ROWS](http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows) Example: ``` mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name -> WHERE id > 100 LIMIT 10; mysql> SELECT FOUND_ROWS(); ``` The first query will still return your articles, while the second will return the number of rows the previous select would have had if not using the LIMIT clause. Hope that helps.
Here's your problem: ``` $last = ceil($rowcount/$page_rows); ``` That's setting $last to be 1, and then you have: ``` if ($pg > $last) { $pg = $last; } ``` Edit: I wonder if you meant this, instead: ``` $last = ceil($page_rows/$rowcount); ``` Edit again: as per Cassy's answer, you probably really just need to set the right values for these variables: ``` $page_rows = 10; $rowcount = 2; ```
pagination incrementing problem
[ "", "php", "" ]
I am specifically looking for JPA code generation technique First, what are all the project could generate JPA compliant code? (Eg. HibernateTools) Second, I would also like to customize the code generation utility, as it has to compliant to our corporate standards. If not, what are all the framework available to generate java code using reflection? so I can write from scratch. Note: I used eclipse to generate JPA code and refactor it repeatedly to make it compliant.
I also have difficulties understanding the question, but I'll try to rephrase: * You have a lot of data in a DB and want to access it via JPA * You don't want to manually write the classes to access the different DBs/tables * Currently all/most of your model classes are generated from within Eclipse * These models have JPA annotations * The model classes (or the annotations) are not according to corporate standards When you say "JPA java code generation", I understand generating JPA annotated model classes from a supplied DB connection. Most frameworks often refer to this as reverse engineering. Now you have two questions: 1. What code generators can be recommended to generate JPA annotated classes? 2. Is it possible to customize the output of these frameworks, and in which way? To answer to the first question: * [Hibernate Tools](http://tools.hibernate.org) - already mentioned in the question, but I prefer this one * [EclipseLink](http://www.eclipse.org/eclipselink/) * [Netbeans](http://wiki.netbeans.org/BestPracticesWithJPAAndBeansBinding) I really like the Netbeans code generation, especially if you show the results to someone not familiar with JPA. At the level of customization I can only share the experience I had with Hibernate Tools. Especially for reproducible results, try to use the [ant-based tasks](http://docs.jboss.org/tools/3.0.0.CR1/en/hibernatetools/html_single/index.html#ant). You can easily add some targets to your build and code generation can be done at two levels: * Configure exporters using [properties](http://docs.jboss.org/tools/3.0.0.CR1/en/hibernatetools/html_single/index.html#d0e3669) * Provide custom [freemarker templates](http://freemarker.sourceforge.net/) With the templates you should be able to cover most of the corporate standards. Look into the `pojo` directory of the hibernate-tools package. The easiest way to customize the code generation is to copy and adapt the templates and have them put before the hibernate-tools.jar in the ant task used to create the pojos. As already pointed out in another comment, it might be difficult to modify the generated code afterwards. I hope the following tips can help you: * Try to separate generated and customized source files in different folders. * Think about using `@MappedSuperclass` for classes which you may want to adapt in a manual step.
Another efficient solution for JPA code generation is "**Telosys Tools**" An **Eclipse plugin** working from an existing database ( "database firts" approach ) with **customizable templates**. This solution is more flexible than Dali thanks to its lightweight model and the Velocity templates (shared on GitHub ) See the web site : <http://www.telosys.org/> The plugin on Eclipse Marketplace : <http://marketplace.eclipse.org/content/telosys-tools> A brief description of the principle : <http://labs.sogeti.com/code-generation-can-it-be-simple-and-pragmatic/> For **JPA generation**, use the **JPA templates** available on GitHub : <https://github.com/telosys-templates-v3>
JPA java code generation
[ "", "java", "jpa", "autocomplete", "templates", "code-generation", "" ]