Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Will learning C++ help me build native applications with good speed? Will it help me as a programmer, and what are the other benefits?
The reason why I want to learn C++ is because I'm disappointed with the UI performances of applications built on top of JVM and .NET. They feel slow, and start slow too. Of course, a r... | If you want to build Windows applications that will run without frameworks such as .NET or virtual machines/interpreters, then your only really viable choices are going to be Visual Basic or C/C++
I've written some small Windows apps before in C++ code, and there is definitely a benefit in terms of speed and ease of d... | yep, C++ is absolutely great. Check [Qt](http://trolltech.com/products/qt). It has a great [Python binding](http://wiki.python.org/moin/PyQt4) too, so you can easily prototype in Python, and when/if you need extra performance, porting to C++ is a mostly 1:1 translation.
But in fact, writing C++ isn't so hard either wh... | Will Learning C++ Help for Building Fast/No-Additional-Requirements Desktop Applications? | [
"",
"c++",
"user-interface",
"native",
""
] |
In c#
```
double tmp = 3.0 * 0.05;
```
tmp = 0.15000000000000002
This has to do with money. The value is really $0.15, but the system wants to round it up to $0.16. 0.151 should probably be rounded up to 0.16, but not 0.15000000000000002
What are some ways I can get the correct numbers (ie 0.15, or 0.16 if the deci... | Use a fixed-point variable type, or a base ten floating point type like Decimal. Floating point numbers are always somewhat inaccurate, and binary floating point representations add another layer of inaccuracy when they convert to/from base two. | Money should be stored as `decimal`, which is a [floating decimal point type](http://pobox.com/~skeet/csharp/decimal.html). The same goes for other data which really is discrete rather than continuous, and which is logically decimal in nature.
Humans have a bias to decimal for obvious reasons, so "artificial" quantiti... | How to fix precision of variable | [
"",
"c#",
".net",
"math",
""
] |
We have a SmartClient built in C# that stubornly remains open when the PC its running on is being restarted. This halts the restart process unless the user first closes the SmartClient or there is some other manual intervention.
This is causing problems when the infrastructure team remotely installs new software that ... | OK, if you have access to the app, you can handle the SessionEnded event.
```
...
Microsoft.Win32.SystemEvents.SessionEnded +=new
Microsoft.Win32.SessionEndedEventHandler(shutdownHandler);
...
private void shutdownHandler(object sender, Microsoft.Win32.SessionEndedEventArgs e) {
// Do stuff
}
``` | It must be a thread that continues to run preventing your application to close. If you are using threading an easy fix would be to set it to background.
> A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent... | C# .Net exe doesn't close when PC is restarted, keeping the machine from restarting | [
"",
"c#",
"multithreading",
"events",
"smartclient",
"restart",
""
] |
How would one create a Singleton class using PHP5 classes? | ```
/**
* Singleton class
*
*/
final class UserFactory
{
private static $inst = null;
// Prevent cloning and de-serializing
private function __clone(){}
private function __wakeup(){}
/**
* Call this method to get singleton
*
* @return UserFactory
*/
public static functi... | Unfortunately [Inwdr's answer](https://stackoverflow.com/questions/203336/creating-the-singleton-design-pattern-in-php5/1939269#1939269) breaks when there are multiple subclasses.
Here is a correct inheritable Singleton base class.
```
class Singleton
{
private static $instances = array();
protected function ... | Creating the Singleton design pattern in PHP5 | [
"",
"php",
"oop",
"design-patterns",
"singleton",
""
] |
Elementree has become the accepted standard for interacting with xml. What is the prevalent web service/SOAP library in use today? | I'm not sure about an accepted standard, but I've found [SOAPpy](http://soapy.sourceforge.net/) to be fairly straight-forward and useful library for handling SOAP-based web services.
> SOAPy is a SOAP/XML Schema Library for Python. Given either a WSDL or SDL document, SOAPy discovers the published API for a web servic... | soaplib is very easy to use and seems to be active.
<http://web.archive.org/web/20090729125144/https://wiki.github.com/jkp/soaplib/> | Python Web Services | [
"",
"python",
"web-services",
""
] |
I know it is easy to recommend several cross platform libraries.
However, are there benefits to treating each platform individually for your product?
Yes there will be some base libraries used in all platforms, but UI and some other things would be different on each platform.
I have no restriction that the product m... | I would say that the benefits of individual development for each platform are:
- native look and feel
- platform knowledge acquired by your developers
-... i'm out of ideas
Seriously, the cost of developing and maintaining 3 separate copies of your application could be huge if you're not careful.
If it's just the ... | I see the benefits as
* being able to get a totally native behavior in all your platforms which is a good thing for end users
The risks being that
* You may end up coding three apps instead of one with a few differences (ie, it's easier to fall in the let's do X differently as well!)
* You'll create slight incompati... | Developing for different platforms individually, does anyone recommend it? | [
"",
"c++",
"user-interface",
"cross-platform",
"platform-specific",
""
] |
How do you delete all the cookies for the current domain using JavaScript? | ```
function deleteAllCookies() {
const cookies = document.cookie.split(";");
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i];
const eqPos = cookie.indexOf("=");
const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=... | ### One liner
In case you want to paste it in quickly...
```
document.cookie.split(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); });
```
And the code for a bookmarklet :
```
javascript:(function(){document.cookie.split(";").for... | Clearing all cookies with JavaScript | [
"",
"javascript",
"cookies",
""
] |
Sometimes I break long conditions in `if`s onto several lines. The most obvious way to do this is:
```
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
```
Isn't very very appealing visually, because the action blends with the conditions. However, it is the ... | You don't need to use 4 spaces on your second conditional line. Maybe use:
```
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
```
Also, don't forget the whitespace is more flexible than you might think:
```
if (
cond1 == 'val1' and cond2 == 'val2'... | I've resorted to the following in the degenerate case where it's simply AND's or OR's.
```
if all( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ):
if any( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ):
```
It shaves a few characters and makes it clear that there's no ... | Styling multi-line conditions in 'if' statements? | [
"",
"python",
"if-statement",
""
] |
I've been searching for a library that can render organisation charts in either flash and/or javascript(preferably jQuery). I know of several javascript and/or flash chart libraries but none of them seem to be able to render an organisation chart such as this: <http://www.fsai.ie/images/org_chart.gif> | [iLog Elixir](http://www.adobe.com/products/flex/ilogelixir/) seems to have what you're looking for, in Flash/Flex. It's a commercial product and quite expensive, though. I Also found [these blog posts](http://blogs.ilog.com/elixir/category/ilog-elixir/org-chart/) (apparently by people from their dev team) where you ca... | I have tried [Google Org Chart](http://code.google.com/apis/chart/interactive/docs/gallery/orgchart.html). It is free and pretty simple to use. I have used it to create a dynamic org chart in SharePoint. There are a few [issues](http://code.google.com/p/google-visualization-api-issues/issues/list?can=2&q=org%20chart&so... | Flash Organisation Chart | [
"",
"javascript",
"jquery",
"flash",
"charts",
""
] |
I am about to start on a journey writing a windows forms application that will open a txt file that is pipe delimited and about 230 mb in size. This app will then insert this data into a sql server 2005 database (obviously this needs to happen swiftly). I am using c# 3.0 and .net 3.5 for this project.
I am not asking ... | Do you have to write a winforms app? It might be much easier and faster to use SSIS. There are some built-in tasks available especially [Bulk Insert task](http://denster.spaces.live.com/Blog/cns!125D53A08EC75357!1210.entry).
Also, worth checking [Flat File Bulk Import methods speed comparison in SQL Server 2005.](http... | I totally recommend SSIS, you can read in millions of records and clean them up along the way in relatively little time.
You will need to set aside some time to get to grips with SSIS, but it should pay off. There are a few other threads here on SO which will probably be useful:
[What's the fastest way to bulk insert... | What are the pitfalls of inserting millions of records into SQL Server from flat file? | [
"",
"c#",
"sql-server",
"sql-server-2005",
"ssis",
"bulkinsert",
""
] |
I have a loop that looks something like this:
```
for (int i = 0; i < max; i++) {
String myString = ...;
float myNum = Float.parseFloat(myString);
myFloats[i] = myNum;
}
```
This is the main content of a method whose sole purpose is to return the array of floats. I want this method to return `null` if the... | All right, after [Jeffrey L Whitledge said](https://stackoverflow.com/questions/141560/should-trycatch-go-inside-or-outside-a-loop#141652) that there was no performance difference (as of 1997), I went and tested it. I ran this small benchmark:
```
public class Main {
private static final int NUM_TESTS = 100;
... | PERFORMANCE:
There is absolutely no performance difference in where the try/catch structures are placed. Internally, they are implemented as a code-range table in a structure that is created when the method is called. While the method is executing, the try/catch structures are completely out of the picture unless a th... | Should try...catch go inside or outside a loop? | [
"",
"java",
"performance",
"loops",
"try-catch",
""
] |
Is there a clean way of cloning a record in SQL that has an index(auto increment). I want to clone all the fields except the index. I currently have to enumerate every field, and use that in an insert select, and I would rather not explicitly list all of the fields, as they may change over time. | Not unless you want to get into dynamic SQL. Since you wrote "clean", I'll assume not.
**Edit:** Since he asked for a dynamic SQL example, I'll take a stab at it. I'm not connected to any databases at the moment, so this is off the top of my head and will almost certainly need revision. But hopefully it captures the s... | There's no easy and clean way that I can think of off the top of my head, but from a few items in your question I'd be concerned about your underlying architecture. Maybe you have an absolutely legitimate reason for wanting to do this, but usually you want to try to avoid duplicates in a database, not make them easier ... | SQL clone record with a unique index | [
"",
"sql",
"mysql",
"database",
""
] |
There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot i... | As Guido says in his [The fate of reduce() in Python 3000](http://www.artima.com/weblogs/viewpost.jsp?thread=98196) post:
> So now reduce(). This is actually the one I've always hated most, because, apart from a few examples involving + or \*, almost every time I see a reduce() call with a non-trivial function argumen... | `reduce()` is not being removed -- it's simply being moved into the `functools` module. Guido's reasoning is that except for trivial cases like summation, code written using `reduce()` is usually clearer when written as an accumulation loop. | What is the problem with reduce()? | [
"",
"python",
"python-3.x",
""
] |
When using py2exe to distribute Python applications with wxPython, some MSVC DLLs are usually needed to make the .exe work on freshly installed machines. In particular, the two most common DLLs are msvcp71.dll and msvcr71.dll
The former can be included in the .exe using [this tip](http://www.py2exe.org/index.cgi/Overr... | Wouldn't it fail to launch, then? You want `msvcr71.dll` in the same directory as the exe, so that the library loader will be able to find and link it into the application's memory map.
It's needed for basic operation, so you can't just let `py2exe` unpack it with the rest of the DLLs. | py2exe can't do this. You can wrap py2exe (there is [an example on the wiki](http://py2exe.org/index.cgi/SingleFileExecutable) showing how to do that with NSIS); you could build your own wrapper if using NSIS or InnoSetup wasn't an option.
Alternatively, if you're positive that your users will have a compatible copy o... | py2exe including MSVC DLLs in the .exe | [
"",
"python",
"dll",
"py2exe",
""
] |
Want to know what the stackoverflow community feels about the various free and non-free Java Profilers and profiling tools available. | JProfiler works very well for us.
<http://www.ej-technologies.com/products/jprofiler/overview.html> | Yourkit is pretty good for CPU analysis.
For memory usage analsis using heap dumps use <http://www.eclipse.org/mat/> | Which Java Profiling tool do you use and which tool you think is the best? | [
"",
"java",
"profiler",
"profiling",
""
] |
What is the most elegant way to solve this:
* open a file for reading, but only if it is not already opened for writing
* open a file for writing, but only if it is not already opened for reading or writing
The built-in functions work like this
```
>>> path = r"c:\scr.txt"
>>> file1 = open(path, "w")
>>> print file1... | I don't think there is a fully crossplatform way. On unix, the fcntl module will do this for you. However on windows (which I assume you are by the paths), you'll need to use the win32file module.
Fortunately, there is a portable implementation ([portalocker](https://github.com/WoLpH/portalocker)) using the platform a... | > The solution should work inside the same process (like in the example above) as well as when another process has opened the file.
If by 'another process' you mean 'whatever process' (i.e. not your program), in Linux there's no way to accomplish this relying only on system calls (*fcntl* & friends). What you want is ... | What is the best way to open a file for exclusive access in Python? | [
"",
"python",
"file",
"locking",
""
] |
Why is it that when I use a converter in my binding expression in WPF, the value is not updated when the data is updated.
I have a simple Person data model:
```
class Person : INotifyPropertyChanged
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
```
My binding expression looks... | **(see edits below; latest: #2)**
It isn't updating because your `Person` object is not capable of notifying anything that the value of `FirstName` or `LastName` has changed. [See this Question](https://stackoverflow.com/questions/159088/dependencyproperty-and-databinding).
And here's how you implement `INotifyProper... | You can also use a MultiBinding.. Bind to the Person object, the FirstName and LastName. That way, the value gets updated as soon as FirstName or LastName throws the property changed event.
```
<MultiBinding Converter="{IMultiValueConverter goes here..}">
<Binding />
<Binding Path="FirstName" />
<Binding P... | WPF Data Binding and IValueConverter | [
"",
"c#",
"wpf",
"data-binding",
"converters",
""
] |
How do you convert a numerical number to an Excel column name in C# without using automation getting the value directly from Excel.
Excel 2007 has a possible range of 1 to 16384, which is the number of columns that it supports. The resulting values should be in the form of excel column names, e.g. A, AA, AAA etc. | Here's how I do it:
```
private string GetExcelColumnName(int columnNumber)
{
string columnName = "";
while (columnNumber > 0)
{
int modulo = (columnNumber - 1) % 26;
columnName = Convert.ToChar('A' + modulo) + columnName;
columnNumber = (columnNumber - modulo) / 26;
}
re... | If anyone needs to do this in Excel without VBA, here is a way:
```
=SUBSTITUTE(ADDRESS(1;colNum;4);"1";"")
```
where colNum is the column number
And in VBA:
```
Function GetColumnName(colNum As Integer) As String
Dim d As Integer
Dim m As Integer
Dim name As String
d = colNum
name = ""
Do W... | How to convert a column number (e.g. 127) into an Excel column (e.g. AA) | [
"",
"c#",
"excel",
""
] |
I've created some fairly simple XAML, and it works perfectly (at least in KAXML). The storyboards run perfectly when called from within the XAML, but when I try to access them from outside I get the error:
```
'buttonGlow' name cannot be found in the name scope of 'System.Windows.Controls.Button'.
```
I am loading th... | Finally found it. When you call Begin on storyboards that reference elements in the ControlTemplate, you must pass in the control template as well.
Changing:
```
pressedButtonStoryboard.Begin(_xamlButton);
```
To:
```
pressedButtonStoryboard.Begin(_xamlButton, _xamlButton.Template);
```
Fixed everything. | I made it work by restructuring the XAML so that the `SolidColorBrush` and `OuterGlowBitmapEffect` were resources of the button and thus referenced are shared by the `Storyboard`s and the elements they're applied to. I retrieved the `Storyboard` and called `Begin()` on it just as you did, but here is the modified XAML ... | Storyboards can't find ControlTemplate elements | [
"",
"c#",
".net",
"wpf",
"xaml",
"animation",
""
] |
I want to loop over the elements of an HTML form, and store the values of the <input> fields in an object. The following code doesn't work, though:
```
function config() {
$("#frmMain").children().map(function() {
var child = $("this");
if (child.is(":checkbox"))
this[child.attr("name")... | don't think you need quotations on this:
```
var child = $("this");
```
try:
```
var child = $(this);
``` | jQuery has an excellent function for looping through a set of elements: [.each()](http://docs.jquery.com/Core/each)
```
$('#formId').children().each(
function(){
//access to form element via $(this)
}
);
``` | Looping over elements in jQuery | [
"",
"javascript",
"jquery",
""
] |
I'm making a mini ORM for a Java program I'm writing... there is a class for each table in my db, all inheriting from `ModelBase`.
`ModelBase` is abstract & provides a bunch of static methods for finding & binding objects from the db, for example:
```
public static ArrayList findAll(Class cast_to_class) {
//build t... | Albeit, I totally agree in the point of "Static is the wrong thing to be using here", I kind of understand what you're trying to address here. Still instance behavior should be the way to work, but if you insist this is what I would do:
Starting from your comment "I need to create an instance of it just to get a strin... | Static is the wrong thing to be using here.
Conceptually static is wrong because it's only for services that don't correspond to an an actual object, physical or conceptual. You have a number of tables, and each should be represented by an actual object in the system, not just be a class. That sounds like it's a bit t... | Alternatives to static methods in Java | [
"",
"java",
"interface",
"static",
""
] |
This question is specifically related to overriding the equals() method for objects with a large number of fields. First off, let me say that this large object cannot be broken down into multiple components without violating OO principles, so telling me "no class should have more than x fields" won't help.
Moving on, ... | If you did want to whitelist for performance reasons, consider using an annotation to indicate which fields to compare. Also, this implementation won't work if your fields don't have good implementations for `equals()`.
P.S. If you go this route for `equals()`, don't forget to do something similar for `hashCode()`.
P... | Use Eclipse, FFS!
Delete the hashCode and equals methods you have.
Right click on the file.
Select Source->Generate hashcode and equals...
Done! No more worries about reflection.
Repeat for each field added, you just use the outline view to delete your two methods, and then let Eclipse autogenerate them. | Java equals(): to reflect or not to reflect | [
"",
"java",
"reflection",
"equals",
""
] |
How do I do forward referencing / declaration in C++ to avoid circular header file references?
I have the #ifndef guard in the header file, yet memory tells me I need this forward referencing thing - which i've used before >< but can't remember how. | You predeclare the class without including it. For example:
```
//#include "Foo.h" // including Foo.h causes circular reference
class Foo;
class Bar
{
...
};
``` | I believe the correct term for what you are talking about is "forward declaration". "Forward referencing" would be a bit confusing. | Forward Referencing or Declaration in C++ | [
"",
"c++",
"syntax",
"forward-declaration",
""
] |
I have a few controls that inherit from `ASP.NET buttons` and use `onserverclick`.
If the user clicks twice, the button fires two server side events. How can I prevent this?
I tried setting `this.disabled='true'` after the click (in the `onclick` attribute) via javascript, but that blocks the first postback as well. | See this example for disabling control on postback. It should help you do what you're trying to achieve.
<http://encosia.com/2007/04/17/disable-a-button-control-during-postback/> | You don't necessarily want to show the button disabled on postback. You want to make sure they don't accidentally submit twice. So disabling or hiding the button as a result of a *server-side* action is already too late in the game. By this point the 2nd request is already on it's way. You need to either do it with jav... | Preventing accidental double clicking on a button | [
"",
"asp.net",
"javascript",
"button",
""
] |
I was previously taught today how to set parameters in a SQL query in .NET in this answer ([click](https://stackoverflow.com/questions/169359/improving-code-readability-for-sql-commands#169369)).
Using parameters with values are fine, but when I try to set a field in the database to null I'm unsuccessful. Either the m... | you want [DBNull](http://msdn.microsoft.com/en-us/library/system.dbnull.aspx).Value.
In my shared DAL code, I use a helper method that just does:
```
foreach (IDataParameter param in cmd.Parameters)
{
if (param.Value == null) param.Value = DBNull.Value;
}
``` | I use a `SqlParameterCollection` extension method that allows me to add a parameter with a nullable value. It takes care of converting `null` to `DBNull`. (Sorry, I'm not fluent in VB.)
```
public static class ExtensionMethods
{
public static SqlParameter AddWithNullable<T>(this SqlParameterCollection parms,
... | Set a database value to null with a SqlCommand + parameters | [
"",
".net",
"sql",
""
] |
How do you organize DB layer, business logic and cross-platform API of your information management system, if uploading and processing 500000 data records in one session is a normal operation (C# .NET 3.5 + MS SQL 2005)?
I’m specifically interested in production-proven paging patterns that behave well with the concurr... | Done the implementation. I have been informed recently that one of the uploads was about 2148849 records. Tiers did successfully deal with the a couple of broken connections and dozens of deadlocks at the DB level during this upload.
In case somebody else needs some info:
* [Product page](http://www.lokad.com/sdk-dot... | This is a good book to start with:
[Patterns of Enterprise Application Architecture](http://www.amazon.co.uk/Enterprise-Application-Architecture-Addison-Wesley-signature/dp/0321127420) by Martin Fowler | Search for information on building large enterprise systems | [
"",
"c#",
".net",
"database",
"scalability",
"reliability",
""
] |
Is there a `string.Empty` in JavaScript, or is it just a case of checking for `""`? | ### Empty string, undefined, null, ...
To check for a [truthy value](https://developer.mozilla.org/en-US/docs/Glossary/Truthy):
```
if (strValue) {
// strValue was non-empty string, true, 42, Infinity, [], ...
}
```
To check for a [falsy value](https://developer.mozilla.org/en-US/docs/Glossary/Falsy):
```
if (!... | For checking if a variable is [falsey](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or if it has length attribute equal to zero (which for a string, means it is empty), I use:
```
function isEmpty(str) {
return (!str || str.length === 0 );
}
```
(Note that strings aren't the only variables with a `len... | How do I check for an empty/undefined/null string in JavaScript? | [
"",
"javascript",
"null",
"is-empty",
""
] |
I have a program 'foo' running different threads, fooT1, fooT2, .. fooTn.
Now if I want write another program 'bar', which could kill the thread fooTr, is that possible?
Reason: One of the thread fooTr tracks product license. If this thread is killed; one may run this product indefinitely. And killing 'foo' itself is... | To my knowledge it is not possible to do this directly. What you could consider however is to create some kind of service on your 'foo' that can be called from 'bar' to kill the thread. There are, of course, hundreds of ways to implement this. My first thought would be to do this using [RMI](https://stackoverflow.com/s... | Actually the java debugger will allow you to kill a thread by injecting an exception into it. I was just trying to work out how to use this feature to kill a thread without wiping out the whole jvm, when I came across this question. If you run the jvm with command line options like:
```
java -Xdebug -Xrunjdwp:transpor... | Java threads: Is it possible view/pause/kill a particular thread from a different java program running on the same JVM? | [
"",
"java",
"multithreading",
"jvm",
""
] |
I'd like to document what high-level (i.e. C++ not inline assembler ) functions or macros are available for Compare And Swap (CAS) atomic primitives...
E.g., WIN32 on x86 has a family of functions `_InterlockedCompareExchange` in the `<_intrin.h>` header. | I'll let others list the various platform-specific APIs, but for future reference in C++09 you'll get the
```
atomic_compare_exchange()
```
operation in the new "Atomic operations library". | glib, a common system library on Linux and Unix systems (but also supported on Windows and Mac OS X), defines [several atomic operations](http://library.gnome.org/devel/glib/2.16/glib-Atomic-Operations.html), including **g\_atomic\_int\_compare\_and\_exchange** and **g\_atomic\_pointer\_compare\_and\_exchange**. | High-level Compare And Swap (CAS) functions? | [
"",
"c++",
"multithreading",
"multicore",
"atomic",
""
] |
This isn't as malicious as it sounds, I want to get the current size of their windows, not look at what is in them. The purpose is to figure out that if every other window is fullscreen then I should start up like that too. Or if all the other processes are only 800x600 despite there being a huge resolution then that i... | Using hints from [WindowMover article](http://www.devx.com/opensource/Article/37773/1954) and [Nattee Niparnan's blog post](http://our.obor.us/?q=node/42) I managed to create this:
```
import win32con
import win32gui
def isRealWindow(hWnd):
'''Return True iff given window is a real Windows application window.'''
... | I'm a big fan of [AutoIt](http://www.autoitscript.com/autoit3/). They have a COM version which allows you to use most of their functions from Python.
```
import win32com.client
oAutoItX = win32com.client.Dispatch( "AutoItX3.Control" )
oAutoItX.Opt("WinTitleMatchMode", 2) #Match text anywhere in a window title
width ... | Get other running processes window sizes in Python | [
"",
"python",
"windows",
"winapi",
"pywin32",
""
] |
I am looking for a relatively good and well supported, and preferably open source blog application that runs on [ASP.NET](http://en.wikipedia.org/wiki/ASP.NET) and [SQL Server](http://en.wikipedia.org/wiki/Microsoft_SQL_Server). It doesn’t need to be packed full of features, it just needs the basics, such as tagging, c... | I used [BlogEngine.NET](http://www.dotnetblogengine.net/) for one of [my clients](http://blog.atomium.be/), can definitely recommend it. | The two big ones are [BlogRngine.NET](http://www.dotnetblogengine.net/) and [Subtext](https://en.wikipedia.org/wiki/Subtext_%28software%29). [dasblog](https://dasblog.codeplex.com/) is good, but just be aware that it's run on XML; there's no database backend which is both a pro and con.
I would strongly recommend you ... | What is a good extendable blogging application for ASP.NET? | [
"",
"c#",
"asp.net",
"blogs",
""
] |
I have a products table that contains a FK for a category, the Categories table is created in a way that each category can have a parent category, example:
```
Computers
Processors
Intel
Pentium
Core 2 Duo
AMD
Athlon
```
I need to make a select query that if the... | The best solution for this is at the database design stage. Your categories table needs to be a *Nested Set*. The article [Managing Hierarchical Data in MySQL](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/) is not that MySQL specific (despite the title), and gives a great overview of the differen... | Looks like a job for a Common Table Expression.. something along the lines of:
```
with catCTE (catid, parentid)
as
(
select cat.catid, cat.catparentid from cat where cat.name = 'Processors'
UNION ALL
select cat.catid, cat.catparentid from cat inner join catCTE on cat.catparentid=catcte.catid
)
select distinct * from ... | Select products where the category belongs to any category in the hierarchy | [
"",
"sql",
"sql-server",
"select",
"hierarchy",
""
] |
What's the best way of inserting information in table A and using the index from table A to relate to table B.
The "solution" I tried is inserting the info in table A (which has a automatically generated ID), then, select the last index and insert it in table B. This may not be very useful, as the last index may chang... | if you're using MSSQL you could use SCOPE\_IDENTITY to return the last id inserted in your current session. You can then use that to insert into table B.
[This article from MSDN](http://msdn.microsoft.com/en-us/library/ms190315.aspx) gives a decent example on how to do it. | This is the sequence solution (for postgres), you'd have to do it in a stored procedure or on your application code, of course.
```
postgres=# create table foo(id serial primary key, text varchar);
NOTICE: CREATE TABLE will create implicit sequence "foo_id_seq" for serial column "foo.id"
NOTICE: CREATE TABLE / PRIMA... | Best way to make double insert | [
"",
"sql",
"database",
""
] |
What is the best way to free resources (in this case unlock the ReadWriteLock) when leaving the scope ? How to cover all possible ways (return, break, exceptions etc)? | A try/finally block is the closest thing that you can get to this behaviour:
```
Lock l = new Lock();
l.lock(); // Call the lock before calling try.
try {
// Do some processing.
// All code must go in here including break, return etc.
return something;
} finally {
l.unlock();
}
``` | Like mike said, a finally block should be your choice. see the [finally block tutorial](http://java.sun.com/docs/books/tutorial/essential/exceptions/finally.html), where it is stated:
> The finally block **always** executes when
> the try block exits. This ensures that
> the finally block is executed even if
> an unex... | AutoLock in Java - how to? | [
"",
"java",
"synchronization",
"locking",
""
] |
Visual Studio includes support for \_\_forceinline. The Microsoft Visual Studio 2005 documentation states:
> The \_\_forceinline keyword overrides
> the cost/benefit analysis and relies
> on the judgment of the programmer
> instead.
This raises the question: When is the compiler's cost/benefit analysis wrong? And, ho... | The compiler is making its decisions based on static code analysis, whereas if you profile as don says, you are carrying out a dynamic analysis that can be much farther reaching. The number of calls to a specific piece of code is often largely determined by the context in which it is used, e.g. the data. Profiling a ty... | You know better than the compiler only when your profiling data tells you so. | When should I use __forceinline instead of inline? | [
"",
"c++",
"visual-studio",
"inline-functions",
""
] |
I can select all the distinct values in a column in the following ways:
* `SELECT DISTINCT column_name FROM table_name;`
* `SELECT column_name FROM table_name GROUP BY column_name;`
But how do I get the row count from that query? Is a subquery required? | You can use the `DISTINCT` keyword within the [`COUNT`](http://technet.microsoft.com/en-us/library/ms175997%28v=sql.90%29.aspx) aggregate function:
```
SELECT COUNT(DISTINCT column_name) AS some_alias FROM table_name
```
This will count only the distinct values for that column. | This will give you BOTH the distinct column values and the count of each value. I usually find that I want to know both pieces of information.
```
SELECT [columnName], count([columnName]) AS CountOf
FROM [tableName]
GROUP BY [columnName]
``` | SQL to find the number of distinct values in a column | [
"",
"sql",
"distinct",
""
] |
I've seen the question (and answer) when posed for [MS SQL Server](https://stackoverflow.com/questions/202940/unit-tests-framework-for-databases), though I don't yet know of one for Oracle and PL/SQL. Are there xUnit style testing frameworks for Oracle's PL/SQL? What are they? | The most commonly used is probably [utPLSQL](http://utplsql.org/)
The original author of this toolkit now works for Quest, which has a [commercial PL/SQL unit testing application](http://www.quest.com/code-tester-for-oracle/). | The last version of [SQL Developer](http://www.oracle.com/technology/products/database/sql_developer/index.html) includes an Unit Test suite very interesting. | Unit Testing Framework for Oracle PL/SQL? | [
"",
"sql",
"oracle",
"unit-testing",
"plsql",
""
] |
How do you get the max value of an enum? | Enum.GetValues() seems to return the values in order, so you can do something like this:
```
// given this enum:
public enum Foo
{
Fizz = 3,
Bar = 1,
Bang = 2
}
// this gets Fizz
var lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Last();
```
**Edit**
For those not willing to read through the comment... | I agree with Matt's answer. If you need just min and max int values, then you can do it as follows.
**Maximum:**
```
Enum.GetValues(typeof(Foo)).Cast<int>().Max();
```
**Minimum:**
```
Enum.GetValues(typeof(Foo)).Cast<int>().Min();
``` | Getting the max value of an enum | [
"",
"c#",
"enums",
""
] |
I have a simple Python script that I want to stop executing if a condition is met.
For example:
```
done = True
if done:
# quit/stop/exit
else:
# do other stuff
```
Essentially, I am looking for something that behaves equivalently to the 'return' keyword in the body of a function which allows the flow of the... | To exit a script you can use,
```
import sys
sys.exit()
```
You can also provide an exit status value, usually an integer.
```
import sys
sys.exit(0)
```
Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero.
```
import sys
sys.ex... | You could put the body of your script into a function and then you could return from that function.
```
def main():
done = True
if done:
return
# quit/stop/exit
else:
# do other stuff
if __name__ == "__main__":
#Run as main program
main()
``` | How do I abort the execution of a Python script? | [
"",
"python",
"syntax",
"scripting",
"exit",
""
] |
I'm using the `mechanize` module to execute some web queries from Python. I want my program to be error-resilient and handle all kinds of errors (wrong URLs, 403/404 responsese) gracefully. However, I can't find in mechanize's documentation the errors / exceptions it throws for various errors.
I just call it with:
``... | ```
$ perl -0777 -ne'print qq($1) if /__all__ = \[(.*?)\]/s' __init__.py | grep Error
'BrowserStateError',
'ContentTooShortError',
'FormNotFoundError',
'GopherError',
'HTTPDefaultErrorHandler',
'HTTPError',
'HTTPErrorProcessor',
'LinkNotFoundError',
'LoadError',
'ParseError',
'RobotExclusionError',
'URLError',
```
O... | While this has been posted a long time ago, I think there is still a need to answer the question correctly since it comes up in Google's search results for this very question.
As I write this, mechanize (**version** = (0, 1, 11, None, None)) in Python 265 raises urllib2.HTTPError and so the http status is available th... | Errors with Python's mechanize module | [
"",
"python",
"exception",
"urllib2",
"mechanize",
""
] |
Does anyone know where I can find a library of common but difficult (out of the ordinary) SQL script examples. I am talking about those examples you cannot find in the documentation but do need very often to accomplish tasks such as finding duplicates etc.
It would be a big time saver to have something like that handy... | You may find [this wiki on LessThanDot](http://wiki.lessthandot.com/index.php/Category:Microsoft_SQL_Server) useful, for the most part, it is by Denis Gobo, Microsoft SQL MVP.
EDIT:
The wiki includes **100+ SQL Server Programming Hacks**, the list is, I think, too long to include here, however, there is a [comprehensi... | Here are a few that I find very useful:
* [SQL Server Best Practices](http://technet.microsoft.com/en-us/sqlserver/bb331794.aspx) - Microsoft SQL Server White Papers and Best Practices
* [vyaskn](http://vyaskn.tripod.com/) - A mixture of articles From DBA to Developer
* [Backup, Integrity Check and Index
Optimizatio... | Library of Useful (Difficult) SQL scripts | [
"",
"sql",
"scripting",
""
] |
I have a JUnit 3.x TestCase which I would like to be able to parameterize. I'd like to parametrize the entire `TestCase` (including the fixture). However, the `TestSuite.addTestSuite()` method does not allow be to pass a `TestCase` object, just a class:
```
TestSuite suite = new TestSuite("suite");
suite.addTest... | If this is Java 5 or higher, you might want to consider switching to JUnit 4, which has support for parameterized test cases built in. | Rather than create a parameterized test case for the multiple/different backends you want to test against, I would look into making my test cases abstract. Each new implementation of your API would need to supply an implementing TestCase class.
If you currently have a test method that looks something like
```
public ... | Parameterized test case classes in JUnit 3.x | [
"",
"java",
"junit",
""
] |
I'm working on a commercial (not open source) C++ project that runs on a linux-based system. I need to do some regex within the C++ code. (I know: I now have 2 problems.)
QUESTION: What libraries do people who regularly do regex from C/C++ recommend I look into? A quick search has brought the following to my attention... | Thanks for all the suggestions.
I tried out a few things today, and with the stuff we're trying to do, I opted for the simplest solution where I don't have to download any other 3rd-party library. In the end, I #include <regex.h> and used the standard C POSIX calls regcomp() and regexec(). Not C++, but in a pinch this... | [Boost.Regex](http://www.boost.org/libs/regex/) is very good and is slated to become part of the C++0x standard (it's already in TR1).
Personally, I find [Boost.Xpressive](http://www.boost.org/libs/xpressive/) much nicer to work with. It is a header-only library and it has some nice features such as static regexes (re... | C++: what regex library should I use? | [
"",
"c++",
"regex",
"linux",
""
] |
A python script need to spawn multiple sub-processes via fork(). All of those child processes should run simultaneously and the parent process should be waiting for all of them to finish. Having an ability to set some timeout on a "slow" child would be nice.
The parent process goes on processing the rest of the script ... | Simple example:
```
import os
children = []
for job in jobs:
child = os.fork()
if child:
children.append(child)
else:
pass # really should exec the job
for child in children:
os.waitpid(child, 0)
```
Timing out a slow child is a little more work; you can use `wait` instead of `waitpid... | *Ephemient*: each child in your code will stay in the for loop after his job ends. He will fork again and again. Moreover, the children that start when children[] is not empty will try to wait for some of their brothers at the end of the loop. Eventually someone will crash. This is a workaround:
```
import os, time
d... | What is the best way to run multiple subprocesses via fork()? | [
"",
"python",
"linux",
""
] |
I can't find any information about this on either www.episerver.com or world.episerver.com, anyone knows? | thread safe is a nebulous concept. In this particular case, if you are sharing data between different requests, it is not. Otherwise by the nature of web requests it is. | From what I've seen Episerver uses two mechanisms to achieve thread-safety:
* Locking (when initializing expensive resources)
* Immutable data (when passing page data around) | Is EPiServer threadsafe? | [
"",
"c#",
"asp.net",
"multithreading",
"episerver",
""
] |
I have a site, from which you can download an HTML file. This HTML file contains a form with hidden fields, which is right away posted back to the site using JavaScript. This is a way of allowing users to download to their own machine data that they edit on the site.
On some machines, you get an IE "yellow bar" when t... | The yellow bar is because your page is executing in the Local Machine security zone in IE. On different machines, the Local Machine security zone might be configured in different ways, so you can see the yellow bar on some machines and not see it on other machines.
To learn more about the IE's URL Security Zones, you ... | Look here for details on the [MOTW - Mark Of The Web](http://msdn.microsoft.com/en-us/library/ms537628(VS.85).aspx)
If you add this to your locally served pages, IE will not show the yellow bar.
<http://msdn.microsoft.com/en-us/library/ms537628(VS.85).aspx> | Looking for doc on why IE "yellow bar" shows when opening a HTML file that contains JavaScript | [
"",
"javascript",
"security",
"internet-explorer",
""
] |
Say you've loaded a text file into a string, and you'd like to convert all Unicode escapes into actual Unicode characters inside of the string.
Example:
> "The following is the top half of an integral character in Unicode '\u2320', and this is the lower half '\U2321'." | The answer is simple and works well with strings up to at least several thousand characters.
Example 1:
```
Regex rx = new Regex( @"\\[uU]([0-9A-F]{4})" );
result = rx.Replace( result, match => ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString() );
```
Example 2:
```
Regex rx = new R... | Refactored a little more:
```
Regex regex = new Regex (@"\\U([0-9A-F]{4})", RegexOptions.IgnoreCase);
string line = "...";
line = regex.Replace (line, match => ((char)int.Parse (match.Groups[1].Value,
NumberStyles.HexNumber)).ToString ());
``` | How do I convert Unicode escape sequences to Unicode characters in a .NET string? | [
"",
"c#",
".net",
"unicode",
""
] |
We are using c++ to develop an application that runs in Windows CE 4 on an embedded system.
One of our constraint is that all the memory used by the application shall be allocated during **startup only**. We wrote a lot of containers and algorithms that are using only preallocated memory instead of allocating new one.... | You could write your own allocator for the container, which allocates from a fixed size static buffer. Depending on the usage patterns of the container the allocator could be as simple as incrementing a pointer (e.g. when you only insert stuff into the container once at app startup, and don't continuously add/remove el... | **We use boost for embedded systems**. With boost you can **pick and choose** what you use. We use **`smart_ptr`** and **`boost::bind`** in all of our projects. We write software for **cheap cell phones**.
And if Windows CE can run on your hardware I would expect that **parts of boost** would be applicable.
There are p... | Using boost in embedded system with memory limitation | [
"",
"c++",
"boost",
"embedded",
"windows-ce",
""
] |
How can I find the public facing IP for my net work in Python? | This will fetch your remote IP address
```
import urllib
ip = urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read()
```
If you don't want to rely on someone else, then just upload something like this PHP script:
```
<?php echo $_SERVER['REMOTE_ADDR']; ?>
```
and change the URL in the Python or if ... | <https://api.ipify.org/?format=json> is pretty straight forward
can be parsed by just running `requests.get("https://api.ipify.org/?format=json").json()['ip']` | Finding a public facing IP address in Python? | [
"",
"python",
"ip-address",
""
] |
Just got a request from my boss for an application I'm working on. Basically we're getting an email address setup for an external client to submit excel files to.
What I need is a way to automatically pick up any email sent to this address, so I can take the attachment, process it and save it to a folder.
Any informa... | Email -> mailserver ->[something] -> file-on-disk.
File on disk is pretty easy to parse, use [JavaMail](http://java.sun.com/products/javamail/javadocs/javax/mail/package-summary.html).
The [something] could be:
* listener for smtp connections (overkill)!
* [Pop3](http://java.sun.com/products/javamail/javadocs/com/su... | *Edit:* since I first wrote this answer, Wiser has moved and now claims to only be a unit testing tool, so take the answer below with a pinch of salt...
---
Svrist's answer is good, but if you want to avoid his middle step (the mailserver that writes the mail to disk for later pickup by the Java system) you can use [... | Automated processing of an Email in Java | [
"",
"java",
"email",
"lotus-notes",
""
] |
How do you reverse a string in C or C++ without requiring a separate buffer to hold the reversed string? | The standard algorithm is to use pointers to the start / end, and walk them inward until they meet or cross in the middle. Swap as you go.
---
Reverse ASCII string, i.e. a 0-terminated array where every character fits in 1 `char`. (Or other non-multibyte character sets).
```
void strrev(char *head)
{
if (!head) re... | ```
#include <algorithm>
std::reverse(str.begin(), str.end());
```
This is the simplest way in C++. | How do you reverse a string in place in C or C++? | [
"",
"c++",
"c",
"string",
"reverse",
""
] |
I've got a 'task list' database that uses the adjacency list model (see below) so each 'task' can have unlimited sub-tasks. The table has an 'TaskOrder' column so everything renders in the correct order on a treeview.
Is there an SQL statement (MS-SQL 2005) that will select all the child nodes for a specified parent a... | Couple of different ways... Since the TaskOrder is scoped by parent id, it's not terribly difficult to gather it. In SQL Server, I'd put a trigger on delete that decrements all the ones 'higher' than the one you deleted, thereby closing the gap (pseudocode follows):
```
CREATE TRIGGER ON yourtable FOR DELETE
AS
UPDA... | If you're only using TaskOrder for sorting, it would certainly be simpler to simply leave the holes in TaskOrder, because simply deleting items won't make the sorting incorrect. But then I'm not sure about your application's needs. | SQL to reorder nodes in a hierarchy | [
"",
"sql",
"sql-server",
"hierarchy",
"adjacency-list-model",
""
] |
I'd like to set a cookie via Django with that has several different values to it, similar to .NET's [HttpCookie.Values](http://msdn.microsoft.com/en-us/library/system.web.httpcookie_members(VS.80).aspx) property. Looking at the [documentation](http://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpR... | .NETs multi-value cookies work exactly the same way as what you're doing in django using a separator. They've just abstracted that away for you. What you're doing is fine and proper, and I don't think Django has anything specific to 'solve' this problem.
I will say that you're doing the right thing, in not using multi... | If you're looking for something a little more abstracted, try using [sessions](http://docs.djangoproject.com/en/dev/topics/http/sessions/#examples). I believe the way they work is by storing an id in the cookie that matches a database record. You can store whatever you want in it. It's not exactly the same as what you'... | Does Django support multi-value cookies? | [
"",
"python",
"django",
"cookies",
""
] |
I have seen people say that it is bad form to use catch with no arguments, especially if that catch doesn't do anything:
```
StreamReader reader=new StreamReader("myfile.txt");
try
{
int i = 5 / 0;
}
catch // No args, so it will catch any exception
{}
reader.Close();
```
However, this is considered good form:
`... | The big difference is that `try...catch` will swallow the exception, hiding the fact that an error occurred. `try..finally` will run your cleanup code and then the exception will keep going, to be handled by something that knows what to do with it. | "Finally" is a statement of "Something you must always do to make sure program state is sane". As such, it's always good form to have one, if there's any possibility that exceptions may throw off the program state. The compiler also goes to great lengths to ensure that your Finally code is run.
"Catch" is a statement ... | Why is try {...} finally {...} good; try {...} catch{} bad? | [
"",
"c#",
".net",
"exception",
"try-catch",
"try-catch-finally",
""
] |
```
echo $_POST["name"]; //returns the value a user typed into the "name" field
```
I would like to be able to also return the text of the key. In this example, I want to return the text "name". Can I do this? | Check out the array\_keys() function assuming this is PHP.
<https://www.php.net/array_keys> | $\_POST is just a normal associative array so you can also loop over the entire thing like this:
```
foreach($_POST as $key=>$value)
{
echo "$key=$value";
}
``` | How do I get the key values from $_POST? | [
"",
"php",
"arrays",
""
] |
I only just recently discovered that Visual C++ 2008 (and perhaps earlier versions as well?) supports `for each` syntax on stl lists et al to facilitate iteration.
For example:
```
list<Object> myList;
for each (Object o in myList)
{
o.foo();
}
```
I was very happy to discover it, but I'm concerned about portabili... | For each is not standard C or C++ syntax. If you want to be able to compile this code in gcc or g++, you will need to create an iterator and use a standard for loop.
QuantumPete
[edit]
This seems to be a new feature introduced into MS Visual C++, so this is definitely not portable. Ref: <http://msdn.microsoft.com/en-... | I wouldn't use that. While it's a tempting feature, the syntax is incompatible with the upcoming C++0x standard, which uses:
```
list<Object> myList;
for (Object o : myList)
{
o.foo();
}
```
to do the same thing. | Visual c++ "for each" portability | [
"",
"c++",
"visual-c++",
"stl",
"foreach",
""
] |
I am looking to create symlinks (soft links) from Java on a Windows Vista/ 2008 machine. I'm happy with the idea that I need to call out to the JNI to do this. I am after help on the actual C code though. What is the appropriate system call to create the link? Pointers to some good documentation on this subject would b... | Symbolic links in Windows are created using the [CreateSymbolicLink API Function](http://msdn.microsoft.com/en-us/library/aa363866.aspx), which takes parameters very similar to the command line arguments accepted by [the Mklink command line utility](http://technet.microsoft.com/en-us/library/cc753194.aspx).
Assuming y... | This has been on my list to try, from my notes:
The API:
<http://msdn.microsoft.com/en-us/library/aa363866(VS.85).aspx>
```
BOOLEAN WINAPI CreateSymbolicLink(
__in LPTSTR lpSymlinkFileName,
__in LPTSTR lpTargetFileName,
__in DWORD dwFlags
);
```
Some C# examples:
[http://community.bartdesmet.net/blogs/bar... | How do I create a symlink in Windows Vista? | [
"",
"c++",
"c",
"windows",
"java-native-interface",
"symlink",
""
] |
To save network traffic I'd like to compress my data. The only trick is that I the client is a c application and the server is php. I'm looking for an open source compression library that's available for both c and php.
I guess I could write an external c application to decompress my data, but I'm trying to avoid spaw... | [Zlib](http://www.zlib.net/) provides C APIs, and is part of the PHP functional API as well. | gzip is one of the most (if not the most) popular compression scheme. PHP has [supported it since version 4](http://php.net/zlib). If you need even better compression, [consider bzip2](https://www.php.net/manual/en/book.bzip2.php). | compression library for c and php | [
"",
"php",
"c",
"compression",
""
] |
I can get the executable location from the process, how do I get the icon from file?
Maybe use windows api LoadIcon(). I wonder if there is .NET way... | ```
Icon ico = Icon.ExtractAssociatedIcon(theProcess.MainModule.FileName);
``` | This is a sample from a console application implementation.
```
using System;
using System.Drawing; //For Icon
using System.Reflection; //For Assembly
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
try
{
//G... | How can I get the icon from the executable file only having an instance of it's Process in C# | [
"",
"c#",
""
] |
I have some code where I'm returning an array of objects.
Here's a simplified example:
```
string[] GetTheStuff() {
List<string> s = null;
if( somePredicate() ) {
s = new List<string>(); // imagine we load some data or something
}
return (s == null) ?
new string[0] :
s.ToArray... | Even if it's being called "hundreds and hundreds" of times, I'd say it's a premature optimization. If the result is clearer as an empty array, use that.
Now for the actual answer: yes, an empty array takes some memory. It has the normal object overhead (8 bytes on x86, I believe) and 4 bytes for the count. I don't kno... | The upcoming version 4.6 of .NET (later in 2015) contains [a static method](https://msdn.microsoft.com/en-us/library/dn906179.aspx) returning a length-zero `string[]`:
```
Array.Empty<string>()
```
I suppose it returns the same instance if called many times. | Does an empty array in .NET use any space? | [
"",
"c#",
".net",
"arrays",
""
] |
Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion?
```
class MyClass(object):
def my_function():
"""This docstring works!"""
return True
my_list = []
"""This docstring does not work!"""
``` | To my knowledge, it is not possible to assign docstrings to module data members.
[PEP 224](http://www.python.org/dev/peps/pep-0224/) suggests this feature, but the PEP was rejected.
I suggest you document the data members of a module in the module's docstring:
```
# module.py:
"""About the module.
module.data: cont... | It **is** possible to make documentation of module's data, with use of [epydoc](http://epydoc.sourceforge.net/) syntax. Epydoc is one of the most frequently used documentation tools for Python.
The syntax for documenting is `#:` above the variable initialization line, like this:
```
# module.py:
#: Very important da... | Docstrings for data? | [
"",
"python",
"docstring",
""
] |
So I need to generate a code that can be tied to a specific user/prospect with a dollar amount built into it. It needs to be reversible so that client application can confirm the validity of the code and apply the discount a manager intends.
I'd like to make the code as short as possible but it needs to be well obfusc... | Generate a public/private key pair for signing. Digitally sign the combination of user ID and coupon value using the private key. Publish the coupon value + signature as the coupon code, encoded, for example, using letters and numbers. The client application would verify the code by recreating the combination of data t... | Sounds like a case for asymetric encryption. You could give out the public key to everybody, thus providing them with the info for validating the coupon, but the ability to create a cupon would rest with the owner of the private key (= you).
I would create a coupon class that serialises to xml, and then encrypt the xm... | Generate User Specific 1 Time Coupon Code | [
"",
"c#",
"language-agnostic",
"encoding",
"cryptography",
""
] |
Please help! I'm really at my wits' end.
My program is a little personal notes manager (google for "cintanotes").
On some computers (and of course I own none of them) it crashes with an unhandled exception just after start.
Nothing special about these computers could be said, except that they tend to have AMD CPUs.
En... | So it doesnnt crash when configuration is DEBUG Configuration? There are many things different than a RELEASE configruation:
1.) Initialization of globals
2.) Actual machine Code generated etc..
So first step is find out what are exact settings for each parameter in the RELEASE mode as compared to the DEBUG mode.
-AD | > 4) Writig a log shows that the crash happen on a declaration of a local int variable! how could that be? Memory corruption?
What is the underlying code in the executable / assembly? Declaration of int is no code at all, and as such cannot crash. Do you initialize the int somehow?
To see the code where the crash hap... | Heisenbug: WinApi program crashes on some computers | [
"",
"c++",
"debugging",
"winapi",
"crash",
"gdi",
""
] |
Stateless beans in Java do not keep their state between two calls from the client. So in a nutshell we might consider them as objects with business methods. Each method takes parameters and return results. When the method is invoked some local variables are being created in execution stack. When the method returns the ... | Pooling does several things.
One, by having one bean per instance, you're guaranteed to be threads safe (Servlets, for example, are not thread safe).
Two, you reduce any potential startup time that a bean might have. While Session Beans are "stateless", they only need to be stateless with regards to the client. For e... | Pooling enhances performance.
A single instance handling all requests/threads would lead to a lot of contention and blocking.
Since you don't know which instance will be used (and several threads could use a single instance concurrently), the beans must be threadsafe.
The container can manage pool size based on actu... | Why pool Stateless session beans? | [
"",
"java",
"ejb",
"pooling",
"stateless-session-bean",
""
] |
I know I can compile individual source files, but sometimes -- say, when editing a header file used by many `.cpp` files -- multiple source files need to be recompiled. That's what Build is for.
Default behavior of the "Build" command in VC9 (Visual C++ 2008) is to attempt to compile all files that need it. Sometimes ... | I came up with a better macro guys. It stops immediately after the first error/s (soon as build window is updated).
Visual Studio -> Tools -> Macros -> Macro IDE... (or ALT+F11)
```
Private Sub OutputWindowEvents_OnPaneUpdated(ByVal pPane As OutputWindowPane) Handles OutputWindowEvents.PaneUpdated
If Not (pPane.N... | This can be done by adding a macro that is run in response to the event OnBuildProjConfigDone.
The macro is as follows:
```
Private Sub BuildEvents_OnBuildProjConfigDone(ByVal Project As String, ByVal ProjectConfig As String, ByVal Platform As String, ByVal SolutionConfig As String, ByVal Success As Boolean) Handles ... | Automatically stop Visual C++ 2008 build at first compile error? | [
"",
"c++",
"visual-studio",
"visual-studio-2008",
"visual-c++",
"visual-studio-2005",
""
] |
Can somebody give me a complete and working example of calling the `AllocateAndInitializeSid` function from C# code?
I found [this](http://msdn.microsoft.com/en-us/library/aa375213(VS.85).aspx):
```
BOOL WINAPI AllocateAndInitializeSid(
__in PSID_IDENTIFIER_AUTHORITY pIdentifierAuthority,
__in BYTE nSubAuthor... | Using [P/Invoke Interop Assistant](http://www.codeplex.com/clrinterop):
```
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct SidIdentifierAuthority {
/// BYTE[6]
[System.Runtime.InteropServices.MarshalAsAttribute(
... | If you are targeting .NET 2.0 or later, the class System.Security.Principal.SecurityIdentifier wraps a SID and allows you to avoid the error-prone Win32 APIs.
Not exactly an answer to your question, but who knows it may be useful. | How to call the AllocateAndInitializeSid function from C#? | [
"",
"c#",
".net",
"winapi",
""
] |
In my code, I am creating a collection of objects which will be accessed by various threads in a fashion that is only safe if the objects are immutable. When an attempt is made to insert a new object into my collection, I want to test to see if it is immutable (if not, I'll throw an exception).
One thing I can do is t... | There is no reliable way to detect if a class is immutable. This is because there are so many ways a property of a class might be altered and you can't detect all of them via reflection.
The only way to get close to this is:
* Only allow final properties of types that are immutable (primitive types and classes you kn... | Use the [Immutable](http://jcip.net.s3-website-us-east-1.amazonaws.com/annotations/doc/net/jcip/annotations/Immutable.html) annotation from [Java Concurrency in Practice](http://jcip.net/). The tool [FindBugs](http://findbugs.sourceforge.net/) can then help in detecting classes which are mutable but shouldn't be. | How do I identify immutable objects in Java | [
"",
"java",
"functional-programming",
"immutability",
""
] |
I can hookup to `AppDomain.CurrentDomain.UnhandledException` to log exceptions from background threads, but how do I prevent them terminating the runtime? | First, you really should try not to have exceptions thrown - and not handled - in a background thread. If you control the way your delegate is run, encapsulate it in a try catch block and figure a way to pass the exception information back to your main thread (using EndInvoke if you explicitly called BeginInvoke, or by... | From Joe Albahari's excellent [threading](http://www.albahari.com/threading/) article:
> The .NET framework provides a
> lower-level event for global exception
> handling:
> AppDomain.UnhandledException. This
> event fires when there's an unhandled
> exception in any thread, and in any
> type of application (with or w... | How to prevent an exception in a background thread from terminating an application? | [
"",
"c#",
".net",
"exception",
""
] |
I have a string that looks like this:
```
"Name1=Value1;Name2=Value2;Name3=Value3"
```
Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:
```
dict = {
"Name1": "Value1",
"Name2": "Value2",
"Name3": "Value3"
}
```
I have looked t... | There's no builtin, but you can accomplish this fairly simply with a generator comprehension:
```
s= "Name1=Value1;Name2=Value2;Name3=Value3"
dict(item.split("=") for item in s.split(";"))
```
**[Edit]** From your update you indicate you may need to handle quoting. This does complicate things, depending on what the e... | This comes close to doing what you wanted:
```
>>> import urlparse
>>> urlparse.parse_qs("Name1=Value1;Name2=Value2;Name3=Value3")
{'Name2': ['Value2'], 'Name3': ['Value3'], 'Name1': ['Value1']}
``` | Splitting a semicolon-separated string to a dictionary, in Python | [
"",
"python",
"string",
"dictionary",
"split",
""
] |
I have a function that I use called sqlf(), it emulates prepared statements. For instance I can do things like:
```
$sql = sqlf("SELECT * FROM Users WHERE name= :1 AND email= :2",'Big "John"','bj@example.com') ;
```
For various reasons, I cannot use prepared statements, but I would like to emulate them. The problem t... | Null is the only value that you can guarantee is not in the set. How come it is not an option? Anything else can be seen as part of the potential set, they are all values. | I would say that passing an empty array as argument for an IN() clause is an error. You have control over the syntax of the query when calling this function, so you should also be responsible for the inputs. I suggest checking for emptiness of the argument before calling the function. | "SELECT * FROM users WHERE id IN ( )" == FAIL | [
"",
"php",
"mysql",
""
] |
I'm trying to get my head around the Error Handling in MVC.
What I'm looking for is a centralized way to catch errors, log them, if possible resolve them, if nessecary take other actions and finally show the correct view to the user.
I think I can use the [HandleError] filter for this, but I don't see any way to route... | [HandleErrorAttribute](http://www.codeplex.com/aspnet/SourceControl/FileView.aspx?itemId=266465&changeSetId=16503) that comes with MVC is a pretty basic IExceptionFilter.
You have a few options to achieve what i think u want.
You can either use [HandleError (Type=typeof(MyException),View="ErrorView")] on actions/cont... | Leppi, iIf you want to send to Action Result, you can define Action and Controller to Redirect on Error. It's a good example, but personaly i don´t like no use custom pages or http codes to codes
Here is and example of my IExtenptionFilter. My base controler has a default IExceptionFilter to process all no controlled ... | Handle errors with ErrorController rather than a direct view | [
"",
"c#",
"asp.net-mvc",
"error-handling",
"error-logging",
""
] |
The Project's Web section (under project properties in VS2008) has a list of debuggers: ASP.NET, Native Code, SQL Server. What is Native Code? | Native code is machine code executed directly by the CPU. This is in contrast to .NET bytecode, which is interpreted by the .NET virtual machine.
A nice MSDN hit: [Debugging Native Code](https://learn.microsoft.com/en-us/visualstudio/debugger/debugging-native-code?view=vs-2017) | Native code doesn't run on the Common Language Runtime (CLR). An example would be a non-managed C++ application. | What is Native Code? | [
"",
"c#",
"asp.net",
"visual-studio-2008",
""
] |
I know that it *does* consider ' ' as `NULL`, but that doesn't do much to tell me *why* this is the case. As I understand the SQL specifications, ' ' is not the same as `NULL` -- one is a valid datum, and the other is indicating the absence of that same information.
Feel free to speculate, but please indicate if that'... | I believe the answer is that Oracle is very, very old.
Back in the olden days before there was a SQL standard, Oracle made the design decision that empty strings in `VARCHAR`/`VARCHAR2` columns were `NULL` and that there was only one sense of NULL (there are relational theorists that would differentiate between data t... | [Tom Kyte](http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:5984520277372) VP of Oracle:
> A ZERO length varchar is treated as
> NULL.
>
> '' is not treated as NULL.
>
> '' when assigned to a char(1) becomes
> ' ' (char types are blank padded
> strings).
>
> '' when assigned to a varchar2(1)
> becom... | Why does Oracle 9i treat an empty string as NULL? | [
"",
"sql",
"oracle",
"null",
"string",
""
] |
My organization is working on building RESTful webservices on JBoss appserver. The QA team is used to testing SOAP webservices so far using SoapUI. SoapUI has a new version that has REST capabilities. We're considering using that.
1. Are there any publicly available RESTful services available on the net for free that ... | [soapUI](http://www.soapui.org) will do the job as well, check out [this blog post](http://www.eviware.com/blogs/oleblog/?p=11) to get started. | Please try Firefox addon Poster , which is simple to use and gets you up nd running quickly | Testing REST webservices | [
"",
"java",
"web-services",
"rest",
"testing",
"rest-client",
""
] |
I'm wondering if anyone can recommend a good C++ tree implementation, hopefully one that is
stl compatible if at all possible.
For the record, I've written tree algorithms many times before, and I know it can be fun, but I want to be pragmatic and lazy if at all possible. So an actual link to a working solution is the... | I don't know about your requirements, but wouldn't you be better off with a graph (implementations for example in [Boost Graph](http://www.boost.org/doc/libs/release/libs/graph/doc/index.html)) if you're interested mostly in the structure and not so much in tree-specific benefits like speed through balancing? You can '... | Take a look at [this](http://tree.phi-sci.com/).
The tree.hh library for C++ provides an STL-like container class for n-ary trees, templated over the data stored at the nodes. Various types of iterators are provided (post-order, pre-order, and others). Where possible the access methods are compatible with the STL or a... | What's a good and stable C++ tree implementation? | [
"",
"c++",
"tree",
"graph-theory",
""
] |
I'm looking for a way to validate the SQL schema on a production DB after updating an application version. If the application does not match the DB schema version, there should be a way to warn the user and list the changes needed.
Is there a tool or a framework (to use programatically) with built-in features to do th... | Try this SQL.
- Run it against each database.
- Save the output to text files.
- Diff the text files.
```
/* get list of objects in the database */
SELECT name,
type
FROM sysobjects
ORDER BY type, name
/* get list of columns in each table / parameters for each stored procedure */
SELECT so.name,
... | I hope I can help - this is the article I suggest reading:
[Compare SQL Server database schemas automatically](http://solutioncenter.apexsql.com/compare-sql-server-database-schemas-automatically/)
It describes how you can automate the SQL Server schema comparison and synchronization process using T-SQL, SSMS or a thi... | how to compare/validate sql schema | [
"",
"sql",
"redgate",
""
] |
Is there a way to run some custom Javascript whenever a client-side ASP.NET validator (`RequiredFieldValidator`, `RangeValidator`, etc) is triggered?
Basically, I have a complicated layout that requires I run a custom script whenever a DOM element is shown or hidden. I'm looking for a way to automatically run this scr... | See [this comment](https://stackoverflow.com/questions/124682/can-you-have-custom-client-side-javascript-validation-for-standard-aspnet-web-f#125158) for how I managed to extend the ASP.Net client side validation. [Others](http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=362) have managed to extend it using ... | The best solution I've identified for my specific situation is this:
1. Create a global JS data structure mapping control IDs to a visibility state.
2. Register the client IDs of the validators (or anything else, for that matter) in this data structure.
3. Every 250 milliseconds, loop through the global data structure... | Run custom Javascript whenever a client-side ASP.NET validator is triggered? | [
"",
"asp.net",
"javascript",
""
] |
Is the standard Java 1.6 [javax.xml.parsers.DocumentBuilder](http://java.sun.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilder.html) class thread safe? Is it safe to call the parse() method from several threads in parallel?
The JavaDoc doesn't mention the issue, but the [JavaDoc for the same class](http://java.s... | Even though DocumentBuilder.parse appears not to mutate the builder it does on the Sun JDK default implementation (based on Apache Xerces). Eccentric design decision. What can you do? I guess use a ThreadLocal:
```
private static final ThreadLocal<DocumentBuilder> builderLocal =
new ThreadLocal<DocumentBuilder>() ... | There's a reset() method on DocumentBuilder which restores it to the state when it was first created. If you're going the ThreadLocal route, don't forget to call this or you're hosed. | Is DocumentBuilder.parse() thread safe? | [
"",
"java",
"thread-safety",
""
] |
When I build XML up from scratch with `XmlDocument`, the `OuterXml` property already has everything nicely indented with line breaks. However, if I call `LoadXml` on some very "compressed" XML (no line breaks or indention) then the output of `OuterXml` stays that way. So ...
What is the simplest way to get beautified ... | Based on the other answers, I looked into [`XmlTextWriter`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmltextwriter) and came up with the following helper method:
```
static public string Beautify(this XmlDocument doc)
{
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new Xml... | As adapted from [Erika Ehrli's](http://blogs.msdn.com/erikaehrli/archive/2005/11/16/IndentXMLFilesandDocuments.aspx) blog, this should do it:
```
XmlDocument doc = new XmlDocument();
doc.LoadXml("<item><name>wrench</name></item>");
// Save the document to a file and auto-indent the output.
using (XmlTextWriter writer ... | What is the simplest way to get indented XML with line breaks from XmlDocument? | [
"",
"c#",
".net",
"xmldocument",
"outerxml",
""
] |
I was a C++ developer (mostly ATL/COM stuff) until, as many of us, I switched to C# in 2001. I didn't do much C++ programming since then.
Do you have any tips on how to revive my C++ skills? What has changed in C++ in the last years? Are there good books, articles or blogs covering the language. The problem is that mo... | I personally find that syntax is where i mostly need to catch up when i wander back to a language i havent used in a long time. But the concepts and what the language is about stays the same in memory.
Assuming its the same with you, i would say its a good idea to relook at the texts you remember to have been useful t... | [Boost](http://boost.org) - though it, and other libraries were around back then, its only relatively recently that it's taken off in a big way. Google for TR1 and c++0x standards too. You should defintely read up on STL because (IMHO) its the thing that makes C++ special.
ATL is as good a dead technology (don't get m... | How to revive C++ skills | [
"",
"c++",
""
] |
I basically need to show a wait window to the user. For this i have put two seperate window forms in the application. the first form is the main form with a button. The second one is a empty one with just a label text. On click of the button in Form1 i do the below
```
Form2 f = new Form2();
f.Show();
Thread.Sleep(200... | That's because you probably do some lengthy operation in the same thread (UI thread). You should execute your code in a new thread (see Thread class) or at least call Application.DoEvents periodically from inside your lengthy operation to update the UI. | Here is a Waiting Box class I use. Here is how you use it:
```
using WaitingBox;
ShowWaitingBox waiting = new ShowWaitingBox("Title Text","Some Text so the user knows whats going on..");
waiting.Start();
//do something that takes a while
waiting.Stop();
```
Here is the code for WaitingBox:
```
using System;
... | Wait window in a windows application | [
"",
"c#",
".net",
".net-2.0",
""
] |
I recently had to work on a project where the previous developer modified the wp-admin directory. It seems like a bad idea to me, since Wordpress is constantly updated. Am I just not at that level of expertise with modifying Wordpress? | Being open source, I think it's a common thing for software like WordPress to be modified and extended at any point.
To modify or not to modify is a choice between trade-offs. New features can be encapsulated as modules, which may, perhaps, cause their functionality to be less integrated than desired. However, fully i... | Well, it is a bad idea only in that it means you are now responsible for maintaining an internal defacto fork ... every time WordPress releases an update, you have to do a three-way diff to merge your changes into the new "real" WordPress. (Three-way diff means you do a diff between your fork of the old version and the... | Is it necessary in any circumstance to modify Wordpress other than writing plugins and themes? | [
"",
"php",
"wordpress",
""
] |
I've been getting this undefined symbol building with this command line:
```
$ gcc test.cpp
Undefined symbols:
"___gxx_personality_v0", referenced from:
etc...
```
test.cpp is simple and should build fine. What is the deal? | Use
```
g++ test.cpp
```
instead, since this is c++ code.
---
Or, if you *really* want to use `gcc`, add `-lstdc++` to the command line, like so:
```
gcc test.cpp -lstdc++
```
Running `md5` against the `a.out` produced under each scenario shows that it's the same output.
But, yeah, `g++` probably makes your worl... | The `.cpp` extension causes `gcc` to compile your file as a C++ file. (See the [GCC docs](http://gcc.gnu.org/onlinedocs/gcc-4.4.1/gcc/Overall-Options.html#index-file-name-suffix-71).)
Try compiling the same file, but rename it to have a `.c` extension:
```
mv test.cpp
gcc test.c
```
Alternatively, you can explicitly... | Undefined Symbol ___gxx_personality_v0 on link | [
"",
"c++",
"c",
"gcc",
"g++",
""
] |
Assuming we always use a Sun JVM (say, 1.5+), is it always safe to cast a Graphics reference to Graphics2D?
I haven't seen it cause any problems yet and, to my understanding, the Graphics class is legacy code but the Java designers didn't want to change the interfaces for Swing and AWT classes in order to preserver ba... | According to the discussion [here](https://community.oracle.com/thread/1350311?db=5), it **is always safe to cast from `Graphics` to `Graphics2D`**. However I am not able to quickly find the official Sun statement on this.
> The reason it is valid to cast from
> Graphics to Graphics2D, is because Sun
> have said that ... | In the book [Filthy Rich Client](http://filthyrichclients.org) by Chet Haase and Romain Guy they are saying that Swing almost always uses a `Graphics2D` object. Exceptions from this are printing and Swing's `DebugGraphics` object. So as long as none of these situations apply to your code it is safe to cast to `Graphics... | Java2D: Is it always safe to cast Graphics into Graphics2D | [
"",
"java",
"java-2d",
""
] |
I've discovered that cElementTree is about 30 times faster than `xml.dom.minidom` and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.
Can it be done? | After a bit of work, I found the answer myself. Looking at the ElementTree.py source code, I found there was special handling of XML comments and preprocessing instructions. What they do is create a factory function for the special element type that uses a special (non-string) tag value to differentiate it from regular... | [lxml](http://lxml.de/) has support for [CDATA](http://lxml.de/api.html#cdata) and API like ElementTree. | How to output CDATA using ElementTree | [
"",
"python",
"xml",
""
] |
Last week we released Omniture's analytics code onto a large volume of web sites after tinkering and testing for the last week or so.
On almost all of our site templates, it works just fine. In a few scattered, unpredictable situations, there is a *crippling, browser-crashing experience* that *may* turn away some user... | I did an "inspect element" on a link in that page with firebug, and in the DOM tab it says there is an onclick function (anonymous), and also some other function called "s\_onclick\_0".
I coaxed firebug placing a watch like
```
alert(document.links[0].onclick)
```
to alert me the onclick function that omniture (i gu... | DOM doesn't provide any means to introspecting through the events listeners' collections associated with a node.
The only situation where listener can be identified is when it was added through setting a property or an attribute on the element - check on onxxx property or attribute.
There have been a talk recently on... | Get a handle on event listening in JavaScript | [
"",
"javascript",
"firebug",
"event-listener",
""
] |
**E.g.** Is it more secure to use `mod_php` instead of `php-cgi`?
Or is it more secure to use `mod_perl` instead of traditional `cgi-scripts`?
I'm mainly interested in security concerns, but speed might be an issue if there are significant differences. | Security in what sense? Either way it really depends on what script is running and how well it is written. Too many scripts these days are half-assed and do not properly do input validation.
I personally prefer FastCGI to mod\_php since if a FastCGI process dies a new one will get spawned, whereas I have seen mod\_php... | If you run your own server go the module way, it's somewhat faster.
If you're on a shared server the decision has already been taken for you, usually on the CGI side. The reason for this are filesystem permissions. PHP as a module runs with the permissions of the http server (usually 'apache') and unless you can chmod ... | Is there a difference between apache module vs cgi (concerning security)? | [
"",
"php",
"perl",
"apache",
"mod-perl",
"mod-php",
""
] |
Is there a way to listen for a javascript function to exit? A trigger that could be setup when a function has completed?
I am attempting to use a user interface obfuscation technique (BlockUI) while an AJAX object is retrieving data from the DB, but the function doesn't necessarily execute last, even if you put it at ... | However you're accomplishing your Ajax routines, what you need is a "callback" function that will run once it's complete:
```
function ajaxCall(callback){
//do ajax stuff...
callback();
}
```
Then:
```
function doStuff(){
blockUI();
ajaxCall(unblockUI);
}
``` | Your AJAX call should specify a callback function. You can call the unblockUI from within the callback.
[SAJAX](http://www.modernmethod.com/sajax/) is a simple AJAX library that has more help on how to do AJAX calls.
There's also [another post](https://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perfor... | Javascript: Trigger action on function exit | [
"",
"javascript",
"triggers",
"function-exit",
""
] |
I am working on a web application in Java which gets data from servlets via AJAX calls.
This application features several page elements which get new data from the server at fairly rapid intervals.
With a lot of users, the demand on the server has a potential to get fairly high, so I am curious:
**Which approach off... | There is no performance reason to have more than one servlet. In a web application, only a single instance of a servlet class is instantitated, no matter how many requests. Requests are not serialized, they are handled concurrently, hence the need for your servlet to be thread safe. | The [struts framework](http://struts.apache.org/) uses one servlet for everything in your app. Your stuff plugs into that one servlet. If it works for them, it will probably work for you. | Java Servlets: Performance | [
"",
"java",
"ajax",
"servlets",
""
] |
Is it possible to get the route/virtual url associated with a controller action or on a view? I saw that Preview 4 added LinkBuilder.BuildUrlFromExpression helper, but it's not very useful if you want to use it on the master, since the controller type can be different. Any thoughts are appreciated. | You can get that data from ViewContext.RouteData. Below are some examples for how to access (and use) that information:
/// These are added to my viewmasterpage, viewpage, and viewusercontrol base classes:
```
public bool IsController(string controller)
{
if (ViewContext.RouteData.Values["controller"] != null)
... | I always try to implement the simplest solution that meets the project requirements. As Enstein said, "Make things as simple as possible, but not simpler." Try this.
```
<%: Request.Path %>
``` | Asp.Net MVC: How do I get virtual url for the current controller/view? | [
"",
"c#",
"asp.net-mvc",
"routes",
""
] |
In PHP 5, what is the difference between using `self` and `$this`?
When is each appropriate? | # Short Answer
> Use `$this` to refer to the current
> object. Use `self` to refer to the
> current class. In other words, use
> `$this->member` for non-static members,
> use `self::$member` for static members.
# Full Answer
Here is an example of **correct** usage of `$this` and `self` for non-static and static memb... | The keyword self does **NOT** refer merely to the 'current class', at least not in a way that restricts you to static members. Within the context of a non-static member, `self` also provides a way of bypassing the vtable ([see wiki on vtable](https://en.wikipedia.org/wiki/Virtual_method_table)) for the current object. ... | When should I use 'self' over '$this'? | [
"",
"php",
"class",
"oop",
"scope",
""
] |
How can we produce the effect of the red line under a bad spelling word like the image below :
[alt text http://img505.imageshack.us/img505/7253/options285x395rg9.th.png](http://img505.imageshack.us/img505/7253/options285x395rg9.th.png)
**Update**
I do not want to use Google or whatever spell program. I would like t... | You can do this using a [RichTextBox](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.richtextbox?view=windowsdesktop-6.0) control, which will allow you to set the underline style and underline color on any portion of text.
And here's an [example](https://web.archive.org/web/20200803184227/http://gee... | use google's spellchecker
<http://www.asp101.com/articles/jeremy/googlespell/default.asp> | How to add to a textbox the red line (like bad spelling in Word)? | [
"",
"c#",
".net",
".net-2.0",
""
] |
Seems like the subtraction is triggering some kind of issue and the resulting value is wrong.
```
double tempCommission = targetPremium.doubleValue()*rate.doubleValue()/100d;
```
78.75 = 787.5 \* 10.0/100d
```
double netToCompany = targetPremium.doubleValue() - tempCommission;
```
708.75 = 787.5 - 78.75
```
double... | To control the precision of floating point arithmetic, you should use [java.math.BigDecimal](http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html). Read [The need for BigDecimal](https://blogs.oracle.com/CoreJavaTechTips/entry/the_need_for_bigdecimal) by John Zukowski for more information.
Given your exampl... | As the previous answers stated, this is a consequence of doing floating point arithmetic.
As a previous poster suggested, When you are doing numeric calculations, use `java.math.BigDecimal`.
However, there is a gotcha to using `BigDecimal`. When you are converting from the double value to a `BigDecimal`, you have a c... | How to resolve a Java Rounding Double issue | [
"",
"java",
"math",
"rounding",
""
] |
I'm writing some JNI code in C++ to be called from an applet on Windows XP. I've been able to successfully run the applet and have the JNI library loaded and called, even going so far as having it call functions in other DLLs. I got this working by setting up the PATH system environment variable to include the director... | I figured out the problem. This was a doozy. The message "The specified procedure could not be found" for UnsatisfiedLinkError indicates that a function in the root dll or in **a dependent dll** could not be found. The most likely cause of this in a JNI situation is that the native JNI function is not exported correctl... | There is a chance that the DLL was built using C++(as opposed to C). unless you took care to do an extern on the procedure,this is one possible reason.
Try exporting all the functions from the DLL. If the list includes your function, then you're good. | UnsatisfiedLinkError: The specified procedure could not be found | [
"",
"java",
"java-native-interface",
""
] |
When using the ObsoleteAtribute in .Net it gives you compiler warnings telling you that the object/method/property is obsolete and somthing else should be used. I'm currently working on a project that requires a lot of refactoring an ex-employees code. I want to write a custom attribute that I can use to mark methods o... | ## Update
This is now possible with Roslyn (Visual Studio 2015). You can [build](https://johnkoerner.com/csharp/creating-your-first-code-analyzer/) a [code analyzer](https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix) to check for a custom attribute
---
*Origin... | This is worth a try.
You can't extend Obsolete, because it's final, but maybe you can create your own attribute, and mark that class as obsolete like this:
```
[Obsolete("Should be refactored")]
public class MustRefactor: System.Attribute{}
```
Then when you mark your methods with the "MustRefactor" attribute, the c... | Custom Compiler Warnings | [
"",
"c#",
".net",
"vb.net",
"attributes",
"compiler-warnings",
""
] |
I have a c++ header file containing a class.
I want to use this class in several projects, bu I don't want to create a separate library for it, so I'm putting both methods declarations and definitions in the header file:
```
// example.h
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
namespace test_ns{
class TestClass{
public... | These are not equivalent. The second example given has an implicit 'inline' modifier on the method and so the compiler will reconcile multiple definitions itself (most likely with internal linkage of the method if it isn't inlineable).
The first example isn't inline and so if this header is included in multiple transl... | Inside the class body is considered to be inline by the compiler.
If you implement outside of body, but still in header, you have to mark the method as 'inline' explicitly.
```
namespace test_ns{
class TestClass{
public:
inline void testMethod();
};
void TestClass::testMethod(){
// some code here...
}
} // ... | multiple definition error including c++ header file with inline code from multiple sources | [
"",
"c++",
""
] |
Recently I converted a Swing application to Webstart. The process was pretty straightforward, but I found that after I close all windows, my application's JVM did not terminate. The thread dump showed that there are a couple of non-daemon threads, notably Swing's EDT, AWT and a couple of websart related threads.
The a... | Because of bugs in WebStart, yes. WebStart starts up a "secure thread" for it's own purposes that interacts with the EDT. This SecureThread prevents the automatic termination of the Java process one would expect when all windows and AWT resources are disposed.
For more information see <http://www.pushing-pixels.org/?p... | The AWT EDT is usually the culprit. For some years now it has had some logic to shutdown when there are no undisposed windows. However, there are recurrent problems with leaks, including within the implementation of AWT and Swing. Therefore, I strongly suggest using System.exit in production releases (you might possibl... | Do I have to explicitly call System.exit() in a Webstart application? | [
"",
"java",
"swing",
"java-web-start",
""
] |
I want to store a a c# DateTimeOffset value in a SQL Server 2005 database.
Sql 2008 has this as a built-in-type, but SQL Server 2005 does not.
The DateTimeOffset structure has a DateTime value which I store as DateTime, an an Offset property (of type TimeSpan). Since this is the time zone relative to UTC, presumably ... | It's not a good idea to assume that an offset is a number of hours or half-hours - there are certainly quarter-hour timezones around.
Using milliseconds for the offset is probably the most flexible, but I'd argue that minutes is a lot easier to read. If you're ever going to look at the "raw" data in the database, it's... | Normalize all DateTimeOffsets to a common offset, preferably UTC. Then just store the DateTime as usual. Upon extraction restore the offset, which should be a constant. This doesn't retain the originating offset but the offset is ambiguous to a timezone anyway.
If you actually need to know the date/time origin, then y... | Storing a c# DateTimeOffset value in a SQL Server 2005 database | [
"",
"c#",
"sql-server-2005",
"datetimeoffset",
""
] |
Is there a difference (performance, overhead) between these two ways of merging data sets?
```
MyTypedDataSet aDataSet = new MyTypedDataSet();
aDataSet .Merge(anotherDataSet);
aDataSet .Merge(yetAnotherDataSet);
```
and
```
MyTypedDataSet aDataSet = anotherDataSet;
aDataSet .Merge(yetAnotherDataSet);
```
Which do y... | While Keith is right, I suppose the example was simply badly chosen. Generally, it is better to initialize to the “right” object from the beginning and *not* construct an intermediate, empty object as in your case. Two reasons:
1. Performance. This should be obvious: Object creation costs time so creating less objects... | Those two lines do different things.
The first one creates a new set, and then merges a second set into it.
The second one sets the ds reference to point to the second set, so:
```
MyTypedDataSet ds1 = new MyTypedDataSet();
ds1.Merge(anotherDataSet);
//ds1 is a copy of anotherDataSet
ds1.Tables.Add("test")
//anothe... | Differences Between DataSet Merges | [
"",
"c#",
"object",
"initialization",
"dataset",
""
] |
I checked out a project from SVN and did not specify the project type, so it checked out as a "default" project. What is the easiest way to quickly convert this into a "Java" project?
I'm using Eclipse version 3.3.2. | Open the .project file and add java nature and builders.
```
<projectDescription>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core... | Manually changing XML and/or settings is very dangerous in eclipse unless you know exactly what you're doing. In the other case you might end up finding your complete project is screwed. Taking a backup is very recommended!
How to do it just using Eclipse?
1. Select project.
2. Open the project properties through Pro... | How to change an Eclipse default project into a Java project | [
"",
"java",
"eclipse",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.