Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I am using wxWidgets and Visual C++ to create functionality similar to using Unix "tail -f" with rich formatting (colors, fonts, images) in a GUI. I am targeting both wxMSW and wxMAC. The obvious answer is to use wxTextCtrl with wxTE\_RICH, using calls to wxTextCtrl::SetDefaultStyle() and wxTextCtrl::WriteText(). How...
Derive from wxVListBox. From the docs: > wxVListBox is a listbox-like control with the following two main differences from a regular listbox: it can have an arbitrarily huge number of items because it doesn't store them itself but uses OnDrawItem() callback to draw them (so it is a Virtual listbox) and its items can h...
Have you considered limiting the amount of lines in the view? When we had a similar issue, we just made sure never more than 10,000 lines are in the view. If more lines come in at the bottom we remove lines at the top. This was not using WxWidgets, it was using a native Cocoa UI on Mac, but the issue is the same. If a ...
How do I append a large amount of rich content (images, formatting) quickly to a control without using tons of CPU?
[ "", "c++", "performance", "wxwidgets", "" ]
I'm working on some code that uses a pattern in its business and data tiers that uses events to signal errors e.g. ``` resource = AllocateLotsOfMemory(); if (SomeCondition()) { OnOddError(new OddErrorEventArgs(resource.StatusProperty)); resource.FreeLotsOfMemory(); return; } ``` This looked superf...
Take a look at [this post](http://www.udidahan.com/2008/08/25/domain-events-take-2/) by Udi Dahan. Its an elegant approach for dispatching domain events. The previous poster is correct in saying that you should not be using an event mechanism to recover from fatal errors, but it is a very useful pattern for notificatio...
It seems odd to me too. There are a few advantages - such as allowing multiple "handlers" but the semantics are significantly different to normal error handling. In particular, the fact that it doesn't automatically get propagated up the stack concerns me - unless the error handlers themselves throw an exception, the l...
Using events rather than exceptions to implement error handling
[ "", "c#", "design-patterns", "exception", "events", "" ]
Other than pasting a WDSL in the tech spec, what are the recommended ways to document a WCF web-service before you begin coding?
We recently published a WCF based SOAP interface for third parties to integrate against. For each method we provided the following: * Method name * Request example (wire format dump) * Request parameters explanation * Response example (wire format dump) * Request parameters explanation * Caveats (gotchas) * History W...
Document the contract interface as you would document any other interface. Describe the operations, pre-conditions, post-conditions, reasons for throwing a fault, etc.
How to document a WCF web-service in a technical spec?
[ "", "c#", "wcf", "web-services", "" ]
I've seen reference in some C# posted questions to a "using" clause. Does java have the equivalent?
Yes. Java 1.7 introduced the [try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) construct allowing you to write: ``` try(InputStream is1 = new FileInputStream("/tmp/foo"); InputStream is2 = new FileInputStream("/tmp/bar")) { /* do stuff with is1 and is...
Yes, since Java 7 you can rewrite: ``` InputStream is1 = new FileInputStream("/tmp/foo"); try{ InputStream is2 = new FileInputStream("/tmp/bar"); try{ /* do stuff with is1 and is2 */ } finally { is2.close(); } } finally { is1.close(); } ``` As ``` try(InputStream is1 = new Fil...
Does java have an equivalent to the C# "using" clause
[ "", "java", "syntax", "" ]
I have a class that encapsulates tcp socket communications with a server. For each command message sent to the server, the server will send back a response message that invariably contains a response code (OK, Fail). Using my class, each command can be executed either sync or async. There are basically two types of ex...
I think your strategy is basically sound. Keep in mind that the purpose of Exceptions is to deal with exceptional conditions. The closer to the source of the problem, the better. In your case, it appears that your strategy is something like "It didn't work right now. Let's retry". I don't see a reason to really raise...
My preference is you throw an exception any time your method does not successfully complete its mission. So if I, the caller, call yourObject.UploadFile(), I will assume the file was uploaded successfully when the call returns. If it fails for any reason, I expect your object will throw an exception. If you want to dis...
Exceptions vs Result Codes for a socket client class
[ "", "c#", ".net", "networking", "sockets", "tcp", "" ]
I've made some unit tests (in test class). The tutorial I've read said that I should make a TestSuite for the unittests. Odd is that when I'm running the unit test directly (selecting the test class - Run as jUnit test) everything is working fine, altough when I'm trying the same thing with the test suite there's alwa...
I'm not experienced in ant - so I'm not using it for testing it right now. Searching the internet it seems like I'm mixing up the old jUnit 3.8 and jUnit 4.0 behavior. Trying now a way to use the "new behavior" edited: now it works: AllTest changed to: ``` import org.junit.runner.RunWith; import org.junit.runners...
Be careful when using an IDE's code-completion to add the import for `@Test`. It has to be `import org.junit.Test` and **not** `import org.testng.annotations.Test`, for example. If you use the second one by mistake, you'll get the "no runnable methods" error. (I was using Intellij Idea 2017 which imported `org.junit.ju...
JUnit and junit.framework.TestSuite - No runnable methods
[ "", "java", "unit-testing", "junit", "" ]
Assume my objects are in perfect working order (i.e. TDD makes me think they work). I have a list that I create like this (except indented properly): ``` var result = from v in vendors from p in v.Products orderby p.Name select p; ``` This works - I get all products from all ve...
(Edited for clarity.) The problem is the foreach loop, and the fact that the "a" variable is being captured and then changed each time. Here's a modification which will work, by effectively introducing a "new" variable for each iteration of the loop, and capturing that new variable. ``` foreach (Attribute a in requir...
``` var result = from v in vendors from p in v.Products where requiredAttributes.All(a => p.Attributes.Contains(a)) orderby p.Name select p; ``` HTH.
Building a LINQ query programmatically without local variables tricking me
[ "", "c#", "linq", "" ]
We are using SQL Server 2005, but this question can be for any [RDBMS](http://en.wikipedia.org/wiki/Relational_database_management_system). Which of the following is more efficient, when selecting all columns from a view? ``` Select * from view ``` or ``` Select col1, col2, ..., colN from view ```
NEVER, EVER USE "SELECT \*"!!!! This is the cardinal rule of query design! There are multiple reasons for this. One of which is, that if your table only has three fields on it and you use all three fields in the code that calls the query, there's a great possibility that you will be adding more fields to that table a...
It is best practice to select each column by name. In the future your DB schema might change to add columns that you would then not need for a particular query. I would recommend selecting each column by name.
SQL query - Select * from view or Select col1, col2, ... colN from view
[ "", "sql", "sql-server", "" ]
``` inline int factorial(int n) { if(!n) return 1; else return n*factorial(n-1); } ``` As I was reading [this](https://rads.stackoverflow.com/amzn/click/com/0201543303), found that the above code would lead to "infinite compilation" if not handled by compiler correctly. How does the compiler decide whether to...
First, the `inline` specification on a function is just a hint. The compiler can (and often does) completely ignore the presence or absence of an `inline` qualifier. With that said, a compiler *can* inline a recursive function, much as it can unroll an infinite loop. It simply has to place a limit on the level to which...
Indeed, if your compiler does not act intelligently, it may try inserting copies of your `inline`d function recursively, creating infinitely-large code. Most modern compilers will recognize this, however. They can either: 1. Not inline the function at all 2. Inline it up to a certain depth, and if it hasn't terminated...
Can a recursive function be inline?
[ "", "c++", "c", "compiler-construction", "" ]
I've always handled optional parameters in JavaScript like this: ``` function myFunc(requiredArg, optionalArg){ optionalArg = optionalArg || 'defaultValue'; // Do stuff } ``` Is there a better way to do it? Are there any cases where using `||` like that is going to fail?
Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative ``` if (typeof optionalArg === 'undefined') { optionalArg = 'default'; } ``` Or an alternative idiom: ``` optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg; ``` Use whichever idiom communicates ...
In **ECMAScript 2015** (aka "**ES6**") you can declare default argument values in the function declaration: ``` function myFunc(requiredArg, optionalArg = 'defaultValue') { // do stuff } ``` More about them in [this article on MDN](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/default_parameters)....
Is there a better way to do optional function parameters in JavaScript?
[ "", "javascript", "function", "arguments", "" ]
So, bitfields. Specifically, large bitfields. I understand how to manipulate individual values in a bitfield, but how would I go about doing this on a large set, such as say: ``` uint[] bitfield = new uint[4] { 0x0080000, 0x00FA3020, 0x00C8000, 0x0FF00D0 }; ``` The specific problem I'm having is doing left and right ...
What makes you think that BitArray uses bools internally? It uses Boolean values to represent the bits in terms of the API, but under the hood I believe it uses an int[].
I'm not sure if it's the best way to do it, but this could work (constraining shifts to be in the range 0-31. ``` public static void ShiftLeft(uint[] bitfield, int shift) { if(shift < 0 || shift > 31) { // handle error here return; } int len = bitfield.Length; ...
Bitfields in C#
[ "", "c#", "data-structures", "bit-manipulation", "bit-fields", "" ]
I'm writing some cross-platform code between Windows and Mac. If `list::end()` "returns an iterator that addresses the location succeeding the last element in a list" and can be checked when traversing a list forward, what is the best way to traverse the list backwards? This code works on the Mac but not on Windows (...
Use `reverse_iterator` instead of `iterator`. Use `rbegin()` & `rend()` instead of `begin()` & `end()`. Another possibility, if you like using the [`BOOST_FOREACH`](http://www.boost.org/doc/libs/1_36_0/doc/html/foreach.html) macro is to use the `BOOST_REVERSE_FOREACH` macro introduced in Boost 1.36.0.
The best/easiest way to reverse iterate a list is (as already stated) to use reverse iterators rbegin/rend. However, I did want to mention that reverse iterators are implemented storing the "current" iterator position off-by-one (at least on the GNU implementation of the standard library). This is done to simplify th...
How do you iterate backwards through an STL list?
[ "", "c++", "list", "stl", "iterator", "traversal", "" ]
I am after documentation on using wildcard or regular expressions (not sure on the exact terminology) with a jQuery selector. I have looked for this myself but have been unable to find information on the syntax and how to use it. Does anyone know where the documentation for the syntax is? EDIT: The attribute filters ...
James Padolsey created a [wonderful filter](http://james.padolsey.com/javascript/regex-selector-for-jquery/) that allows regex to be used for selection. Say you have the following `div`: ``` <div class="asdf"> ``` Padolsey's `:regex` filter can select it like so: ``` $("div:regex(class, .*sd.*)") ``` Also, check t...
You can use the [`filter`](http://docs.jquery.com/Traversing/filter#expr) function to apply more complicated regex matching. Here's an example which would just match the first three divs: ``` $('div') .filter(function() { return this.id.match(/abc+d/); }) .html("Matched!"); ``` ``` <script src="https:/...
jQuery selector regular expressions
[ "", "javascript", "jquery", "regex", "jquery-selectors", "" ]
I find it odd that in Visual C# 2008 Express edition, when you use the database explorer, your options are: 1. Microsoft Access 2. SQL Server Compact 3.5, and 3. SQL Server Database File. BUT if you use Visual Web Developer 2008 Express, you can connect to a regular SQL Server, Oracle, ODBC, etc. For people developi...
You should be able to choose the SQL Server Database file option to get the right kind of database (the `system.data.SqlClient` provider), and then manually correct the connection string to point to your db. I think the reasoning behind those db choices probably goes something like this: * If you're using the Express...
Workaround: 1. Open your solution in Visual Web Developer Express. It will not load some of the projects in the solution but it is ok. 2. Make a new connection in Database Explorer to the required database from SQL Server. 3. Add a new class library project. 4. Add a LINQ to SQL Classes item and link it to your databa...
Connecting to SQL Server with Visual Studio Express Editions
[ "", "c#", "visual-studio-2008", "visual-web-developer", "" ]
I have a method running in a seperate thread. The thread is created and started from a form in a windows application. If an exception is thrown from inside the thread, what is the best way to pass it back to the main application. Right now, I'm passing a reference to the main form into the thread, then invoking the met...
So you're using Invoke to marshall back to the UI thread, by the looks of it - which is exactly what you need to do. I'd personally use an Action<Exception> for simplicity's sake, and possibly BeginInvoke instead of Invoke, but basically you're doing the right thing.
Use the BackgroundWorker class in the .NET framework instead. It is the best practice for performing UI work on a different thread.
catching exceptions from another thread
[ "", "c#", ".net", "multithreading", "exception", "" ]
If something goes wrong in a WCF REST call, such as the requested resource is not found, how can I play with the HTTP response code (setting it to something like HTTP 404, for example) in my OperationContract method?
There is a [`WebOperationContext`](http://msdn.microsoft.com/en-us/library/system.servicemodel.web.weboperationcontext.aspx) that you can access and it has a [`OutgoingResponse`](http://msdn.microsoft.com/en-us/library/system.servicemodel.web.weboperationcontext.outgoingresponse.aspx) property of type [`OutgoingWebResp...
If you need to return a reason body then have a look at [WebFaultException](http://msdn.microsoft.com/en-us/library/dd989924.aspx) For example ``` throw new WebFaultException<string>("Bar wasn't Foo'd", HttpStatusCode.BadRequest ); ```
How can I return a custom HTTP status code from a WCF REST method?
[ "", "c#", ".net", "wcf", "rest", "" ]
In PHP I can name my array indices so that I may have something like: ``` $shows = Array(0 => Array('id' => 1, 'name' => 'Sesame Street'), 1 => Array('id' => 2, 'name' => 'Dora The Explorer')); ``` Is this possible in Python?
This sounds like the PHP array using named indices is very similar to a python dict: ``` shows = [ {"id": 1, "name": "Sesaeme Street"}, {"id": 2, "name": "Dora The Explorer"}, ] ``` See <http://docs.python.org/tutorial/datastructures.html#dictionaries> for more on this.
PHP arrays are actually maps, which is equivalent to dicts in Python. Thus, this is the Python equivalent: `showlist = [{'id':1, 'name':'Sesaeme Street'}, {'id':2, 'name':'Dora the Explorer'}]` Sorting example: ``` from operator import attrgetter showlist.sort(key=attrgetter('id')) ``` BUT! With the example you p...
Python: can I have a list with named indices?
[ "", "python", "arrays", "" ]
I've got a (poorly written) base class that I want to wrap in a proxy object. The base class resembles the following: ``` public class BaseClass : SomeOtherBase { public BaseClass() {} public BaseClass(int someValue) {} //...more code, not important here } ``` and, my proxy resembles: ``` public BaseClas...
If you do not explicitly call any constructor in the base class, the parameterless constructor will be called implicitly. There's no way around it, you cannot instantiate a class without a constructor being called.
There is a way to create an object without calling *any* instance constructors. Before you proceed, be very sure you want to do it this way. 99% of the time this is the wrong solution. This is how you do it: ``` FormatterServices.GetUninitializedObject(typeof(MyClass)); ``` Call it in place of the object's construc...
How can I prevent a base constructor from being called by an inheritor in C#?
[ "", "c#", "oop", "inheritance", "proxy", "constructor", "" ]
It looks like some work has been done to make [pthread-win32](http://sourceware.org/pthreads-win32/) work with x64, but there are no build instructions. I have tried simly building with the Visual Studio x64 Cross Tools Command Prompt, but when I try to link to the lib from an x64 application, it can't see any of the f...
Until it's officially released, it looks like you have to check out the CVS head to get version 2.9 of the library. Version 2.9 has all the x64 patches, but you will still have problems if you try to compile the static library from the command line. The only workaround I know of is to use the DLLs instead of staticall...
You can use the **vcpkg** [here](https://learn.microsoft.com/en-us/cpp/build/vcpkg?view=vs-2019). Which is the Windows package manager for C++. It supports pthread building and also other open source libraries. I wanted to use a static pthread library. When i downloaded the pthread i got the dll(pthread.dll) and impor...
How do you compile static pthread-win32 lib for x64?
[ "", "c++", "c", "windows", "64-bit", "pthreads", "" ]
We are trying to look at optimizing our localization testing. Our QA group had a suggestion of a special mode to force all strings from the resources to be entirely contained of X. We already API hijack LoadString, and the MFC implementation of it, so doing it should not be a major hurdle. My question is how would yo...
If this approach is to highlight formatted strings (or format sequences) in the application (i.e. all text appearing other than XXXX), you could locate the escape sequence (using regex perhaps) and insert block quotes around the formatted (substituted) values, e.g. Some\ntext -> Some[\n]text You get readability (al...
The pseudo-localisation feature of [appTranslator](http://www.apptranslator.com) can help you there: It modifies untranslated strings to use diacritics, text widening or shortening and such. So far, you're not interested. Where it becomes interesting is that it optionally encloses such strings in brackets. The idea was...
Localization testing, formatting all strings with XXXXX
[ "", "c++", "mfc", "localization", "" ]
Does anyone know how I can get a format string to use [bankers rounding](http://en.wikipedia.org/wiki/Rounding#Round-to-even_method)? I have been using "{0:c}" but that doesn't round the same way that bankers rounding does. The [`Math.Round()`](http://msdn.microsoft.com/en-us/library/system.math.round.aspx) method does...
Can't you simply call Math.Round() on the string input to get the behavior you want? Instead of: ``` string s = string.Format("{0:c}", 12345.6789); ``` Do: ``` string s = string.Format("{0:c}", Math.Round(12345.6789)); ```
Regexp is a pattern matching language. You can't do arithmetic operations in Regexp. Do some experiements with IFormatProvider and ICustomFormatter. Here is a link might point you in the right direction. <http://codebetter.com/blogs/david.hayden/archive/2006/03/12/140732.aspx>
.NET currency formatter: can I specify the use of banker's rounding?
[ "", "c#", ".net", "formatting", "bankers-rounding", "" ]
So why exactly is it that it's always recommended to use `const` as often as possible? It seems to me that using `const` can be more of a pain than a help in C++. But then again, I'm coming at this from the python perspective: if you don't want something to be changed, don't change it. So with that said, here are a few...
This is the definitive article on "const correctness": <https://isocpp.org/wiki/faq/const-correctness>. In a nutshell, using const is good practice because... 0. It protects you from accidentally changing variables that aren't intended be changed, 1. It protects you from making accidental variable assignments. For in...
Here's a piece of code with a common error that const correctness can protect you against: ``` void foo(const int DEFCON) { if (DEFCON = 1) //< FLAGGED AS COMPILER ERROR! WORLD SAVED! { fire_missiles(); } } ```
Sell me const-correctness
[ "", "c++", "const-correctness", "" ]
I'm currently working with PHPUnit to try and develop tests alongside what I'm writing, however, I'm currently working on writing the Session Manager, and am having issues doing so... The constructor for the Session handling class is ``` private function __construct() { if (!headers_sent()) { session_...
Well, your session manager is basically broken by design. To be able to test something, it must be possible to isolate it from side effects. Unfortunately, PHP is designed in such a way, that it encourages liberal use of global state (`echo`, `header`, `exit`, `session_start` etc. etc.). The best thing you can do, is ...
Create a bootstrap file for phpunit, which calls: ``` session_start(); ``` Then start phpunit like this: ``` phpunit --bootstrap pathToBootstrap.php --anotherSwitch /your/test/path/ ``` The bootstrap file gets called before everything else, so the header hasn't been sent and everything should work fine.
Unit Testing with items that need to send headers
[ "", "php", "unit-testing", "phpunit", "" ]
As part of the base class for some extensive unit testing, I am writing a helper function which recursively compares the nodes of one XmlDocument object to another in C# (.NET). Some requirements of this: * The first document is the **source**, e.g. what I want the XML document to look like. Thus the second is the one...
Microsoft has an [XML diff API](http://msdn.microsoft.com/en-us/library/aa302294.aspx) that you can use. Unofficial NuGet: <https://www.nuget.org/packages/XMLDiffPatch>.
I googled up a more complete list of solutions of this problem today, I am going to try one of them soon: * <http://xmlunit.sourceforge.net/> * <http://msdn.microsoft.com/en-us/library/aa302294.aspx> * <http://jolt.codeplex.com/wikipage?title=Jolt.Testing.Assertions.XML.Adaptors> * <http://www.codethinked.com/checking...
How would you compare two XML Documents?
[ "", "c#", ".net", "xml", "compare", "xmldocument", "" ]
I am able to serialize an object into a file and then restore it again as is shown in the next code snippet. I would like to serialize the object into a string and store into a database instead. Can anyone help me? ``` LinkedList<Diff_match_patch.Patch> patches = // whatever... FileOutputStream fileStream = new FileOu...
Sergio: You should use [BLOB](http://docs.oracle.com/javase/6/docs/api/java/sql/Blob.html). It is pretty straighforward with JDBC. The problem with the second code you posted is the encoding. You should additionally encode the bytes to make sure none of them fails. If you still want to write it down into a String yo...
How about writing the data to a ByteArrayOutputStream instead of a FileOutputStream? Otherwise, you could serialize the object using XMLEncoder, persist the XML, then deserialize via XMLDecoder.
How to serialize an object into a string
[ "", "java", "serialization", "" ]
Is there a simple way to write a common function for each of the `CRUD (create, retreive, update, delete)` operations in `PHP` WITHOUT using any framework. For example I wish to have a single create function that takes the table name and field names as parameters and inserts data into a `mySQL database`. Another requir...
I wrote this very thing, it's kind of a polished scaffold. It's basically a class the constructor of which takes the table to be used, an array containing field names and types, and an action. Based on this action the object calls a method on itself. For example: This is the array I pass: ``` $data = array(array('nam...
If you try to write such function you'll soon discover that you've just realized yet another framework.
Common CRUD functions in PHP
[ "", "php", "crud", "" ]
Coming from C++ to Java, the obvious unanswered question is why didn't Java include operator overloading? Isn't `Complex a, b, c; a = b + c;` much simpler than `Complex a, b, c; a = b.add(c);`? Is there a known reason for this, valid arguments for *not* allowing operator overloading? Is the reason arbitrary, or lost ...
Assuming you wanted to overwrite the previous value of the object referred to by `a`, then a member function would have to be invoked. ``` Complex a, b, c; // ... a = b.add(c); ``` In C++, this expression tells the compiler to create three (3) objects on the stack, perform addition, and *copy* the resultant value fro...
There are a lot of posts complaining about operator overloading. I felt I had to clarify the "operator overloading" concepts, offering an alternative viewpoint on this concept. # Code obfuscating? This argument is a fallacy. ## Obfuscating is possible in all languages... It is as easy to obfuscate code in C or Jav...
Why doesn't Java offer operator overloading?
[ "", "java", "operator-overloading", "" ]
Linux supports sending an arbitrary Posix-Signal such as `SIGINT` or `SIGTERM` to a process using the `kill`-Command. While `SIGINT` and `SIGTERM` are just boring old ways to end a process in a friendly or not-so-friendly kind of way, `SIGQUIT` is meant to trigger a core dump. This can be used to trigger a running Java...
If what you want is to explicitly/programmatically kill another program/process of any kind, within the SysInternals' pstools there is a small tool named "pskill" that behaves just like Unixen "kill" would do. If you want something else, keep reading (though I may be wrong on some of the specifics below - it's been eo...
Windows is not POSIX. It does not have signals. The only 'signals' that console programs get is if they call `SetConsoleCtrlHandler`, in which case it can be notified that the user has pressed Ctrl+C, Ctrl+Break, closed the console window, logged off, or shut the system down. Everything else is done with IPC, typicall...
Sending an arbitrary Signal in Windows?
[ "", "java", "windows", "utilities", "" ]
What are my options? I tried MonoDevelop over a year ago but it was extremely buggy. Is the latest version a stable development environment?
MonoDevelop 2.0 has been released, it now has a decent GUI Debugger, code completion, Intellisense C# 3.0 support (including linq), and a decent GTK# Visual Designer. In short, since the 2.0 release I have started using Mono Develop again and am very happy with it so far. Check out the [MonoDevelop website](http://mo...
Microsoft has released [Visual Studio Code](https://www.visualstudio.com/en-us/products/code-vs.aspx "Visual Studio Code") for Linux, which has good C# support, naturally.
IDE's for C# development on Linux?
[ "", "c#", "linux", "ide", "mono", "" ]
Is there any way to set the same icon to all my forms without having to change one by one? Something like when you setup `GlobalAssemblyInfo` for all your projects inside your solution.
One option would be to inherit from a common base-Form that sets the Icon in the constructor (presumably from a resx). Another option might be [PostSharp](http://www.postsharp.org/) - it seems like it should be possible to do this (set .Icon) via AOP; not trivial, though. Finally, you could use a simple utility method ...
1. In the project properties > Application > Icon and Manifest > browse for a \*.ico file and add it there. 2. In the constructor or `_Load` event of a Form, simply add: ``` this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath); ```
Set same icon for all my Forms
[ "", "c#", ".net", "winforms", "icons", "" ]
In your opinion, is it ever valid to use the @ operator to suppress an error/warning in PHP whereas you may be handling the error? If so, in what circumstances would you use this? Code examples are welcome. Edit: Note to repliers. I'm not looking to turn error reporting off, but, for example, common practice is to u...
I would suppress the error **and handle it**. Otherwise you may have a **TOCTOU** issue (Time-of-check, time-of-use. For example a file may get deleted after file\_exists returns true, but before fopen). But I wouldn't just suppress errors to make them go away. These better be visible.
Note: Firstly, I realise 99% of PHP developers use the error suppression operator (I used to be one of them), so I'm expecting any PHP dev who sees this to disagree. > In your opinion, is it ever valid to use the @ operator to suppress an error/warning in PHP whereas you may be handling the error? **Short answer:** ...
Suppress error with @ operator in PHP
[ "", "php", "operators", "error-suppression", "" ]
Typically you will find STL code like this: ``` for (SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(); Iter != m_SomeMemberContainerVar.end(); ++Iter) { } ``` But we actually have the recommendation to write it like this: ``` SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVa...
If you wrap your code into lines properly, the inline form would be equally readable. Besides, you should always do the `iterEnd = container.end()` as an optimization: ``` for (SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(), IterEnd = m_SomeMemberContainerVar.end(); Iter != IterEnd;...
Another alternative is to use a foreach macro, for example [boost foreach](http://www.boost.org/doc/libs/1_36_0/doc/html/foreach.html): ``` BOOST_FOREACH( ContainedType item, m_SomeMemberContainerVar ) { mangle( item ); } ``` I know macros are discouraged in modern c++, but until the auto keyword is widely availab...
Is Iterator initialization inside for loop considered bad style, and why?
[ "", "c++", "stl", "coding-style", "iteration", "iterator", "" ]
I have months stored in SQL Server as 1,2,3,4,...12. I would like to display them as January,February etc. Is there a function in SQL Server like MonthName(1) = January? I am trying to avoid a CASE statement, if possible.
A little hacky but should work: ``` SELECT DATENAME(month, DATEADD(month, @mydate-1, CAST('2008-01-01' AS datetime))) ```
I think this is the best way to get the **month name** when you have the **month number** ``` Select DateName( month , DateAdd( month , @MonthNumber , 0 ) - 1 ) ``` Or ``` Select DateName( month , DateAdd( month , @MonthNumber , -1 ) ) ```
Convert Month Number to Month Name Function in SQL
[ "", "sql", "sql-server", "t-sql", "sql-server-2005", "" ]
Is there any *easy* way to explicitly make an already threaded application utilise a multicore environment? (if avaliable). The first problem would be how do I determine if my runtime environment supports multi-core applications? If I then determine that I can use multi core functionality, can I explicitly assign thr...
If your application is already threaded properly, you dont have to do anything. Thread context execution and handling is done for you. Now when it comes to threading, is your app threaded in a way to utilize the cores? do you have processor intensive tasks split into seperate threads. If not, then you will need to mak...
Hi there are 2 extentions that I know about [Parallel C# Homepage](http://www.parallelcsharp.com/) [Check out Somasegars MSDN blog on MS June CTP for parallel 3.5 extenstions](http://blogs.msdn.com/somasegar/archive/2008/06/02/june-2008-ctp-parallel-extensions-to-the-net-fx.aspx) MSDN The library is made up of the ...
Explicit multi-core C# applications
[ "", "c#", "multicore", "runtime-environment", "" ]
I'm looking for a profiler to use with native C++. It certainly does not have to be free, however cost does factor into the purchase decision. This is for commercial work so I can't use personal or academic licensed copies. The key features I'm looking for are: * Process level metrics * Component level metrics * Line...
On Windows, [GlowCode](http://www.glowcode.com) is affordable, fairly easy to use, and offers a free trial so you can see if it works for you.
Many people are not aware but MSFT is making a great progress putting the best possible tools for improving performance in the hands of devlopers for free :-). They are exposing to all of us the internals of Windows tracing: ETW. [perftools](http://www.microsoft.com/whdc/system/sysperf/perftools.mspx) It is part of t...
What are some good profilers for native C++ on Windows?
[ "", "c++", "windows", "performance", "profiling", "" ]
An interesting issue came up recently. We came across some code that is using `hashCode()` as a salt source for MD5 encryption but this raises the question: will `hashCode()` return the same value for the same object on different VMs, different JDK versions and operating systems? Even if its not guaranteed, has it chan...
No. From <http://tecfa.unige.ch/guides/java/langspec-1.0/javalang.doc1.html>: > The general contract of hashCode is as > follows: > > * Whenever it is invoked on the same object more than once during an > execution of a Java application, > hashCode must consistently return the > same integer. The integer may be ...
It depends on the type: * If you've got a type which hasn't overridden hashCode() then it will probably return a different hashCode() each time you run the program. * If you've got a type which overrides hashCode() but doesn't document how it's calculated, it's perfectly legitimate for an object with the same data to ...
Is String.hashCode() portable across VMs, JDKs and OSs?
[ "", "java", "hashcode", "" ]
Since I have started using this site, I keep hearing about the Boost library. I am wondering what are some of the major benefits of the Boost library (hence why should I use it) and how portable is the Boost library?
Boost is organized by several members of the standard committee. So it is a breeding ground for libraries that will be in the next standard. 1. It is an extension to the STL (it fills in the bits left out) 2. It is well documented. 3. It is well peer-reviewed. 4. It has high activity so bugs are found and fixed quic...
You can simply read the [Boost Background Information](http://www.boost.org/users/) page to get a quick overview of why you should use Boost and what you can use it for. Worth the few minutes it takes.
Benefits and portability of Boost Library
[ "", "c++", "boost", "" ]
I am trying to store more than 1 data item at a single index in my linked-list. All of the examples in my textbook seem to illustrate adding only 1 piece of data per index. I'm assuming it is possible to add more? For example, using the Collections API to store an integer I would do the following: ``` LinkedList <Int...
There seems to be a little confusion about how linked lists work. Essentially, a linked list is composed of nodes, each of which contains one datum (an object, which itself can contain several member variables, to be precise), and a link to the next node in the list (or a null pointer if there is no such next node). Yo...
Use a structure. For example: ``` private struct Node { int Num1; int Num2; int Num3; } ``` ... ``` LinkedList<Node> list = new LnkedList<Node>(); Node n = new Node(); n.Num1 = 10; n.Num2 = 100; n.Num3 = 1000; list.Add(n); ``` Note; I assume this is in C#; correct me if I'm wrong and I will fix the co...
Storing more than 1 data item at a single index in a linked-list?
[ "", "java", "collections", "linked-list", "" ]
How do I manipulate images at the pixel level in C#? I need to be able to read/modify each bitmap pixel RGB values separately. A code sample would be appreciated.
If you want speed, then [LockBits](http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.lockbits.aspx). See here for a good walkthrough by Bob Powell. If you just want to edit a few, then [GetPixel](http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.getpixel.aspx)/[SetPixel](http://msdn.microsoft.co...
A sample code routine (I use this for simple merge and compare functionality. It takes two images and produces a third greyscale image showing the differences between the two images as a greyscale tone level. The darker it is, the more the diff.): ``` public static Bitmap Diff(Bitmap src1, Bitmap src2, int x1, int...
How to manipulate images at the pixel level in C#
[ "", "c#", "image-processing", "image-manipulation", "" ]
Today at work we came across the following code (some of you might recognize it): ``` #define GET_VAL( val, type ) \ { \ ASSERT( ( pIP + sizeof(type) ) <= pMethodEnd ); \ val = ( *((type *&)(pIP))++ ); \ } ``` Basically we have...
The inverse square root implementation in Quake 3: ``` float InvSqrt (float x){ float xhalf = 0.5f*x; int i = *(int*)&x; i = 0x5f3759df - (i>>1); x = *(float*)&i; x = x*(1.5f - xhalf*x*x); return x; } ``` **Update:** [How this works](http://www.lomont.org/Math/Papers/2003/InvSqrt.pdf) (thanks ...
This was on reddit recently <http://www.eelis.net/C++/analogliterals.xhtml> ``` assert((o-----o | ! ! ! ! ! ! ! o-----o ).area == ( o---------o | ! ! ! o---------...
What is the most hard to understand piece of C++ code you know?
[ "", "c++", "" ]
I'm using a vendor API to obtain a JDBC connection to the application's database. The API works when running in the application server or when running in a stand-alone mode. I want to run a series of SQL statements in a single transaction. I'm fine with them occurring in the context of the JTA transaction if it exists....
Even if it's straight JDBC, you can have a JTA transaction enabled. Checking the autoCommit flag will NOT help in this regard. You can be in a transaction, distributed or otherwise, with autoCommit set to false. autoCommit set to true would tell you you're not in a distributed transaction but a value of false just mean...
What thilo says does make sense. Otherwise, Not sure of a straight way BUT I will give you a "hack" way write a BAD SQL which you know will give a DB exception. That will result in a stack trace. From the stack trace, you can find out if it is a JTA derived connection or NOT ?
How do you determine if a JDBC Connection was retrieved from a JTA enabled DataSource or straight JDBC?
[ "", "java", "jdbc", "transactions", "jta", "" ]
I'm having some minor problems with some animations I'm trying to set up. I have a couple divs stacked on top of each other kind of like this. ``` <div id="div1"> Stuff... </div> <div id="div2"> More Stuff... </div> ``` Each of these divs has a drop shadow applied to it via jQuery plugin (jquery.dropshadow.js)....
I would suggest using **CSS** for your drop shadows, and **not JS**. I have dealt with this exact problem in the past and I have completely stopped using JS for drop shadows. I have never seen animations with JS shadows look as smooth as pure CSS. Also, using too much JS to alter the page elements can cause performanc...
I think the only way to do this (at least with that particular drop shadow plugin) would be targeting both the element you want **and** all the drop-shadow "phantom" elements, in your animation. So, for example: ``` <style type="text/css"> #div1 { width: 50px; } </style> <div id="div1"> ...
jQuery animation
[ "", "javascript", "jquery", "animation", "user-interface", "" ]
If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this. ``` for i in r...
I'd start by writing a generator method: ``` def grid_objects(alist, blist): for i in range(len(alist)): for j in range(len(alist[i])): yield(alist[i][j], blist[i][j]) ``` Then whenever you need to iterate over the lists your code looks like this: ``` for (a, b) in grid_objects(alist, blist):...
If anyone is interested in performance of the above solutions, here they are for 4000x4000 grids, from fastest to slowest: * [Brian](https://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189111): 1.08s (modified, with `izip` instead of `zip`) * [John](https://sta...
How can I, in python, iterate over multiple 2d lists at once, cleanly?
[ "", "python", "" ]
How can I get list all the files within a folder recursively in Java?
Not sure how you want to represent the tree? Anyway here's an example which scans the entire subtree using recursion. Files and directories are treated alike. Note that [File.listFiles()](http://docs.oracle.com/javase/6/docs/api/java/io/File.html#listFiles%28%29) returns null for non-directories. ``` public static voi...
``` import java.io.File; public class Test { public static void main( String [] args ) { File actual = new File("."); for( File f : actual.listFiles()){ System.out.println( f.getName() ); } } } ``` It displays indistinctly files and folders. See the methods in File class to...
How to scan a folder in Java?
[ "", "java", "file", "directory", "" ]
I currently have a Java SAX parser that is extracting some info from a 30GB XML file. Presently it is: * reading each XML node * storing it into a string object, * running some regexex on the string * storing the results to the database For several million elements. I'm running this on a computer with 16GB of memory...
First, try to find out what's slowing you down. * How much faster is the parser when you parse from memory? * Does using a `BufferedInputStream` with a large size help? Is it easy to split up the XML file? In general, shuffling through 30 GiB of any kind of data will take some time, since you have to load it from the...
1. Just to cover the bases, is Java able to use your 16GB? You (obviously) need to be on a 64-bit OS, and you need to run Java with -d64 -XMx10g (or however much memory you want to allocate to it). 2. It is highly unlikely memory is a limiting factor for what you're doing, so you really shouldn't see it fully utilized....
Searching for regex patterns on a 30GB XML dataset. Making use of 16gb of memory
[ "", "java", "xml", "" ]
I moved a [WordPress](http://en.wikipedia.org/wiki/WordPress) installation to a new folder on a Windows/[IIS](http://en.wikipedia.org/wiki/Internet_Information_Services) server. I'm setting up 301 redirects in PHP, but it doesn't seem to be working. My post URLs have the following format: ``` http:://www.example.com/O...
Maybe, because you are under IIS, ``` $_SERVER['PATH_INFO'] ``` is what you want, based on the URLs you used to explain. For Apache, you'd use `$_SERVER['REQUEST_URI']`.
``` $pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; } return $pageURL; ```
How can I get the current page's full URL on a Windows/IIS server?
[ "", "php", "iis", "" ]
using MVP, what is the normal order of construction and dependency injection. normally you create a presenter for each view and pass the view into the presenter on constructor. But what if you have: 1. A Service that multiple views need to listen to events on. 2. Multiple views all pointing to the same data model cac...
Here is what I do: First, I define theses interfaces: ``` public interface IView<TPresenter> { TPresenter Presenter { get; set; } } public interface IPresenter<TView, TPresenter> where TView : IView<TPresenter> where TPresenter : IPresenter<TView, TPresenter> { TView View { get; set; } } ``` Then th...
In WinForms, I prefer a simple approach. Usually you're dealing with a few UserControls on a design surface -- make these your view classes. .NET creates the control hierarchy for you (via InitializeComponent). If you use the [Passive View](http://martinfowler.com/eaaDev/PassiveScreen.html) pattern, each view then inst...
MVP dependency injection
[ "", "c#", "winforms", "mvp", "" ]
For posting AJAX forms in a form with many parameters, I am using a solution of creating an `iframe`, posting the form to it by POST, and then accessing the `iframe`'s content. specifically, I am accessing the content like this: ``` $("some_iframe_id").get(0).contentWindow.document ``` I tested it and it worked. On ...
Solved it by myself! The problem was, that even though the correct response was being sent (verified with Fiddler), it was being sent with an HTTP 500 error code (instead of 200). So it turns out, that if a response is sent with an error code, IE replaces the content of the `iframe` with an error message loaded from ...
Beware of security limitations associated to **iFrames**, like *Cross domain* restriction (aka CORS). Below are 3 common errors related to CORS : 1. Load an iFrame with a different domain. (Ex: opening "*www.foo.com*" while top frame is "*www.ooof.com*") 2. Load an iFrame with a different port: iFrame's URL *port* dif...
"Access is denied" error on accessing iframe document object
[ "", "javascript", "ajax", "iframe", "" ]
I understand the mantra of "don't roll your own" when it comes to site security frameworks. For most cases anyway. I'm going to be collaborating on a site that integrates text-messaging into the system. I'd like to use an existing, well-tested security framework to protect the users data, but I need it to also prote...
Note that techniques applied to passwords aren't applicable here. You can store a password salted and hashed (although the value of doing so can be disputed), but that doesn't work for phone numbers. If someone jacks your server, they can do anything the server can. This must include recovering the phone number, but d...
Since you need to be able to retrieve the phone numbers, the only thing you can really do to protect them (beyond the normal things you would do to protecting your db) is encrypt them. This means that you need to: * Make sure the key doesn't leak when you inadvertently leak a database dump. * Make sure your system doe...
Is there a PHP security framework that protects phone numbers as well as passwords?
[ "", "php", "security", "sms", "spam-prevention", "" ]
I want to consume a web service over https from a java client. What steps will i need to take in order to do this?
Really, there shouldn't much different from consuming a web service over HTTP. The big thing is that the process calling the web service will have to trust the server's SSL certificate. If the certificate was purchased from a well-known certificate-issuing authority, this usually isn't a problem. Otherwise, the client ...
You may need to use the [keytool](https://web.archive.org/web/20100606064854/http://java.sun.com:80/j2se/1.4.2/docs/tooldocs/windows/keytool.html) command to trust the server's SSL certificate. I've generally found that it is necessary to run something like this: ``` keytool -importcert -v -trustcacerts -alias ServerN...
Consume Webservice using https protocol
[ "", "java", "web-services", "https", "" ]
So I have a small C# app that needs to periodically check the contents of directories on multiple machines on the network. I thought I could just read \hostname\C$ as a directory path, but with the normal Directory class there doesn't seem to be a way to authenticate against the other servers so you can access the hidd...
From <http://bytes.com/forum/thread689145.html>: > All processes run in the context of a > logged-in user account. If you want to > open a file on another computer, your > application must be running in the > context of a user that has permissions > to open files on that machine. You can > do this with Impersonation. ...
To authenticate with a share to which the user running the process does not have permission (which is often the case for administrative shares), try running the net use command: ``` net use SERVERNAME\IPC$ /user:USERNAME PASSWORD ``` Try running this in a separate process before the code which actually tries to acces...
Reading hidden share in C#
[ "", "c#", "impersonation", "fileshare", "" ]
What is an elegant way to sort objects in PHP? I would love to accomplish something similar to this. ``` $sortedObjectArary = sort($unsortedObjectArray, $Object->weight); ``` Basically specify the array I want to sort as well as the field I want to sort on. I looked into multidimensional array sorting and there might...
Almost verbatim from the manual: ``` function compare_weights($a, $b) { if($a->weight == $b->weight) { return 0; } return ($a->weight < $b->weight) ? -1 : 1; } usort($unsortedObjectArray, 'compare_weights'); ``` If you want objects to be able to sort themselves, see example 3 here: <http://php...
For php >= 5.3 ``` function osort(&$array, $prop) { usort($array, function($a, $b) use ($prop) { return $a->$prop > $b->$prop ? 1 : -1; }); } ``` Note that this uses Anonymous functions / closures. Might find reviewing the php docs on that useful.
Sort Object in PHP
[ "", "php", "arrays", "sorting", "" ]
What is the simplest SOAP example using Javascript? To be as useful as possible, the answer should: * Be functional (in other words actually work) * Send at least one parameter that can be set elsewhere in the code * Process at least one result value that can be read elsewhere in the code * Work with most modern brow...
This is the simplest JavaScript SOAP Client I can create. ``` <html> <head> <title>SOAP JavaScript Client Test</title> <script type="text/javascript"> function soap() { var xmlhttp = new XMLHttpRequest(); xmlhttp.open('POST', 'https://somesoapurl.com/', true); // bu...
There are many quirks in the way browsers handle XMLHttpRequest, this JS code will work across all browsers: <https://github.com/ilinsky/xmlhttprequest> This JS code converts XML into easy to use JavaScript objects: <http://www.terracoder.com/index.php/xml-objectifier> The JS code above can be included in the pag...
Simplest SOAP example
[ "", "javascript", "soap", "" ]
I have a SQL Server 2005 database and I have 4 GB of text files that I need to import into it. The question is, if these 4 GB of text files are 1.2 GB when they are zipped, how big would the database be if they are imported? Does SQL Server shrink data by default, or how would I set this (think create a database as a d...
SQL Server will not shrink data by default. In fact, there will be a small overhead per column and row, so it would require more space. If you really must store those files in the DB (it is recommended that you don't), take a look at this [article](http://mitch-wheat.blogspot.com/2007/05/save-and-restore-filesimages-t...
There are two primary factors: * Indexing will increase the space requirement. * Normalization will decrease the space requirement.
SQL Server Storage of Data: 4 gb Raw, how much in SQL Server?
[ "", "sql", "sql-server", "" ]
On my team, we usually do string concatentation like this: ``` var url = // some dynamically generated URL var sb = new StringBuffer(); sb.append("<a href='").append(url).append("'>click here</a>"); ``` Obviously the following is much more readable: ``` var url = // some dynamically generated URL var sb = "<a href='...
Internet Explorer is the only browser which really suffers from this in today's world. (Versions 5, 6, and 7 were dog slow. 8 does not show the same degradation.) What's more, IE gets slower and slower the longer your string is. If you have long strings to concatenate then definitely use an array.join technique. (Or s...
Your example is not a good one in that it is very unlikely that the performance will be signficantly different. In your example readability should trump performance because the performance gain of one vs the other is negligable. The benefits of an array (StringBuffer) are only apparent when you are doing many concatent...
is the + operator less performant than StringBuffer.append()
[ "", "javascript", "string", "concatenation", "" ]
I have those maps in my repository. ``` public IQueryable<AwType> GetAwTypes() { return from awt in _db.AwTypes select new AwType { Id = awt.Id, Header = awt.Header, Description = awt.Description }; } public IQueryable<Aw> GetAws() { ...
AwType is a reference type. It would be a bad idea to group on that reference type... Each AwType in that query is a unique reference, so n elements would yield n groups. Try this: ``` var awGroups = from aw in _repository.GetAws() group aw by aw.AwType.ID into newGroup //changed to group on ID select newGroup; Lis...
You can group by an anonymous type, eg new { Foo, Bar }
Is there a way to write a group by query in LinqToSql grouping not on a scalar value?
[ "", "c#", "linq", "linq-to-sql", "" ]
How do I toggle the visibility of an element using `.hide()`, `.show()`, or `.toggle()`? How do I test if an element is `visible` or `hidden`?
Since the question refers to a single element, this code might be more suitable: ``` // Checks CSS content for display:[none|block], ignores visibility:[true|false] $(element).is(":visible"); // The same works with hidden $(element).is(":hidden"); ``` It is the same as [twernt's suggestion](https://stackoverflow.com...
You can use the [`hidden`](http://docs.jquery.com/Selectors/hidden) selector: ``` // Matches all elements that are hidden $('element:hidden') ``` And the [`visible`](http://docs.jquery.com/Selectors/visible) selector: ``` // Matches all elements that are visible $('element:visible') ```
How do I check if an element is hidden in jQuery?
[ "", "javascript", "jquery", "dom", "visibility", "display", "" ]
I have an MFC app which I have been working on for a few weeks now, I want to manually set the dimensions of the main frame when it is loaded, can someone give me a hand with this, specifically where to put the code as well? Thanks!
You can also set the size (with `SetWindowPos()`) from within `CMainFrame::OnCreate()`, or in the `CWinApp`-derived class' `InitInstance`. Look for the line that says `pMainFrame->ShowWindow()`, and call `pMainFrame->SetWindowPos()` before that line. That's where I always do it.
Find your screen size with .. ``` CRect rect; SystemParametersInfo(SPI_GETWORKAREA,0,&rect,0); screen_x_size=rect.Width(); screen_y_size=rect.Height(); ``` use these values to calculate the X and Y size of your window then .. ``` ::SetWindowPos(m_hWnd,HWND_TOPMOST,0,0,main_x_size,main_y_size,SWP_NOZORDER); ``` Wh...
Sizing an MFC Window
[ "", "c++", "mfc", "" ]
In PHP, function parameters can be passed by reference by prepending an ampersand to the parameter in the function declaration, like so: ``` function foo(&$bar) { // ... } ``` Now, I am aware that this is *not* designed to improve performance, but to allow functions to change variables that are normally out of th...
The Zend Engine uses copy-on-write, and when you use a reference yourself, it incurs a little extra overhead. Can only find [this mention](http://web.archive.org/web/20130406174901/http://www.thedeveloperday.com/php-lazy-copy/) at time of writing though, and comments in [the manual](http://www.php.net/references) conta...
In a test with 100 000 iterations of calling a function with a string of 20 kB, the results are: ### Function that just reads / uses the parameter ``` pass by value: 0.12065005 seconds pass by reference: 1.52171397 seconds ``` ### Function to write / change the parameter ``` pass by value: 1.52223396 sec...
In PHP (>= 5.0), is passing by reference faster?
[ "", "php", "performance", "pass-by-reference", "" ]
I've been playing with the .NET built in localization features and they seem to all rely on putting data in resx files. But most systems can't rely on this because they are database driven. So how do you solve this issue? Is there a built in .NET way, or do you create a translations table in SQL and do it all manually...
In my opinion, localizing dynamic content (e.g., your FAQ) should be done by you in your database. Depending on how your questions are stored, I would probably create a "locale" column and use that when selecting the FAQ questions from the database. I'm not sure if this would scale very well when you started localizing...
For a given item in your data model, split out the description part into a localized table with a locale Id column (LCID). So the table for Product would not in fact contain the products description or name, but only its hard and fast values (ProductId, EAN, NumberInStock, NextStockData, IsActive, IsPublished) etc. P...
How do you localize a database driven website
[ "", "c#", ".net", "asp.net", "localization", "" ]
Since multiple inheritance is bad (it makes the source more complicated) C# does not provide such a pattern directly. But sometimes it would be helpful to have this ability. For instance I'm able to implement the missing multiple inheritance pattern using interfaces and three classes like that: ``` public interface I...
> Since multiple inheritance is bad (it makes the source more complicated) C# does not provide such a pattern directly. But sometimes it would be helpful to have this ability. C# and the .net CLR have not implemented MI because they have not concluded how it would inter-operate between C#, VB.net and the other languag...
Consider just using *[composition](http://en.wikipedia.org/wiki/Object_composition)* instead of trying to simulate Multiple Inheritance. You can use Interfaces to define what classes make up the composition, eg: `ISteerable` implies a property of type `SteeringWheel`, `IBrakable` implies a property of type `BrakePedal`...
Multiple Inheritance in C#
[ "", "c#", "interface", "multiple-inheritance", "" ]
I'm told that the template system in C++ is Turing-complete at compile time. This is mentioned in [this post](https://stackoverflow.com/questions/75538/hidden-features-of-c#75627) and also on [wikipedia](http://en.wikipedia.org/wiki/C%2B%2B). Can you provide a nontrivial example of a computation that exploits this pro...
Example ``` #include <iostream> template <int N> struct Factorial { enum { val = Factorial<N-1>::val * N }; }; template<> struct Factorial<0> { enum { val = 1 }; }; int main() { // Note this value is generated at compile time. // Also note that most compilers have a limit on the depth of the recursi...
I've done a turing machine in C++11. Features that C++11 adds are not significant for the turing machine indeed. It just provides for arbitrary length rule lists using variadic templates, instead of using perverse macro metaprogramming :). The names for the conditions are used to output a diagram on stdout. i've remove...
C++ templates Turing-complete?
[ "", "c++", "templates", "template-meta-programming", "turing-complete", "" ]
I have created some extra functionality on my Linq-to-SQL classes to make things easier as I develop my applications. For example I have defined a property that retrieves active contracts from a list of contracts. However if I try to use this property in a lambda expression or in general in a query it either throws an ...
When accessed individually, I suspect that having a query that returns IQueryable would work - however, I expect that when this is part of a larger Expression, the expression interpreter will complain (which seems like what you are describing). However, I suspect that you might be able to break it down a bit. Try addi...
That worked like a charm. The SQL statment generated by **CustomersWithActiveContracts** looked fine to me. ``` {SELECT [t0].[CustomerID], [t0].[cFirstName], [t0].[cLastName] FROM [dbo].[Customers] AS [t0] WHERE (( SELECT COUNT(*) FROM [dbo].[Contracts] AS [t1] WHERE (([t1].[ContractEndDate] > @p0) OR ([t...
Mapping computed properties in Linq-to-SQL to actuall SQL statements
[ "", "c#", ".net", "linq", "linq-to-sql", "" ]
Is it possible, in Java, to enforce that a class have a specific set of subclasses and no others? For example: ``` public abstract class A {} public final class B extends A {} public final class C extends A {} public final class D extends A {} ``` Can I somehow enforce that no other subclasses of A can ever be create...
Church encoding to the rescue: ``` public abstract class A { public abstract <R> R fold(R b, R c, R d); } ``` There are only three implementations possible: ``` public final class B extends A { public <R> R fold(R b, R c, R d) { return b; } } public final class C extends A { public <R> R fold(R b, R c, ...
Give class **`A`** a constructor with package-level accessibility (and no other constructors). Thanks, Dave L., for the bit about no other constructors.
Is there a way to implement algebraic types in Java?
[ "", "java", "class", "abstract-class", "final", "adts", "" ]
I refactored a slow section of an application we inherited from another company to use an inner join instead of a subquery like: ``` WHERE id IN (SELECT id FROM ...) ``` **The refactored query runs about 100x faster.** (~50 seconds to ~0.3) I expected an improvement, but can anyone explain why it was so drastic? The ...
A "correlated subquery" (i.e., one in which the where condition depends on values obtained from the rows of the containing query) will execute once for each row. A non-correlated subquery (one in which the where condition is independent of the containing query) will execute once at the beginning. The SQL engine makes t...
You are running the subquery **once for every row** whereas the join happens on indexes.
Subqueries vs joins
[ "", "sql", "mysql", "performance", "database-design", "join", "" ]
I'm using Java for accessing Alfresco content server via it's web service API for importing some content into it. Content should have some NamedValue properties set to UTF-8(cyrillic) string. I keep getting the Sax parser exception: ``` org.xml.sax.SAXParseException: An invalid XML character (Unicode: 0x1b) was found ...
The problem was that `alfresco-web-service-client.jar` library I used was from 2.9B distribution (I am hitting 2.9B community content server), and dependency libs `bcprov-jdk15-136.jar` and `xmlsec-1.4.0.jar` were not adequate (remained old from 2.1 verison). I should have used `bcprov-jdk15-137.jar` and `xmlsec-1.4.1....
The easiest way to get around it is I think to escape cyrillicString, for instance with [escapeXml](http://commons.apache.org/lang/api-release/org/apache/commons/lang/StringEscapeUtils.html#escapeXml(java.lang.String)) from Jakarta Commons, or by converting the whole string to XML entities if it's not enough. But in th...
Java, Alfresco Web Service API and Unicode NamedValues
[ "", "java", "web-services", "unicode", "alfresco", "" ]
In the following code, both `amp_swap()` and `star_swap()` seems to be doing the same thing. So why will someone prefer to use one over the other? Which one is the preferred notation and why? Or is it just a matter of taste? ``` #include <iostream> using namespace std; void amp_swap(int &x, int &y) { int temp = ...
One is using a reference, one is using a pointer. I would use the one with references, because you can't pass a NULL reference (whereas you can pass a NULL pointer). So if you do: ``` star_swap(NULL, NULL); ``` Your application will crash. Whereas if you try: ``` amp_swap(NULL, NULL); // This won't compile ``` Al...
An argument can also be made for preferring the pointer version over the reference version. In fact, from a documentation point of view it's superior because the caller is made aware of the fact that the input arguments are going to be modified; compare these two calls: ``` swap(a, b); swap(&a, &b); // This cries “wil...
What's the Difference Between func(int &param) and func(int *param)?
[ "", "c++", "pointers", "reference", "" ]
For a long time ago, I have thought that, in java, reversing the domain you own for package naming is silly and awkward. Which do you use for package naming in your projects?
Once you understand why the convention exists, it shouldn't feel silly or awkward in the least. This scheme does two important things: * All of your code is contained in packages that no one else will collide with. You own your domain name, so it's isolated. If we didn't have this convention, many companies would hav...
I actually think the reverse domain name package naming is one of the more brilliant conventions in Java.
Do you really use your reverse domain for package naming in java?
[ "", "java", "namespaces", "" ]
*When using threads I sometimes visualise them as weaving together 3 or more dimensional interconnections between Objects in a Spatial context. This isn't a general use case scenario, but for what I do it is a useful way to think about it.* ### Are there any APIs which you use which aid threading? ### Have you used t...
**Are there any APIs which you use which aid threading?** You mean appart from `java.util.concurrent`? [FunctionalJava](http://www.functionaljava.org/) got some constructs which aid in concurrent programming, as described in a multipart tutorial that starts [here](http://apocalisp.wordpress.com/2008/06/18/parallel-str...
## First of all The usual disclaimer: concurrent programming, in any language, using any abstraction level, is **hard** and **complicated** and has many risks. Take into consideration: * Concurrent programming complicates any application by magnitude * Unit-testing critical sections is hard, and sometimes impossible ...
Java: Threading Techniques & Concepts
[ "", "java", "multithreading", "visualization", "" ]
I am trying to animate a change in backgroundColor using jQuery on mouseover. I have checked some example and I seem to have it right, it works with other properties like fontSize, but with backgroundColor I get and "Invalid Property" js error. The element I am working with is a div. ``` $(".usercontent").mouseover(f...
The color plugin is only 4kb so much cheaper than the UI library. Of course you'll want to use a [decent version](http://github.com/jquery/jquery-color) of the plugin and not [some buggy old thing](http://plugins.jquery.com/project/color) which doesn't handle Safari and crashes when the transitions are too fast. Since ...
I had the same problem and fixed it by including jQuery UI. Here is the complete script : ``` <!-- include Google's AJAX API loader --> <script src="http://www.google.com/jsapi"></script> <!-- load JQuery and UI from Google (need to use UI to animate colors) --> <script type="text/javascript"> google.load("jqueryui", ...
jQuery animate backgroundColor
[ "", "javascript", "jquery", "colors", "jquery-animate", "" ]
I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array. I couldn't have phrased it better than the person that posted [the same question here](http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21062554.html). But to keep it original, I'll phr...
Update (2021) - **Java 17** now includes [`java.util.HexFormat`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/HexFormat.html) (only took 25 years): `HexFormat.of().parseHex(s)` --- For older versions of Java: Here's a solution that I think is better than any posted so far: ``` /* s must b...
**One-liners:** ``` import javax.xml.bind.DatatypeConverter; public static String toHexString(byte[] array) { return DatatypeConverter.printHexBinary(array); } public static byte[] toByteArray(String s) { return DatatypeConverter.parseHexBinary(s); } ``` **Warnings**: * in Java 9 Jigsaw this is no longer p...
Convert a string representation of a hex dump to a byte array using Java?
[ "", "java", "byte", "hex", "dump", "" ]
So I build an array of various dates. Birthdays, anniversaries, and holidays. I'd like to order the array by which one is happening next, essentially sort October to September (wrapping to next year) so if my array is ``` $a = ([0]=>"1980-04-14", [1]=>"2007-06-08", [2]=>"2008-12-25", [3]=>"1978-11-03") ``` I'd li...
``` function relative_year_day($date) { $value = date('z', strtotime($date)) - date('z'); if ($value < 0) $value += 365; return $value; } function cmp($a, $b) { $aValue = relative_year_day($a); $bValue = relative_year_day($b); if ($aValue == $bValue) return 0; return ($a...
I would be tempted to establish the original year of the event, and then add enough whole years to it to ensure that the value is greater than your reference date (normally today's date). Or, possibly, greater than or equal to the reference date. You can then sort in simple date order. **Edited to add**: I'm not flue...
Order dates by upcoming
[ "", "php", "arrays", "sorting", "" ]
Using the following query and results, I'm looking for the most recent entry where the ChargeId and ChargeType are unique. ``` select chargeId, chargeType, serviceMonth from invoice CHARGEID CHARGETYPE SERVICEMONTH 1 101 R 8/1/2008 2 161 N 2/1/2008 3 101 R ...
You can use a **GROUP BY** to group items by type and id. Then you can use the **MAX()** Aggregate function to get the most recent service month. The below returns a result set with ChargeId, ChargeType, and MostRecentServiceMonth ``` SELECT CHARGEID, CHARGETYPE, MAX(SERVICEMONTH) AS "MostRecentServiceMonth" FRO...
So this isn't what the requester was asking for but it is the answer to "SQL selecting rows by most recent date". Modified from <http://wiki.lessthandot.com/index.php/Returning_The_Maximum_Value_For_A_Row> ``` SELECT t.chargeId, t.chargeType, t.serviceMonth FROM( SELECT chargeId,MAX(serviceMonth) AS serviceMonth...
SQL selecting rows by most recent date with two unique columns
[ "", "sql", "oracle", "" ]
I would like to remove the domain/computer information from a login id in C#. So, I would like to make either "Domain\me" or "Domain\me" just "me". I could always check for the existence of either, and use that as the index to start the substring...but I am looking for something more elegant and compact. Worse case sc...
when all you have is a hammer, everything looks like a nail..... use a razor blade ---- ``` using System; using System.Text.RegularExpressions; public class MyClass { public static void Main() { string domainUser = Regex.Replace("domain\\user",".*\\\\(.*)", "$1",RegexOptions.None); Console.Wri...
You could abuse the Path class, thusly: ``` string shortName = System.IO.Path.GetFileNameWithoutExtension(ResourceLoginName); ```
Remove domain information from login id in C#
[ "", "c#", "string", "indexof", "" ]
When writing async method implementations using the BeginInvoke/EndInvoke pattern the code might look something like the following (and to save you guessing this is an async wrapper around a cache): ``` IAsyncResult BeginPut(string key, object value) { Action<string, object> put = this.cache.Put; return put.Be...
I was wrong, there is a cleaner way. You create `Action( IAsyncResult )` delegates for the specific `EndInvoke()` method in the same context where you already know the specific type of the delegate, passing it as the AsyncState. I'm passing `EndPut()` as the callback for convenience. ``` IAsyncResult BeginPut( string...
Why not avoid the problem by just going back to the more general overload: ``` IAsyncResult BeginPut(string key, object value) { return this.BeginPut(null, key, value); } IAsyncResult BeginPut(string region, string key, object value) { Action<string, string, object> put = this.Put; return put.BeginInvoke(reg...
Ending asynchronous delegate invocation with partial type information
[ "", "c#", "asynchronous", "delegates", "" ]
What's the best and most efficient way to count keywords in JavaScript? Basically, I'd like to take a string and get the top N words or phrases that occur in the string, mainly for the use of suggesting tags. I'm looking more for conceptual hints or links to real-life examples than actual code, but I certainly wouldn't...
Cut, paste + execute demo: ``` var text = "Text to be examined to determine which n words are used the most"; // Find 'em! var wordRegExp = /\w+(?:'\w{1,2})?/g; var words = {}; var matches; while ((matches = wordRegExp.exec(text)) != null) { var word = matches[0].toLowerCase(); if (typeof words[word] == "unde...
Once you have that array of words cleaned up, and let's say you call it `wordArray`: ``` var keywordRegistry = {}; for(var i = 0; i < wordArray.length; i++) { if(keywordRegistry.hasOwnProperty(wordArray[i]) == false) { keywordRegistry[wordArray[i]] = 0; } keywordRegistry[wordArray[i]] = keywordRegistry...
What's the best way to count keywords in JavaScript?
[ "", "javascript", "regex", "arrays", "string", "" ]
What is the difference between using the `Runnable` and `Callable` interfaces when designing a concurrent thread in Java, why would you choose one over the other?
See explanation [here](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Callable.html). > The Callable interface is similar to > Runnable, in that both are designed > for classes whose instances are > potentially executed by another > thread. **A Runnable, however, does not > return a result and cannot th...
> What are the differences in the applications of `Runnable` and `Callable`. Is the difference only with the return parameter present in `Callable`? Basically, yes. See the answers to [this question](https://stackoverflow.com/questions/141284/the-difference-between-the-runnable-and-callable-interfaces-in-java). And th...
The difference between the Runnable and Callable interfaces in Java
[ "", "java", "multithreading", "interface", "runnable", "callable", "" ]
I'm creating some text boxes on my form programmatically which I need to reference later using FindControl. I've put the FindControl instruction in the page load method after the code which creates them but get an error: > **Object reference not set to an instance of an object.** I assume this is because the textbox...
Did you put your textbox control inside of another control such as a panel or grid? If so you need to recursively search all the controls on the page. Here is an example of a recursive FindControl implementation: [Recursive Page.FindControl](http://www.codinghorror.com/blog/2005/06/recursive-pagefindcontrol.html). You...
If you create textboxes programmatically you can use directly that to manipulate them. No need for FindControl (which would also be slower) ``` TextBox txt = new TextBox(); ... txt.Text = "Text"; ``` If you need access in different methods you can just make txt a private variable of the class. If you really need to ...
Page Lifecycle - Using FindControl to reference a control created programmatically during page load
[ "", "c#", "asp.net", ".net", "controls", "" ]
Say I have class A with ``` class A { final String foo() { // .. computing result, contacting database, whatever .. return "some computed value"; } // ... and a bazillion other methods, some of them final. } ``` Now I have class B with ``` class B { String methodIWantToTest(A a) { String output...
You can try the [JMockit](http://jmockit.org) mocking library.
I'd remove the "final" and just put in a comment "Don't override this method!!". If you can't trust coworkers not to follow simple instructions, it's hopeless anyway.
How to go about mocking a class with final methods?
[ "", "java", "unit-testing", "mocking", "legacy-code", "" ]
I have a data warehouse containing typical star schemas, and a whole bunch of code which does stuff like this (obviously a lot bigger, but this is illustrative): ``` SELECT cdim.x ,SUM(fact.y) AS y ,dim.z FROM fact INNER JOIN conformed_dim AS cdim ON cdim.cdim_dim_id = fact.cdim_dim_id INNER JOIN nonconfor...
1. I’ve used this technique on several data warehouses I look after. I have not noticed any performance degradation when running reports based off of the views versus a table direct approach but have never performed a detailed analysis. 2. I created the views using the designer in SQL Server management studio and did n...
Make the view or views into into one or more summary fact tables and materialize it. These only need to be refreshed when the main fact table is refreshed. The materialized views will be faster to query and this can be a win if you have a lot of queries that can be satisfied by the summary. You can use the data dictio...
Typical Kimball Star-schema Data Warehouse - Model Views Feasible? and How to Code Gen
[ "", "sql", "sql-server", "t-sql", "code-generation", "data-warehouse", "" ]
Is there a way to respond to the back button being hit (or backspace being pressed) in javascript when only the location hash changes? That is to say when the browser is not communicating with the server or reloading the page.
Use the [`hashchange`](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers.onhashchange) event: ``` window.addEventListener("hashchange", function(e) { // ... }) ``` If you need to support older browsers, check out the [`hashChange` Event section](https://github.com/Modernizr/Modernizr/wiki/HTML5-C...
I did a fun hack to solve this issue to my satisfaction. I've got an AJAX site that loads content dynamically, then modifies the window.location.hash, and I had code to run upon $(document).ready() to parse the hash and load the appropriate section. The thing is that I was perfectly happy with my section loading code f...
Is there a way to catch the back button event in javascript?
[ "", "javascript", "" ]
Should I try to actually upgrade my existing app, or just rewrite it mostly from scratch, saving what pieces (templates, etc) I can?
Although this depends on what you're doing, most applications should be able to just upgrade and then fix everything that breaks. In my experience, the main things that I've had to fix after an upgrade are 1. Changes to some of the funky stuff with models, such as the syntax for following foreign keys. 2. A small set ...
Upgrade. For me it was very simple: change `__str__()` to `__unicode__()`, write basic `admin.py`, and done. Just start running your app on 1.0, test it, and when you encounter an error use the documentation on [backwards-incompatible changes](http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges) to see how ...
What's the best way to upgrade from Django 0.96 to 1.0?
[ "", "python", "django", "" ]
In Javascript, I have an object: ``` obj = { one: "foo", two: "bar" }; ``` Now, I want do do this ``` var a = 'two'; if(confirm('Do you want One')) { a = 'one'; } alert(obj.a); ``` But of course it doesn't work. What would be the correct way of referencing this object dynamically?
short answer: `obj[a]` long answer: `obj.field` is just a shorthand for `obj["field"]`, for the special case where the key is a constant string without spaces, dots, or other nasty things. in your question, the key wasn't a constant, so simply use the full syntax.
Like this: ``` obj[a] ```
How do I reference an object dynamically?
[ "", "javascript", "json", "" ]
Say I have the following: ``` <ul> <li>First item</li> <li>Second item</li> <li>Third item</li> </ul> ``` How would I select all the child elements after the first one using jQuery? So I can achieve something like: ``` <ul> <li>First item</li> <li class="something">Second item</li> <li class="something">Third ...
You should be able to use the "not" and "first child" selectors. ``` $("li:not(:first-child)").addClass("something"); ``` <http://docs.jquery.com/Selectors/not> <http://docs.jquery.com/Selectors/firstChild>
Based on my totally unscientific analysis of the four methods here, it looks like there's not a lot of speed difference among them. I ran each on a page containing a series of unordered lists of varying length and timed them using the Firebug profiler. ``` $("li").slice(1).addClass("something"); ``` Average Time: 5.3...
Select all child elements except the first
[ "", "javascript", "jquery", "" ]
I am writing a drop-in replacement for a legacy application in Java. One of the requirements is that the ini files that the older application used have to be read as-is into the new Java Application. The format of this ini files is the common windows style, with header sections and key=value pairs, using # as the chara...
The library I've used is [ini4j](http://ini4j.sourceforge.net/). It is lightweight and parses the ini files with ease. Also it uses no esoteric dependencies to 10,000 other jar files, as one of the design goals was to use only the standard Java API This is an example on how the library is used: ``` Ini ini = new Ini(...
As [mentioned](https://stackoverflow.com/a/190633), [ini4j](http://ini4j.sourceforge.net/index.html) can be used to achieve this. Let me show one other example. If we have an INI file like this: ``` [header] key = value ``` The following should display `value` to STDOUT: ``` Ini ini = new Ini(new File("/path/to/fil...
What is the easiest way to parse an INI file in Java?
[ "", "java", "parsing", "ini", "" ]
I'm looking for a tool that will be able to build a parser (in C#) if I give it a BNF grammar (eg. <http://savage.net.au/SQL/sql-2003-2.bnf>) Does such a generator exist?
Normally BNF grammars are too ambiguous. ANTLR will be probably good for what you are looking for.
You will have to tweak the BNF a bit, but [TinyPG](http://www.codeproject.com/KB/recipes/TinyPG.aspx "TinyPG") is a great tool.
Parser-generator that outputs C# given a BNF grammar?
[ "", "c#", "parsing", "bnf", "" ]
Take the following C# class: ``` c1 { event EventHandler someEvent; } ``` If there are a lot of subscriptions to `c1`'s `someEvent` event and I want to clear them all, what is the best way to achieve this? **Also consider that subscriptions to this event could be/are lambdas/anonymous delegates.** Currently my solu...
From within the class, you can set the (hidden) variable to null. A null reference is the canonical way of representing an empty invocation list, effectively. From outside the class, you can't do this - events basically expose "subscribe" and "unsubscribe" and that's it. It's worth being aware of what field-like even...
Add a method to c1 that will set 'someEvent' to null. ``` public class c1 { event EventHandler someEvent; public ResetSubscriptions() => someEvent = null; } ```
How can I clear event subscriptions in C#?
[ "", "c#", ".net", "events", "delegates", "" ]
[PEP 8](http://www.python.org/dev/peps/pep-0008/) states: > Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. However if the class/method/function that I am importing is only used in rare cases, surely it is more efficient to do the ...
Module importing is quite fast, but not instant. This means that: * Putting the imports at the top of the module is fine, because it's a trivial cost that's only paid once. * Putting the imports within a function will cause calls to that function to take longer. So if you care about efficiency, put the imports at the...
Putting the import statement inside of a function can prevent circular dependencies. For example, if you have 2 modules, X.py and Y.py, and they both need to import each other, this will cause a circular dependency when you import one of the modules causing an infinite loop. If you move the import statement in one of t...
Should import statements always be at the top of a module?
[ "", "python", "optimization", "pep8", "" ]
How do I iterate over a timespan after days, hours, weeks or months? Something like: ``` for date in foo(from_date, to_date, delta=HOURS): print date ``` Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates...
Use [dateutil](http://labix.org/python-dateutil) and its rrule implementation, like so: ``` from dateutil import rrule from datetime import datetime, timedelta now = datetime.now() hundredDaysLater = now + timedelta(days=100) for dt in rrule.rrule(rrule.MONTHLY, dtstart=now, until=hundredDaysLater): print dt ```...
I don't think there is a method in Python library, but you can easily create one yourself using [datetime](http://docs.python.org/lib/module-datetime.html) module: ``` from datetime import date, datetime, timedelta def datespan(startDate, endDate, delta=timedelta(days=1)): currentDate = startDate while curren...
How to iterate over a timespan after days, hours, weeks and months?
[ "", "python", "datetime", "" ]
In MS Transact SQL, let's say I have a table (Orders) like this: ``` Order Date Order Total Customer # 09/30/2008 8.00 1 09/15/2008 6.00 1 09/01/2008 9.50 1 09/01/2008 1.45 2 09/16/2008 4.50 2 09/17/2008 8.75 ...
This should make it ``` select avg(total), customer from orders o1 where orderdate in ( select top 2 date from orders o2 where o2.customer = o1.customer order by date desc ) group by customer ```
In SQL Server 2005 you have the RANK function, used with partition: ``` USE AdventureWorks; GO SELECT i.ProductID, p.Name, i.LocationID, i.Quantity ,RANK() OVER (PARTITION BY i.LocationID ORDER BY i.Quantity DESC) AS 'RANK' FROM Production.ProductInventory i INNER JOIN Production.Product p ON i....
SQL sub-query problem with grouping, average
[ "", "sql", "sql-server-2005", "" ]
What's the difference between using a define statement and an enum statement in C/C++ (and is there any difference when using them with either C or C++)? For example, when should one use ``` enum {BUFFER = 1234}; ``` over ``` #define BUFFER 1234 ```
`enum` defines a syntactical element. `#define` is a pre-preprocessor directive, executed *before* the compiler sees the code, and therefore is not a language element of C itself. Generally enums are preferred as they are type-safe and more easily discoverable. Defines are harder to locate and can have complex behavi...
`#define` statements are handled by the pre-processor before the compiler gets to see the code so it's basically a text substitution (it's actually a little more intelligent with the use of parameters and such). Enumerations are part of the C language itself and have the following advantages. 1/ They may have type an...
Difference between Enum and Define Statements
[ "", "c++", "c", "enums", "c-preprocessor", "" ]
I'm not sure if the term's actually "Array Addition". I'm trying to understand what does the following line do: ``` int var[2 + 1] = {2, 1}; ``` How is that different from `int var[3]`? I've been using Java for several years, so I'd appreciate if explained using Java-friendly words. Edit: Thousands of thanks to ev...
It's not different. C++ allows expressions (even non-constant expressions) in the subscripts of array declarations (with some limitations; anything other than the initial subscript on a multi-dimensional array must be constant). ``` int var[]; // illegal int var[] = {2,1}; // automatically sized to 2 int var[3] = {2...
> How is that different from `int var[3]`? In no way that I can see.
C++ compile-time expression as an array size
[ "", "c++", "arrays", "" ]
I'm writing an import utility that is using phone numbers as a unique key within the import. I need to check that the phone number does not already exist in my DB. The problem is that phone numbers in the DB could have things like dashes and parenthesis and possibly other things. I wrote a function to remove these thi...
I may misunderstand, but you've got two sets of data to remove the strings from one for current data in the database and then a new set whenever you import. For updating the existing records, I would just use SQL, that only has to happen once. However, SQL isn't optimized for this sort of operation, since you said yo...
I saw this solution with T-SQL code and PATINDEX. I like it :-) ``` CREATE Function [fnRemoveNonNumericCharacters](@strText VARCHAR(1000)) RETURNS VARCHAR(1000) AS BEGIN WHILE PATINDEX('%[^0-9]%', @strText) > 0 BEGIN SET @strText = STUFF(@strText, PATINDEX('%[^0-9]%', @strText), 1, '') END RETU...
Fastest way to remove non-numeric characters from a VARCHAR in SQL Server
[ "", "sql", "sql-server", "performance", "optimization", "" ]
I'm using .NET to make an application with a drawing surface, similar to Visio. The UI connects two objects on the screen with Graphics.DrawLine. This simple implementation works fine, but as the surface gets more complex, I need a more robust way to represent the objects. One of these robust requirements is determinin...
The representation of lines by y = mx + c is problematic for computer graphics, because vertical lines require m to be infinite. Furthermore, lines in computer graphics have a start and end point, unlike mathematical lines which are infinite in extent. One is usually only interested in a crossing of lines if the cross...
You can ask Dr. Math, see [this link](https://web.archive.org/web/20180211083203/http://mathforum.org/library/drmath/view/53254.html).
How do I determine the intersection point of two lines in GDI+?
[ "", "c#", ".net", "graphics", "geometry", "gdi+", "" ]
What are my options for programmatically accessing a Microsoft Project file? What are the pros and cons of each approach? I will basically need to import all data from the file into another data structure. Using the Office Interop assembies is low on the preference scale.
Here are the options: 1. Interop (messy and horribly slow for large projects) 2. Save project in XML and work with it (messy) 3. Save project in the database (that's not publishing and it is available for project 2003 only - see ODBC option while saving). I've seen it being used a lot in the integrat...
The MPXJ ([mpxj.sf.net](http://mpxj.sf.net)) library comes in both Java and .Net flavours and will allow you to read and write multiple Microsoft Project file formats using a single consistent API. I am aware of commercial products which use both the Java and the .Net versions of MPXJ without any issues. Disclaimer: I...
Programmatically access a Microsoft Project (MPP) file from C#
[ "", "c#", "ms-project", "" ]
What would be the most efficient way of recording to a log (.txt) from a console program on C# and .NET 2.2? My program loops multiple times always outputting different data based on what the user wants, so I'm searching for the most efficient way to achieve this. I know I can always reopen a stream and then close it,...
You could hook into the tracing framework that forms part of the CLR. Using a simple class like: <http://www.chaosink.co.uk/files/tracing.zip> you can selectively log diagnostic information. To use it add the class to your application. Create an inistance of the tracer in your class like: ``` private Tracing trace = n...
Consider using [log4net](http://logging.apache.org/log4net/index.html): > a tool to help the programmer output log statements to a variety of output targets... We have kept the framework similar in spirit to the original log4j while taking advantage of new features in the .NET runtime. For more information on log4net ...
Efficient way of logging to txt file from a console program
[ "", "c#", ".net", "performance", "logging", "" ]
I want to be able to list only the directories inside some folder. This means I don't want filenames listed, nor do I want additional sub-folders. Let's see if an example helps. In the current directory we have: ``` >>> os.listdir(os.getcwd()) ['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', ...
Filter the result using os.path.isdir() (and use os.path.join() to get the real path): ``` >>> [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ] ['ctypes', 'distutils', 'encodings', 'lib-tk', 'config', 'idlelib', 'xml', 'bsddb', 'hotshot', 'logging', 'doc', 'test', 'compiler', 'curse...
## os.walk Use [`os.walk`](https://docs.python.org/3/library/os.html#os.walk) with [`next`](https://docs.python.org/3/library/functions.html#next) item function: ``` next(os.walk('.'))[1] ``` For *Python <=2.5* use: ``` os.walk('.').next()[1] ``` ### How this works `os.walk` is a generator and calling `next` will...
How to list only top level directories in Python?
[ "", "python", "filesystems", "" ]
I'm trying to do something like the following: ``` enum E; void Foo(E e); enum E {A, B, C}; ``` which the compiler rejects. I've had a quick look on Google and the consensus seems to be "you can't do it". Why is that? Clarification 2: I'm doing this as I have private methods in a class that take said enum, and I d...
The reason the enum can't be forward declared is that, without knowing the values, the compiler can't know the storage required for the enum variable. C++ compilers are allowed to specify the actual storage space based on the size necessary to contain all the values specified. If all that is visible is the forward decl...
Forward declaration of enums is possible since C++11. Previously, the reason enum types couldn't be forward declared was because the size of the enumeration depended on its contents. As long as the size of the enumeration is specified by the application, it can be forward declared: ``` enum Enum1; ...
Forward declaring an enum in C++
[ "", "c++", "enums", "forward-declaration", "" ]
I'm working on a loosely coupled cluster for some data processing. The network code and processing code is in place, but we are evaluating different methodologies in our approach. Right now, as we should be, we are I/O bound on performance issues, and we're trying to decrease that bottleneck. Obviously, faster switches...
MPI MIGHT use sockets. But there are also MPI implementation to be used with SAN (System area network) that use direct distributed shared memory. That of course if you have the hardware for that. So MPI allows you to use such resources in the future. On that case you can gain massive performance improvements (on my exp...
I would recommend using MPI instead of rolling your own, unless you are very good at that sort of thing. Having wrote some distributed computing-esque applications using my own protocols, I always find myself reproducing (and poorly reproducing) features found within MPI. Performance wise I would not expect MPI to giv...
MPI or Sockets?
[ "", "c++", "c", "cluster-computing", "hpc", "" ]
Is there an elegant way to have performant, natural sorting in a MySQL database? For example if I have this data set: * Final Fantasy * Final Fantasy 4 * Final Fantasy 10 * Final Fantasy 12 * Final Fantasy 12: Chains of Promathia * Final Fantasy Adventure * Final Fantasy Origins * Final Fantasy Tactics Any other **e...
I think this is why a lot of things are sorted by release date. A solution could be to create another column in your table for the "SortKey". This could be a sanitized version of the title which conforms to a pattern you create for easy sorting or a counter.
Here is a quick solution: ``` SELECT alphanumeric, integer FROM sorting_test ORDER BY LENGTH(alphanumeric), alphanumeric ```
Natural Sort in MySQL
[ "", "sql", "mysql", "sorting", "natural-sort", "" ]