Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception. For instance: ``` System.out.println("obj: "+obj); ``` instead of: ``` System.out.println("obj: "+obj.toString()); ``` Is there any difference apart from t...
There's little difference. Use the one that's shorter and works more often. If you actually want to get the string value of an object for other reasons, and want it to be null friendly, do this: ``` String s = String.valueOf(obj); ``` **Edit**: The question was extended, so I'll extend my answer. In both cases, the...
As others have said - use the `"" + obj` method. According to The [Java Language Spec](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.18.1): * If the term is null, use `"null"` * Primitive types are converted using the boxed-type constructor `new Boolean(X)` or whatever * `toString()` is in...
Explicit vs implicit call of toString
[ "", "java", "tostring", "" ]
I have a desktop application having heavyweight components (JxBrowser) in a JFrame. How can I make a snapshot from the GUI and save it to for example a png file? Note: The method using Graphics2d and Component.paint()/paintAll()/print/printAll works only for lightweight components. Any answers appreciated! **EDIT** ...
My name is Roman and I'm developer at TeamDev. JxBrowser component it's a heavyweight component that embedds a native mozilla window to display web pages. To get screenshot of a full web page from JxBrowser component you can really use the Java Robot functionality with web page scrolling. For small web pages this solu...
You mean programmatically? What about ``` Point p = yourAwtComponent.getLocationOnScreen(); int w = yourAwtComponent.getWidth(); int h = yourAwtComponent.getHeight(); Rectangle rectangle = new Rectangle( p.x, p.y, w, h ); Image image = robot.createScreenCapture(rectangle); ``` And then something like this: ``...
Capturing heavyweight java components?
[ "", "java", "user-interface", "screenshot", "jxbrowser", "" ]
I have some jQuery/JavaScript code that I want to run only when there is a hash (`#`) anchor link in a URL. How can you check for this character using JavaScript? I need a simple catch-all test that would detect URLs like these: * `example.com/page.html#anchor` * `example.com/page.html#anotheranchor` Basically someth...
Simple use of [location hash](https://developer.mozilla.org/en-US/docs/Web/API/Location/hash): ``` if(window.location.hash) { // Fragment exists } else { // Fragment doesn't exist } ```
``` if(window.location.hash) { var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character alert (hash); // hash found } else { // No hash found } ```
How can you check for a #hash in a URL using JavaScript?
[ "", "javascript", "jquery", "anchor", "fragment-identifier", "" ]
When I write code like this in VS 2008: ``` .h struct Patterns { string ptCreate; string ptDelete; string ptDrop; string ptUpdate; string ptInsert; string ptSelect; }; class QueryValidate { string query; string pattern; static Patterns pts; public: ...
You're trying to create a non-static member (ptCreate) of a static member (pts). This won't work like this. You got two options, either use a struct initializer list for the Patterns class. ``` Patterns QueryValidate::pts = {"CREATE", "DELETE"}; // etc. for every string ``` Or, much safer (and better in my opinion),...
You can only initialize the structure as a whole, as in: ``` Patterns QueryValidate::pts = { "something", "something", ... }; ```
Why can't I use static members, for example static structures, in my classes in VS2008?
[ "", "c++", "visual-studio-2008", "definition", "static-members", "" ]
I'm working with a MySQL query that writes into an outfile. I run this query once every day or two and so I want to be able to remove the outfile without having to resort to su or sudo. The only way I can think of making that happen is to have the outfile written as owned by someone other than the mysql user. Is this p...
The output file is created by the mysqld process, not by your client process. Therefore the output file must be owned by the uid and gid of the mysqld process. You can avoid having to sudo to access the file if you access it from a process under a uid or gid that can access the file. In other words, if mysqld creates ...
Not using the "SELECT...INTO OUTFILE" syntax, no. You need to run the query (ie client) as another user, and redirect the output. For example, edit your crontab to run the following command whenever you want: ``` mysql db_schema -e 'SELECT col,... FROM table' > /tmp/outfile.txt ``` That will create /tmp/outfile.txt ...
How can I have MySQL write outfiles as a different user?
[ "", "mysql", "sql", "into-outfile", "" ]
I have a fairly huge database with a master table with a single column GUID (custom GUID like algorithm) as primary key and 8 child tables that have foreign key relationships with this GUID column. All the tables have approximately 3-8 million records. None of these tables have any BLOB/CLOB/TEXT or any other fancy dat...
Your ideas should work. the first is probably the way I would use. Some cautions and things to think about when doing this: Do not do this unless you have a current backup. I would leave both values in the main table. That way if you ever have to figure out from some old paperwork which record you need to access, y...
It's difficult to say what the "best" or "most suitable" approach is as you have not described what you are looking for in a solution. For example, do the tables need to be available for query while you are migrating to new IDs? Do they need to be available for concurrent modification? Is it important to complete the m...
updating primary key of master and child tables for large tables
[ "", "sql", "sql-server", "oracle", "migration", "mysql4", "" ]
I'm getting a strange error from `g++` 3.3 in the following code: ``` #include <bitset> #include <string> using namespace std; template <int N, int M> bitset<N> slice_bitset(const bitset<M> &original, size_t start) { string str = original.to_string<char, char_traits<char>, allocator<char> >(); string newstr ...
The selected answer from [CAdaker](https://stackoverflow.com/questions/231868/c-two-or-more-data-types-in-declaration#231904) solves the problem, but does not explain **why** it solves the problem. When a function template is being parsed, lookup does not take place in dependent types. As a result, constructs such as ...
Use either just ``` original.to_string(); ``` or, if you really need the type specifiers, ``` original.template to_string<char, char_traits<char>, allocator<char> >(); ```
C++ two or more data types in declaration
[ "", "c++", "templates", "g++", "" ]
I am trying to set the innerxml of a xmldoc but get the exception: Reference to undeclared entity ``` XmlDocument xmldoc = new XmlDocument(); string text = "Hello, I am text &alpha; &nbsp; &ndash; &mdash;" xmldoc.InnerXml = "<p>" + text + "</p>"; ``` This throws the exception: > Reference to undeclared entity 'alpha...
XML, unlike HTML does not define entities (ie named references to UNICODE characters) so &alpha; &mdash; etc. are not translated to their corresponding character. You must use the numerical value instead. You can only use &lt; and &amp; in XML If you want to create HTML, use an HtmlDocument instead.
In .Net, you can use the `System.Xml.XmlConvert` class: ``` string text = XmlConvert.EncodeName("Hello &alpha;"); ``` Alternatively, you can declare the entities locally by putting the declarations between square brackets in a DOCTYPE declaration. Add the following header to your xml: ``` <!DOCTYPE documentElement[ ...
Reference to undeclared entity exception while working with XML
[ "", "c#", "xml", "dtd", "" ]
I have a collection of domain objects that I need to convert into another type for use by the .NET framework. What is the best practice for doing such a transformation? Specifically, I have a type called ContentEntry and I need to convert it into a SyndicationItem for use in putting into a SyndicationFeed. The convers...
As as cannot modify the SyndicationItem's constructors, I'd suggest you use the [factory pattern](http://en.wikipedia.org/wiki/Factory_method_pattern). Create a SyndicationItemFactory class that has the method CreateSyndicationItem(). This method returns a SyndicationItem object. In this case, you'll only need one vers...
I'd suggest looking at [Adapter Pattern](http://en.wikipedia.org/wiki/Adapter_pattern) > In computer programming, the adapter > design pattern (often referred to as > the wrapper pattern or simply a > wrapper) translates one interface for > a class into a compatible interface.
Best OO practice to adapt one type to another?
[ "", "c#", ".net", "oop", "" ]
I'm using Tomcat 5.5 as my servlet container. My web application deploys via .jar and has some resource files (textual files with strings and configuration parameters) located under its WEB-INF directory. Tomcat 5.5 runs on ubuntu linux. The resource file is read with a file reader: `fr = new FileReader("messages.pro...
I'm guessing the problem is you're trying to use a relative path to access the file. Using absolute path should help (i.e. "/home/tomcat5/properties/messages.properties"). However, the usual solution to this problem is to use the getResourceAsStream method of the ClassLoader. Deploying the properties file to "WEB-INF/...
If you are trying to access this file from a Servlet-aware class, such as a ContextListener or other lifecycle listener, you can use the ServletContext object to get the path to a resource. These three are roughly equivalent. (Don't confuse getResourceAsStream as the same as the one provided by the `ClassLoader` class...
tomcat 5.5 - problem with reading resource files
[ "", "java", "tomcat", "servlets", "resources", "" ]
I want to execute a php-script from php that will use different constants and different versions of classes that are already defined. Is there a sandbox php\_module where i could just: ``` sandbox('script.php'); // run in a new php environment ``` instead of ``` include('script.php'); // run in the same environment...
There is [runkit](http://www.php.net/runkit), but you may find it simpler to just call the script over the command line (Use [shell\_exec](http://www.php.net/shell_exec)), if you don't need any interaction between the master and child processes.
The is a class on GitHub that may help, early stages but looks promising. <https://github.com/fregster/PHPSandbox>
Is there a way to execute php code in a sandbox from within php
[ "", "php", "module", "sandbox", "" ]
I'm using [Interop.Domino.dll](http://www.codeproject.com/KB/cs/lotusnoteintegrator.aspx) to retrieve E-mails from a Lotus "Database" (Term used loosely). I'm having some difficulty in retrieving certain fields and wonder how to do this properly. I've been using `NotesDocument.GetFirstItem` to retrieve Subject, From an...
Hah, got it! ``` Object[] ni = (Object[])nDoc.Items; string names_values = ""; for (int x = 0; x < ni.Length; x++) { NotesItem item = (NotesItem)ni[x]; if (!string.IsNullOrEmpty(item.Name)) names_values += x.ToString() + ": " + item.Name + "\t\t" + item.Text + "\r\n"; } ``` This returned a list of indices, names, and...
The Body item is a NotesRichTextItem, not a regular NotesItem. They are a different type of object in the Lotus Notes world (and often the source of much developer frustration!) I don't have much experience with using COM to connect to Domino, and I know there are differences in what you have access to, but the Domino...
C#, Lotus Interop: Getting Message Information
[ "", "c#", "lotus-notes", "interop-domino", "" ]
In PHP 5.2 there was a nice security function added called "input\_filter", so instead of saying: ``` $name = $_GET['name']; ``` you can now say: ``` $name = filter_input (INPUT_GET, 'name', FILTER_SANITIZE_STRING); ``` and it automatically sanitizes your string, there is also: * `FILTER_SANITIZE_ENCODED` * `FILTE...
You could manually force it to read the arrays again by using [filter\_var](https://www.php.net/manual/en/function.filter-var.php) and [filter\_var\_array](https://www.php.net/manual/en/function.filter-var-array.php) ``` $name = filter_var ( $_GET['name'], FILTER_SANITIZE_STRING ); ```
A handy way to do this without modifying the global array: ``` if (!($name = filter_input(INPUT_GET, 'name'))) { $name = 'default_value'; } ``` Or using the ternary operator: ``` $name = ($name = filter_input(INPUT_GET, 'name')) ? $name : 'default_value'; ```
PHP's new input_filter does not read $_GET or $_POST arrays
[ "", "php", "security", "filter-input", "" ]
I have already visited [Preferred Python unit-testing framework](https://stackoverflow.com/questions/191673/preferred-python-unit-testing-framework). I am not just looking at Python Unit Testing Framework, but also code coverage with respect to unit tests. So far I have only come across [coverage.py](http://nedbatcheld...
PyDev seems to allow code coverage from within Eclipse. I've yet to find how to integrate that with my own (rather complex) build process, so I use Ned Batchelder's coverage.py at the command line.
We use this [Django coverage integration](http://www.djangosnippets.org/snippets/705/), but instead of using the default coverage.py reporting, we generate some simple HTML: [Colorize Python source using the built-in tokenizer](http://code.activestate.com/recipes/52298/).
Code Coverage and Unit Testing of Python Code
[ "", "python", "visual-studio-2008", "unit-testing", "code-coverage", "" ]
Informed options needed about the merits of flat file database. I'm considering using a flat file database scheme to manage data for a custom blog. It would be deployed on Linux OS variant and written in Java. What are the possible negatives or positives regarding performance for reading and writing of both articles a...
Flat file databases have their place and are quite workable for the right domain. Mail servers and NNTP servers of the past really pushed the limits of how far you can really take these things (which is actually quite far -- files systems can have millions of files and directories). Flat file DBs two biggest weakness...
*(answer copied and modified from [here](https://stackoverflow.com/questions/326203/alternatives-to-mysql#326210))* I would advise against using a flat file for anything besides read-only access, because then you'd have to deal with concurrency issues like making sure only one process is writing to the file at once. I...
Are flat file databases any good?
[ "", "java", "database", "linux", "architecture", "" ]
I'm creating a multi-part web form in ASP.NET that uses Panels for the different steps, making only the Panel for the current step visible. On Step 1, I have a drop-down list that uses a Javascript function to reconfigure some of the fields in the same Panel via "onchange". Obviously, since the client-side script is on...
You might consider an ASP.Net Wizard control for this- it will automate a lot of what you're trying to do.
I suggest you to use the MultiView control, which is let's say semantically more appropiate. And then store this data in ViewState. I have written something similar and it rocks.
Good way to maintain ASP.NET Panel states?
[ "", "c#", "panel", "state", "" ]
How do you get a list of files within a directory so each can be processed?
But `boost::filesystem` can do that: <http://www.boost.org/doc/libs/1_37_0/libs/filesystem/example/simple_ls.cpp>
Here's what I use: ``` /* Returns a list of files in a directory (except the ones that begin with a dot) */ void GetFilesInDirectory(std::vector<string> &out, const string &directory) { #ifdef WINDOWS HANDLE dir; WIN32_FIND_DATA file_data; if ((dir = FindFirstFile((directory + "/*").c_str(), &file_data))...
How do I get a list of files in a directory in C++?
[ "", "c++", "file", "directory", "" ]
How can I parse integers passed to an application as command line arguments if the app is unicode? Unicode apps have a main like this: ``` int _tmain(int argc, _TCHAR* argv[]) ``` argv[?] is a wchar\_t\*. That means i can't use atoi. How can I convert it to an integer? Is stringstream the best option?
if you have a TCHAR array or a pointer to the begin of it, you can use `std::basic_istringstream` to work with it: ``` std::basic_istringstream<_TCHAR> ss(argv[x]); int number; ss >> number; ``` Now, `number` is the converted number. This will work in ANSI mode (\_TCHAR is typedef'ed to `char`) and in Unicode (\_TCHA...
Dry coded and I don't develop on Windows, but using [`TCLAP`](http://tclap.sf.net/), this should get you running with wide character `argv` values: ``` #include <iostream> #ifdef WINDOWS # define TCLAP_NAMESTARTSTRING "~~" # define TCLAP_FLAGSTARTSTRING "/" #endif #include "tclap/CmdLine.h" int main(int argc, _TCHAR...
Parsing command line arguments in a unicode C++ application
[ "", "c++", "command-line", "unicode", "" ]
So I am currently learning C++ and decided to make a program that tests my skills I have learned so far. Now in my code I want to check if the value that the user enters is a double, if it is not a double I will put a if loop and ask them to reenter it. The problem I have is how do I go about checking what type of vari...
There is no suitable way to check if a string *really* contains a double within the standard library. You probably want to use [Boost](http://www.boost.org/). The following solution is inspired by recipe 3.3 in [C++ Cookbook](https://rads.stackoverflow.com/amzn/click/com/0596007612): ``` #include <iostream> #include <...
## Safe C++ Way You can define a function for this using `std::istringstream`: ``` #include <sstream> bool is_double(std::string const& str) { std::istringstream ss(str); // always keep the scope of variables as close as possible. we see // 'd' only within the following block. { double d; ...
Check variable type in C++
[ "", "c++", "variables", "double", "" ]
Is it possible to have a WPF window/element detect the drag'n'dropping of a file from windows explorer in C# .Net 3.5? I've found solutions for WinForms, but none for WPF.
Unfortunately, TextBox, RichTextBox, and FlowDocument viewers always mark drag-and-drop events as handled, which prevents them from bubbling up to your handlers. You can restore drag-and-drop events being intercepted by these controls by force-handling the drag-and-drop events (use UIElement.AddHandler and set handledE...
Try the following : ``` private void MessageTextBox_Drop(object sender, DragEventArgs e) { if (e.Data is DataObject && ((DataObject)e.Data).ContainsFileDropList()) { foreach (string filePath in ((DataObject)e.Data).GetFileDropList()) { // Processing here ...
Detect Drag'n'Drop file in WPF?
[ "", "c#", "wpf", ".net-3.5", "drag-and-drop", "" ]
Obviously it gets updated during a write operation, but are there any non-destructive operations that also force an update? Basically looking to be able to do the equivalent of the \*nix touch command, but in C# programmatically.
Use the function SetFileTime (C++) or File.SetLastWriteTime (C#) to set the last write time to the current time.
[System.IO.File.SetLastWriteTime(string path, DateTime lastWriteTime);](http://msdn.microsoft.com/en-us/library/system.io.file.setlastwritetime.aspx)
What's required for Windows to update the "file modified" timestamp?
[ "", "c#", "windows", "file", "timestamp", "" ]
I recently started building a console version of a web application. I copied my custom sections from my web.config. to my app.config. When I go to get config information i get this error: An error occurred creating the configuration section handler for x/y: Could not load type 'x' from assembly 'System.Configuration ...
it sounds like your config-section handler is not defined ``` <configSection> <section name="YOUR_CLASS_NAME_HERE" type="YOUR.NAMESPACE.CLASSNAME, YOUR.NAMESPACE, Version=1.1.0.0, Culture=neutral, PublicKeyToken=PUBLIC_TOKEN_ID_FROM_ASSEMBLY" allowLocation="true" all...
I had this identical issue recently. I created a custom sectiongroup for a web application(ran just fine), but when I ported this layer to a console app, the sectiongroup was failing. You were correct in your question regarding how much of the "type" is required in your section definition. I've modified your configura...
App.config - custom section not working
[ "", "c#", "" ]
Is it possible to have a file belong to multiple subpackages? For example: ``` /** * Name * * Desc * * @package Core * @subpackage Sub1 * @subpackage Sub2 */ ``` Thanks!
It appears that PHPDoc does not allow you to do it for namespacing reasons. From the [PHPDoc Docs](http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_tags.subpackage.pkg.html): > NOTE: The @subpackage tag is intended to help categorize the elements that are in an actual @package value. Since PHP...
You can use the following to do this: ``` * @package popcap\system\cache ``` This will create a hierarchy of packages when you compile the PHPdocs.
multiple subpackages for phpdoc
[ "", "php", "phpdoc", "" ]
How do you safely encode a URL using JavaScript such that it can be put into a GET string? ``` var myUrl = "http://example.com/index.html?param=1&anotherParam=2"; var myOtherUrl = "http://example.com/index.html?url=" + myUrl; ``` I assume that you need to encode the `myUrl` variable on that second line?
Check out the built-in function [encodeURIComponent(str)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) and [encodeURI(str)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI). In your case, this should work: ``` var myOt...
You have three options: * `escape()` will not encode: `@*/+` * `encodeURI()` will not encode: `~!@#$&*()=:/,;?+'` * `encodeURIComponent()` will not encode: `~!*()'` But in your case, if you want to pass a [URL](http://en.wikipedia.org/wiki/Uniform_Resource_Locator) into a `GET` parameter of other page, you should use...
Encode URL in JavaScript
[ "", "javascript", "url", "encode", "urlencode", "" ]
I just don't get it. Tried on VC++ 2008 and G++ 4.3.2 ``` #include <map> class A : public std::multimap<int, bool> { public: size_type erase(int k, bool v) { return erase(k); // <- this fails; had to change to __super::erase(k) } }; int main() { A a; a.erase(0, false); a.erase(0); //...
When you declare a function in a class with the same name but different signature from a superclass, then the name resolution rules state that the compiler should *stop looking* for the function you are trying to call once it finds the first match. After finding the function by name, *then* it applies the overload reso...
1: You need to be *extremely* careful when deriving from C++ standard library containers. It can be done, but because they don't have virtual destructors and other such niceties, it is usually the wrong approach. 2: Overload rules are a bit quirky here. The compiler first looks in the derived class, and if it finds *a...
What is wrong with this inheritance?
[ "", "c++", "templates", "" ]
I have a layout similar to this: ``` <div id="..."><img src="..."></div> ``` and would like to use a jQuery selector to select the child `img` inside the `div` on click. To get the `div`, I've got this selector: ``` $(this) ``` How can I get the child `img` using a selector?
The jQuery constructor accepts a 2nd parameter called [`context`](http://api.jquery.com/jQuery/#jQuery-selector-context) which can be used to override the context of the selection. ``` jQuery("img", this); ``` Which is the same as using [`.find()`](http://api.jquery.com/find) like this: ``` jQuery(this).find("img");...
You could also use ``` $(this).find('img'); ``` which would return all `img`s that are descendants of the `div`
How to get the children of the $(this) selector?
[ "", "javascript", "jquery", "jquery-selectors", "" ]
I'm trying to get the contents from another file with `file_get_contents` (don't ask why). I have two files: *test1.php* and *test2.php*. *test1.php* returns a string, bases on the user that is logged in. *test2.php* tries to get the contents of *test1.php* and is being executed by the browser, thus getting the cook...
First, this is probably just a typo in your question, but the third arguments to file\_get\_contents() needs to be your streaming context, NOT the array of options. I ran a quick test with something like this, and everything worked as expected ``` $opts = array('http' => array('header'=> 'Cookie: ' . $_SERVER['HTTP_CO...
Just to share this information. When using `session_start()`, the session file is lock by PHP. Thus the actual script is the only script that can access the session file. If you try to access it via `fsockopen()` or `file_get_contents()` you can wait a long time since you try to open a file that has been locked. One w...
How to send cookies with file_get_contents
[ "", "php", "session", "cookies", "file-get-contents", "" ]
I am trying to deserialize a stream but I always get this error "End of Stream encountered before parsing was completed"? Here is the code: ``` //Some code here BinaryFormatter b = new BinaryFormatter(); return (myObject)b.Deserialize(s);//s---> is a Stream object that has been fill up with da...
Try to set the position to 0 of your stream and do not use your object but the object type. ``` BinaryFormatter b = new BinaryFormatter(); s.Position = 0; return (YourObjectType)b.Deserialize(s); ```
Make sure the serialization completed, and that the serialization type matches the de-serialization type (i.e., make sure you're serializing with a BinaryFormatter if you're de-serializing with one). Also, make sure that the stream you serialized to really finished serializing, with a Stream.Flush() or something to tha...
End of Stream encountered before parsing was completed?
[ "", "c#", ".net", "serialization", ".net-2.0", "c#-2.0", "" ]
I am porting an existing application to C# and want to improve performance wherever possible. Many existing loop counters and array references are defined as System.UInt32, instead of the Int32 I would have used. Is there any significant performance difference for using UInt32 vs Int32?
I don't think there are any performance considerations, other than possible difference between signed and unsigned arithmetic at the processor level but at that point I think the differences are moot. The bigger difference is in the CLS compliance as the unsigned types are not CLS compliant as not all languages suppor...
The short answer is "No. Any performance impact will be negligible". The correct answer is "It depends." A better question is, "Should I use uint when I'm certain I don't need a sign?" The reason you cannot give a definitive "yes" or "no" with regards to performance is because the target platform will ultimately det...
In C# is there any significant performance difference for using UInt32 vs Int32
[ "", "c#", "performance", "int32", "uint32", "" ]
In C++ often do something like this: ``` typedef map<int, vector<int> > MyIndexType; ``` Where I then use it like this: ``` MyIndexType myIndex; for( ... some loop ...) { myIndex[someId].push_back(someVal); } ``` If there was no entry in the map the code will insert a new empty vector and then append to it. In P...
You want to use: ``` from collections import defaultdict myIndex = defaultdict(list) myIndex[someId].append(someVal) ``` Standard Library [`defaultdict` objects](http://docs.python.org/library/collections.html#id3). Example usage from the Python documentation: ``` >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3),...
Something like this perhaps: ``` myIndex = {} for (someId,someVal) in collection: myIndex.setdefault(someId, []).append(someVal) ```
What is the equivalent of map<int, vector<int> > in Python?
[ "", "python", "dictionary", "" ]
In java, there's three levels of access: * Public - Open to the world * Private - Open only to the class * Protected - Open only to the class and its subclasses (inheritance). So why does the java compiler allow this to happen? TestBlah.java: ``` public class TestBlah { public static void main(String[] args) {...
Actually it should be: > Open only to the [**classes on the same package**](http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html) the class and its subclasses (inheritance) That's why
Because protected means subclass *or* other classes in the same package. And there's actually a fourth "default" level of access, when the modifier is omitted, which provides access to other classes in the same package. So `protected` is between default and `public` access.
Java Protected Access Not Working
[ "", "java", "inheritance", "visibility", "protected", "access-levels", "" ]
Is it faster to do the following: ``` if ($var != 'test1' && $var != 'test2' && $var != 'test3' && $var != 'test4') { ... } ``` Or: ``` if (!in_array($var, array('test1', 'test2', 'test3', 'test4') { ... } ``` Is there a number of values at which point it's faster to do one or the other? (In this case, the array...
i'd strongly suggest just using `in_array()`, any speed difference would be negligible, but the readability of testing each variable separately is horrible. just for fun here's a test i ran: ``` $array = array('test1', 'test2', 'test3', 'test4'); $var = 'test'; $iterations = 1000000; $start = microtime(true); for($i...
Note that if you're looking to replace a bunch of `!==` statements, you should pass the third parameter to [`in_array`](http://uk.php.net/manual/en/function.in-array.php) as `true`, which enforces type checking on the items in the array. Ordinary `!=` doesn't require this, obviously.
Which is faster: in_array() or a bunch of expressions in PHP?
[ "", "php", "arrays", "if-statement", "" ]
How can I retrieve raw time-series data from a Proficy Historian/iHistorian? Ideally, I would ask for data for a particular tag between two dates.
There are several different sampling modes you can experiment with. * Raw * Interpolated * Lab * Trend * Calculated These modes are available using all of the following APIs. * User API (ihuapi.dll) * SDK (ihsdk.dll) * OLEDB (iholedb.dll) * Client Acess API (Proficy.Historian.ClientAccess.API) Of these the trend sa...
A coworker of mine put this together: In web.config: ``` <add name="HistorianConnectionString" providerName="ihOLEDB.iHistorian.1" connectionString=" Provider=ihOLEDB.iHistorian; User Id=; Password=; Data Source=localhost;" /> ``` In the data layer: ``` public DataTable GetPr...
How do I query raw data from a Proficy Historian?
[ "", "c#", "oledb", "proficy", "historian", "" ]
I always have this notion that writing SQL queries in the code behind is not good compared to writing it using a SqlDataSource ``` SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection); DataSet ds = new DataSet(); ad.Fill(ds, "Categories"); myGridView.DataSource = ds; myGridView.DataBind...
SQL queries in the code-behind and SQL queries in a SqlDataSource are pretty much equivalent. they're both about the same security-wise; as for easier to maintain, SqlDataSource may be a bit easier in most cases. A data-access layer is preferred, but SqlDataSource is sometimes a good-enough expediency. I wouldn't hit...
I wouldn't write SQL queries in code behind full stop. How about a data access layer? What happens if you want to change your backing store? You're going to have to re-write all your code-behind. What happens where you need to use the data in more than one place? You duplicate code. You need think seriously about ho...
Writing queries in code behind vs. SqlDataSource
[ "", "asp.net", "sql", "" ]
I'm having an issue dragging a file from Windows Explorer on to a Windows Forms application. It works fine when I drag text, but for some reason it is not recognizing the file. Here is my test code: ``` namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { ...
The problem comes from Vista's [UAC](http://en.wikipedia.org/wiki/User_Account_Control). DevStudio is running as administrator, but explorer is running as a regular user. When you drag a file from explorer and drop it on your DevStudio hosted application, that is the same as a non-privileged user trying to communicate ...
I added the code that [arul](https://stackoverflow.com/questions/281706/drag-and-drop-from-windows-file-explorer-onto-a-windows-form-is-not-working#281770) mentioned and things still didn't work, but it got me thinking. I started thinking it might be a Vista issue so I sent it to a friend that had Windows XP and it wo...
Drag and drop from Windows File Explorer onto a Windows Form is not working
[ "", "c#", "winforms", "drag-and-drop", "vista64", "" ]
I am in the process of writing an application that will need multiple forms of authentication. The application will need to support authentication to Active Directory, but be able to fail back to a SQL Membership Provider if the user is not in Active Directory. We can handle the failing to the SQL Provider in code bas...
This is the way I've handled a similar situation based on [this info](http://beensoft.blogspot.com/2008/06/mixing-forms-and-windows-authentication.html): 1. Configured the application to use Forms authentication. 2. Set the LoginUrl to a page called WinLogin.aspx. 3. In WinLogin.aspx, use Request.ServerVariables["LOGO...
As far as I know, Web Applications are configured to use either Windows Authentication or Forms Authentication, but not both. Therefore, I do not believe it is possible to automatically authenticate internal users while requiring others to enter a username / password. You could authenticate to Active Directory or a SQ...
ASP.NET Application to authenticate to Active Directory or SQL via Windows Authentication or Forms Authentication
[ "", "asp.net", "sql", "active-directory", "asp.net-membership", "membership", "" ]
I've been preaching both to my colleagues and here on SO about the goodness of using parameters in SQL queries, especially in .NET applications. I've even gone so far as to promise them as giving immunity against SQL injection attacks. But I'm starting to wonder if this really is true. Are there any known SQL injectio...
**Placeholders** are enough to prevent injections. You might still be open to buffer overflows, but that is a completely different flavor of attack from an SQL injection (the attack vector would not be SQL syntax but binary). Since the parameters passed will all be escaped properly, there isn't any way for an attacker ...
No, there is still risk of SQL injection any time you interpolate unvalidated data into an SQL query. Query parameters help to avoid this risk by separating literal values from the SQL syntax. ``` 'SELECT * FROM mytable WHERE colname = ?' ``` That's fine, but there are other purposes of interpolating data into a dyn...
Are Parameters really enough to prevent Sql injections?
[ "", "asp.net", "sql", "database", "sql-injection", "" ]
I'm searching for an easy to handle python native module to create python object representation from xml. I found several modules via google (one of them is [XMLObject](http://freenet.mcnabhosting.com/python/xmlobject/)) but didn't want to try out all of them. What do you think is the best way to do such things? **E...
You say you want an *object* representation, which I would interpret to mean that nodes become objects, and the attributes and children of the node are represented as attributes of the object (possibly according to some Schema). This is what XMLObject does, I believe. There are some packages that I know of. [4Suite](h...
I second the suggestion of xml.etree.ElementTree, mostly because it's now in the stdlib. There is also a faster implementation, xml.etree.cElementTree available too. If you really need performance, I would suggest lxml <http://www.ibm.com/developerworks//xml/library/x-hiperfparse/>
module to create python object representation from xml
[ "", "python", "xml", "pickle", "" ]
I have a 'reference' SQL Server 2005 database that is used as our global standard. We're all set up for keeping general table schema and data properly synchronized, but don't yet have a good solution for other objects like views, stored procedures, and user-defined functions. I'm aware of products like [Redgate's SQL ...
You can use the system tables to do this. For example, ``` select * from sys.syscomments ``` The "text" column will give you all of the code for the store procedures (plus other data). It is well worth looking at all the system tables and procedures. In fact, I suspect this is what RedGate's software and other tool...
1) Keep all your views, triggers, functions, stored procedures, table schemas etc in Source Control and use that as the master. 2) Failing that, use your reference DB as the master and script out views and stored procedures etc: Right click DB, Tasks->Generate Scripts and choose your objects. 3) You could even use tr...
How can I synchronize views and stored procedures between SQL Server databases?
[ "", "sql", "sql-server", "" ]
I was working on some code recently and came across a method that had 3 for-loops that worked on 2 different arrays. Basically, what was happening was a foreach loop would walk through a vector and convert a DateTime from an object, and then another foreach loop would convert a long value from an object. Each of these...
Well, you've got complications if the two vectors are of different sizes. As has already been pointed out, this doesn't increase the overall complexity of the issue, so I'd stick with the simplest code - which is probably 2 loops, rather than 1 loop with complicated test conditions re the two different lengths. Actual...
The best approach? Write the most readable code, work out its complexity, and work out if that's actually a problem. If each of your loops is O(n), then you've still only got an O(n) operation. Having said that, it does sound like a LINQ approach would be more readable... and quite possibly more efficient as well. Ad...
Back to basics; for-loops, arrays/vectors/lists, and optimization
[ "", "c#", "arrays", "optimization", "list", "performance", "" ]
I'm having some trouble navigating Java's rule for inferring generic type parameters. Consider the following class, which has an optional list parameter: ``` import java.util.Collections; import java.util.List; public class Person { private String name; private List<String> nicknames; public Person(String na...
The issue you're encountering is that even though the method `emptyList()` returns `List<T>`, you haven't provided it with the type, so it defaults to returning `List<Object>`. You can supply the type parameter, and have your code behave as expected, like this: ``` public Person(String name) { this(name,Collections....
You want to use: ``` Collections.<String>emptyList(); ``` If you look at the source for what emptyList does you see that it actually just does a ``` return (List<T>)EMPTY_LIST; ```
Collections.emptyList() returns a List<Object>?
[ "", "java", "generics", "type-inference", "" ]
I have a script which logs on to a remote server and tries to rename files, using PHP. The code currently looks something like this example from the php.net website: ``` if (ftp_rename($conn_id, $old_file, $new_file)) { echo "successfully renamed $old_file to $new_file\n"; } else { echo "There was a problem while r...
Looking at the FTP API here: <http://us.php.net/manual/en/function.ftp-rename.php> There doesn't seem to be any way to get anything but true or false. However, you could use ftp\_raw to send a raw RENAME command, and then parse the returned message.
You could use error\_get\_last() if return value is false.
How to get the FTP error when using PHP
[ "", "php", "error-handling", "ftp", "" ]
``` $sourcePath = 'images/'; // Path of original image $sourceUrl = ''; $sourceName = 'photo1.jpg'; // Name of original image $thumbPath = 'thumbs/'; // Writeable thumb path $thumbUrl = 'thumbs/'; $thumbName = "test_thumb.jpg"; // Tip: Name dynamically $thumbWidth = 100; // Intended dimension of thumb // Beyond this p...
Use [imagecreatetruecolor](http://pl2.php.net/manual/en/function.imagecreatetruecolor.php) instead of imagecreate and [imagecopyresampled](http://pl2.php.net/manual/en/function.imagecopyresampled.php) instead of imagecopyresized.
The third parameter is worth including as Dominic points out. It specifies the jpeg quality. On the issue of "and it looks like it has been squashed", remember, you're making a square thumbnail from a source image which itself may or may not be square. One way to get around this is to work with the source dimensions ...
Generating thumbnails using PHP causes bad image quality
[ "", "php", "gdlib", "" ]
I have a Freemarker template which contains a bunch of placeholders for which values are supplied when the template is processed. I want to conditionally include part of the template if the userName variable is supplied, something like: ``` [#if_exists userName] Hi ${userName}, How are you? [/#if_exists] ``` Howeve...
To check if the value exists: ``` [#if userName??] Hi ${userName}, How are you? [/#if] ``` Or with the standard freemarker syntax: ``` <#if userName??> Hi ${userName}, How are you? </#if> ``` To check if the value exists and is not empty: ``` <#if userName?has_content> Hi ${userName}, How are you? </#if>...
This one seems to be a better fit: ``` <#if userName?has_content> ... do something </#if> ``` <http://freemarker.sourceforge.net/docs/ref_builtins_expert.html>
How to check if a variable exists in a FreeMarker template?
[ "", "java", "templates", "freemarker", "" ]
I have an abstract base class and I want to declare a field or a property that will have a different value in each class that inherits from this parent class. I want to define it in the baseclass so I can reference it in a base class method - for example overriding ToString to say "This object is of type *property/fie...
Of the three solutions only **Option 1** is **polymorphic**. Fields by themselves cannot be overridden. Which is exactly why **Option 2** returns the ***new*** keyword warning. The solution to the warning is not to append the “new” keyword, but to implement Option 1. **If you need your field to be polymorphic you ne...
Option 2 is a non-starter - you can't *override* fields, you can only *hide* them. Personally, I'd go for option 1 every time. I try to keep fields private at all times. That's if you really need to be able to override the property at all, of course. Another option is to have a read-only property in the base class whi...
Overriding fields or properties in subclasses
[ "", "c#", "properties", "field", "" ]
Due to a weird request, I can't put `null` in a database if there is no value. I'm wondering what can I put in the store procedure for nothing instead of `null`. For example: ``` insert into blah (blah1) values (null) ``` Is there something like nothing or empty for "blah1" instead using `null`?
I would push back on this bizarre request. That's exactly what `NULL` is for in SQL, to denote a missing or inapplicable value in a column. Is the requester experiencing grief over SQL logic with `NULL`? **edit:** Okay, I've read your reply with the extra detail about this job assignment (btw, generally you should ed...
Depends on the data type of the column. For numbers (integers, etc) it could be zero (0) but if varchar then it can be an empty string (""). I agree with other responses that NULL is best suited for this because it transcends all data types denoting the absence of a value. Therefore, zero and empty string might serve ...
TSQL: No value instead of Null
[ "", "sql", "sql-server", "t-sql", "null", "" ]
## How is it possible to call a client side javascript method after a *specific* update panel has been loaded? **`Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler)`** does not work for me because this will fire after ANY update panel finishes loading, and I can find no client side way to ...
You can hook the [PageRequestManager.beginRequest](http://msdn.microsoft.com/en-us/library/bb397432.aspx) event and inspect the [BeginRequestEventArgs.postBackElement](http://msdn.microsoft.com/en-us/library/bb397485.aspx) property. Note that it doesn't *really* give you the UpdatePanel, but the control inside of the ...
Thanks - both good answers. I went with the client side script "pageloaded" in the end. That is a fairly buried method that google did not reveal to me. For those who are interested, this code works with FireBug to give a good demo of the PageLoaded method working to find the updated panels: ``` <script type="text/jav...
How to call a client side javascript function after a specific UpdatePanel has been loaded
[ "", "asp.net", "javascript", "ajax", "updatepanel", "" ]
The C++ standard dictates that member variables inside a single access section must be layed out in memory in the same order they were declared in. At the same time, compilers are free to choose the mutual ordering of the access sections themselves. This freedom makes it impossible in theory to link binaries created by...
> This freedom makes it impossible in theory to link binaries created by different compilers. It's impossible for a number of reasons, and structure layout is the most minor. vtables, implementations of `operator new` and `delete`, data type sizes... > So what are the remaining reasons for the strict in-section order...
[edit] I learnt something new today! found the following standard quote: > Nonstatic data members of a > (non-union) class declared without an > intervening access-specifier are > allocated so that later members have > higher addresses within a class > object. The order of allocation of > nonstatic data members separa...
Class layout in C++: Why are members sometimes ordered?
[ "", "c++", "" ]
How do I check if the timestamp date of a record is before midnight today? datediff is driving me nuts...
Here is how to get 0 hour of today in SQL ``` SELECT (CAST(FLOOR(CAST(GETDATE() as FLOAT)) AS DateTime)) ``` Just compare your time against that. Don't use varchar casts since they are slow. [Check this list](https://stackoverflow.com/questions/202243/custom-datetime-formatting-in-sql-server#202288) for more date t...
Try: ``` WHERE dtColumn < DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE())) ```
SQL date comparison
[ "", "sql", "t-sql", "" ]
I encountered a problem when running some old code that was handed down to me. It works 99% of the time, but once in a while, I notice it throwing a "Violation reading location" exception. I have a variable number of threads potentially executing this code throughout the lifetime of the process. The low occurrence freq...
Given an address of "4", Likely the "this" pointer is null or the iterator is bad. You should be able to see this in the debugger. If this is null, then the problem isn't in that function but who ever is calling that function. If the iterator is bad, then it's the race condition you alluded to. Most iterators can't tol...
mappedChars is static so it's shared by all the threads that execute DoStuff(). That alone could be your problem. If you have to use a static map, then you may need to protect it with a mutex or critical section. Personally, I think using a map for this purpose is overkill. I would write a helper function that takes ...
Violation reading location in std::map operator[]
[ "", "c++", "multithreading", "exception", "stl", "" ]
I have the following entity class (in Groovy): ``` import javax.persistence.Entity import javax.persistence.Id import javax.persistence.GeneratedValue import javax.persistence.GenerationType @Entity public class ServerNode { @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id String firstName Stri...
I don't know if leaving `hibernate` off the front makes a difference. The [reference](http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html#configuration-misc-properties) suggests it should be `hibernate.hbm2ddl.auto` A value of `create` will create your tables at sessionFactory creati...
You might try changing this line in your persistence.xml from ``` <property name="hbm2ddl.auto" value="create"/> ``` to: ``` <property name="hibernate.hbm2ddl.auto" value="update"/> ``` This is supposed to maintain the schema to follow any changes you make to the Model each time you run the app. Got this from [Jav...
Hibernate: Automatically creating/updating the db tables based on entity classes
[ "", "java", "mysql", "hibernate", "jpa", "groovy", "" ]
I have a Queue object that I need to ensure is thread-safe. Would it be better to use a lock object like this: ``` lock(myLockObject) { //do stuff with the queue } ``` Or is it recommended to use Queue.Synchronized like this: ``` Queue.Synchronized(myQueue).whatever_i_want_to_do(); ``` From reading the MSDN docs it...
Personally I always prefer locking. It means that *you* get to decide the granularity. If you just rely on the Synchronized wrapper, each individual operation is synchronized but if you ever need to do more than one thing (e.g. iterating over the whole collection) you need to lock anyway. In the interests of simplicity...
There's a major problem with the `Synchronized` methods in the old collection library, in that they synchronize at too low a level of granularity (per method rather than per unit-of-work). There's a classic race condition with a synchronized queue, shown below where you check the `Count` to see if it is safe to dequeu...
In C# would it be better to use Queue.Synchronized or lock() for thread safety?
[ "", "c#", "multithreading", "queue", "" ]
I have seen this syntax in MSDN: [`yield break`](https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx), but I don't know what it does. Does anyone know?
It specifies that an iterator has come to an end. You can think of `yield break` as a `return` statement which does not return a value. For example, if you define a function as an iterator, the body of the function may look like this: ``` for (int i = 0; i < 5; i++) { yield return i; } Console.Out.WriteLine("You...
Ends an iterator block (e.g. says there are no more elements in the IEnumerable).
What does "yield break;" do in C#?
[ "", "c#", ".net", "yield", "" ]
For example: ``` public class A : A.B { public class B { } } ``` Which generates this error from the compiler: > Circular base class dependency > involving 'A' and 'A.B' I always figured a nested class behaved just like a regular class except with special rules concerning accessing the outer class's private mem...
There's no implicit inheritance involved as far as I can tell. I would have expected this to be okay - although I can imagine weirdness if A and B were generic. It's specified in section 10.1.4 of the spec: > When a class B derives from a class A, > it is a compile-time error for A to > depend on B. A class directly ...
This is not a C# thing as much as it is a compiler thing. One of the jobs of a compiler is to lay out a class in memory, that is a bunch of basic data types, pointers, function pointers and other classes. It can't construct the layout for class A until it knows what the layout of class B is. It can't know what the lay...
Why can't a class extend its own nested class in C#?
[ "", "c#", "nested-class", "" ]
This is not to be confused with ["How to tell if a DOM element is visible?"](https://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible) I want to determine if a given DOM element is visible on the page. E.g. if the element is a child of a parent which has `display:none;` set, then it won't be ...
From a quick test in Firefox, it looks like the size and position properties (clientWidth, offsetTop etc.) all return 0 when an element is hidden by a parent being `display:none`.
Using [Prototype](http://prototypejs.org): ``` if($('someDiv').visible) {...} ```
How to tell if a DOM element is displayed?
[ "", "javascript", "html", "css", "dom", "" ]
Can I write to the end of a 5GB file in Java? This question came up in my office and no one is sure what the answer is.
This should be possible fairly easily using a [RandomAccessFile](http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html). Something like the following should work: ``` String filename; RandomAccessFile myFile = new RandomAccessFile(filename, "rw"); // Set write pointer to the end of the file myFile.seek...
Yes. Take a look at this link RandomAccessFile <http://java.sun.com/javase/6/docs/api/java/io/RandomAccessFile.html#seek(long)> That is , you open the file, and then set the position to the end of the file. And start writing from there. Tell us how it went.
Can I write to the end of a 5GB file in Java?
[ "", "java", "file-io", "" ]
The thing is I've been using the [lock statement](http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx) to protect a critical part of my code, but now, I realize I could allow concurrent execution of that critical code is some conditions are met. Is there a way to condition the lock?
``` Action doThatThing = someMethod; if (condition) { lock(thatThing) { doThatThing(); } } else { doThatThing(); } ```
``` bool locked = false; if (condition) { Monitor.Enter(lockObject); locked = true; } try { // possibly critical section } finally { if (locked) Monitor.Exit(lockObject); } ``` EDIT: yes, there is a race condition unless you can assure that the condition is constant while threads are entering.
How can I write a conditional lock in C#?
[ "", "c#", ".net", "multithreading", "locking", "" ]
I want to load 52 images (deck of cards) in gif format from my recourse folder into an Image[] in c#. Any ideas? Thanks, Jon
You can read a Bitmap from a file like this; ``` public static Bitmap GetBitmap( string filename ) { Bitmap retBitmap = null; string path = String.Concat( BitmapDir, filename ); if ( File.Exists( path ) ) { try { retBitmap = new Bitmap( path, true ); } ...
Assuming that you have the images in a folder on your local file system and that you are running under .NET 3.5: ``` Image[] cards = Directory.GetFiles(cardsFolder).Select(f => Image.FromFile(f)).ToArray(); ``` One-liners are always nice :-)
How do I get images located in my recourse folder into an array?
[ "", "c#", "" ]
I have a MySQL table containing domain names: ``` +----+---------------+ | id | domain | +----+---------------+ | 1 | amazon.com | | 2 | google.com | | 3 | microsoft.com | | | ... | +----+---------------+ ``` I'd like to be able to search through this table for a full hostname (i.e. 'www....
You can use the column on the right of the like too: ``` SELECT domain FROM table WHERE 'www.google.com' LIKE CONCAT('%', domain); ``` or ``` SELECT domain FROM table WHERE 'www.google.com' LIKE CONCAT('%', domain, '%'); ``` It's not particularly efficient but it works.
In `mysql` you can use regular expressions (`RLIKE`) to perform matches. Given this ability you could do something like this: ``` SELECT * FROM table WHERE 'www.google.com' RLIKE domain; ``` It appears that the way `RLIKE` has been implemented it is even smart enough to treat the dot in that field (normally a wildcar...
Inverse of SQL LIKE '%value%'
[ "", "sql", "mysql", "database", "" ]
Currently I have the function CreateLog() for creating a a log4net Log with name after the constructing instance's class. Typically used as in: ``` class MessageReceiver { protected ILog Log = Util.CreateLog(); ... } ``` If we remove lots of error handling the implementation boils down to: [EDIT: Please rea...
> Is there anyone who can show me how to implement a zero argument CreateLog() that gets the name from the subclass and not the declaring class? I don't think you'll be able to do it by looking at the stack frame. While your class is `IMReceiver`, the call to `CreateLog` method is in the `MessageReceiver` class. The ...
Normally, [MethodBase.ReflectedType](http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.reflectedtype.aspx) would have your info. But, according to MSDN [StackFrame.GetMethod](http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe.getmethod.aspx): > The method that is currently executi...
How do I find the type of the object instance of the caller of the current function?
[ "", "c#", ".net", "reflection", "logging", "" ]
At every company I have worked at, I have found that people are still writing their SQL queries in the ANSI-89 standard: ``` select a.id, b.id, b.address_1 from person a, address b where a.id = b.id ``` rather than the ANSI-92 standard: ``` select a.id, b.id, b.address_1 from person a inner join address b on a.id = ...
According to "SQL Performance Tuning" by Peter Gulutzan and Trudy Pelzer, of the six or eight RDBMS brands they tested, there was no difference in optimization or performance of SQL-89 versus SQL-92 style joins. One can assume that most RDBMS engines transform the syntax into an internal representation before optimizin...
Well the ANSI092 standard includes some pretty heinous syntax. [Natural Joins](http://en.wikipedia.org/wiki/Join_(SQL)#Natural_join) are one and the USING Clause is another. IMHO, the addition of a column to a table shouldn't break code but a NATURAL JOIN breaks in a most egregious fashion. The "best" way to break is b...
Why isn't SQL ANSI-92 standard better adopted over ANSI-89?
[ "", "sql", "join", "ansi-sql", "ansi-92", "" ]
I have a Google Map that suddenly stopped working for no apparent reason (I hadn't touched the code for months, but the wrapper code from our CMS may have changed without Corporate telling me). <http://www.democratandchronicle.com/section/builder> (sorry about the nasty HTML outside the map, most of that comes from o...
This resolved itself. I suspect an update to the API broke something for a version or two.
I've had random problems with Google Maps API at times and more than once it has been fixed by going back one API version. i.e. if your google maps API javascript inclusion string is like this `http://maps.google.com/maps?file=api&v=2.xd&key=XXXXX` change the **2.x** to something a few versions back (back when it was w...
Google Maps API - GMarker.openInfoWindowHtml() stopped working
[ "", "javascript", "google-maps", "mapping", "openinfowindowhtml", "" ]
Our site has multiple "wizards" where various data is collected over several pages, and cannot be committed to the database until the last step. What is the best/correct way to make a wizard like this with ASP.Net MVC edit: My boss is now saying "no javascript" - any thoughts on how to get around that restriction?
I don't believe there is a best/correct way, but the way I'd do it is... Each wizard gets its own page. Each step gets its own div. All steps are in the same form. The previous/next buttons would essentially hide/show the div in each step of the process. The last step's submit button submits the entire form. It would...
If you can't use JavaScript, then make each step a view, with a method in the controller, and keep your data in session until ready to submit to the database. You can make your Next and Prev buttons using the ActionLink HtmlHelper method.
how to make a wizard with ASP.Net MVC
[ "", "c#", ".net", "asp.net-mvc", "wizard", "" ]
I am looking for good ideas for implementing a generic way to have a single line (or anonymous delegate) of code execute with a timeout. ``` TemperamentalClass tc = new TemperamentalClass(); tc.DoSomething(); // normally runs in 30 sec. Want to error at 1 min ``` I'm looking for a solution that can elegantly be imp...
The really tricky part here was killing the long running task through passing the executor thread from the Action back to a place where it could be aborted. I accomplished this with the use of a wrapped delegate that passes out the thread to kill into a local variable in the method that created the lambda. I submit th...
**We are using code like this heavily in productio**n: ``` var result = WaitFor<Result>.Run(1.Minutes(), () => service.GetSomeFragileResult()); ``` Implementation is open-sourced, works efficiently even in parallel computing scenarios and is available as a part of [Lokad Shared Libraries](https://github.com/Lokad/lok...
Implement C# Generic Timeout
[ "", "c#", "multithreading", "c#-3.0", "asynchronous", "timeout", "" ]
We have 50+ Java batch processes that run at different times of the day. They run on a Solaris box, and are started via cron. Currently, the only way we only know if they succeed or fail is by an email generated at the end of each batch process. We have a support team that monitors these emails. Recently, we've had iss...
Is there currently some batch management system in-place? Or are the jobs run through the OS scheduler? (ie, Windows `Schedule Tasks` or \*nix `cron`) [Quartz](http://www.opensymphony.com/quartz) is an Open Source (Apache License) java-based job scheduler that has infrastructure in place for *listeners* that can be us...
I don't know about open source batch monitoring applications but there is a new sub project of Spring: Spring-Batch that provides a batch processing framework. I've used it successfully in a few new projects. When you kick off a batch job you can wire up a job execution listener. In my case, when the job fails with an...
Java batch monitoring
[ "", "java", "frameworks", "monitoring", "batch-processing", "" ]
I understand that using the "===" compares type, so running the following code results in "not equal" because it's comparing a number type to a string type. ``` var a = 20; var b = "20"; if (a === b) { alert("They are equal"); } else { alert("They are not equal"); } ``` But I dont understand h...
The `==` operator compares only the values of the variables. If the types are different, a conversion is operated. So the number 20 is converted to the string "20" and the result is compared. The `===` operator compares not only the values, but also the types, so no cast is operated. In this case `"20" !== 20`
The JavaScript engine sees the a as a number and casts the b to number before the valuation.
How is "20" and 20 considered equal in JavaScript?
[ "", "javascript", "comparison", "binary", "operators", "ascii", "" ]
Do you have any ideas how to call DoEvents from a C# DLL
Don't. It's sketchy enough when you are the app controlling the event loop; pumping messages from a DLL just adds to the risk that you'll end up hitting code a naive programmer didn't make safe for re-entrancy.
Do you mean `System.Windows.Forms.Application.DoEvents()`?
DoEvents In a DLL
[ "", "c#", "dll", "" ]
Python is installed in a local directory. My directory tree looks like this: ``` (local directory)/site-packages/toolkit/interface.py ``` My code is in here: ``` (local directory)/site-packages/toolkit/examples/mountain.py ``` To run the example, I write `python mountain.py`, and in the code I have: ``` from tool...
Based on your comments to orip's post, I guess this is what happened: 1. You edited `__init__.py` on windows. 2. The windows editor added something non-printing, perhaps a carriage-return (end-of-line in Windows is CR/LF; in unix it is LF only), or perhaps a CTRL-Z (windows end-of-file). 3. You used WinSCP to copy the...
I ran into something very similar when I did this exercise in LPTHW; I could never get Python to recognise that I had files in the directory I was calling from. But I was able to get it to work in the end. What I did, and what I recommend, is to try this: (NOTE: From your initial post, I am assuming you are using an \...
Python error "ImportError: No module named"
[ "", "python", "importerror", "python-import", "" ]
I'm trying to convert an Excel document into a table in SQL 2005. I found the link below and am wondering if it looks like a solution. If so, what would the @excel\_full\_file\_name syntax be and where would the path be relative to? <http://www.siccolo.com/Articles/SQLScripts/how-to-create-sql-to-convert-Excel_to_tabl...
You can use the BULK INSERT T-SQL command if you just want a pure sql solution. You have to save the file as csv/text first. ``` BULK INSERT YourDestinationTable FROM 'D:\YourFile.csv' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' ) GO ``` Alternativel...
Glancing over the code, I would expect it to be the full path name of the excel document: For example: c:\path\to\my\excel\document.xls I haven't installed the procedure though or run it, so I could be wrong - but that's what it appears to be at first glance.
Creating a SQL table from a xls (Excel) file
[ "", "sql", "excel", "sql-server-2005", "database-table", "" ]
I'll try to explain my scenario as best i can; At each application *tick* I query the current state of the keyboard and mouse and wrap them in individual classes and data structures. For the keyboard it's an array of my *Keys* enum (one item for each of the keys that are currently pressed) and for the mouse it's a cla...
Why are you querying the state of the keyboard and mouse with each tick? A much better and traditional solution would be to capture events fired from the keyboard and mouse. That way you only need to update the state when you HAVE to.
If you simply query your keyboard and mouse every tick, I can guarantee you'll run into problems. When you query every tick, you'll find that you miss inputs that occur quickly (within the time domain of a single tick). Imagine a situation where the user presses and releases a key/button between two ticks (it will happ...
Passing input to a state machine (c#)
[ "", "c#", "user-input", "state-machine", "" ]
I have a user table in my mysql database that has a password column. Currently, I use the MD5 algorithm to hash the users' password for storage in the database. Now I like to think that I am a security conscience person. I noticed while reading the MySQL docs that they don't recommend MD5 or the SHA/SHA1 hashing method...
It's not necessarily that you shouldn't use MD5, as much it's that you shouldn't use *just* MD5, as this leaves you vulnerable to rainbow-table attacks (a rainbow table is a table of precomputed hash values - if your password is even remotely common or simple, the attacker needs merely to look up the hash and he knows ...
MD5 is considered to be weak by today's standards. It would still take some work to crack a hash made with MD5, but it's several times easier than guessing the password by brute-force. Ideally, cracking a hash should not be easier than brute-force. SHA1 is also considered easier to crack than guessing the password by ...
What function to use to hash passwords in MySQL?
[ "", "php", "mysql", "hash", "passwords", "" ]
I have the following shell script registered in my "Login Items" preferences but it does not seem to have any effect. It is meant to launch the moinmoin wiki but only works when it is run by hand from a terminal window, after which it runs until the machine is next shut down. ``` #!/bin/bash cd /Users/stuartcw/Documen...
launchd is one of the best parts of MacOS X, and it causes me great pain to not be able to find it on other systems. Edit and place this in `/Library/LaunchDaemons` as `com.you.wiki.plist` ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DT...
Try using launchd. More info at <http://www.macgeekery.com/tips/all_about_launchd_items_and_how_to_make_one_yourself>
Shell Script doesn't run automatically though it is registered in Mac OS X Login Items
[ "", "python", "macos", "bash", "launchd", "moinmoin", "" ]
I am trying to write my first real python function that does something real. What i want to accomplish is searching a given folder, and then open all images and merging them together so they make a filmstrip image. Imagine 5 images stacked on top of eachother in one image. I have this code now, which should be pretty ...
It is not an answer to your question, but It might be helpful: ``` #!/usr/bin/env python from PIL import Image def makefilmstrip(images, mode='RGB', color='white'): """Return a combined (filmstripped, each on top of the other) image of the images. """ width = max(img.size[0] for img in images) heigh...
I think if you change your `try` section to this: ``` filmstripimage.save(filmstrip_url, 'jpg', quality=90, optimize=1) ```
How to complete this python function to save in the same folder?
[ "", "python", "image-processing", "python-imaging-library", "" ]
Why does nvarchar(256) seem to the be the standard for user names in SQL Server? Any system functions that return a user name return nvarchar(256), the ASP Membership provider uses nvarchar(256) 256 seems like an odd number (yes, I know its even...) - 255 I could understand (1 byte address) but 256 doesn't make sense...
As programmers we automatically count starting at 0, but in this case nvarchar(0) would mean no characters. Turns out that 256 is your nice round number 2^8.
2^8 is 256, not 255. Many times you will see numbering schemes from 0-255 which is 256 numbers when you include the 0.
nvarchar(256)....?
[ "", "sql", "sql-server", "" ]
I'm looking at some GXT code for GWT and I ran across this use of Generics that I can't find another example of in the Java tutorials. The class name is [`com.extjs.gxt.ui.client.data.BaseModelData`](http://extjs.com/deploy/gxtdocs/com/extjs/gxt/ui/client/data/BaseModelData.html) if you want to look at all of the code....
The method returns a type of whatever you expect it to be (`<X>` is defined in the method and is absolutely unbounded). This is very, very dangerous as no provision is made that the return type actually matches the returned value. The only advantage this has is that you don't have to cast the return value of such gen...
The type is declared on the method. That's that "`<X>`" means. The type is scoped then to just the method and is relevant to a particular call. The reason your test code compiles is that the compiler tries to determine the type and will complain only if it can't. There are cases where you have to be explicit. For exam...
Java Generics: Generic type defined as return type only
[ "", "java", "generics", "java-5", "" ]
This originally was a problem I ran into at work, but is now something I'm just trying to solve for my own curiosity. I want to find out if int 'a' contains the int 'b' in the most efficient way possible. I wrote some code, but it seems no matter what I write, parsing it into a string and then using indexOf is twice a...
This is along Kibbee's line, but I got a little intrigued by this before he posted and worked this out: ``` long mask ( long n ) { long m = n % 10; long n_d = n; long div = 10; int shl = 0; while ( n_d >= 10 ) { n_d /= 10; long t = n_d % 10; m |= ( t << ( shl += 4 )); ...
It *should* be faster string way, because your problem is textual, not mathematical. Notice that the your "contains" relationship says nothing about the numbers, it only says something about their *decimal* representations. Notice also that the function you want to write will be unreadable - another developer will nev...
Finding numerical substrings mathematically, without string comparison
[ "", "java", "performance", "integer", "substring", "contains", "" ]
I traditionally deploy a set of web pages which allow for manual validation of core application functionality. One example is LoggerTest.aspx which generates and logs a test exception. I've always chosen to raise a DivideByZeroException using an approach similar to the following code snippet: ``` try { int zero = 0...
``` try { throw new DivideByZeroException(); } catch (DivideByZeroException ex) { LogHelper.Error("TEST EXCEPTION", ex); } ```
Short answer: ``` throw new Exception("Test Exception"); ``` You will need ``` using System; ```
What's the best way to raise an exception in C#?
[ "", "c#", "exception", "" ]
Based on their work, how do you distinguish a great SQL developer? Examples might include: Seldom uses CURSORs, and tries to refactor them away. Seldom uses temporary tables, and tries to refactor them away. Handles NULL values in OUTER JOINs with confidence. Avoids SQL extensions that are not widely implemente...
I've found that a great SQL developer is usually also a great database designer, and will prefer to be involved in both the design and implementation of the database. That's because a bad database design can frustrate and hold back even the best developer - good SQL instincts don't always work right in the face of path...
I don't think that cursors, temporary tables or other SQL practices are inherently bad or that their usage is a clear sign of how good a database programmer is. I think there is the right tool for every type of problem. Sure, if you only have a hammer, everything looks like a nail. I think a great SQL programmer or da...
Signs of a great SQL developer
[ "", "sql", "" ]
I have a php script which accesses a MSSQL2005 database, reads some data from it and sends the results in a mail. There are special characters in both some column names and in the fields itself. When I access the script through my browser (webserver iis), the query is executed correctly and the contents of the mail a...
Depending on the type of characters you have in your database, it might be a console limitation I guess. If you type `chcp` in the console, you'll see what is the active code page, which might something like [CP437](http://en.wikipedia.org/wiki/Code_page_437) also known as Extended ASCII. If you have characters out of ...
PHP's poor support for the non English world is well known. I've never used a database with characters outside the basic ASCII realm, but obviously you already have a work around and it seems you just have to live with it. If you wanted to take it a step further, you could: 1. Write an array that contains all the spec...
PHP, MSSQL2005 and Codepages
[ "", "php", "sql-server", "encoding", "codepages", "" ]
What is the difference between `HAVING` and `WHERE` in an `SQL SELECT` statement? EDIT: I have marked Steven's answer as the correct one as it contained the key bit of information on the link: > When `GROUP BY` is not used, `HAVING` behaves like a `WHERE` clause The situation I had seen the `WHERE` in did not have `...
> HAVING specifies a search condition for a > group or an aggregate function used in SELECT statement. [Source](http://blog.sqlauthority.com/2007/07/04/sql-server-definition-comparison-and-difference-between-having-and-where-clause/)
HAVING: is used to check conditions *after* the aggregation takes place. WHERE: is used to check conditions *before* the aggregation takes place. This code: ``` select City, CNT=Count(1) From Address Where State = 'MA' Group By City ``` Gives you a table of all cities in MA and the number of addresses in each city...
What is the difference between HAVING and WHERE in SQL?
[ "", "sql", "where-clause", "having", "" ]
I have a C# application that is a client to a web service. One of my requirements is to allow capturing the SOAP that I send, so that if there is a problem, I can either fix the bug, or demonstrate that the problem is in the service I am calling. My WebReference proxy service class derives from `System.Web.Services.Pr...
I think what you are looking for is addressed in this question: [Getting RAW Soap Data from a Web Reference Client running in ASP.net](https://stackoverflow.com/questions/300674/getting-raw-soap-data-from-a-web-reference-client-running-in-aspnet) It looks like a lot of code though.
If the application is running on your local box and the web service isn't doing anything funky, you can use Fiddler. Fire Up IE, run Fiddler, and you'll see your web service calls go through fiddler's proxy too. I just used this this morning to do almost the same thing. I had to prove the data my web service was sendi...
In C#, how would I capture the SOAP used in a web service call?
[ "", "c#", "web-services", "soap", "" ]
I am using the SharpZipLib open source .net library from [www.icsharpcode.net](http://www.icsharpcode.net) My goal is to unzip an xml file and read it into a dataset. However I get the following error reading the file into a dataset: "Data at the root level is invalid. Line 1, position 1." I believe what is happening ...
Well, what does the final file look like? (compared to the original). You don't show the zipping code, which might be part of the puzzle, especially as you are partially swallowing the exception. I would also try ensuring everything `IDisposable` is `Dispose()`d, ideally via `using`; also - in case the problem is with...
I compared the original with the final using TextPad and they are identical. Also I rewrote the code to take advantage of the using. Here is the code. My issue seems to be centered around file locking or something. If I unzip the file quit the application then start it up it will read find. ``` private string UnZipFil...
Unzipping a file error
[ "", "c#", "xml", "" ]
I have a WCF service which will be hosted under IIS. Now I have some resources(Connections) that I create within service constructor. I need to free up those resources when IIS which is hosting the service shuts down or resets. These are not the resources that I will be clearing out every time client disconnects but th...
Well, I'm out of ideas, but I think that [this article](http://msdn.microsoft.com/en-us/library/bb332338.aspx) contains your answer in the chapter: "Accessing ServiceHost in IIS". It seems you need to build your own HostFactory because out of the box IIS uses the standard HostFactory and practically controls the creati...
You can use the IDisposable pattern with finalizer on the class that holds the resources. On unload of AppDomain, all objects are finalized and if the object that has reference to the resources (such connections) has a finalizer, the finalizer will be called and you can close / dispose the resources at that point.
How to Create a Listener for WCF ServiceHost events when service is hosted under IIS?
[ "", "c#", "wcf", "iis", "" ]
I have a stored procedure that creates and opens some cursors. It closes them at the end, but if it hits an error those cursors are left open! Then subsequent runs fail when it tries to create cursors since a cursor with the name already exists. Is there a way I can query which cursors exists and if they are open or n...
This seems to work for me: ``` CREATE PROCEDURE dbo.p_cleanUpCursor @cursorName varchar(255) AS BEGIN DECLARE @cursorStatus int SET @cursorStatus = (SELECT cursor_status('global',@cursorName)) DECLARE @sql varchar(255) SET @sql = '' IF @cursorStatus > 0 SET @sql = 'CLOSE '+@cursorName ...
[Look here](http://msdn.microsoft.com/en-us/library/aa172595(SQL.80).aspx) for info on how to find cursors. I have never used any of them because I could figure out a way to get it done without going Row By Agonizing Row. You should rebuild the sp to either * not use cursors ( we can help - there is almost always a...
Is there any way to get a list of open/allocated cursors in SQL server?
[ "", "sql", "sql-server", "sql-server-2000", "database-cursor", "" ]
The C++ standard imposes an ordering on class member variables in memory. It says that the addresses of member variables have to increase in the order of declaration, but only inside one access section. Very specifically, this does not seem to prevent compilers from laying out access sections in an interleaved way. For...
I checked out the C++ standard. In section 9.2, paragraph (or clause or whatever) 12, it says "The order of allocation of nonstatic data members separated by an access-specifier is unspecified." "Unspecified" means implementation-dependent behavior that need not be documented. Therefore, the standard is explicitly say...
And no, i think he is NOT trying to spam. This is a valid question and quite interesting i think. Ok now i think compilers can do that. The standard says in 9.2. p12: `Implementation alignment require- ments might cause two adjacent members not to be allocated immediately after each other; so might requirements for s...
Can C++ access sections be interleaved?
[ "", "c++", "" ]
Python has a [number of soap stacks](https://stackoverflow.com/questions/206154/whats-the-best-soap-client-library-for-python-and-where-is-the-documentation-fo); as near as I can tell, all have substantial defects. Has anyone had luck consuming *and* using WSDL for S3, EC2, and SQS in python? My experience is that su...
The REST or "Query" APIs are definitely easier to use than SOAP, but unfortunately at least one service (EC2) doesn't provide any alternatives to SOAP. As you've already discovered, Python's existing SOAP implementations are woefully inadequate for most purposes; one workaround approach is to just generate the XML for ...
if i'm not mistaken, you can consume Amazon Web Services via REST as well as SOAP. using REST with python would be *much* easier.
What's the best python soap stack for consuming Amazon Web Services WSDL?
[ "", "python", "amazon-web-services", "soap", "wsdl", "" ]
I have an application that uses `Ajax.Request` and its `onSuccess` event handler in lots of places. I need to call a function (that will check the response) before all these `onSuccess` events fire. I tried using `Ajax.Responders.register` with `onComplete` event but it fires after `Ajax.Request`'s `onSuccess` event. ...
This might be a little late, but for the benefit of anyone else wondering about the same problem I will propose this solution: You can use Prototypes own implementation of aspect-oriented programming to do this. Granted you will have to modify all your onSuccess-parameters, but it can be done with a simple search-and-...
similar to Aleksander Krzywinski's answer, but I believe this would prevent you from having to sprinkle the use of "wrap" everywhere, by consolidating it to the onCreate Responder. ``` Ajax.Responders.register({ onCreate: function(request) { request.options['onSuccess'] = request.options['onSuccess'].wrap(vali...
Extending every Ajax.Request onSuccess event (Javascript Prototype Framework)
[ "", "javascript", "ajax", "prototypejs", "" ]
I am trying to create a Key Listener in java however when I try ``` KeyListener listener = new KeyListener(); ``` Netbeans is telling me that KeyListener is abstract;cannot be instantiated. I know that I am missing some other piece of this key listener, but since this is my first time using a key listener i am unsure...
`KeyListener` is an interface - it has to be implemented by something. So you could do: ``` KeyListener listener = new SomeKeyListenerImplementation(); ``` but you can't instantiate it directly. You *could* use an anonymous inner class: ``` KeyListener listener = new KeyListener() { public void keyPressed(KeyEve...
KeyListener is an interface, so you must write a class that implements it to use it. As Jon suggested, you could create an anonymous class that implements it inline, but there's a class called KeyAdapter that is an abstract class implementing KeyListener, with empty methods for each interface method. If you subclass Ke...
KeyListener in Java is abstract; cannot be instantiated?
[ "", "java", "instantiation", "keylistener", "" ]
In the application there is a dialog where only numeric string entries are valid. Therefore I would like to set the numeric keyboard layout. Does anyone know how to simulate key press on the keyboard or any other method to change the keyboard layout? Thanks!
You don't need to. Just like full windows, you can set the edit control to be numeric input only. You can either do it [manually](http://msdn.microsoft.com/en-us/library/bb761655(VS.85).aspx) or in the dialog editor in the properites for the edit control. The SIP should automatically display the numeric keyboard when...
There is only one way to do this (edit: this is referring to the SIP in non-smartphone Windows Mobile, so I'm not sure it's relevant to your question), and it does involve simulating a mouse click on the 123 button. This is only half the problem, however, since you also need to know whether the keyboard is already in n...
Changing Keyboard Layout on Windows Mobile
[ "", "c++", "windows-mobile", "" ]
I'm developing an application with a team in .Net (C++) and provide a COM interface to interact with python and other languages. What we've found is that pushing data through COM turns out to be pretty slow. I've considered several alternatives: * dumping data to a file and sending the file path through com * Shared...
Staying within the Windows interprocess communication mechanisms, we had positive experience using *windows named pipes*. Using Windows overlapped IO and the `win32pipe` module from [pywin32](http://pywin32.sourceforge.net/). You can learn much about win32 and python in the [Python Programming On Win32](http://oreilly...
XML/JSON and a either a Web Service or directly through a socket. It is also language and platform independent so if you decide you want to host the python portion on UNIX you can, or if you want to suddenly use Java or PHP or pretty much any other language you can. As a general rule proprietary protocols/architecture...
What's the best way to transfer data from python to another application in windows?
[ "", "python", "winapi", "com", "data-transfer", "" ]
Basically I need to insert a bunch of data to an Excel file. Creating an OleDB connection appears to be the fastest way but I've seen to have run into memory issues. The memory used by the process seems to keep growing as I execute INSERT queries. I've narrowed them down to only happen when I output to the Excel file (...
The answer is **Yes**, the formula you describe *does* equal a bad time. If you have a database handy (SQL Server or Access are good for this), you can do all of your inserts into a database table, and then export the table all at once into an Excel spreadsheet. Generally speaking, databases are good at handling lots...
Here are a couple of ideas: Is the target workbook open? There is a bug ([Memory leak occurs when you query an open Excel worksheet by using ActiveX Data Objects](http://support.microsoft.com/kb/319998/en-us)) which IIRC is actually in the OLE DB provider for Jet (which you are using) although this isn't confirmed in ...
Does ADO.NET + massive INSERTs + Excel + C# = "A bad time"?
[ "", "c#", "excel", "ado.net", "memory-management", "memory-leaks", "" ]
How do I pad a numeric string with zeroes to the left, so that the string has a specific length?
To pad strings: ``` >>> n = '4' >>> print(n.zfill(3)) 004 ``` To pad numbers: ``` >>> n = 4 >>> print(f'{n:03}') # Preferred method, python >= 3.6 004 >>> print('%03d' % n) 004 >>> print(format(n, '03')) # python >= 2.6 004 >>> print('{0:03d}'.format(n)) # python >= 2.6 + python 3 004 >>> print('{foo:03d}'.format(f...
Just use the [`rjust`](https://docs.python.org/3/library/stdtypes.html#str.rjust) method of the string object. This example creates a 10-character length string, padding as necessary: ``` >>> s = 'test' >>> s.rjust(10, '0') >>> '000000test' ```
How do I pad a string with zeros?
[ "", "python", "string", "zero-padding", "" ]
Today my colleagues and me have a discussion about the usage of the `final` keyword in Java to improve the garbage collection. For example, if you write a method like: ``` public Double doCalc(final Double value) { final Double maxWeight = 1000.0; final Double totalWeight = maxWeight * value; return totalWei...
Here's a slightly different example, one with final reference-type fields rather than final value-type local variables: ``` public class MyClass { public final MyOtherObject obj; } ``` Every time you create an instance of MyClass, you'll be creating an outgoing reference to a MyOtherObject instance, and the GC w...
Declaring a local variable `final` will not affect garbage collection, it only means you can not modify the variable. Your example above should not compile as you are modifying the variable `totalWeight` which has been marked `final`. On the other hand, declaring a primitive (`double` instead of `Double`) `final` will ...
Does using final for variables in Java improve garbage collection?
[ "", "java", "garbage-collection", "final", "" ]
I want to make this specialized w/o changing main. Is it possible to specialize something based on its base class? I hope so. -edit- I'll have several classes that inherit from SomeTag. I don't want to write the same specialization for each of them. ``` class SomeTag {}; class InheritSomeTag : public SomeTag {}; te...
This article describes a neat trick: <http://www.gotw.ca/publications/mxc++-item-4.htm> Here's the basic idea. You first need an IsDerivedFrom class (this provides runtime and compile-time checking): ``` template<typename D, typename B> class IsDerivedFrom { class No { }; class Yes { No no[3]; }; static Yes T...
Update for concepts, using C++-20: ``` #include <concepts> struct NotSomeTag { }; struct SomeTag { }; struct InheritSomeTag : SomeTag { }; template<typename T> concept ConceptSomeTag = std::is_base_of_v<SomeTag, T>; template<class T> struct MyClass { }; // Specialization. template<ConceptSomeTag ST> struct MyClass...
Template specialization based on inherit class
[ "", "c++", "templates", "specialization", "" ]
I'm working on a PyGTK/glade application that currently has 16 windows/dialogs and is about 130KB, and will eventually have around 25 windows/dialogs and be around 200KB. Currently, I'm storing all the windows in one monolithic glade file. When I run a window I call it like... ``` self.wTree = gtk.glade.XML("interface...
In my projects, I always have one window per glade file. I'd recommend the same for your project. The following are the two main reasons: * It will be faster and use less memory, since each call to gtk.glade.XML() parses the whole thing. Sure you can pass in the root argument to avoid creating the widget tree for all...
Did you take some timings to find out whether it makes a difference? The problem is that, as far as I understand it, Glade always creates all widgets when it parses an XML file, so if you open the XML file and only read a single widget, you are wasting a lot of resources. The other problem is that you need to re-read...
How to handle a glade project with many windows
[ "", "python", "gtk", "pygtk", "glade", "" ]
A puzzler from a coworker that I cannot figure out... ``` update btd.dbo.tblpayroll set empname = ( select b.Legal_Name from ( SELECT Legal_Name, Employee_ID FROM Com.dbo.Workers WHE...
I suspect that the optimizer is attempting to apply the where clause of the outer select before the inner select. Presumably it thinks it would be able to do an index lookup on Employee\_ID resulting in a faster query in this case. Try: ``` update btd.dbo.tblpayroll set empname = ( select Legal_Name ...
Maybe N is considered currency symbol? You can try to replace IsNumeric with ``` LIKE REPLICATE('[0-9]',/*length of Employee_ID*/) ``` or just ``` LIKE '[0-9]%' ``` if letter cannot be in the middle
Data not filtering before a join
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
I have a class `Page` that creates an instance of `DB`, which is named `$db`. In the `__construct()` of `Page`, I create the new `$db` object and I pull a bunch of config data from a file. Now the DB class has a method `_connectToDB()` which (attempts) to connect to the database. Is there a way in the DB class to ca...
I find that it's often easier to initialise all the "important" objects close to whatever variables they need to know. You could try it this way: ``` /* Code to get config variables here */ $DB = new DB($config); /* You might want to delete the database password from $config here */ $Page = new Page($config, $DB); ```...
You can use `static` if you want to share variables without passing these: ``` class page{ static $configArray = []; function doWhatever(){ $db = new DB(); $db->connectToDB(); } } class DB{ function connectToDB(){ $dbUsername = page::$configArray['dbUserName']; } } ``` In t...
Can you get a calling class's variables?
[ "", "php", "oop", "" ]
When would I implement IDispose on a class as opposed to a destructor? I read [this article](http://www.dotnetspider.com/resources/1382-Understanding-IDisposable-pattern.aspx), but I'm still missing the point. My assumption is that if I implement IDispose on an object, I can explicitly 'destruct' it as opposed to wait...
A finalizer (aka destructor) is part of garbage collection (GC) - it is indeterminate when (or even if) this happens, as GC mainly happens as a result of memory pressure (i.e. need more space). Finalizers are usually only used for cleaning up *unmanaged* resources, since managed resources will have their own collection...
The role of the `Finalize()` method is to ensure that a .NET object can clean up unmanaged resources **when garbage collected**. However, objects such as database connections or file handlers should be released as soon as possible, instead on relying on garbage collection. For that you should implement `IDisposable` in...
What is the difference between using IDisposable vs a destructor in C#?
[ "", "c#", ".net", "dispose", "destructor", "" ]
I have run into a bit of a tricky problem in some C++ code, which is most easily described using code. I have classes that are something like: ``` class MyVarBase { } class MyVar : public MyVarBase { int Foo(); } class MyBase { public: MyBase(MyVarBase* v) : m_var(v) {} virtual MyVarBase* GetVar() { ret...
The correct way to do this is to have the variable only in the base class. As the derived class knows it must be of dynamic type `MyVar`, this is totally reasonable: ``` class MyClass : public MyBase { public: MyClass(MyVar* v) : MyBase(v) {} MyVar* GetVar() { return static_cast<MyVar*>(MyBase::GetVar()); } } ...
Without knowing more of the context, it's hard to say for sure, but I'd reconsider whether you need this class hierarchy in the first place. Do you really need the MyVarBase and MyBase classes? Could you get away with composition instead of inheritance? Maybe you don't need the class heirarchy at all, if you template t...
Overriding a member variable in C++
[ "", "c++", "oop", "" ]
First of all, I'm not looking for miracle... I know how PHP works and that there's not really way to hide my code from the clients without using encryption. But that comes with the cost of an extension to be installed on the running server. I'm looking for something different though... I'm not looking to encrypt my co...
Obfuscating things can only inconvenience your legitimate, law-abiding customers, while the people who would would rip you off are not your target paying customers anyway. (edited out other thoughts about obfuscation) Another suggestion for protecting your software: create a business model in which the code is an inco...
You need to consider your objectives: 1) **Are you trying to prevent people from reading/modifying your code?** If yes, you'll need an obfuscation/encryption tool. I've used [Zend Guard](http://www.zend.com/en/products/guard/) with good success. 2) **Are you trying to prevent unauthorized redistribution of your code?...
Best solution to protect PHP code without encryption
[ "", "php", "encryption", "obfuscation", "" ]